clang 23.0.0git
ExprConstant.cpp
Go to the documentation of this file.
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
11// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
25// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
27//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
33//===----------------------------------------------------------------------===//
34
35#include "ByteCode/Context.h"
36#include "ByteCode/Frame.h"
37#include "ByteCode/State.h"
38#include "ExprConstShared.h"
39#include "clang/AST/APValue.h"
41#include "clang/AST/ASTLambda.h"
42#include "clang/AST/Attr.h"
44#include "clang/AST/CharUnits.h"
46#include "clang/AST/Expr.h"
48#include "clang/AST/OSLog.h"
52#include "clang/AST/Type.h"
53#include "clang/AST/TypeLoc.h"
58#include "llvm/ADT/APFixedPoint.h"
59#include "llvm/ADT/Sequence.h"
60#include "llvm/ADT/SmallBitVector.h"
61#include "llvm/ADT/StringExtras.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/Debug.h"
64#include "llvm/Support/SaveAndRestore.h"
65#include "llvm/Support/SipHash.h"
66#include "llvm/Support/TimeProfiler.h"
67#include "llvm/Support/raw_ostream.h"
68#include <cstring>
69#include <functional>
70#include <limits>
71#include <optional>
72
73#define DEBUG_TYPE "exprconstant"
74
75using namespace clang;
76using llvm::APFixedPoint;
77using llvm::APInt;
78using llvm::APSInt;
79using llvm::APFloat;
80using llvm::FixedPointSemantics;
81
82namespace {
83 struct LValue;
84 class CallStackFrame;
85 class EvalInfo;
86
87 using SourceLocExprScopeGuard =
89
91 return B.getType();
92 }
93
94 /// Get an LValue path entry, which is known to not be an array index, as a
95 /// field declaration.
96 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
97 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
98 }
99 /// Get an LValue path entry, which is known to not be an array index, as a
100 /// base class declaration.
101 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
102 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
103 }
104 /// Determine whether this LValue path entry for a base class names a virtual
105 /// base class.
106 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
107 return E.getAsBaseOrMember().getInt();
108 }
109
110 /// Given an expression, determine the type used to store the result of
111 /// evaluating that expression.
112 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
113 if (E->isPRValue())
114 return E->getType();
115 return Ctx.getLValueReferenceType(E->getType());
116 }
117
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
120 ///
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
124 return nullptr;
125
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. In exotic cases, we might also see a
129 // top-level ExprWithCleanups. Ignore them either way.
130 if (const auto *FE = dyn_cast<FullExpr>(E))
131 E = FE->getSubExpr()->IgnoreParens();
132
133 if (const auto *Cast = dyn_cast<CastExpr>(E))
134 E = Cast->getSubExpr()->IgnoreParens();
135
136 if (const auto *CE = dyn_cast<CallExpr>(E))
137 return CE->getCalleeAllocSizeAttr() ? CE : nullptr;
138 return nullptr;
139 }
140
141 /// Determines whether or not the given Base contains a call to a function
142 /// with the alloc_size attribute.
143 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144 const auto *E = Base.dyn_cast<const Expr *>();
145 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146 }
147
148 /// Determines whether the given kind of constant expression is only ever
149 /// used for name mangling. If so, it's permitted to reference things that we
150 /// can't generate code for (in particular, dllimported functions).
151 static bool isForManglingOnly(ConstantExprKind Kind) {
152 switch (Kind) {
153 case ConstantExprKind::Normal:
154 case ConstantExprKind::ClassTemplateArgument:
155 case ConstantExprKind::ImmediateInvocation:
156 // Note that non-type template arguments of class type are emitted as
157 // template parameter objects.
158 return false;
159
160 case ConstantExprKind::NonClassTemplateArgument:
161 return true;
162 }
163 llvm_unreachable("unknown ConstantExprKind");
164 }
165
166 static bool isTemplateArgument(ConstantExprKind Kind) {
167 switch (Kind) {
168 case ConstantExprKind::Normal:
169 case ConstantExprKind::ImmediateInvocation:
170 return false;
171
172 case ConstantExprKind::ClassTemplateArgument:
173 case ConstantExprKind::NonClassTemplateArgument:
174 return true;
175 }
176 llvm_unreachable("unknown ConstantExprKind");
177 }
178
179 /// The bound to claim that an array of unknown bound has.
180 /// The value in MostDerivedArraySize is undefined in this case. So, set it
181 /// to an arbitrary value that's likely to loudly break things if it's used.
182 static const uint64_t AssumedSizeForUnsizedArray =
183 std::numeric_limits<uint64_t>::max() / 2;
184
185 /// Determines if an LValue with the given LValueBase will have an unsized
186 /// array in its designator.
187 /// Find the path length and type of the most-derived subobject in the given
188 /// path, and find the size of the containing array, if any.
189 static unsigned
190 findMostDerivedSubobject(const ASTContext &Ctx, APValue::LValueBase Base,
192 uint64_t &ArraySize, QualType &Type, bool &IsArray,
193 bool &FirstEntryIsUnsizedArray) {
194 // This only accepts LValueBases from APValues, and APValues don't support
195 // arrays that lack size info.
196 assert(!isBaseAnAllocSizeCall(Base) &&
197 "Unsized arrays shouldn't appear here");
198 unsigned MostDerivedLength = 0;
199 // The type of Base is a reference type if the base is a constexpr-unknown
200 // variable. In that case, look through the reference type.
201 Type = getType(Base).getNonReferenceType();
202
203 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
204 if (Type->isArrayType()) {
205 const ArrayType *AT = Ctx.getAsArrayType(Type);
206 Type = AT->getElementType();
207 MostDerivedLength = I + 1;
208 IsArray = true;
209
210 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
211 ArraySize = CAT->getZExtSize();
212 } else {
213 assert(I == 0 && "unexpected unsized array designator");
214 FirstEntryIsUnsizedArray = true;
215 ArraySize = AssumedSizeForUnsizedArray;
216 }
217 } else if (Type->isAnyComplexType()) {
218 const ComplexType *CT = Type->castAs<ComplexType>();
219 Type = CT->getElementType();
220 ArraySize = 2;
221 MostDerivedLength = I + 1;
222 IsArray = true;
223 } else if (const auto *VT = Type->getAs<VectorType>()) {
224 Type = VT->getElementType();
225 ArraySize = VT->getNumElements();
226 MostDerivedLength = I + 1;
227 IsArray = true;
228 } else if (const FieldDecl *FD = getAsField(Path[I])) {
229 Type = FD->getType();
230 ArraySize = 0;
231 MostDerivedLength = I + 1;
232 IsArray = false;
233 } else {
234 // Path[I] describes a base class.
235 ArraySize = 0;
236 IsArray = false;
237 }
238 }
239 return MostDerivedLength;
240 }
241
242 /// A path from a glvalue to a subobject of that glvalue.
243 struct SubobjectDesignator {
244 /// True if the subobject was named in a manner not supported by C++11. Such
245 /// lvalues can still be folded, but they are not core constant expressions
246 /// and we cannot perform lvalue-to-rvalue conversions on them.
247 LLVM_PREFERRED_TYPE(bool)
248 unsigned Invalid : 1;
249
250 /// Is this a pointer one past the end of an object?
251 LLVM_PREFERRED_TYPE(bool)
252 unsigned IsOnePastTheEnd : 1;
253
254 /// Indicator of whether the first entry is an unsized array.
255 LLVM_PREFERRED_TYPE(bool)
256 unsigned FirstEntryIsAnUnsizedArray : 1;
257
258 /// Indicator of whether the most-derived object is an array element.
259 LLVM_PREFERRED_TYPE(bool)
260 unsigned MostDerivedIsArrayElement : 1;
261
262 /// The length of the path to the most-derived object of which this is a
263 /// subobject.
264 unsigned MostDerivedPathLength : 28;
265
266 /// The size of the array of which the most-derived object is an element.
267 /// This will always be 0 if the most-derived object is not an array
268 /// element. 0 is not an indicator of whether or not the most-derived object
269 /// is an array, however, because 0-length arrays are allowed.
270 ///
271 /// If the current array is an unsized array, the value of this is
272 /// undefined.
273 uint64_t MostDerivedArraySize;
274 /// The type of the most derived object referred to by this address.
275 QualType MostDerivedType;
276
277 typedef APValue::LValuePathEntry PathEntry;
278
279 /// The entries on the path from the glvalue to the designated subobject.
281
282 SubobjectDesignator() : Invalid(true) {}
283
284 explicit SubobjectDesignator(QualType T)
285 : Invalid(false), IsOnePastTheEnd(false),
286 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
287 MostDerivedPathLength(0), MostDerivedArraySize(0),
288 MostDerivedType(T.isNull() ? QualType() : T.getNonReferenceType()) {}
289
290 SubobjectDesignator(const ASTContext &Ctx, const APValue &V)
291 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
292 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
293 MostDerivedPathLength(0), MostDerivedArraySize(0) {
294 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
295 if (!Invalid) {
296 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
297 llvm::append_range(Entries, V.getLValuePath());
298 if (V.getLValueBase()) {
299 bool IsArray = false;
300 bool FirstIsUnsizedArray = false;
301 MostDerivedPathLength = findMostDerivedSubobject(
302 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
303 MostDerivedType, IsArray, FirstIsUnsizedArray);
304 MostDerivedIsArrayElement = IsArray;
305 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
306 }
307 }
308 }
309
310 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
311 unsigned NewLength) {
312 if (Invalid)
313 return;
314
315 assert(Base && "cannot truncate path for null pointer");
316 assert(NewLength <= Entries.size() && "not a truncation");
317
318 if (NewLength == Entries.size())
319 return;
320 Entries.resize(NewLength);
321
322 bool IsArray = false;
323 bool FirstIsUnsizedArray = false;
324 MostDerivedPathLength = findMostDerivedSubobject(
325 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
326 FirstIsUnsizedArray);
327 MostDerivedIsArrayElement = IsArray;
328 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
329 }
330
331 void setInvalid() {
332 Invalid = true;
333 Entries.clear();
334 }
335
336 /// Determine whether the most derived subobject is an array without a
337 /// known bound.
338 bool isMostDerivedAnUnsizedArray() const {
339 assert(!Invalid && "Calling this makes no sense on invalid designators");
340 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
341 }
342
343 /// Determine what the most derived array's size is. Results in an assertion
344 /// failure if the most derived array lacks a size.
345 uint64_t getMostDerivedArraySize() const {
346 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
347 return MostDerivedArraySize;
348 }
349
350 /// Determine whether this is a one-past-the-end pointer.
351 bool isOnePastTheEnd() const {
352 assert(!Invalid);
353 if (IsOnePastTheEnd)
354 return true;
355 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
356 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
357 MostDerivedArraySize)
358 return true;
359 return false;
360 }
361
362 /// Get the range of valid index adjustments in the form
363 /// {maximum value that can be subtracted from this pointer,
364 /// maximum value that can be added to this pointer}
365 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
366 if (Invalid || isMostDerivedAnUnsizedArray())
367 return {0, 0};
368
369 // [expr.add]p4: For the purposes of these operators, a pointer to a
370 // nonarray object behaves the same as a pointer to the first element of
371 // an array of length one with the type of the object as its element type.
372 bool IsArray = MostDerivedPathLength == Entries.size() &&
373 MostDerivedIsArrayElement;
374 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
375 : (uint64_t)IsOnePastTheEnd;
376 uint64_t ArraySize =
377 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
378 return {ArrayIndex, ArraySize - ArrayIndex};
379 }
380
381 /// Check that this refers to a valid subobject.
382 bool isValidSubobject() const {
383 if (Invalid)
384 return false;
385 return !isOnePastTheEnd();
386 }
387 /// Check that this refers to a valid subobject, and if not, produce a
388 /// relevant diagnostic and set the designator as invalid.
389 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
390
391 /// Get the type of the designated object.
392 QualType getType(ASTContext &Ctx) const {
393 assert(!Invalid && "invalid designator has no subobject type");
394 return MostDerivedPathLength == Entries.size()
395 ? MostDerivedType
396 : Ctx.getCanonicalTagType(getAsBaseClass(Entries.back()));
397 }
398
399 /// Update this designator to refer to the first element within this array.
400 void addArrayUnchecked(const ConstantArrayType *CAT) {
401 Entries.push_back(PathEntry::ArrayIndex(0));
402
403 // This is a most-derived object.
404 MostDerivedType = CAT->getElementType();
405 MostDerivedIsArrayElement = true;
406 MostDerivedArraySize = CAT->getZExtSize();
407 MostDerivedPathLength = Entries.size();
408 }
409 /// Update this designator to refer to the first element within the array of
410 /// elements of type T. This is an array of unknown size.
411 void addUnsizedArrayUnchecked(QualType ElemTy) {
412 Entries.push_back(PathEntry::ArrayIndex(0));
413
414 MostDerivedType = ElemTy;
415 MostDerivedIsArrayElement = true;
416 // The value in MostDerivedArraySize is undefined in this case. So, set it
417 // to an arbitrary value that's likely to loudly break things if it's
418 // used.
419 MostDerivedArraySize = AssumedSizeForUnsizedArray;
420 MostDerivedPathLength = Entries.size();
421 }
422 /// Update this designator to refer to the given base or member of this
423 /// object.
424 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
425 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
426
427 // If this isn't a base class, it's a new most-derived object.
428 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
429 MostDerivedType = FD->getType();
430 MostDerivedIsArrayElement = false;
431 MostDerivedArraySize = 0;
432 MostDerivedPathLength = Entries.size();
433 }
434 }
435 /// Update this designator to refer to the given complex component.
436 void addComplexUnchecked(QualType EltTy, bool Imag) {
437 Entries.push_back(PathEntry::ArrayIndex(Imag));
438
439 // This is technically a most-derived object, though in practice this
440 // is unlikely to matter.
441 MostDerivedType = EltTy;
442 MostDerivedIsArrayElement = true;
443 MostDerivedArraySize = 2;
444 MostDerivedPathLength = Entries.size();
445 }
446
447 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
448 uint64_t Idx) {
449 Entries.push_back(PathEntry::ArrayIndex(Idx));
450 MostDerivedType = EltTy;
451 MostDerivedPathLength = Entries.size();
452 MostDerivedArraySize = 0;
453 MostDerivedIsArrayElement = false;
454 }
455
456 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
457 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
458 const APSInt &N);
459 /// Add N to the address of this subobject.
460 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N, const LValue &LV);
461 };
462
463 /// A scope at the end of which an object can need to be destroyed.
464 enum class ScopeKind {
465 Block,
466 FullExpression,
467 Call
468 };
469
470 /// A reference to a particular call and its arguments.
471 struct CallRef {
472 CallRef() : OrigCallee(), CallIndex(0), Version() {}
473 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
474 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
475
476 explicit operator bool() const { return OrigCallee; }
477
478 /// Get the parameter that the caller initialized, corresponding to the
479 /// given parameter in the callee.
480 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
481 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
482 : PVD;
483 }
484
485 /// The callee at the point where the arguments were evaluated. This might
486 /// be different from the actual callee (a different redeclaration, or a
487 /// virtual override), but this function's parameters are the ones that
488 /// appear in the parameter map.
489 const FunctionDecl *OrigCallee;
490 /// The call index of the frame that holds the argument values.
491 unsigned CallIndex;
492 /// The version of the parameters corresponding to this call.
493 unsigned Version;
494 };
495
496 /// A stack frame in the constexpr call stack.
497 class CallStackFrame : public interp::Frame {
498 public:
499 EvalInfo &Info;
500
501 /// Parent - The caller of this stack frame.
502 CallStackFrame *Caller;
503
504 /// Callee - The function which was called.
505 const FunctionDecl *Callee;
506
507 /// This - The binding for the this pointer in this call, if any.
508 const LValue *This;
509
510 /// CallExpr - The syntactical structure of member function calls
511 const Expr *CallExpr;
512
513 /// Information on how to find the arguments to this call. Our arguments
514 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
515 /// key and this value as the version.
516 CallRef Arguments;
517
518 /// Source location information about the default argument or default
519 /// initializer expression we're evaluating, if any.
520 CurrentSourceLocExprScope CurSourceLocExprScope;
521
522 // Note that we intentionally use std::map here so that references to
523 // values are stable.
524 typedef std::pair<const void *, unsigned> MapKeyTy;
525 typedef std::map<MapKeyTy, APValue> MapTy;
526 /// Temporaries - Temporary lvalues materialized within this stack frame.
527 MapTy Temporaries;
528
529 /// CallRange - The source range of the call expression for this call.
530 SourceRange CallRange;
531
532 /// Index - The call index of this call.
533 unsigned Index;
534
535 /// The stack of integers for tracking version numbers for temporaries.
536 SmallVector<unsigned, 2> TempVersionStack = {1};
537 unsigned CurTempVersion = TempVersionStack.back();
538
539 unsigned getTempVersion() const { return TempVersionStack.back(); }
540
541 void pushTempVersion() {
542 TempVersionStack.push_back(++CurTempVersion);
543 }
544
545 void popTempVersion() {
546 TempVersionStack.pop_back();
547 }
548
549 CallRef createCall(const FunctionDecl *Callee) {
550 return {Callee, Index, ++CurTempVersion};
551 }
552
553 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
554 // on the overall stack usage of deeply-recursing constexpr evaluations.
555 // (We should cache this map rather than recomputing it repeatedly.)
556 // But let's try this and see how it goes; we can look into caching the map
557 // as a later change.
558
559 /// LambdaCaptureFields - Mapping from captured variables/this to
560 /// corresponding data members in the closure class.
561 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
562 FieldDecl *LambdaThisCaptureField = nullptr;
563
564 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
565 const FunctionDecl *Callee, const LValue *This,
566 const Expr *CallExpr, CallRef Arguments);
567 ~CallStackFrame();
568
569 // Return the temporary for Key whose version number is Version.
570 APValue *getTemporary(const void *Key, unsigned Version) {
571 MapKeyTy KV(Key, Version);
572 auto LB = Temporaries.lower_bound(KV);
573 if (LB != Temporaries.end() && LB->first == KV)
574 return &LB->second;
575 return nullptr;
576 }
577
578 // Return the current temporary for Key in the map.
579 APValue *getCurrentTemporary(const void *Key) {
580 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
581 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
582 return &std::prev(UB)->second;
583 return nullptr;
584 }
585
586 // Return the version number of the current temporary for Key.
587 unsigned getCurrentTemporaryVersion(const void *Key) const {
588 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
589 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
590 return std::prev(UB)->first.second;
591 return 0;
592 }
593
594 /// Allocate storage for an object of type T in this stack frame.
595 /// Populates LV with a handle to the created object. Key identifies
596 /// the temporary within the stack frame, and must not be reused without
597 /// bumping the temporary version number.
598 template<typename KeyT>
599 APValue &createTemporary(const KeyT *Key, QualType T,
600 ScopeKind Scope, LValue &LV);
601
602 /// Allocate storage for a parameter of a function call made in this frame.
603 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
604
605 void describe(llvm::raw_ostream &OS) const override;
606
607 Frame *getCaller() const override { return Caller; }
608 SourceRange getCallRange() const override { return CallRange; }
609 const FunctionDecl *getCallee() const override { return Callee; }
610
611 bool isStdFunction() const {
612 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
613 if (DC->isStdNamespace())
614 return true;
615 return false;
616 }
617
618 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
619 /// permitted. See MSConstexprDocs for description of permitted contexts.
620 bool CanEvalMSConstexpr = false;
621
622 private:
623 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
624 ScopeKind Scope);
625 };
626
627 /// Temporarily override 'this'.
628 class ThisOverrideRAII {
629 public:
630 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
631 : Frame(Frame), OldThis(Frame.This) {
632 if (Enable)
633 Frame.This = NewThis;
634 }
635 ~ThisOverrideRAII() {
636 Frame.This = OldThis;
637 }
638 private:
639 CallStackFrame &Frame;
640 const LValue *OldThis;
641 };
642
643 // A shorthand time trace scope struct, prints source range, for example
644 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
645 class ExprTimeTraceScope {
646 public:
647 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
648 : TimeScope(Name, [E, &Ctx] {
650 }) {}
651
652 private:
653 llvm::TimeTraceScope TimeScope;
654 };
655
656 /// RAII object used to change the current ability of
657 /// [[msvc::constexpr]] evaulation.
658 struct MSConstexprContextRAII {
659 CallStackFrame &Frame;
660 bool OldValue;
661 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
662 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
663 Frame.CanEvalMSConstexpr = Value;
664 }
665
666 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
667 };
668}
669
670static bool HandleDestruction(EvalInfo &Info, const Expr *E,
671 const LValue &This, QualType ThisType);
672static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
674 QualType T);
675
676namespace {
677 /// A cleanup, and a flag indicating whether it is lifetime-extended.
678 class Cleanup {
679 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
680 APValue::LValueBase Base;
681 QualType T;
682
683 public:
684 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
685 ScopeKind Scope)
686 : Value(Val, Scope), Base(Base), T(T) {}
687
688 /// Determine whether this cleanup should be performed at the end of the
689 /// given kind of scope.
690 bool isDestroyedAtEndOf(ScopeKind K) const {
691 return (int)Value.getInt() >= (int)K;
692 }
693 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
694 if (RunDestructors) {
695 SourceLocation Loc;
696 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
697 Loc = VD->getLocation();
698 else if (const Expr *E = Base.dyn_cast<const Expr*>())
699 Loc = E->getExprLoc();
700 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
701 }
702 *Value.getPointer() = APValue();
703 return true;
704 }
705
706 bool hasSideEffect() {
707 return T.isDestructedType();
708 }
709 };
710
711 /// A reference to an object whose construction we are currently evaluating.
712 struct ObjectUnderConstruction {
713 APValue::LValueBase Base;
714 ArrayRef<APValue::LValuePathEntry> Path;
715 friend bool operator==(const ObjectUnderConstruction &LHS,
716 const ObjectUnderConstruction &RHS) {
717 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
718 }
719 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
720 return llvm::hash_combine(Obj.Base, Obj.Path);
721 }
722 };
723 enum class ConstructionPhase {
724 None,
725 Bases,
726 AfterBases,
727 AfterFields,
728 Destroying,
729 DestroyingBases
730 };
731}
732
733namespace llvm {
734template<> struct DenseMapInfo<ObjectUnderConstruction> {
735 using Base = DenseMapInfo<APValue::LValueBase>;
736 static ObjectUnderConstruction getEmptyKey() {
737 return {Base::getEmptyKey(), {}}; }
738 static ObjectUnderConstruction getTombstoneKey() {
739 return {Base::getTombstoneKey(), {}};
740 }
741 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
742 return hash_value(Object);
743 }
744 static bool isEqual(const ObjectUnderConstruction &LHS,
745 const ObjectUnderConstruction &RHS) {
746 return LHS == RHS;
747 }
748};
749}
750
751namespace {
752 /// A dynamically-allocated heap object.
753 struct DynAlloc {
754 /// The value of this heap-allocated object.
755 APValue Value;
756 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
757 /// or a CallExpr (the latter is for direct calls to operator new inside
758 /// std::allocator<T>::allocate).
759 const Expr *AllocExpr = nullptr;
760
761 enum Kind {
762 New,
763 ArrayNew,
764 StdAllocator
765 };
766
767 /// Get the kind of the allocation. This must match between allocation
768 /// and deallocation.
769 Kind getKind() const {
770 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
771 return NE->isArray() ? ArrayNew : New;
772 assert(isa<CallExpr>(AllocExpr));
773 return StdAllocator;
774 }
775 };
776
777 struct DynAllocOrder {
778 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
779 return L.getIndex() < R.getIndex();
780 }
781 };
782
783 /// EvalInfo - This is a private struct used by the evaluator to capture
784 /// information about a subexpression as it is folded. It retains information
785 /// about the AST context, but also maintains information about the folded
786 /// expression.
787 ///
788 /// If an expression could be evaluated, it is still possible it is not a C
789 /// "integer constant expression" or constant expression. If not, this struct
790 /// captures information about how and why not.
791 ///
792 /// One bit of information passed *into* the request for constant folding
793 /// indicates whether the subexpression is "evaluated" or not according to C
794 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
795 /// evaluate the expression regardless of what the RHS is, but C only allows
796 /// certain things in certain situations.
797 class EvalInfo final : public interp::State {
798 public:
799 /// CurrentCall - The top of the constexpr call stack.
800 CallStackFrame *CurrentCall;
801
802 /// CallStackDepth - The number of calls in the call stack right now.
803 unsigned CallStackDepth;
804
805 /// NextCallIndex - The next call index to assign.
806 unsigned NextCallIndex;
807
808 /// StepsLeft - The remaining number of evaluation steps we're permitted
809 /// to perform. This is essentially a limit for the number of statements
810 /// we will evaluate.
811 unsigned StepsLeft;
812
813 /// Enable the experimental new constant interpreter. If an expression is
814 /// not supported by the interpreter, an error is triggered.
815 bool EnableNewConstInterp;
816
817 /// BottomFrame - The frame in which evaluation started. This must be
818 /// initialized after CurrentCall and CallStackDepth.
819 CallStackFrame BottomFrame;
820
821 /// A stack of values whose lifetimes end at the end of some surrounding
822 /// evaluation frame.
823 llvm::SmallVector<Cleanup, 16> CleanupStack;
824
825 /// EvaluatingDecl - This is the declaration whose initializer is being
826 /// evaluated, if any.
827 APValue::LValueBase EvaluatingDecl;
828
829 enum class EvaluatingDeclKind {
830 None,
831 /// We're evaluating the construction of EvaluatingDecl.
832 Ctor,
833 /// We're evaluating the destruction of EvaluatingDecl.
834 Dtor,
835 };
836 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
837
838 /// EvaluatingDeclValue - This is the value being constructed for the
839 /// declaration whose initializer is being evaluated, if any.
840 APValue *EvaluatingDeclValue;
841
842 /// Stack of loops and 'switch' statements which we're currently
843 /// breaking/continuing; null entries are used to mark unlabeled
844 /// break/continue.
845 SmallVector<const Stmt *> BreakContinueStack;
846
847 /// Set of objects that are currently being constructed.
848 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
849 ObjectsUnderConstruction;
850
851 /// Current heap allocations, along with the location where each was
852 /// allocated. We use std::map here because we need stable addresses
853 /// for the stored APValues.
854 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
855
856 /// The number of heap allocations performed so far in this evaluation.
857 unsigned NumHeapAllocs = 0;
858
859 struct EvaluatingConstructorRAII {
860 EvalInfo &EI;
861 ObjectUnderConstruction Object;
862 bool DidInsert;
863 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
864 bool HasBases)
865 : EI(EI), Object(Object) {
866 DidInsert =
867 EI.ObjectsUnderConstruction
868 .insert({Object, HasBases ? ConstructionPhase::Bases
869 : ConstructionPhase::AfterBases})
870 .second;
871 }
872 void finishedConstructingBases() {
873 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
874 }
875 void finishedConstructingFields() {
876 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
877 }
878 ~EvaluatingConstructorRAII() {
879 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
880 }
881 };
882
883 struct EvaluatingDestructorRAII {
884 EvalInfo &EI;
885 ObjectUnderConstruction Object;
886 bool DidInsert;
887 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
888 : EI(EI), Object(Object) {
889 DidInsert = EI.ObjectsUnderConstruction
890 .insert({Object, ConstructionPhase::Destroying})
891 .second;
892 }
893 void startedDestroyingBases() {
894 EI.ObjectsUnderConstruction[Object] =
895 ConstructionPhase::DestroyingBases;
896 }
897 ~EvaluatingDestructorRAII() {
898 if (DidInsert)
899 EI.ObjectsUnderConstruction.erase(Object);
900 }
901 };
902
903 ConstructionPhase
904 isEvaluatingCtorDtor(APValue::LValueBase Base,
905 ArrayRef<APValue::LValuePathEntry> Path) {
906 return ObjectsUnderConstruction.lookup({Base, Path});
907 }
908
909 /// If we're currently speculatively evaluating, the outermost call stack
910 /// depth at which we can mutate state, otherwise 0.
911 unsigned SpeculativeEvaluationDepth = 0;
912
913 /// The current array initialization index, if we're performing array
914 /// initialization.
915 uint64_t ArrayInitIndex = -1;
916
917 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
918 : State(const_cast<ASTContext &>(C), S), CurrentCall(nullptr),
919 CallStackDepth(0), NextCallIndex(1),
920 StepsLeft(C.getLangOpts().ConstexprStepLimit),
921 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
922 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
923 /*This=*/nullptr,
924 /*CallExpr=*/nullptr, CallRef()),
925 EvaluatingDecl((const ValueDecl *)nullptr),
926 EvaluatingDeclValue(nullptr) {
927 EvalMode = Mode;
928 }
929
930 ~EvalInfo() {
931 discardCleanups();
932 }
933
934 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
935 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
936 EvaluatingDecl = Base;
937 IsEvaluatingDecl = EDK;
938 EvaluatingDeclValue = &Value;
939 }
940
941 bool CheckCallLimit(SourceLocation Loc) {
942 // Don't perform any constexpr calls (other than the call we're checking)
943 // when checking a potential constant expression.
944 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
945 return false;
946 if (NextCallIndex == 0) {
947 // NextCallIndex has wrapped around.
948 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
949 return false;
950 }
951 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
952 return true;
953 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
954 << getLangOpts().ConstexprCallDepth;
955 return false;
956 }
957
958 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
959 uint64_t ElemCount, bool Diag) {
960 // FIXME: GH63562
961 // APValue stores array extents as unsigned,
962 // so anything that is greater that unsigned would overflow when
963 // constructing the array, we catch this here.
964 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
965 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
966 if (Diag)
967 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
968 return false;
969 }
970
971 // FIXME: GH63562
972 // Arrays allocate an APValue per element.
973 // We use the number of constexpr steps as a proxy for the maximum size
974 // of arrays to avoid exhausting the system resources, as initialization
975 // of each element is likely to take some number of steps anyway.
976 uint64_t Limit = getLangOpts().ConstexprStepLimit;
977 if (Limit != 0 && ElemCount > Limit) {
978 if (Diag)
979 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
980 << ElemCount << Limit;
981 return false;
982 }
983 return true;
984 }
985
986 std::pair<CallStackFrame *, unsigned>
987 getCallFrameAndDepth(unsigned CallIndex) {
988 assert(CallIndex && "no call index in getCallFrameAndDepth");
989 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
990 // be null in this loop.
991 unsigned Depth = CallStackDepth;
992 CallStackFrame *Frame = CurrentCall;
993 while (Frame->Index > CallIndex) {
994 Frame = Frame->Caller;
995 --Depth;
996 }
997 if (Frame->Index == CallIndex)
998 return {Frame, Depth};
999 return {nullptr, 0};
1000 }
1001
1002 bool nextStep(const Stmt *S) {
1003 if (getLangOpts().ConstexprStepLimit == 0)
1004 return true;
1005
1006 if (!StepsLeft) {
1007 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1008 return false;
1009 }
1010 --StepsLeft;
1011 return true;
1012 }
1013
1014 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1015
1016 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1017 std::optional<DynAlloc *> Result;
1018 auto It = HeapAllocs.find(DA);
1019 if (It != HeapAllocs.end())
1020 Result = &It->second;
1021 return Result;
1022 }
1023
1024 /// Get the allocated storage for the given parameter of the given call.
1025 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1026 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1027 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1028 : nullptr;
1029 }
1030
1031 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1032 struct StdAllocatorCaller {
1033 unsigned FrameIndex;
1034 QualType ElemType;
1035 const Expr *Call;
1036 explicit operator bool() const { return FrameIndex != 0; };
1037 };
1038
1039 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1040 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1041 Call = Call->Caller) {
1042 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1043 if (!MD)
1044 continue;
1045 const IdentifierInfo *FnII = MD->getIdentifier();
1046 if (!FnII || !FnII->isStr(FnName))
1047 continue;
1048
1049 const auto *CTSD =
1050 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1051 if (!CTSD)
1052 continue;
1053
1054 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1055 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1056 if (CTSD->isInStdNamespace() && ClassII &&
1057 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1058 TAL[0].getKind() == TemplateArgument::Type)
1059 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1060 }
1061
1062 return {};
1063 }
1064
1065 void performLifetimeExtension() {
1066 // Disable the cleanups for lifetime-extended temporaries.
1067 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1068 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1069 });
1070 }
1071
1072 /// Throw away any remaining cleanups at the end of evaluation. If any
1073 /// cleanups would have had a side-effect, note that as an unmodeled
1074 /// side-effect and return false. Otherwise, return true.
1075 bool discardCleanups() {
1076 for (Cleanup &C : CleanupStack) {
1077 if (C.hasSideEffect() && !noteSideEffect()) {
1078 CleanupStack.clear();
1079 return false;
1080 }
1081 }
1082 CleanupStack.clear();
1083 return true;
1084 }
1085
1086 private:
1087 const interp::Frame *getCurrentFrame() override { return CurrentCall; }
1088 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1089
1090 unsigned getCallStackDepth() override { return CallStackDepth; }
1091 bool stepsLeft() const override { return StepsLeft > 0; }
1092
1093 public:
1094 /// Notes that we failed to evaluate an expression that other expressions
1095 /// directly depend on, and determine if we should keep evaluating. This
1096 /// should only be called if we actually intend to keep evaluating.
1097 ///
1098 /// Call noteSideEffect() instead if we may be able to ignore the value that
1099 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1100 ///
1101 /// (Foo(), 1) // use noteSideEffect
1102 /// (Foo() || true) // use noteSideEffect
1103 /// Foo() + 1 // use noteFailure
1104 [[nodiscard]] bool noteFailure() {
1105 // Failure when evaluating some expression often means there is some
1106 // subexpression whose evaluation was skipped. Therefore, (because we
1107 // don't track whether we skipped an expression when unwinding after an
1108 // evaluation failure) every evaluation failure that bubbles up from a
1109 // subexpression implies that a side-effect has potentially happened. We
1110 // skip setting the HasSideEffects flag to true until we decide to
1111 // continue evaluating after that point, which happens here.
1112 bool KeepGoing = keepEvaluatingAfterFailure();
1113 EvalStatus.HasSideEffects |= KeepGoing;
1114 return KeepGoing;
1115 }
1116
1117 class ArrayInitLoopIndex {
1118 EvalInfo &Info;
1119 uint64_t OuterIndex;
1120
1121 public:
1122 ArrayInitLoopIndex(EvalInfo &Info)
1123 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1124 Info.ArrayInitIndex = 0;
1125 }
1126 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1127
1128 operator uint64_t&() { return Info.ArrayInitIndex; }
1129 };
1130 };
1131
1132 /// Object used to treat all foldable expressions as constant expressions.
1133 struct FoldConstant {
1134 EvalInfo &Info;
1135 bool Enabled;
1136 bool HadNoPriorDiags;
1137 EvaluationMode OldMode;
1138
1139 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1140 : Info(Info),
1141 Enabled(Enabled),
1142 HadNoPriorDiags(Info.EvalStatus.Diag &&
1143 Info.EvalStatus.Diag->empty() &&
1144 !Info.EvalStatus.HasSideEffects),
1145 OldMode(Info.EvalMode) {
1146 if (Enabled)
1147 Info.EvalMode = EvaluationMode::ConstantFold;
1148 }
1149 void keepDiagnostics() { Enabled = false; }
1150 ~FoldConstant() {
1151 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1152 !Info.EvalStatus.HasSideEffects)
1153 Info.EvalStatus.Diag->clear();
1154 Info.EvalMode = OldMode;
1155 }
1156 };
1157
1158 /// RAII object used to set the current evaluation mode to ignore
1159 /// side-effects.
1160 struct IgnoreSideEffectsRAII {
1161 EvalInfo &Info;
1162 EvaluationMode OldMode;
1163 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1164 : Info(Info), OldMode(Info.EvalMode) {
1165 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1166 }
1167
1168 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1169 };
1170
1171 /// RAII object used to optionally suppress diagnostics and side-effects from
1172 /// a speculative evaluation.
1173 class SpeculativeEvaluationRAII {
1174 EvalInfo *Info = nullptr;
1175 Expr::EvalStatus OldStatus;
1176 unsigned OldSpeculativeEvaluationDepth = 0;
1177
1178 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1179 Info = Other.Info;
1180 OldStatus = Other.OldStatus;
1181 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1182 Other.Info = nullptr;
1183 }
1184
1185 void maybeRestoreState() {
1186 if (!Info)
1187 return;
1188
1189 Info->EvalStatus = OldStatus;
1190 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1191 }
1192
1193 public:
1194 SpeculativeEvaluationRAII() = default;
1195
1196 SpeculativeEvaluationRAII(
1197 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1198 : Info(&Info), OldStatus(Info.EvalStatus),
1199 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1200 Info.EvalStatus.Diag = NewDiag;
1201 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1202 }
1203
1204 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1205 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1206 moveFromAndCancel(std::move(Other));
1207 }
1208
1209 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1210 maybeRestoreState();
1211 moveFromAndCancel(std::move(Other));
1212 return *this;
1213 }
1214
1215 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1216 };
1217
1218 /// RAII object wrapping a full-expression or block scope, and handling
1219 /// the ending of the lifetime of temporaries created within it.
1220 template<ScopeKind Kind>
1221 class ScopeRAII {
1222 EvalInfo &Info;
1223 unsigned OldStackSize;
1224 public:
1225 ScopeRAII(EvalInfo &Info)
1226 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1227 // Push a new temporary version. This is needed to distinguish between
1228 // temporaries created in different iterations of a loop.
1229 Info.CurrentCall->pushTempVersion();
1230 }
1231 bool destroy(bool RunDestructors = true) {
1232 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1233 OldStackSize = std::numeric_limits<unsigned>::max();
1234 return OK;
1235 }
1236 ~ScopeRAII() {
1237 if (OldStackSize != std::numeric_limits<unsigned>::max())
1238 destroy(false);
1239 // Body moved to a static method to encourage the compiler to inline away
1240 // instances of this class.
1241 Info.CurrentCall->popTempVersion();
1242 }
1243 private:
1244 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1245 unsigned OldStackSize) {
1246 assert(OldStackSize <= Info.CleanupStack.size() &&
1247 "running cleanups out of order?");
1248
1249 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1250 // for a full-expression scope.
1251 bool Success = true;
1252 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1253 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1254 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1255 Success = false;
1256 break;
1257 }
1258 }
1259 }
1260
1261 // Compact any retained cleanups.
1262 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1263 if (Kind != ScopeKind::Block)
1264 NewEnd =
1265 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1266 return C.isDestroyedAtEndOf(Kind);
1267 });
1268 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1269 return Success;
1270 }
1271 };
1272 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1273 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1274 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1275}
1276
1277bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1278 CheckSubobjectKind CSK) {
1279 if (Invalid)
1280 return false;
1281 if (isOnePastTheEnd()) {
1282 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1283 << CSK;
1284 setInvalid();
1285 return false;
1286 }
1287 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1288 // must actually be at least one array element; even a VLA cannot have a
1289 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1290 return true;
1291}
1292
1293void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1294 const Expr *E) {
1295 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1296 // Do not set the designator as invalid: we can represent this situation,
1297 // and correct handling of __builtin_object_size requires us to do so.
1298}
1299
1300void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1301 const Expr *E,
1302 const APSInt &N) {
1303 // If we're complaining, we must be able to statically determine the size of
1304 // the most derived array.
1305 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1306 Info.CCEDiag(E, diag::note_constexpr_array_index)
1307 << N << /*array*/ 0
1308 << static_cast<unsigned>(getMostDerivedArraySize());
1309 else
1310 Info.CCEDiag(E, diag::note_constexpr_array_index)
1311 << N << /*non-array*/ 1;
1312 setInvalid();
1313}
1314
1315CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1316 const FunctionDecl *Callee, const LValue *This,
1317 const Expr *CallExpr, CallRef Call)
1318 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1319 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1320 Index(Info.NextCallIndex++) {
1321 Info.CurrentCall = this;
1322 ++Info.CallStackDepth;
1323}
1324
1325CallStackFrame::~CallStackFrame() {
1326 assert(Info.CurrentCall == this && "calls retired out of order");
1327 --Info.CallStackDepth;
1328 Info.CurrentCall = Caller;
1329}
1330
1331static bool isRead(AccessKinds AK) {
1332 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1333 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1334}
1335
1337 switch (AK) {
1338 case AK_Read:
1340 case AK_MemberCall:
1341 case AK_DynamicCast:
1342 case AK_TypeId:
1344 case AK_Dereference:
1345 return false;
1346 case AK_Assign:
1347 case AK_Increment:
1348 case AK_Decrement:
1349 case AK_Construct:
1350 case AK_Destroy:
1351 return true;
1352 }
1353 llvm_unreachable("unknown access kind");
1354}
1355
1356static bool isAnyAccess(AccessKinds AK) {
1357 return isRead(AK) || isModification(AK);
1358}
1359
1360/// Is this an access per the C++ definition?
1362 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1363 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1364}
1365
1366/// Is this kind of access valid on an indeterminate object value?
1368 switch (AK) {
1369 case AK_Read:
1370 case AK_Increment:
1371 case AK_Decrement:
1372 case AK_Dereference:
1373 // These need the object's value.
1374 return false;
1375
1378 case AK_Assign:
1379 case AK_Construct:
1380 case AK_Destroy:
1381 // Construction and destruction don't need the value.
1382 return true;
1383
1384 case AK_MemberCall:
1385 case AK_DynamicCast:
1386 case AK_TypeId:
1387 // These aren't really meaningful on scalars.
1388 return true;
1389 }
1390 llvm_unreachable("unknown access kind");
1391}
1392
1393namespace {
1394 struct ComplexValue {
1395 private:
1396 bool IsInt;
1397
1398 public:
1399 APSInt IntReal, IntImag;
1400 APFloat FloatReal, FloatImag;
1401
1402 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1403
1404 void makeComplexFloat() { IsInt = false; }
1405 bool isComplexFloat() const { return !IsInt; }
1406 APFloat &getComplexFloatReal() { return FloatReal; }
1407 APFloat &getComplexFloatImag() { return FloatImag; }
1408
1409 void makeComplexInt() { IsInt = true; }
1410 bool isComplexInt() const { return IsInt; }
1411 APSInt &getComplexIntReal() { return IntReal; }
1412 APSInt &getComplexIntImag() { return IntImag; }
1413
1414 void moveInto(APValue &v) const {
1415 if (isComplexFloat())
1416 v = APValue(FloatReal, FloatImag);
1417 else
1418 v = APValue(IntReal, IntImag);
1419 }
1420 void setFrom(const APValue &v) {
1421 assert(v.isComplexFloat() || v.isComplexInt());
1422 if (v.isComplexFloat()) {
1423 makeComplexFloat();
1424 FloatReal = v.getComplexFloatReal();
1425 FloatImag = v.getComplexFloatImag();
1426 } else {
1427 makeComplexInt();
1428 IntReal = v.getComplexIntReal();
1429 IntImag = v.getComplexIntImag();
1430 }
1431 }
1432 };
1433
1434 struct LValue {
1435 APValue::LValueBase Base;
1436 CharUnits Offset;
1437 SubobjectDesignator Designator;
1438 bool IsNullPtr : 1;
1439 bool InvalidBase : 1;
1440 // P2280R4 track if we have an unknown reference or pointer.
1441 bool AllowConstexprUnknown = false;
1442
1443 const APValue::LValueBase getLValueBase() const { return Base; }
1444 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1445 CharUnits &getLValueOffset() { return Offset; }
1446 const CharUnits &getLValueOffset() const { return Offset; }
1447 SubobjectDesignator &getLValueDesignator() { return Designator; }
1448 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1449 bool isNullPointer() const { return IsNullPtr;}
1450
1451 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1452 unsigned getLValueVersion() const { return Base.getVersion(); }
1453
1454 void moveInto(APValue &V) const {
1455 if (Designator.Invalid)
1456 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1457 else {
1458 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1459 V = APValue(Base, Offset, Designator.Entries,
1460 Designator.IsOnePastTheEnd, IsNullPtr);
1461 }
1462 if (AllowConstexprUnknown)
1463 V.setConstexprUnknown();
1464 }
1465 void setFrom(const ASTContext &Ctx, const APValue &V) {
1466 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1467 Base = V.getLValueBase();
1468 Offset = V.getLValueOffset();
1469 InvalidBase = false;
1470 Designator = SubobjectDesignator(Ctx, V);
1471 IsNullPtr = V.isNullPointer();
1472 AllowConstexprUnknown = V.allowConstexprUnknown();
1473 }
1474
1475 void set(APValue::LValueBase B, bool BInvalid = false) {
1476#ifndef NDEBUG
1477 // We only allow a few types of invalid bases. Enforce that here.
1478 if (BInvalid) {
1479 const auto *E = B.get<const Expr *>();
1480 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1481 "Unexpected type of invalid base");
1482 }
1483#endif
1484
1485 Base = B;
1486 Offset = CharUnits::fromQuantity(0);
1487 InvalidBase = BInvalid;
1488 Designator = SubobjectDesignator(getType(B));
1489 IsNullPtr = false;
1490 AllowConstexprUnknown = false;
1491 }
1492
1493 void setNull(ASTContext &Ctx, QualType PointerTy) {
1494 Base = (const ValueDecl *)nullptr;
1495 Offset =
1497 InvalidBase = false;
1498 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1499 IsNullPtr = true;
1500 AllowConstexprUnknown = false;
1501 }
1502
1503 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1504 set(B, true);
1505 }
1506
1507 std::string toString(ASTContext &Ctx, QualType T) const {
1508 APValue Printable;
1509 moveInto(Printable);
1510 return Printable.getAsString(Ctx, T);
1511 }
1512
1513 private:
1514 // Check that this LValue is not based on a null pointer. If it is, produce
1515 // a diagnostic and mark the designator as invalid.
1516 template <typename GenDiagType>
1517 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1518 if (Designator.Invalid)
1519 return false;
1520 if (IsNullPtr) {
1521 GenDiag();
1522 Designator.setInvalid();
1523 return false;
1524 }
1525 return true;
1526 }
1527
1528 public:
1529 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1530 CheckSubobjectKind CSK) {
1531 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1532 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1533 });
1534 }
1535
1536 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1537 AccessKinds AK) {
1538 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1539 if (AK == AccessKinds::AK_Dereference)
1540 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1541 else
1542 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1543 });
1544 }
1545
1546 // Check this LValue refers to an object. If not, set the designator to be
1547 // invalid and emit a diagnostic.
1548 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1549 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1550 Designator.checkSubobject(Info, E, CSK);
1551 }
1552
1553 void addDecl(EvalInfo &Info, const Expr *E,
1554 const Decl *D, bool Virtual = false) {
1555 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1556 Designator.addDeclUnchecked(D, Virtual);
1557 }
1558 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1559 if (!Designator.Entries.empty()) {
1560 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1561 Designator.setInvalid();
1562 return;
1563 }
1564 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1565 assert(getType(Base).getNonReferenceType()->isPointerType() ||
1566 getType(Base).getNonReferenceType()->isArrayType());
1567 Designator.FirstEntryIsAnUnsizedArray = true;
1568 Designator.addUnsizedArrayUnchecked(ElemTy);
1569 }
1570 }
1571 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1572 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1573 Designator.addArrayUnchecked(CAT);
1574 }
1575 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1576 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1577 Designator.addComplexUnchecked(EltTy, Imag);
1578 }
1579 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1580 uint64_t Size, uint64_t Idx) {
1581 if (checkSubobject(Info, E, CSK_VectorElement))
1582 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1583 }
1584 void clearIsNullPointer() {
1585 IsNullPtr = false;
1586 }
1587 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1588 const APSInt &Index, CharUnits ElementSize) {
1589 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1590 // but we're not required to diagnose it and it's valid in C++.)
1591 if (!Index)
1592 return;
1593
1594 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1595 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1596 // offsets.
1597 uint64_t Offset64 = Offset.getQuantity();
1598 uint64_t ElemSize64 = ElementSize.getQuantity();
1599 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1600 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1601
1602 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1603 Designator.adjustIndex(Info, E, Index, *this);
1604 clearIsNullPointer();
1605 }
1606 void adjustOffset(CharUnits N) {
1607 Offset += N;
1608 if (N.getQuantity())
1609 clearIsNullPointer();
1610 }
1611 };
1612
1613 struct MemberPtr {
1614 MemberPtr() {}
1615 explicit MemberPtr(const ValueDecl *Decl)
1616 : DeclAndIsDerivedMember(Decl, false) {}
1617
1618 /// The member or (direct or indirect) field referred to by this member
1619 /// pointer, or 0 if this is a null member pointer.
1620 const ValueDecl *getDecl() const {
1621 return DeclAndIsDerivedMember.getPointer();
1622 }
1623 /// Is this actually a member of some type derived from the relevant class?
1624 bool isDerivedMember() const {
1625 return DeclAndIsDerivedMember.getInt();
1626 }
1627 /// Get the class which the declaration actually lives in.
1628 const CXXRecordDecl *getContainingRecord() const {
1629 return cast<CXXRecordDecl>(
1630 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1631 }
1632
1633 void moveInto(APValue &V) const {
1634 V = APValue(getDecl(), isDerivedMember(), Path);
1635 }
1636 void setFrom(const APValue &V) {
1637 assert(V.isMemberPointer());
1638 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1639 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1640 Path.clear();
1641 llvm::append_range(Path, V.getMemberPointerPath());
1642 }
1643
1644 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1645 /// whether the member is a member of some class derived from the class type
1646 /// of the member pointer.
1647 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1648 /// Path - The path of base/derived classes from the member declaration's
1649 /// class (exclusive) to the class type of the member pointer (inclusive).
1650 SmallVector<const CXXRecordDecl*, 4> Path;
1651
1652 /// Perform a cast towards the class of the Decl (either up or down the
1653 /// hierarchy).
1654 bool castBack(const CXXRecordDecl *Class) {
1655 assert(!Path.empty());
1656 const CXXRecordDecl *Expected;
1657 if (Path.size() >= 2)
1658 Expected = Path[Path.size() - 2];
1659 else
1660 Expected = getContainingRecord();
1661 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1662 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1663 // if B does not contain the original member and is not a base or
1664 // derived class of the class containing the original member, the result
1665 // of the cast is undefined.
1666 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1667 // (D::*). We consider that to be a language defect.
1668 return false;
1669 }
1670 Path.pop_back();
1671 return true;
1672 }
1673 /// Perform a base-to-derived member pointer cast.
1674 bool castToDerived(const CXXRecordDecl *Derived) {
1675 if (!getDecl())
1676 return true;
1677 if (!isDerivedMember()) {
1678 Path.push_back(Derived);
1679 return true;
1680 }
1681 if (!castBack(Derived))
1682 return false;
1683 if (Path.empty())
1684 DeclAndIsDerivedMember.setInt(false);
1685 return true;
1686 }
1687 /// Perform a derived-to-base member pointer cast.
1688 bool castToBase(const CXXRecordDecl *Base) {
1689 if (!getDecl())
1690 return true;
1691 if (Path.empty())
1692 DeclAndIsDerivedMember.setInt(true);
1693 if (isDerivedMember()) {
1694 Path.push_back(Base);
1695 return true;
1696 }
1697 return castBack(Base);
1698 }
1699 };
1700
1701 /// Compare two member pointers, which are assumed to be of the same type.
1702 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1703 if (!LHS.getDecl() || !RHS.getDecl())
1704 return !LHS.getDecl() && !RHS.getDecl();
1705 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1706 return false;
1707 return LHS.Path == RHS.Path;
1708 }
1709}
1710
1711void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1712 const LValue &LV) {
1713 if (Invalid || !N)
1714 return;
1715 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1716 if (isMostDerivedAnUnsizedArray()) {
1717 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1718 // Can't verify -- trust that the user is doing the right thing (or if
1719 // not, trust that the caller will catch the bad behavior).
1720 // FIXME: Should we reject if this overflows, at least?
1721 Entries.back() =
1722 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1723 return;
1724 }
1725
1726 // [expr.add]p4: For the purposes of these operators, a pointer to a
1727 // nonarray object behaves the same as a pointer to the first element of
1728 // an array of length one with the type of the object as its element type.
1729 bool IsArray =
1730 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1731 uint64_t ArrayIndex =
1732 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1733 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1734
1735 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1736 if (!Info.checkingPotentialConstantExpression() ||
1737 !LV.AllowConstexprUnknown) {
1738 // Calculate the actual index in a wide enough type, so we can include
1739 // it in the note.
1740 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1741 (llvm::APInt &)N += ArrayIndex;
1742 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1743 diagnosePointerArithmetic(Info, E, N);
1744 }
1745 setInvalid();
1746 return;
1747 }
1748
1749 ArrayIndex += TruncatedN;
1750 assert(ArrayIndex <= ArraySize &&
1751 "bounds check succeeded for out-of-bounds index");
1752
1753 if (IsArray)
1754 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1755 else
1756 IsOnePastTheEnd = (ArrayIndex != 0);
1757}
1758
1759static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1760static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1761 const LValue &This, const Expr *E,
1762 bool AllowNonLiteralTypes = false);
1763static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1764 bool InvalidBaseOK = false);
1765static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1766 bool InvalidBaseOK = false);
1767static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1768 EvalInfo &Info);
1769static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1770static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1771static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1772 EvalInfo &Info);
1773static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1774static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1775static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info);
1776static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1777 EvalInfo &Info);
1778static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1779static std::optional<uint64_t>
1780EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
1781 std::string *StringResult = nullptr);
1782
1783/// Evaluate an integer or fixed point expression into an APResult.
1784static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1785 EvalInfo &Info);
1786
1787/// Evaluate only a fixed point expression into an APResult.
1788static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1789 EvalInfo &Info);
1790
1791//===----------------------------------------------------------------------===//
1792// Misc utilities
1793//===----------------------------------------------------------------------===//
1794
1795/// Negate an APSInt in place, converting it to a signed form if necessary, and
1796/// preserving its value (by extending by up to one bit as needed).
1797static void negateAsSigned(APSInt &Int) {
1798 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1799 Int = Int.extend(Int.getBitWidth() + 1);
1800 Int.setIsSigned(true);
1801 }
1802 Int = -Int;
1803}
1804
1805template<typename KeyT>
1806APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1807 ScopeKind Scope, LValue &LV) {
1808 unsigned Version = getTempVersion();
1809 APValue::LValueBase Base(Key, Index, Version);
1810 LV.set(Base);
1811 return createLocal(Base, Key, T, Scope);
1812}
1813
1814/// Allocate storage for a parameter of a function call made in this frame.
1815APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1816 LValue &LV) {
1817 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1818 APValue::LValueBase Base(PVD, Index, Args.Version);
1819 LV.set(Base);
1820 // We always destroy parameters at the end of the call, even if we'd allow
1821 // them to live to the end of the full-expression at runtime, in order to
1822 // give portable results and match other compilers.
1823 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1824}
1825
1826APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1827 QualType T, ScopeKind Scope) {
1828 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1829 unsigned Version = Base.getVersion();
1830 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1831 assert(Result.isAbsent() && "local created multiple times");
1832
1833 // If we're creating a local immediately in the operand of a speculative
1834 // evaluation, don't register a cleanup to be run outside the speculative
1835 // evaluation context, since we won't actually be able to initialize this
1836 // object.
1837 if (Index <= Info.SpeculativeEvaluationDepth) {
1838 if (T.isDestructedType())
1839 Info.noteSideEffect();
1840 } else {
1841 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1842 }
1843 return Result;
1844}
1845
1846APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1847 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1848 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1849 return nullptr;
1850 }
1851
1852 DynamicAllocLValue DA(NumHeapAllocs++);
1854 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1855 std::forward_as_tuple(DA), std::tuple<>());
1856 assert(Result.second && "reused a heap alloc index?");
1857 Result.first->second.AllocExpr = E;
1858 return &Result.first->second.Value;
1859}
1860
1861/// Produce a string describing the given constexpr call.
1862void CallStackFrame::describe(raw_ostream &Out) const {
1863 bool IsMemberCall = false;
1864 bool ExplicitInstanceParam = false;
1865 if (const auto *MD = dyn_cast<CXXMethodDecl>(Callee)) {
1866 IsMemberCall = !isa<CXXConstructorDecl>(MD) && !MD->isStatic();
1867 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
1868 }
1869
1870 if (!IsMemberCall)
1871 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1872 /*Qualified=*/false);
1873
1874 if (This && IsMemberCall) {
1875 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1876 const Expr *Object = MCE->getImplicitObjectArgument();
1877 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1878 /*Indentation=*/0);
1879 if (Object->getType()->isPointerType())
1880 Out << "->";
1881 else
1882 Out << ".";
1883 } else if (const auto *OCE =
1884 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1885 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1886 Info.Ctx.getPrintingPolicy(),
1887 /*Indentation=*/0);
1888 Out << ".";
1889 } else {
1890 APValue Val;
1891 This->moveInto(Val);
1892 Val.printPretty(
1893 Out, Info.Ctx,
1894 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1895 Out << ".";
1896 }
1897 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1898 /*Qualified=*/false);
1899 }
1900
1901 Out << '(';
1902
1903 llvm::ListSeparator Comma;
1904 for (const ParmVarDecl *Param :
1905 Callee->parameters().slice(ExplicitInstanceParam)) {
1906 Out << Comma;
1907 const APValue *V = Info.getParamSlot(Arguments, Param);
1908 if (V)
1909 V->printPretty(Out, Info.Ctx, Param->getType());
1910 else
1911 Out << "<...>";
1912 }
1913
1914 Out << ')';
1915}
1916
1917/// Evaluate an expression to see if it had side-effects, and discard its
1918/// result.
1919/// \return \c true if the caller should keep evaluating.
1920static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1921 assert(!E->isValueDependent());
1922 APValue Scratch;
1923 if (!Evaluate(Scratch, Info, E))
1924 // We don't need the value, but we might have skipped a side effect here.
1925 return Info.noteSideEffect();
1926 return true;
1927}
1928
1929/// Should this call expression be treated as forming an opaque constant?
1930static bool IsOpaqueConstantCall(const CallExpr *E) {
1931 unsigned Builtin = E->getBuiltinCallee();
1932 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1933 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1934 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
1935 Builtin == Builtin::BI__builtin_function_start);
1936}
1937
1938static bool IsOpaqueConstantCall(const LValue &LVal) {
1939 const auto *BaseExpr =
1940 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
1941 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
1942}
1943
1945 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1946 // constant expression of pointer type that evaluates to...
1947
1948 // ... a null pointer value, or a prvalue core constant expression of type
1949 // std::nullptr_t.
1950 if (!B)
1951 return true;
1952
1953 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1954 // ... the address of an object with static storage duration,
1955 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1956 return VD->hasGlobalStorage();
1958 return true;
1959 // ... the address of a function,
1960 // ... the address of a GUID [MS extension],
1961 // ... the address of an unnamed global constant
1963 }
1964
1965 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1966 return true;
1967
1968 const Expr *E = B.get<const Expr*>();
1969 switch (E->getStmtClass()) {
1970 default:
1971 return false;
1972 case Expr::CompoundLiteralExprClass: {
1974 return CLE->isFileScope() && CLE->isLValue();
1975 }
1976 case Expr::MaterializeTemporaryExprClass:
1977 // A materialized temporary might have been lifetime-extended to static
1978 // storage duration.
1979 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1980 // A string literal has static storage duration.
1981 case Expr::StringLiteralClass:
1982 case Expr::PredefinedExprClass:
1983 case Expr::ObjCStringLiteralClass:
1984 case Expr::ObjCEncodeExprClass:
1985 return true;
1986 case Expr::ObjCBoxedExprClass:
1987 case Expr::ObjCArrayLiteralClass:
1988 case Expr::ObjCDictionaryLiteralClass:
1989 return cast<ObjCObjectLiteral>(E)->isExpressibleAsConstantInitializer();
1990 case Expr::CallExprClass:
1992 // For GCC compatibility, &&label has static storage duration.
1993 case Expr::AddrLabelExprClass:
1994 return true;
1995 // A Block literal expression may be used as the initialization value for
1996 // Block variables at global or local static scope.
1997 case Expr::BlockExprClass:
1998 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1999 // The APValue generated from a __builtin_source_location will be emitted as a
2000 // literal.
2001 case Expr::SourceLocExprClass:
2002 return true;
2003 case Expr::ImplicitValueInitExprClass:
2004 // FIXME:
2005 // We can never form an lvalue with an implicit value initialization as its
2006 // base through expression evaluation, so these only appear in one case: the
2007 // implicit variable declaration we invent when checking whether a constexpr
2008 // constructor can produce a constant expression. We must assume that such
2009 // an expression might be a global lvalue.
2010 return true;
2011 }
2012}
2013
2014static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2015 return LVal.Base.dyn_cast<const ValueDecl*>();
2016}
2017
2018// Information about an LValueBase that is some kind of string.
2021 StringRef Bytes;
2023};
2024
2025// Gets the lvalue base of LVal as a string.
2026static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2027 LValueBaseString &AsString) {
2028 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2029 if (!BaseExpr)
2030 return false;
2031
2032 // For ObjCEncodeExpr, we need to compute and store the string.
2033 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2034 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2035 AsString.ObjCEncodeStorage);
2036 AsString.Bytes = AsString.ObjCEncodeStorage;
2037 AsString.CharWidth = 1;
2038 return true;
2039 }
2040
2041 // Otherwise, we have a StringLiteral.
2042 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2043 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2044 Lit = PE->getFunctionName();
2045
2046 if (!Lit)
2047 return false;
2048
2049 AsString.Bytes = Lit->getBytes();
2050 AsString.CharWidth = Lit->getCharByteWidth();
2051 return true;
2052}
2053
2054// Determine whether two string literals potentially overlap. This will be the
2055// case if they agree on the values of all the bytes on the overlapping region
2056// between them.
2057//
2058// The overlapping region is the portion of the two string literals that must
2059// overlap in memory if the pointers actually point to the same address at
2060// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2061// the overlapping region is "cdef\0", which in this case does agree, so the
2062// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2063// "bazbar" + 3, the overlapping region contains all of both strings, so they
2064// are not potentially overlapping, even though they agree from the given
2065// addresses onwards.
2066//
2067// See open core issue CWG2765 which is discussing the desired rule here.
2068static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2069 const LValue &LHS,
2070 const LValue &RHS) {
2071 LValueBaseString LHSString, RHSString;
2072 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2073 !GetLValueBaseAsString(Info, RHS, RHSString))
2074 return false;
2075
2076 // This is the byte offset to the location of the first character of LHS
2077 // within RHS. We don't need to look at the characters of one string that
2078 // would appear before the start of the other string if they were merged.
2079 CharUnits Offset = RHS.Offset - LHS.Offset;
2080 if (Offset.isNegative()) {
2081 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2082 return false;
2083 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2084 } else {
2085 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2086 return false;
2087 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2088 }
2089
2090 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2091 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2092 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2093 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2094
2095 // The null terminator isn't included in the string data, so check for it
2096 // manually. If the longer string doesn't have a null terminator where the
2097 // shorter string ends, they aren't potentially overlapping.
2098 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2099 if (Shorter.size() + NullByte >= Longer.size())
2100 break;
2101 if (Longer[Shorter.size() + NullByte])
2102 return false;
2103 }
2104
2105 // Otherwise, they're potentially overlapping if and only if the overlapping
2106 // region is the same.
2107 return Shorter == Longer.take_front(Shorter.size());
2108}
2109
2110static bool IsWeakLValue(const LValue &Value) {
2112 return Decl && Decl->isWeak();
2113}
2114
2115static bool isZeroSized(const LValue &Value) {
2117 if (isa_and_nonnull<VarDecl>(Decl)) {
2118 QualType Ty = Decl->getType();
2119 if (Ty->isArrayType())
2120 return Ty->isIncompleteType() ||
2121 Decl->getASTContext().getTypeSize(Ty) == 0;
2122 }
2123 return false;
2124}
2125
2126static bool HasSameBase(const LValue &A, const LValue &B) {
2127 if (!A.getLValueBase())
2128 return !B.getLValueBase();
2129 if (!B.getLValueBase())
2130 return false;
2131
2132 if (A.getLValueBase().getOpaqueValue() !=
2133 B.getLValueBase().getOpaqueValue())
2134 return false;
2135
2136 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2137 A.getLValueVersion() == B.getLValueVersion();
2138}
2139
2140static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2141 assert(Base && "no location for a null lvalue");
2142 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2143
2144 // For a parameter, find the corresponding call stack frame (if it still
2145 // exists), and point at the parameter of the function definition we actually
2146 // invoked.
2147 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2148 unsigned Idx = PVD->getFunctionScopeIndex();
2149 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2150 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2151 F->Arguments.Version == Base.getVersion() && F->Callee &&
2152 Idx < F->Callee->getNumParams()) {
2153 VD = F->Callee->getParamDecl(Idx);
2154 break;
2155 }
2156 }
2157 }
2158
2159 if (VD)
2160 Info.Note(VD->getLocation(), diag::note_declared_at);
2161 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2162 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2163 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2164 // FIXME: Produce a note for dangling pointers too.
2165 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2166 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2167 diag::note_constexpr_dynamic_alloc_here);
2168 }
2169
2170 // We have no information to show for a typeid(T) object.
2171}
2172
2177
2178/// Materialized temporaries that we've already checked to determine if they're
2179/// initializsed by a constant expression.
2182
2184 EvalInfo &Info, SourceLocation DiagLoc,
2185 QualType Type, const APValue &Value,
2186 ConstantExprKind Kind,
2187 const FieldDecl *SubobjectDecl,
2188 CheckedTemporaries &CheckedTemps);
2189
2190/// Check that this reference or pointer core constant expression is a valid
2191/// value for an address or reference constant expression. Return true if we
2192/// can fold this expression, whether or not it's a constant expression.
2193static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2194 QualType Type, const LValue &LVal,
2195 ConstantExprKind Kind,
2196 CheckedTemporaries &CheckedTemps) {
2197 bool IsReferenceType = Type->isReferenceType();
2198
2199 APValue::LValueBase Base = LVal.getLValueBase();
2200 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2201
2202 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2203 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2204
2205 // Additional restrictions apply in a template argument. We only enforce the
2206 // C++20 restrictions here; additional syntactic and semantic restrictions
2207 // are applied elsewhere.
2208 if (isTemplateArgument(Kind)) {
2209 int InvalidBaseKind = -1;
2210 StringRef Ident;
2211 if (Base.is<TypeInfoLValue>())
2212 InvalidBaseKind = 0;
2213 else if (isa_and_nonnull<StringLiteral>(BaseE))
2214 InvalidBaseKind = 1;
2215 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2216 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2217 InvalidBaseKind = 2;
2218 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2219 InvalidBaseKind = 3;
2220 Ident = PE->getIdentKindName();
2221 }
2222
2223 if (InvalidBaseKind != -1) {
2224 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2225 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2226 << Ident;
2227 return false;
2228 }
2229 }
2230
2231 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2232 FD && FD->isImmediateFunction()) {
2233 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2234 << !Type->isAnyPointerType();
2235 Info.Note(FD->getLocation(), diag::note_declared_at);
2236 return false;
2237 }
2238
2239 // Check that the object is a global. Note that the fake 'this' object we
2240 // manufacture when checking potential constant expressions is conservatively
2241 // assumed to be global here.
2242 if (!IsGlobalLValue(Base)) {
2243 if (Info.getLangOpts().CPlusPlus11) {
2244 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2245 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2246 << BaseVD;
2247 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2248 if (VarD && VarD->isConstexpr()) {
2249 // Non-static local constexpr variables have unintuitive semantics:
2250 // constexpr int a = 1;
2251 // constexpr const int *p = &a;
2252 // ... is invalid because the address of 'a' is not constant. Suggest
2253 // adding a 'static' in this case.
2254 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2255 << VarD
2256 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2257 } else {
2258 NoteLValueLocation(Info, Base);
2259 }
2260 } else {
2261 Info.FFDiag(Loc);
2262 }
2263 // Don't allow references to temporaries to escape.
2264 return false;
2265 }
2266 assert((Info.checkingPotentialConstantExpression() ||
2267 LVal.getLValueCallIndex() == 0) &&
2268 "have call index for global lvalue");
2269
2270 if (LVal.allowConstexprUnknown()) {
2271 if (BaseVD) {
2272 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2273 NoteLValueLocation(Info, Base);
2274 } else {
2275 Info.FFDiag(Loc);
2276 }
2277 return false;
2278 }
2279
2280 if (Base.is<DynamicAllocLValue>()) {
2281 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2282 << IsReferenceType << !Designator.Entries.empty();
2283 NoteLValueLocation(Info, Base);
2284 return false;
2285 }
2286
2287 if (BaseVD) {
2288 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2289 // Check if this is a thread-local variable.
2290 if (Var->getTLSKind())
2291 // FIXME: Diagnostic!
2292 return false;
2293
2294 // A dllimport variable never acts like a constant, unless we're
2295 // evaluating a value for use only in name mangling, and unless it's a
2296 // static local. For the latter case, we'd still need to evaluate the
2297 // constant expression in case we're inside a (inlined) function.
2298 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>() &&
2299 !Var->isStaticLocal())
2300 return false;
2301
2302 // In CUDA/HIP device compilation, only device side variables have
2303 // constant addresses.
2304 if (Info.getLangOpts().CUDA && Info.getLangOpts().CUDAIsDevice &&
2305 Info.Ctx.CUDAConstantEvalCtx.NoWrongSidedVars) {
2306 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2307 !Var->hasAttr<CUDAConstantAttr>() &&
2308 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2309 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2310 Var->hasAttr<HIPManagedAttr>())
2311 return false;
2312 }
2313 }
2314 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2315 // __declspec(dllimport) must be handled very carefully:
2316 // We must never initialize an expression with the thunk in C++.
2317 // Doing otherwise would allow the same id-expression to yield
2318 // different addresses for the same function in different translation
2319 // units. However, this means that we must dynamically initialize the
2320 // expression with the contents of the import address table at runtime.
2321 //
2322 // The C language has no notion of ODR; furthermore, it has no notion of
2323 // dynamic initialization. This means that we are permitted to
2324 // perform initialization with the address of the thunk.
2325 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2326 FD->hasAttr<DLLImportAttr>())
2327 // FIXME: Diagnostic!
2328 return false;
2329 }
2330 } else if (const auto *MTE =
2331 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2332 if (CheckedTemps.insert(MTE).second) {
2333 QualType TempType = getType(Base);
2334 if (TempType.isDestructedType()) {
2335 Info.FFDiag(MTE->getExprLoc(),
2336 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2337 << TempType;
2338 return false;
2339 }
2340
2341 APValue *V = MTE->getOrCreateValue(false);
2342 assert(V && "evasluation result refers to uninitialised temporary");
2344 Info, MTE->getExprLoc(), TempType, *V, Kind,
2345 /*SubobjectDecl=*/nullptr, CheckedTemps))
2346 return false;
2347 }
2348 }
2349
2350 // Allow address constant expressions to be past-the-end pointers. This is
2351 // an extension: the standard requires them to point to an object.
2352 if (!IsReferenceType)
2353 return true;
2354
2355 // A reference constant expression must refer to an object.
2356 if (!Base) {
2357 // FIXME: diagnostic
2358 Info.CCEDiag(Loc);
2359 return true;
2360 }
2361
2362 // Does this refer one past the end of some object?
2363 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2364 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2365 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2366 NoteLValueLocation(Info, Base);
2367 }
2368
2369 return true;
2370}
2371
2372/// Member pointers are constant expressions unless they point to a
2373/// non-virtual dllimport member function.
2374static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2375 SourceLocation Loc,
2376 QualType Type,
2377 const APValue &Value,
2378 ConstantExprKind Kind) {
2379 const ValueDecl *Member = Value.getMemberPointerDecl();
2380 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2381 if (!FD)
2382 return true;
2383 if (FD->isImmediateFunction()) {
2384 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2385 Info.Note(FD->getLocation(), diag::note_declared_at);
2386 return false;
2387 }
2388 return isForManglingOnly(Kind) || FD->isVirtual() ||
2389 !FD->hasAttr<DLLImportAttr>();
2390}
2391
2392/// Check that this core constant expression is of literal type, and if not,
2393/// produce an appropriate diagnostic.
2394static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2395 const LValue *This = nullptr) {
2396 // The restriction to literal types does not exist in C++23 anymore.
2397 if (Info.getLangOpts().CPlusPlus23)
2398 return true;
2399
2400 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2401 return true;
2402
2403 // C++1y: A constant initializer for an object o [...] may also invoke
2404 // constexpr constructors for o and its subobjects even if those objects
2405 // are of non-literal class types.
2406 //
2407 // C++11 missed this detail for aggregates, so classes like this:
2408 // struct foo_t { union { int i; volatile int j; } u; };
2409 // are not (obviously) initializable like so:
2410 // __attribute__((__require_constant_initialization__))
2411 // static const foo_t x = {{0}};
2412 // because "i" is a subobject with non-literal initialization (due to the
2413 // volatile member of the union). See:
2414 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2415 // Therefore, we use the C++1y behavior.
2416 if (This && Info.EvaluatingDecl == This->getLValueBase())
2417 return true;
2418
2419 // Prvalue constant expressions must be of literal types.
2420 if (Info.getLangOpts().CPlusPlus11)
2421 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2422 << E->getType();
2423 else
2424 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2425 return false;
2426}
2427
2429 EvalInfo &Info, SourceLocation DiagLoc,
2430 QualType Type, const APValue &Value,
2431 ConstantExprKind Kind,
2432 const FieldDecl *SubobjectDecl,
2433 CheckedTemporaries &CheckedTemps) {
2434 if (!Value.hasValue()) {
2435 if (SubobjectDecl) {
2436 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2437 << /*(name)*/ 1 << SubobjectDecl;
2438 Info.Note(SubobjectDecl->getLocation(),
2439 diag::note_constexpr_subobject_declared_here);
2440 } else {
2441 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2442 << /*of type*/ 0 << Type;
2443 }
2444 return false;
2445 }
2446
2447 // We allow _Atomic(T) to be initialized from anything that T can be
2448 // initialized from.
2449 if (const AtomicType *AT = Type->getAs<AtomicType>())
2450 Type = AT->getValueType();
2451
2452 // Core issue 1454: For a literal constant expression of array or class type,
2453 // each subobject of its value shall have been initialized by a constant
2454 // expression.
2455 if (Value.isArray()) {
2457 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2458 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2459 Value.getArrayInitializedElt(I), Kind,
2460 SubobjectDecl, CheckedTemps))
2461 return false;
2462 }
2463 if (!Value.hasArrayFiller())
2464 return true;
2465 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2466 Value.getArrayFiller(), Kind, SubobjectDecl,
2467 CheckedTemps);
2468 }
2469 if (Value.isUnion() && Value.getUnionField()) {
2470 return CheckEvaluationResult(
2471 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2472 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2473 }
2474 if (Value.isStruct()) {
2475 auto *RD = Type->castAsRecordDecl();
2476 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2477 unsigned BaseIndex = 0;
2478 for (const CXXBaseSpecifier &BS : CD->bases()) {
2479 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2480 if (!BaseValue.hasValue()) {
2481 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2482 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2483 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2484 return false;
2485 }
2486 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2487 Kind, /*SubobjectDecl=*/nullptr,
2488 CheckedTemps))
2489 return false;
2490 ++BaseIndex;
2491 }
2492 }
2493 for (const auto *I : RD->fields()) {
2494 if (I->isUnnamedBitField())
2495 continue;
2496
2497 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2498 Value.getStructField(I->getFieldIndex()), Kind,
2499 I, CheckedTemps))
2500 return false;
2501 }
2502 }
2503
2504 if (Value.isLValue() &&
2506 LValue LVal;
2507 LVal.setFrom(Info.Ctx, Value);
2508 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2509 CheckedTemps);
2510 }
2511
2512 if (Value.isMemberPointer() &&
2514 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2515
2516 // Everything else is fine.
2517 return true;
2518}
2519
2520/// Check that this core constant expression value is a valid value for a
2521/// constant expression. If not, report an appropriate diagnostic. Does not
2522/// check that the expression is of literal type.
2523static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2524 QualType Type, const APValue &Value,
2525 ConstantExprKind Kind) {
2526 // Nothing to check for a constant expression of type 'cv void'.
2527 if (Type->isVoidType())
2528 return true;
2529
2530 CheckedTemporaries CheckedTemps;
2532 Info, DiagLoc, Type, Value, Kind,
2533 /*SubobjectDecl=*/nullptr, CheckedTemps);
2534}
2535
2536/// Check that this evaluated value is fully-initialized and can be loaded by
2537/// an lvalue-to-rvalue conversion.
2538static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2539 QualType Type, const APValue &Value) {
2540 CheckedTemporaries CheckedTemps;
2541 return CheckEvaluationResult(
2543 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2544}
2545
2546/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2547/// "the allocated storage is deallocated within the evaluation".
2548static bool CheckMemoryLeaks(EvalInfo &Info) {
2549 if (!Info.HeapAllocs.empty()) {
2550 // We can still fold to a constant despite a compile-time memory leak,
2551 // so long as the heap allocation isn't referenced in the result (we check
2552 // that in CheckConstantExpression).
2553 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2554 diag::note_constexpr_memory_leak)
2555 << unsigned(Info.HeapAllocs.size() - 1);
2556 }
2557 return true;
2558}
2559
2560static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2561 // A null base expression indicates a null pointer. These are always
2562 // evaluatable, and they are false unless the offset is zero.
2563 if (!Value.getLValueBase()) {
2564 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2565 Result = !Value.getLValueOffset().isZero();
2566 return true;
2567 }
2568
2569 // We have a non-null base. These are generally known to be true, but if it's
2570 // a weak declaration it can be null at runtime.
2571 Result = true;
2572 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2573 return !Decl || !Decl->isWeak();
2574}
2575
2576static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2577 // TODO: This function should produce notes if it fails.
2578 switch (Val.getKind()) {
2579 case APValue::None:
2581 return false;
2582 case APValue::Int:
2583 Result = Val.getInt().getBoolValue();
2584 return true;
2586 Result = Val.getFixedPoint().getBoolValue();
2587 return true;
2588 case APValue::Float:
2589 Result = !Val.getFloat().isZero();
2590 return true;
2592 Result = Val.getComplexIntReal().getBoolValue() ||
2593 Val.getComplexIntImag().getBoolValue();
2594 return true;
2596 Result = !Val.getComplexFloatReal().isZero() ||
2597 !Val.getComplexFloatImag().isZero();
2598 return true;
2599 case APValue::LValue:
2600 return EvalPointerValueAsBool(Val, Result);
2602 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2603 return false;
2604 }
2605 Result = Val.getMemberPointerDecl();
2606 return true;
2607 case APValue::Vector:
2608 case APValue::Matrix:
2609 case APValue::Array:
2610 case APValue::Struct:
2611 case APValue::Union:
2613 return false;
2614 }
2615
2616 llvm_unreachable("unknown APValue kind");
2617}
2618
2619static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2620 EvalInfo &Info) {
2621 assert(!E->isValueDependent());
2622 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2623 APValue Val;
2624 if (!Evaluate(Val, Info, E))
2625 return false;
2626 return HandleConversionToBool(Val, Result);
2627}
2628
2629template<typename T>
2630static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2631 const T &SrcValue, QualType DestType) {
2632 Info.CCEDiag(E, diag::note_constexpr_overflow) << SrcValue << DestType;
2633 if (const auto *OBT = DestType->getAs<OverflowBehaviorType>();
2634 OBT && OBT->isTrapKind()) {
2635 return false;
2636 }
2637 return Info.noteUndefinedBehavior();
2638}
2639
2640static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2641 QualType SrcType, const APFloat &Value,
2642 QualType DestType, APSInt &Result) {
2643 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2644 // Determine whether we are converting to unsigned or signed.
2645 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2646
2647 Result = APSInt(DestWidth, !DestSigned);
2648 bool ignored;
2649 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2650 & APFloat::opInvalidOp)
2651 return HandleOverflow(Info, E, Value, DestType);
2652 return true;
2653}
2654
2655/// Get rounding mode to use in evaluation of the specified expression.
2656///
2657/// If rounding mode is unknown at compile time, still try to evaluate the
2658/// expression. If the result is exact, it does not depend on rounding mode.
2659/// So return "tonearest" mode instead of "dynamic".
2660static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2661 llvm::RoundingMode RM =
2662 E->getFPFeaturesInEffect(Info.getLangOpts()).getRoundingMode();
2663 if (RM == llvm::RoundingMode::Dynamic)
2664 RM = llvm::RoundingMode::NearestTiesToEven;
2665 return RM;
2666}
2667
2668/// Check if the given evaluation result is allowed for constant evaluation.
2669static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2670 APFloat::opStatus St) {
2671 // In a constant context, assume that any dynamic rounding mode or FP
2672 // exception state matches the default floating-point environment.
2673 if (Info.InConstantContext)
2674 return true;
2675
2676 FPOptions FPO = E->getFPFeaturesInEffect(Info.getLangOpts());
2677 if ((St & APFloat::opInexact) &&
2678 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2679 // Inexact result means that it depends on rounding mode. If the requested
2680 // mode is dynamic, the evaluation cannot be made in compile time.
2681 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2682 return false;
2683 }
2684
2685 if ((St != APFloat::opOK) &&
2686 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2688 FPO.getAllowFEnvAccess())) {
2689 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2690 return false;
2691 }
2692
2693 if ((St & APFloat::opStatus::opInvalidOp) &&
2695 // There is no usefully definable result.
2696 Info.FFDiag(E);
2697 return false;
2698 }
2699
2700 // FIXME: if:
2701 // - evaluation triggered other FP exception, and
2702 // - exception mode is not "ignore", and
2703 // - the expression being evaluated is not a part of global variable
2704 // initializer,
2705 // the evaluation probably need to be rejected.
2706 return true;
2707}
2708
2709static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2710 QualType SrcType, QualType DestType,
2711 APFloat &Result) {
2712 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2714 "HandleFloatToFloatCast has been checked with only CastExpr, "
2715 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2716 "the new expression or address the root cause of this usage.");
2717 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2718 APFloat::opStatus St;
2719 APFloat Value = Result;
2720 bool ignored;
2721 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2722 return checkFloatingPointResult(Info, E, St);
2723}
2724
2725static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2726 QualType DestType, QualType SrcType,
2727 const APSInt &Value) {
2728 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2729 // Figure out if this is a truncate, extend or noop cast.
2730 // If the input is signed, do a sign extend, noop, or truncate.
2731 APSInt Result = Value.extOrTrunc(DestWidth);
2732 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2733 if (DestType->isBooleanType())
2734 Result = Value.getBoolValue();
2735 return Result;
2736}
2737
2738static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2739 const FPOptions FPO,
2740 QualType SrcType, const APSInt &Value,
2741 QualType DestType, APFloat &Result) {
2742 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2743 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2744 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2745 return checkFloatingPointResult(Info, E, St);
2746}
2747
2748static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2749 APValue &Value, const FieldDecl *FD) {
2750 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2751
2752 if (!Value.isInt()) {
2753 // Trying to store a pointer-cast-to-integer into a bitfield.
2754 // FIXME: In this case, we should provide the diagnostic for casting
2755 // a pointer to an integer.
2756 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2757 Info.FFDiag(E);
2758 return false;
2759 }
2760
2761 APSInt &Int = Value.getInt();
2762 unsigned OldBitWidth = Int.getBitWidth();
2763 unsigned NewBitWidth = FD->getBitWidthValue();
2764 if (NewBitWidth < OldBitWidth)
2765 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2766 return true;
2767}
2768
2769/// Perform the given integer operation, which is known to need at most BitWidth
2770/// bits, and check for overflow in the original type (if that type was not an
2771/// unsigned type).
2772template<typename Operation>
2773static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2774 const APSInt &LHS, const APSInt &RHS,
2775 unsigned BitWidth, Operation Op,
2776 APSInt &Result) {
2777 if (LHS.isUnsigned()) {
2778 Result = Op(LHS, RHS);
2779 return true;
2780 }
2781
2782 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2783 Result = Value.trunc(LHS.getBitWidth());
2784 if (Result.extend(BitWidth) != Value && !E->getType().isWrapType()) {
2785 if (Info.checkingForUndefinedBehavior())
2786 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2787 diag::warn_integer_constant_overflow)
2788 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2789 /*UpperCase=*/true, /*InsertSeparators=*/true)
2790 << E->getType() << E->getSourceRange();
2791 return HandleOverflow(Info, E, Value, E->getType());
2792 }
2793 return true;
2794}
2795
2796/// Perform the given binary integer operation.
2797static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2798 const APSInt &LHS, BinaryOperatorKind Opcode,
2799 APSInt RHS, APSInt &Result) {
2800 bool HandleOverflowResult = true;
2801 switch (Opcode) {
2802 default:
2803 Info.FFDiag(E);
2804 return false;
2805 case BO_Mul:
2806 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2807 std::multiplies<APSInt>(), Result);
2808 case BO_Add:
2809 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2810 std::plus<APSInt>(), Result);
2811 case BO_Sub:
2812 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2813 std::minus<APSInt>(), Result);
2814 case BO_And: Result = LHS & RHS; return true;
2815 case BO_Xor: Result = LHS ^ RHS; return true;
2816 case BO_Or: Result = LHS | RHS; return true;
2817 case BO_Div:
2818 case BO_Rem:
2819 if (RHS == 0) {
2820 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2821 << E->getRHS()->getSourceRange();
2822 return false;
2823 }
2824 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2825 // this operation and gives the two's complement result.
2826 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2827 LHS.isMinSignedValue())
2828 HandleOverflowResult = HandleOverflow(
2829 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2830 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2831 return HandleOverflowResult;
2832 case BO_Shl: {
2833 if (Info.getLangOpts().OpenCL)
2834 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2835 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2836 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2837 RHS.isUnsigned());
2838 else if (RHS.isSigned() && RHS.isNegative()) {
2839 // During constant-folding, a negative shift is an opposite shift. Such
2840 // a shift is not a constant expression.
2841 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2842 if (!Info.noteUndefinedBehavior())
2843 return false;
2844 RHS = -RHS;
2845 goto shift_right;
2846 }
2847 shift_left:
2848 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2849 // the shifted type.
2850 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2851 if (SA != RHS) {
2852 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2853 << RHS << E->getType() << LHS.getBitWidth();
2854 if (!Info.noteUndefinedBehavior())
2855 return false;
2856 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2857 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2858 // operand, and must not overflow the corresponding unsigned type.
2859 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2860 // E1 x 2^E2 module 2^N.
2861 if (LHS.isNegative()) {
2862 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2863 if (!Info.noteUndefinedBehavior())
2864 return false;
2865 } else if (LHS.countl_zero() < SA) {
2866 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2867 if (!Info.noteUndefinedBehavior())
2868 return false;
2869 }
2870 }
2871 Result = LHS << SA;
2872 return true;
2873 }
2874 case BO_Shr: {
2875 if (Info.getLangOpts().OpenCL)
2876 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2877 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2878 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2879 RHS.isUnsigned());
2880 else if (RHS.isSigned() && RHS.isNegative()) {
2881 // During constant-folding, a negative shift is an opposite shift. Such a
2882 // shift is not a constant expression.
2883 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2884 if (!Info.noteUndefinedBehavior())
2885 return false;
2886 RHS = -RHS;
2887 goto shift_left;
2888 }
2889 shift_right:
2890 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2891 // shifted type.
2892 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2893 if (SA != RHS) {
2894 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2895 << RHS << E->getType() << LHS.getBitWidth();
2896 if (!Info.noteUndefinedBehavior())
2897 return false;
2898 }
2899
2900 Result = LHS >> SA;
2901 return true;
2902 }
2903
2904 case BO_LT: Result = LHS < RHS; return true;
2905 case BO_GT: Result = LHS > RHS; return true;
2906 case BO_LE: Result = LHS <= RHS; return true;
2907 case BO_GE: Result = LHS >= RHS; return true;
2908 case BO_EQ: Result = LHS == RHS; return true;
2909 case BO_NE: Result = LHS != RHS; return true;
2910 case BO_Cmp:
2911 llvm_unreachable("BO_Cmp should be handled elsewhere");
2912 }
2913}
2914
2915/// Perform the given binary floating-point operation, in-place, on LHS.
2916static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2917 APFloat &LHS, BinaryOperatorKind Opcode,
2918 const APFloat &RHS) {
2919 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2920 APFloat::opStatus St;
2921 switch (Opcode) {
2922 default:
2923 Info.FFDiag(E);
2924 return false;
2925 case BO_Mul:
2926 St = LHS.multiply(RHS, RM);
2927 break;
2928 case BO_Add:
2929 St = LHS.add(RHS, RM);
2930 break;
2931 case BO_Sub:
2932 St = LHS.subtract(RHS, RM);
2933 break;
2934 case BO_Div:
2935 // [expr.mul]p4:
2936 // If the second operand of / or % is zero the behavior is undefined.
2937 if (RHS.isZero())
2938 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2939 St = LHS.divide(RHS, RM);
2940 break;
2941 }
2942
2943 // [expr.pre]p4:
2944 // If during the evaluation of an expression, the result is not
2945 // mathematically defined [...], the behavior is undefined.
2946 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2947 if (LHS.isNaN()) {
2948 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2949 return Info.noteUndefinedBehavior();
2950 }
2951
2952 return checkFloatingPointResult(Info, E, St);
2953}
2954
2955static bool handleLogicalOpForVector(const APInt &LHSValue,
2956 BinaryOperatorKind Opcode,
2957 const APInt &RHSValue, APInt &Result) {
2958 bool LHS = (LHSValue != 0);
2959 bool RHS = (RHSValue != 0);
2960
2961 if (Opcode == BO_LAnd)
2962 Result = LHS && RHS;
2963 else
2964 Result = LHS || RHS;
2965 return true;
2966}
2967static bool handleLogicalOpForVector(const APFloat &LHSValue,
2968 BinaryOperatorKind Opcode,
2969 const APFloat &RHSValue, APInt &Result) {
2970 bool LHS = !LHSValue.isZero();
2971 bool RHS = !RHSValue.isZero();
2972
2973 if (Opcode == BO_LAnd)
2974 Result = LHS && RHS;
2975 else
2976 Result = LHS || RHS;
2977 return true;
2978}
2979
2980static bool handleLogicalOpForVector(const APValue &LHSValue,
2981 BinaryOperatorKind Opcode,
2982 const APValue &RHSValue, APInt &Result) {
2983 // The result is always an int type, however operands match the first.
2984 if (LHSValue.getKind() == APValue::Int)
2985 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2986 RHSValue.getInt(), Result);
2987 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2988 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2989 RHSValue.getFloat(), Result);
2990}
2991
2992template <typename APTy>
2993static bool
2995 const APTy &RHSValue, APInt &Result) {
2996 switch (Opcode) {
2997 default:
2998 llvm_unreachable("unsupported binary operator");
2999 case BO_EQ:
3000 Result = (LHSValue == RHSValue);
3001 break;
3002 case BO_NE:
3003 Result = (LHSValue != RHSValue);
3004 break;
3005 case BO_LT:
3006 Result = (LHSValue < RHSValue);
3007 break;
3008 case BO_GT:
3009 Result = (LHSValue > RHSValue);
3010 break;
3011 case BO_LE:
3012 Result = (LHSValue <= RHSValue);
3013 break;
3014 case BO_GE:
3015 Result = (LHSValue >= RHSValue);
3016 break;
3017 }
3018
3019 // The boolean operations on these vector types use an instruction that
3020 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3021 // to -1 to make sure that we produce the correct value.
3022 Result.negate();
3023
3024 return true;
3025}
3026
3027static bool handleCompareOpForVector(const APValue &LHSValue,
3028 BinaryOperatorKind Opcode,
3029 const APValue &RHSValue, APInt &Result) {
3030 // The result is always an int type, however operands match the first.
3031 if (LHSValue.getKind() == APValue::Int)
3032 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3033 RHSValue.getInt(), Result);
3034 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3035 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3036 RHSValue.getFloat(), Result);
3037}
3038
3039// Perform binary operations for vector types, in place on the LHS.
3040static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3041 BinaryOperatorKind Opcode,
3042 APValue &LHSValue,
3043 const APValue &RHSValue) {
3044 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3045 "Operation not supported on vector types");
3046
3047 const auto *VT = E->getType()->castAs<VectorType>();
3048 unsigned NumElements = VT->getNumElements();
3049 QualType EltTy = VT->getElementType();
3050
3051 // In the cases (typically C as I've observed) where we aren't evaluating
3052 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3053 // just give up.
3054 if (!LHSValue.isVector()) {
3055 assert(LHSValue.isLValue() &&
3056 "A vector result that isn't a vector OR uncalculated LValue");
3057 Info.FFDiag(E);
3058 return false;
3059 }
3060
3061 assert(LHSValue.getVectorLength() == NumElements &&
3062 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3063
3064 SmallVector<APValue, 4> ResultElements;
3065
3066 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3067 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3068 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3069
3070 if (EltTy->isIntegerType()) {
3071 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3072 EltTy->isUnsignedIntegerType()};
3073 bool Success = true;
3074
3075 if (BinaryOperator::isLogicalOp(Opcode))
3076 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3077 else if (BinaryOperator::isComparisonOp(Opcode))
3078 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3079 else
3080 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3081 RHSElt.getInt(), EltResult);
3082
3083 if (!Success) {
3084 Info.FFDiag(E);
3085 return false;
3086 }
3087 ResultElements.emplace_back(EltResult);
3088
3089 } else if (EltTy->isFloatingType()) {
3090 assert(LHSElt.getKind() == APValue::Float &&
3091 RHSElt.getKind() == APValue::Float &&
3092 "Mismatched LHS/RHS/Result Type");
3093 APFloat LHSFloat = LHSElt.getFloat();
3094
3095 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3096 RHSElt.getFloat())) {
3097 Info.FFDiag(E);
3098 return false;
3099 }
3100
3101 ResultElements.emplace_back(LHSFloat);
3102 }
3103 }
3104
3105 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3106 return true;
3107}
3108
3109/// Cast an lvalue referring to a base subobject to a derived class, by
3110/// truncating the lvalue's path to the given length.
3111static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3112 const RecordDecl *TruncatedType,
3113 unsigned TruncatedElements) {
3114 SubobjectDesignator &D = Result.Designator;
3115
3116 // Check we actually point to a derived class object.
3117 if (TruncatedElements == D.Entries.size())
3118 return true;
3119 assert(TruncatedElements >= D.MostDerivedPathLength &&
3120 "not casting to a derived class");
3121 if (!Result.checkSubobject(Info, E, CSK_Derived))
3122 return false;
3123
3124 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3125 const RecordDecl *RD = TruncatedType;
3126 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3127 if (RD->isInvalidDecl()) return false;
3128 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3129 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3130 if (isVirtualBaseClass(D.Entries[I]))
3131 Result.Offset -= Layout.getVBaseClassOffset(Base);
3132 else
3133 Result.Offset -= Layout.getBaseClassOffset(Base);
3134 RD = Base;
3135 }
3136 D.Entries.resize(TruncatedElements);
3137 return true;
3138}
3139
3140static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3141 const CXXRecordDecl *Derived,
3142 const CXXRecordDecl *Base,
3143 const ASTRecordLayout *RL = nullptr) {
3144 if (!RL) {
3145 if (Derived->isInvalidDecl()) return false;
3146 RL = &Info.Ctx.getASTRecordLayout(Derived);
3147 }
3148
3149 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3150 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3151 return true;
3152}
3153
3154static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3155 const CXXRecordDecl *DerivedDecl,
3156 const CXXBaseSpecifier *Base) {
3157 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3158
3159 if (!Base->isVirtual())
3160 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3161
3162 SubobjectDesignator &D = Obj.Designator;
3163 if (D.Invalid)
3164 return false;
3165
3166 // Extract most-derived object and corresponding type.
3167 // FIXME: After implementing P2280R4 it became possible to get references
3168 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3169 // locations and if we see crashes in those locations in the future
3170 // it may make more sense to move this fix into Lvalue::set.
3171 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3172 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3173 return false;
3174
3175 // Find the virtual base class.
3176 if (DerivedDecl->isInvalidDecl()) return false;
3177 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3178 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3179 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3180 return true;
3181}
3182
3183static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3184 QualType Type, LValue &Result) {
3185 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3186 PathE = E->path_end();
3187 PathI != PathE; ++PathI) {
3188 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3189 *PathI))
3190 return false;
3191 Type = (*PathI)->getType();
3192 }
3193 return true;
3194}
3195
3196/// Cast an lvalue referring to a derived class to a known base subobject.
3197static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3198 const CXXRecordDecl *DerivedRD,
3199 const CXXRecordDecl *BaseRD) {
3200 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3201 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3202 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3203 llvm_unreachable("Class must be derived from the passed in base class!");
3204
3205 for (CXXBasePathElement &Elem : Paths.front())
3206 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3207 return false;
3208 return true;
3209}
3210
3211/// Update LVal to refer to the given field, which must be a member of the type
3212/// currently described by LVal.
3213static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3214 const FieldDecl *FD,
3215 const ASTRecordLayout *RL = nullptr) {
3216 if (!RL) {
3217 if (FD->getParent()->isInvalidDecl()) return false;
3218 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3219 }
3220
3221 unsigned I = FD->getFieldIndex();
3222 LVal.addDecl(Info, E, FD);
3223 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3224 return true;
3225}
3226
3227/// Update LVal to refer to the given indirect field.
3228static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3229 LValue &LVal,
3230 const IndirectFieldDecl *IFD) {
3231 for (const auto *C : IFD->chain())
3232 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3233 return false;
3234 return true;
3235}
3236
3241
3242/// Get the size of the given type in char units.
3243static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3245 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3246 // extension.
3247 if (Type->isVoidType() || Type->isFunctionType()) {
3248 Size = CharUnits::One();
3249 return true;
3250 }
3251
3252 if (Type->isDependentType()) {
3253 Info.FFDiag(Loc);
3254 return false;
3255 }
3256
3257 if (!Type->isConstantSizeType()) {
3258 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3259 // FIXME: Better diagnostic.
3260 Info.FFDiag(Loc);
3261 return false;
3262 }
3263
3264 if (SOT == SizeOfType::SizeOf)
3265 Size = Info.Ctx.getTypeSizeInChars(Type);
3266 else
3267 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3268 return true;
3269}
3270
3271/// Update a pointer value to model pointer arithmetic.
3272/// \param Info - Information about the ongoing evaluation.
3273/// \param E - The expression being evaluated, for diagnostic purposes.
3274/// \param LVal - The pointer value to be updated.
3275/// \param EltTy - The pointee type represented by LVal.
3276/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3277static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3278 LValue &LVal, QualType EltTy,
3279 APSInt Adjustment) {
3280 CharUnits SizeOfPointee;
3281 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3282 return false;
3283
3284 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3285 return true;
3286}
3287
3288static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3289 LValue &LVal, QualType EltTy,
3290 int64_t Adjustment) {
3291 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3292 APSInt::get(Adjustment));
3293}
3294
3295/// Update an lvalue to refer to a component of a complex number.
3296/// \param Info - Information about the ongoing evaluation.
3297/// \param LVal - The lvalue to be updated.
3298/// \param EltTy - The complex number's component type.
3299/// \param Imag - False for the real component, true for the imaginary.
3300static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3301 LValue &LVal, QualType EltTy,
3302 bool Imag) {
3303 if (Imag) {
3304 CharUnits SizeOfComponent;
3305 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3306 return false;
3307 LVal.Offset += SizeOfComponent;
3308 }
3309 LVal.addComplex(Info, E, EltTy, Imag);
3310 return true;
3311}
3312
3313static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3314 LValue &LVal, QualType EltTy,
3315 uint64_t Size, uint64_t Idx) {
3316 if (Idx) {
3317 CharUnits SizeOfElement;
3318 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3319 return false;
3320 LVal.Offset += SizeOfElement * Idx;
3321 }
3322 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3323 return true;
3324}
3325
3326/// Try to evaluate the initializer for a variable declaration.
3327///
3328/// \param Info Information about the ongoing evaluation.
3329/// \param E An expression to be used when printing diagnostics.
3330/// \param VD The variable whose initializer should be obtained.
3331/// \param Version The version of the variable within the frame.
3332/// \param Frame The frame in which the variable was created. Must be null
3333/// if this variable is not local to the evaluation.
3334/// \param Result Filled in with a pointer to the value of the variable.
3335static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3336 const VarDecl *VD, CallStackFrame *Frame,
3337 unsigned Version, APValue *&Result) {
3338 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3339 // and pointers.
3340 bool AllowConstexprUnknown =
3341 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3342
3343 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3344
3345 auto CheckUninitReference = [&](bool IsLocalVariable) {
3346 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3347 // C++23 [expr.const]p8
3348 // ... For such an object that is not usable in constant expressions, the
3349 // dynamic type of the object is constexpr-unknown. For such a reference
3350 // that is not usable in constant expressions, the reference is treated
3351 // as binding to an unspecified object of the referenced type whose
3352 // lifetime and that of all subobjects includes the entire constant
3353 // evaluation and whose dynamic type is constexpr-unknown.
3354 //
3355 // Variables that are part of the current evaluation are not
3356 // constexpr-unknown.
3357 if (!AllowConstexprUnknown || IsLocalVariable) {
3358 if (!Info.checkingPotentialConstantExpression())
3359 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3360 return false;
3361 }
3362 Result = nullptr;
3363 }
3364 return true;
3365 };
3366
3367 // If this is a local variable, dig out its value.
3368 if (Frame) {
3369 Result = Frame->getTemporary(VD, Version);
3370 if (Result)
3371 return CheckUninitReference(/*IsLocalVariable=*/true);
3372
3373 if (!isa<ParmVarDecl>(VD)) {
3374 // Assume variables referenced within a lambda's call operator that were
3375 // not declared within the call operator are captures and during checking
3376 // of a potential constant expression, assume they are unknown constant
3377 // expressions.
3378 assert(isLambdaCallOperator(Frame->Callee) &&
3379 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3380 "missing value for local variable");
3381 if (Info.checkingPotentialConstantExpression())
3382 return false;
3383
3384 llvm_unreachable(
3385 "A variable in a frame should either be a local or a parameter");
3386 }
3387 }
3388
3389 // If we're currently evaluating the initializer of this declaration, use that
3390 // in-flight value.
3391 if (Info.EvaluatingDecl == Base) {
3392 Result = Info.EvaluatingDeclValue;
3393 return CheckUninitReference(/*IsLocalVariable=*/false);
3394 }
3395
3396 // P2280R4 struck the restriction that variable of reference type lifetime
3397 // should begin within the evaluation of E
3398 // Used to be C++20 [expr.const]p5.12.2:
3399 // ... its lifetime began within the evaluation of E;
3400 if (isa<ParmVarDecl>(VD)) {
3401 if (AllowConstexprUnknown) {
3402 Result = nullptr;
3403 return true;
3404 }
3405
3406 // Assume parameters of a potential constant expression are usable in
3407 // constant expressions.
3408 if (!Info.checkingPotentialConstantExpression() ||
3409 !Info.CurrentCall->Callee ||
3410 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3411 if (Info.getLangOpts().CPlusPlus11) {
3412 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3413 << VD;
3414 NoteLValueLocation(Info, Base);
3415 } else {
3416 Info.FFDiag(E);
3417 }
3418 }
3419 return false;
3420 }
3421
3422 if (E->isValueDependent())
3423 return false;
3424
3425 // Dig out the initializer, and use the declaration which it's attached to.
3426 // FIXME: We should eventually check whether the variable has a reachable
3427 // initializing declaration.
3428 const Expr *Init = VD->getAnyInitializer(VD);
3429 // P2280R4 struck the restriction that variable of reference type should have
3430 // a preceding initialization.
3431 // Used to be C++20 [expr.const]p5.12:
3432 // ... reference has a preceding initialization and either ...
3433 if (!Init && !AllowConstexprUnknown) {
3434 // Don't diagnose during potential constant expression checking; an
3435 // initializer might be added later.
3436 if (!Info.checkingPotentialConstantExpression()) {
3437 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3438 << VD;
3439 NoteLValueLocation(Info, Base);
3440 }
3441 return false;
3442 }
3443
3444 // P2280R4 struck the initialization requirement for variables of reference
3445 // type so we can no longer assume we have an Init.
3446 // Used to be C++20 [expr.const]p5.12:
3447 // ... reference has a preceding initialization and either ...
3448 if (Init && Init->isValueDependent()) {
3449 // The DeclRefExpr is not value-dependent, but the variable it refers to
3450 // has a value-dependent initializer. This should only happen in
3451 // constant-folding cases, where the variable is not actually of a suitable
3452 // type for use in a constant expression (otherwise the DeclRefExpr would
3453 // have been value-dependent too), so diagnose that.
3454 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3455 if (!Info.checkingPotentialConstantExpression()) {
3456 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3457 ? diag::note_constexpr_ltor_non_constexpr
3458 : diag::note_constexpr_ltor_non_integral, 1)
3459 << VD << VD->getType();
3460 NoteLValueLocation(Info, Base);
3461 }
3462 return false;
3463 }
3464
3465 // Check that we can fold the initializer. In C++, we will have already done
3466 // this in the cases where it matters for conformance.
3467 // P2280R4 struck the initialization requirement for variables of reference
3468 // type so we can no longer assume we have an Init.
3469 // Used to be C++20 [expr.const]p5.12:
3470 // ... reference has a preceding initialization and either ...
3471 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3472 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3473 NoteLValueLocation(Info, Base);
3474 return false;
3475 }
3476
3477 // Check that the variable is actually usable in constant expressions. For a
3478 // const integral variable or a reference, we might have a non-constant
3479 // initializer that we can nonetheless evaluate the initializer for. Such
3480 // variables are not usable in constant expressions. In C++98, the
3481 // initializer also syntactically needs to be an ICE.
3482 //
3483 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3484 // expressions here; doing so would regress diagnostics for things like
3485 // reading from a volatile constexpr variable.
3486 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3487 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3488 !AllowConstexprUnknown) ||
3489 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3490 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3491 if (Init) {
3492 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3493 NoteLValueLocation(Info, Base);
3494 } else {
3495 Info.CCEDiag(E);
3496 }
3497 }
3498
3499 // Never use the initializer of a weak variable, not even for constant
3500 // folding. We can't be sure that this is the definition that will be used.
3501 if (VD->isWeak()) {
3502 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3503 NoteLValueLocation(Info, Base);
3504 return false;
3505 }
3506
3507 Result = VD->getEvaluatedValue();
3508
3509 if (!Result && !AllowConstexprUnknown)
3510 return false;
3511
3512 return CheckUninitReference(/*IsLocalVariable=*/false);
3513}
3514
3515/// Get the base index of the given base class within an APValue representing
3516/// the given derived class.
3517static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3518 const CXXRecordDecl *Base) {
3519 Base = Base->getCanonicalDecl();
3520 unsigned Index = 0;
3522 E = Derived->bases_end(); I != E; ++I, ++Index) {
3523 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3524 return Index;
3525 }
3526
3527 llvm_unreachable("base class missing from derived class's bases list");
3528}
3529
3530/// Extract the value of a character from a string literal.
3531static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3532 uint64_t Index) {
3533 assert(!isa<SourceLocExpr>(Lit) &&
3534 "SourceLocExpr should have already been converted to a StringLiteral");
3535
3536 // FIXME: Support MakeStringConstant
3537 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3538 std::string Str;
3539 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3540 assert(Index <= Str.size() && "Index too large");
3541 return APSInt::getUnsigned(Str.c_str()[Index]);
3542 }
3543
3544 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3545 Lit = PE->getFunctionName();
3546 const StringLiteral *S = cast<StringLiteral>(Lit);
3547 const ConstantArrayType *CAT =
3548 Info.Ctx.getAsConstantArrayType(S->getType());
3549 assert(CAT && "string literal isn't an array");
3550 QualType CharType = CAT->getElementType();
3551 assert(CharType->isIntegerType() && "unexpected character type");
3552 APSInt Value(Info.Ctx.getTypeSize(CharType),
3553 CharType->isUnsignedIntegerType());
3554 if (Index < S->getLength())
3555 Value = S->getCodeUnit(Index);
3556 return Value;
3557}
3558
3559// Expand a string literal into an array of characters.
3560//
3561// FIXME: This is inefficient; we should probably introduce something similar
3562// to the LLVM ConstantDataArray to make this cheaper.
3563static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3564 APValue &Result,
3565 QualType AllocType = QualType()) {
3566 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3567 AllocType.isNull() ? S->getType() : AllocType);
3568 assert(CAT && "string literal isn't an array");
3569 QualType CharType = CAT->getElementType();
3570 assert(CharType->isIntegerType() && "unexpected character type");
3571
3572 unsigned Elts = CAT->getZExtSize();
3573 Result = APValue(APValue::UninitArray(),
3574 std::min(S->getLength(), Elts), Elts);
3575 APSInt Value(Info.Ctx.getTypeSize(CharType),
3576 CharType->isUnsignedIntegerType());
3577 if (Result.hasArrayFiller())
3578 Result.getArrayFiller() = APValue(Value);
3579 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3580 Value = S->getCodeUnit(I);
3581 Result.getArrayInitializedElt(I) = APValue(Value);
3582 }
3583}
3584
3585// Expand an array so that it has more than Index filled elements.
3586static void expandArray(APValue &Array, unsigned Index) {
3587 unsigned Size = Array.getArraySize();
3588 assert(Index < Size);
3589
3590 // Always at least double the number of elements for which we store a value.
3591 unsigned OldElts = Array.getArrayInitializedElts();
3592 unsigned NewElts = std::max(Index+1, OldElts * 2);
3593 NewElts = std::min(Size, std::max(NewElts, 8u));
3594
3595 // Copy the data across.
3596 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3597 for (unsigned I = 0; I != OldElts; ++I)
3598 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3599 for (unsigned I = OldElts; I != NewElts; ++I)
3600 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3601 if (NewValue.hasArrayFiller())
3602 NewValue.getArrayFiller() = Array.getArrayFiller();
3603 Array.swap(NewValue);
3604}
3605
3606// Expand an indeterminate vector to materialize all elements.
3607static void expandVector(APValue &Vec, unsigned NumElements) {
3608 assert(Vec.isIndeterminate());
3610 Vec = APValue(Elts.data(), Elts.size());
3611}
3612
3613/// Determine whether a type would actually be read by an lvalue-to-rvalue
3614/// conversion. If it's of class type, we may assume that the copy operation
3615/// is trivial. Note that this is never true for a union type with fields
3616/// (because the copy always "reads" the active member) and always true for
3617/// a non-class type.
3618static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3620 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3621 return !RD || isReadByLvalueToRvalueConversion(RD);
3622}
3624 // FIXME: A trivial copy of a union copies the object representation, even if
3625 // the union is empty.
3626 if (RD->isUnion())
3627 return !RD->field_empty();
3628 if (RD->isEmpty())
3629 return false;
3630
3631 for (auto *Field : RD->fields())
3632 if (!Field->isUnnamedBitField() &&
3633 isReadByLvalueToRvalueConversion(Field->getType()))
3634 return true;
3635
3636 for (auto &BaseSpec : RD->bases())
3637 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3638 return true;
3639
3640 return false;
3641}
3642
3643/// Diagnose an attempt to read from any unreadable field within the specified
3644/// type, which might be a class type.
3645static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3646 QualType T) {
3647 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3648 if (!RD)
3649 return false;
3650
3651 if (!RD->hasMutableFields())
3652 return false;
3653
3654 for (auto *Field : RD->fields()) {
3655 // If we're actually going to read this field in some way, then it can't
3656 // be mutable. If we're in a union, then assigning to a mutable field
3657 // (even an empty one) can change the active member, so that's not OK.
3658 // FIXME: Add core issue number for the union case.
3659 if (Field->isMutable() &&
3660 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3661 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3662 Info.Note(Field->getLocation(), diag::note_declared_at);
3663 return true;
3664 }
3665
3666 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3667 return true;
3668 }
3669
3670 for (auto &BaseSpec : RD->bases())
3671 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3672 return true;
3673
3674 // All mutable fields were empty, and thus not actually read.
3675 return false;
3676}
3677
3678static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3680 bool MutableSubobject = false) {
3681 // A temporary or transient heap allocation we created.
3682 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3683 return true;
3684
3685 switch (Info.IsEvaluatingDecl) {
3686 case EvalInfo::EvaluatingDeclKind::None:
3687 return false;
3688
3689 case EvalInfo::EvaluatingDeclKind::Ctor:
3690 // The variable whose initializer we're evaluating.
3691 if (Info.EvaluatingDecl == Base)
3692 return true;
3693
3694 // A temporary lifetime-extended by the variable whose initializer we're
3695 // evaluating.
3696 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3697 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3698 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3699 return false;
3700
3701 case EvalInfo::EvaluatingDeclKind::Dtor:
3702 // C++2a [expr.const]p6:
3703 // [during constant destruction] the lifetime of a and its non-mutable
3704 // subobjects (but not its mutable subobjects) [are] considered to start
3705 // within e.
3706 if (MutableSubobject || Base != Info.EvaluatingDecl)
3707 return false;
3708 // FIXME: We can meaningfully extend this to cover non-const objects, but
3709 // we will need special handling: we should be able to access only
3710 // subobjects of such objects that are themselves declared const.
3711 QualType T = getType(Base);
3712 return T.isConstQualified() || T->isReferenceType();
3713 }
3714
3715 llvm_unreachable("unknown evaluating decl kind");
3716}
3717
3718static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3719 SourceLocation CallLoc = {}) {
3720 return Info.CheckArraySize(
3721 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3722 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3723 /*Diag=*/true);
3724}
3725
3726static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E,
3727 QualType SourceTy, QualType DestTy,
3728 APValue const &Original, APValue &Result) {
3729 // boolean must be checked before integer
3730 // since IsIntegerType() is true for bool
3731 if (SourceTy->isBooleanType()) {
3732 if (DestTy->isBooleanType()) {
3733 Result = Original;
3734 return true;
3735 }
3736 if (DestTy->isIntegerType() || DestTy->isRealFloatingType()) {
3737 bool BoolResult;
3738 if (!HandleConversionToBool(Original, BoolResult))
3739 return false;
3740 uint64_t IntResult = BoolResult;
3741 QualType IntType = DestTy->isIntegerType()
3742 ? DestTy
3743 : Info.Ctx.getIntTypeForBitwidth(64, false);
3744 Result = APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3745 }
3746 if (DestTy->isRealFloatingType()) {
3747 APValue Result2 = APValue(APFloat(0.0));
3748 if (!HandleIntToFloatCast(Info, E, FPO,
3749 Info.Ctx.getIntTypeForBitwidth(64, false),
3750 Result.getInt(), DestTy, Result2.getFloat()))
3751 return false;
3752 Result = std::move(Result2);
3753 }
3754 return true;
3755 }
3756 if (SourceTy->isIntegerType()) {
3757 if (DestTy->isRealFloatingType()) {
3758 Result = APValue(APFloat(0.0));
3759 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
3760 DestTy, Result.getFloat());
3761 }
3762 if (DestTy->isBooleanType()) {
3763 bool BoolResult;
3764 if (!HandleConversionToBool(Original, BoolResult))
3765 return false;
3766 uint64_t IntResult = BoolResult;
3767 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3768 return true;
3769 }
3770 if (DestTy->isIntegerType()) {
3771 Result = APValue(
3772 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
3773 return true;
3774 }
3775 } else if (SourceTy->isRealFloatingType()) {
3776 if (DestTy->isRealFloatingType()) {
3777 Result = Original;
3778 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
3779 Result.getFloat());
3780 }
3781 if (DestTy->isBooleanType()) {
3782 bool BoolResult;
3783 if (!HandleConversionToBool(Original, BoolResult))
3784 return false;
3785 uint64_t IntResult = BoolResult;
3786 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3787 return true;
3788 }
3789 if (DestTy->isIntegerType()) {
3790 Result = APValue(APSInt());
3791 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
3792 DestTy, Result.getInt());
3793 }
3794 }
3795
3796 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3797 return false;
3798}
3799
3800// do the heavy lifting for casting to aggregate types
3801// because we have to deal with bitfields specially
3802static bool constructAggregate(EvalInfo &Info, const FPOptions FPO,
3803 const Expr *E, APValue &Result,
3804 QualType ResultType,
3805 SmallVectorImpl<APValue> &Elements,
3806 SmallVectorImpl<QualType> &ElTypes) {
3807
3809 {&Result, ResultType, 0}};
3810
3811 unsigned ElI = 0;
3812 while (!WorkList.empty() && ElI < Elements.size()) {
3813 auto [Res, Type, BitWidth] = WorkList.pop_back_val();
3814
3815 if (Type->isRealFloatingType()) {
3816 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3817 *Res))
3818 return false;
3819 ElI++;
3820 continue;
3821 }
3822 if (Type->isIntegerType()) {
3823 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3824 *Res))
3825 return false;
3826 if (BitWidth > 0) {
3827 if (!Res->isInt())
3828 return false;
3829 APSInt &Int = Res->getInt();
3830 unsigned OldBitWidth = Int.getBitWidth();
3831 unsigned NewBitWidth = BitWidth;
3832 if (NewBitWidth < OldBitWidth)
3833 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
3834 }
3835 ElI++;
3836 continue;
3837 }
3838 if (Type->isVectorType()) {
3839 QualType ElTy = Type->castAs<VectorType>()->getElementType();
3840 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3841 SmallVector<APValue> Vals(NumEl);
3842 for (unsigned I = 0; I < NumEl; ++I) {
3843 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], ElTy, Elements[ElI],
3844 Vals[I]))
3845 return false;
3846 ElI++;
3847 }
3848 *Res = APValue(Vals.data(), NumEl);
3849 continue;
3850 }
3851 if (Type->isConstantArrayType()) {
3852 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
3853 ->getElementType();
3854 uint64_t Size =
3855 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3856 *Res = APValue(APValue::UninitArray(), Size, Size);
3857 for (int64_t I = Size - 1; I > -1; --I)
3858 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
3859 continue;
3860 }
3861 if (Type->isRecordType()) {
3862 const RecordDecl *RD = Type->getAsRecordDecl();
3863
3864 unsigned NumBases = 0;
3865 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3866 NumBases = CXXRD->getNumBases();
3867
3868 *Res = APValue(APValue::UninitStruct(), NumBases, RD->getNumFields());
3869
3871 // we need to traverse backwards
3872 // Visit the base classes.
3873 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3874 if (CXXRD->getNumBases() > 0) {
3875 assert(CXXRD->getNumBases() == 1);
3876 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3877 ReverseList.emplace_back(&Res->getStructBase(0), BS.getType(), 0u);
3878 }
3879 }
3880
3881 // Visit the fields.
3882 for (FieldDecl *FD : RD->fields()) {
3883 unsigned FDBW = 0;
3884 if (FD->isUnnamedBitField())
3885 continue;
3886 if (FD->isBitField()) {
3887 FDBW = FD->getBitWidthValue();
3888 }
3889
3890 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
3891 FD->getType(), FDBW);
3892 }
3893
3894 std::reverse(ReverseList.begin(), ReverseList.end());
3895 llvm::append_range(WorkList, ReverseList);
3896 continue;
3897 }
3898 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3899 return false;
3900 }
3901 return true;
3902}
3903
3904static bool handleElementwiseCast(EvalInfo &Info, const Expr *E,
3905 const FPOptions FPO,
3906 SmallVectorImpl<APValue> &Elements,
3907 SmallVectorImpl<QualType> &SrcTypes,
3908 SmallVectorImpl<QualType> &DestTypes,
3909 SmallVectorImpl<APValue> &Results) {
3910
3911 assert((Elements.size() == SrcTypes.size()) &&
3912 (Elements.size() == DestTypes.size()));
3913
3914 for (unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
3915 APValue Original = Elements[I];
3916 QualType SourceTy = SrcTypes[I];
3917 QualType DestTy = DestTypes[I];
3918
3919 if (!handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
3920 return false;
3921 }
3922 return true;
3923}
3924
3925static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy) {
3926
3927 SmallVector<QualType> WorkList = {BaseTy};
3928
3929 unsigned Size = 0;
3930 while (!WorkList.empty()) {
3931 QualType Type = WorkList.pop_back_val();
3933 Type->isBooleanType()) {
3934 ++Size;
3935 continue;
3936 }
3937 if (Type->isVectorType()) {
3938 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3939 Size += NumEl;
3940 continue;
3941 }
3942 if (Type->isConstantMatrixType()) {
3943 unsigned NumEl =
3944 Type->castAs<ConstantMatrixType>()->getNumElementsFlattened();
3945 Size += NumEl;
3946 continue;
3947 }
3948 if (Type->isConstantArrayType()) {
3949 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
3950 ->getElementType();
3951 uint64_t ArrSize =
3952 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3953 for (uint64_t I = 0; I < ArrSize; ++I) {
3954 WorkList.push_back(ElTy);
3955 }
3956 continue;
3957 }
3958 if (Type->isRecordType()) {
3959 const RecordDecl *RD = Type->getAsRecordDecl();
3960
3961 // Visit the base classes.
3962 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3963 if (CXXRD->getNumBases() > 0) {
3964 assert(CXXRD->getNumBases() == 1);
3965 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3966 WorkList.push_back(BS.getType());
3967 }
3968 }
3969
3970 // visit the fields.
3971 for (FieldDecl *FD : RD->fields()) {
3972 if (FD->isUnnamedBitField())
3973 continue;
3974 WorkList.push_back(FD->getType());
3975 }
3976 continue;
3977 }
3978 }
3979 return Size;
3980}
3981
3982static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal,
3983 QualType &SrcTy) {
3984 SrcTy = E->getType();
3985
3986 if (!Evaluate(SrcVal, Info, E))
3987 return false;
3988
3989 assert((SrcVal.isFloat() || SrcVal.isInt() ||
3990 (SrcVal.isVector() && SrcVal.getVectorLength() == 1)) &&
3991 "Not a valid HLSLAggregateSplatCast.");
3992
3993 if (SrcVal.isVector()) {
3994 assert(SrcTy->isVectorType() && "Type mismatch.");
3995 SrcTy = SrcTy->castAs<VectorType>()->getElementType();
3996 SrcVal = SrcVal.getVectorElt(0);
3997 }
3998 if (SrcVal.isMatrix()) {
3999 assert(SrcTy->isConstantMatrixType() && "Type mismatch.");
4000 SrcTy = SrcTy->castAs<ConstantMatrixType>()->getElementType();
4001 SrcVal = SrcVal.getMatrixElt(0, 0);
4002 }
4003 return true;
4004}
4005
4006static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value,
4007 QualType BaseTy, SmallVectorImpl<APValue> &Elements,
4008 SmallVectorImpl<QualType> &Types, unsigned Size) {
4009
4010 SmallVector<std::pair<APValue, QualType>> WorkList = {{Value, BaseTy}};
4011 unsigned Populated = 0;
4012 while (!WorkList.empty() && Populated < Size) {
4013 auto [Work, Type] = WorkList.pop_back_val();
4014
4015 if (Work.isFloat() || Work.isInt()) {
4016 Elements.push_back(Work);
4017 Types.push_back(Type);
4018 Populated++;
4019 continue;
4020 }
4021 if (Work.isVector()) {
4022 assert(Type->isVectorType() && "Type mismatch.");
4023 QualType ElTy = Type->castAs<VectorType>()->getElementType();
4024 for (unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4025 I++) {
4026 Elements.push_back(Work.getVectorElt(I));
4027 Types.push_back(ElTy);
4028 Populated++;
4029 }
4030 continue;
4031 }
4032 if (Work.isMatrix()) {
4033 assert(Type->isConstantMatrixType() && "Type mismatch.");
4034 const auto *MT = Type->castAs<ConstantMatrixType>();
4035 QualType ElTy = MT->getElementType();
4036 // Matrix elements are flattened in row-major order.
4037 for (unsigned Row = 0; Row < Work.getMatrixNumRows() && Populated < Size;
4038 Row++) {
4039 for (unsigned Col = 0;
4040 Col < Work.getMatrixNumColumns() && Populated < Size; Col++) {
4041 Elements.push_back(Work.getMatrixElt(Row, Col));
4042 Types.push_back(ElTy);
4043 Populated++;
4044 }
4045 }
4046 continue;
4047 }
4048 if (Work.isArray()) {
4049 assert(Type->isConstantArrayType() && "Type mismatch.");
4050 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4051 ->getElementType();
4052 for (int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4053 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4054 }
4055 continue;
4056 }
4057
4058 if (Work.isStruct()) {
4059 assert(Type->isRecordType() && "Type mismatch.");
4060
4061 const RecordDecl *RD = Type->getAsRecordDecl();
4062
4064 // Visit the fields.
4065 for (FieldDecl *FD : RD->fields()) {
4066 if (FD->isUnnamedBitField())
4067 continue;
4068 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4069 FD->getType());
4070 }
4071
4072 std::reverse(ReverseList.begin(), ReverseList.end());
4073 llvm::append_range(WorkList, ReverseList);
4074
4075 // Visit the base classes.
4076 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4077 if (CXXRD->getNumBases() > 0) {
4078 assert(CXXRD->getNumBases() == 1);
4079 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4080 const APValue &Base = Work.getStructBase(0);
4081
4082 // Can happen in error cases.
4083 if (!Base.isStruct())
4084 return false;
4085
4086 WorkList.emplace_back(Base, BS.getType());
4087 }
4088 }
4089 continue;
4090 }
4091 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4092 return false;
4093 }
4094 return true;
4095}
4096
4097namespace {
4098/// A handle to a complete object (an object that is not a subobject of
4099/// another object).
4100struct CompleteObject {
4101 /// The identity of the object.
4102 APValue::LValueBase Base;
4103 /// The value of the complete object.
4104 APValue *Value;
4105 /// The type of the complete object.
4106 QualType Type;
4107
4108 CompleteObject() : Value(nullptr) {}
4109 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
4110 : Base(Base), Value(Value), Type(Type) {}
4111
4112 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
4113 // If this isn't a "real" access (eg, if it's just accessing the type
4114 // info), allow it. We assume the type doesn't change dynamically for
4115 // subobjects of constexpr objects (even though we'd hit UB here if it
4116 // did). FIXME: Is this right?
4117 if (!isAnyAccess(AK))
4118 return true;
4119
4120 // In C++14 onwards, it is permitted to read a mutable member whose
4121 // lifetime began within the evaluation.
4122 // FIXME: Should we also allow this in C++11?
4123 if (!Info.getLangOpts().CPlusPlus14 &&
4124 AK != AccessKinds::AK_IsWithinLifetime)
4125 return false;
4126 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
4127 }
4128
4129 explicit operator bool() const { return !Type.isNull(); }
4130};
4131} // end anonymous namespace
4132
4133static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
4134 bool IsMutable = false) {
4135 // C++ [basic.type.qualifier]p1:
4136 // - A const object is an object of type const T or a non-mutable subobject
4137 // of a const object.
4138 if (ObjType.isConstQualified() && !IsMutable)
4139 SubobjType.addConst();
4140 // - A volatile object is an object of type const T or a subobject of a
4141 // volatile object.
4142 if (ObjType.isVolatileQualified())
4143 SubobjType.addVolatile();
4144 return SubobjType;
4145}
4146
4147/// Find the designated sub-object of an rvalue.
4148template <typename SubobjectHandler>
4149static typename SubobjectHandler::result_type
4150findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
4151 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4152 if (Sub.Invalid)
4153 // A diagnostic will have already been produced.
4154 return handler.failed();
4155 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4156 if (Info.getLangOpts().CPlusPlus11)
4157 Info.FFDiag(E, Sub.isOnePastTheEnd()
4158 ? diag::note_constexpr_access_past_end
4159 : diag::note_constexpr_access_unsized_array)
4160 << handler.AccessKind;
4161 else
4162 Info.FFDiag(E);
4163 return handler.failed();
4164 }
4165
4166 APValue *O = Obj.Value;
4167 QualType ObjType = Obj.Type;
4168 const FieldDecl *LastField = nullptr;
4169 const FieldDecl *VolatileField = nullptr;
4170
4171 // Walk the designator's path to find the subobject.
4172 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
4173 // Reading an indeterminate value is undefined, but assigning over one is OK.
4174 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
4175 (O->isIndeterminate() &&
4176 !isValidIndeterminateAccess(handler.AccessKind))) {
4177 // Object has ended lifetime.
4178 // If I is non-zero, some subobject (member or array element) of a
4179 // complete object has ended its lifetime, so this is valid for
4180 // IsWithinLifetime, resulting in false.
4181 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
4182 return false;
4183 if (!Info.checkingPotentialConstantExpression())
4184 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4185 << handler.AccessKind << O->isIndeterminate()
4186 << E->getSourceRange();
4187 return handler.failed();
4188 }
4189
4190 // C++ [class.ctor]p5, C++ [class.dtor]p5:
4191 // const and volatile semantics are not applied on an object under
4192 // {con,de}struction.
4193 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
4194 ObjType->isRecordType() &&
4195 Info.isEvaluatingCtorDtor(
4196 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
4197 ConstructionPhase::None) {
4198 ObjType = Info.Ctx.getCanonicalType(ObjType);
4199 ObjType.removeLocalConst();
4200 ObjType.removeLocalVolatile();
4201 }
4202
4203 // If this is our last pass, check that the final object type is OK.
4204 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
4205 // Accesses to volatile objects are prohibited.
4206 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
4207 if (Info.getLangOpts().CPlusPlus) {
4208 int DiagKind;
4209 SourceLocation Loc;
4210 const NamedDecl *Decl = nullptr;
4211 if (VolatileField) {
4212 DiagKind = 2;
4213 Loc = VolatileField->getLocation();
4214 Decl = VolatileField;
4215 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
4216 DiagKind = 1;
4217 Loc = VD->getLocation();
4218 Decl = VD;
4219 } else {
4220 DiagKind = 0;
4221 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
4222 Loc = E->getExprLoc();
4223 }
4224 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
4225 << handler.AccessKind << DiagKind << Decl;
4226 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4227 } else {
4228 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4229 }
4230 return handler.failed();
4231 }
4232
4233 // If we are reading an object of class type, there may still be more
4234 // things we need to check: if there are any mutable subobjects, we
4235 // cannot perform this read. (This only happens when performing a trivial
4236 // copy or assignment.)
4237 if (ObjType->isRecordType() &&
4238 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4239 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4240 return handler.failed();
4241 }
4242
4243 if (I == N) {
4244 if (!handler.found(*O, ObjType))
4245 return false;
4246
4247 // If we modified a bit-field, truncate it to the right width.
4248 if (isModification(handler.AccessKind) &&
4249 LastField && LastField->isBitField() &&
4250 !truncateBitfieldValue(Info, E, *O, LastField))
4251 return false;
4252
4253 return true;
4254 }
4255
4256 LastField = nullptr;
4257 if (ObjType->isArrayType()) {
4258 // Next subobject is an array element.
4259 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
4261 "vla in literal type?");
4262 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4263 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4264 CAT && CAT->getSize().ule(Index)) {
4265 // Note, it should not be possible to form a pointer with a valid
4266 // designator which points more than one past the end of the array.
4267 if (Info.getLangOpts().CPlusPlus11)
4268 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4269 << handler.AccessKind;
4270 else
4271 Info.FFDiag(E);
4272 return handler.failed();
4273 }
4274
4275 ObjType = AT->getElementType();
4276
4277 if (O->getArrayInitializedElts() > Index)
4278 O = &O->getArrayInitializedElt(Index);
4279 else if (!isRead(handler.AccessKind)) {
4280 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4281 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4282 return handler.failed();
4283
4284 expandArray(*O, Index);
4285 O = &O->getArrayInitializedElt(Index);
4286 } else
4287 O = &O->getArrayFiller();
4288 } else if (ObjType->isAnyComplexType()) {
4289 // Next subobject is a complex number.
4290 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4291 if (Index > 1) {
4292 if (Info.getLangOpts().CPlusPlus11)
4293 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4294 << handler.AccessKind;
4295 else
4296 Info.FFDiag(E);
4297 return handler.failed();
4298 }
4299
4300 ObjType = getSubobjectType(
4301 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4302
4303 assert(I == N - 1 && "extracting subobject of scalar?");
4304 if (O->isComplexInt()) {
4305 return handler.found(Index ? O->getComplexIntImag()
4306 : O->getComplexIntReal(), ObjType);
4307 } else {
4308 assert(O->isComplexFloat());
4309 return handler.found(Index ? O->getComplexFloatImag()
4310 : O->getComplexFloatReal(), ObjType);
4311 }
4312 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4313 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4314 unsigned NumElements = VT->getNumElements();
4315 if (Index == NumElements) {
4316 if (Info.getLangOpts().CPlusPlus11)
4317 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4318 << handler.AccessKind;
4319 else
4320 Info.FFDiag(E);
4321 return handler.failed();
4322 }
4323
4324 if (Index > NumElements) {
4325 Info.CCEDiag(E, diag::note_constexpr_array_index)
4326 << Index << /*array*/ 0 << NumElements;
4327 return handler.failed();
4328 }
4329
4330 ObjType = VT->getElementType();
4331 assert(I == N - 1 && "extracting subobject of scalar?");
4332
4333 if (O->isIndeterminate()) {
4334 if (isRead(handler.AccessKind)) {
4335 Info.FFDiag(E);
4336 return handler.failed();
4337 }
4338 expandVector(*O, NumElements);
4339 }
4340 assert(O->isVector() && "unexpected object during vector element access");
4341 return handler.found(O->getVectorElt(Index), ObjType);
4342 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4343 if (Field->isMutable() &&
4344 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4345 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4346 << handler.AccessKind << Field;
4347 Info.Note(Field->getLocation(), diag::note_declared_at);
4348 return handler.failed();
4349 }
4350
4351 // Next subobject is a class, struct or union field.
4352 RecordDecl *RD = ObjType->castAsCanonical<RecordType>()->getDecl();
4353 if (RD->isUnion()) {
4354 const FieldDecl *UnionField = O->getUnionField();
4355 if (!UnionField ||
4356 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4357 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4358 // Placement new onto an inactive union member makes it active.
4359 O->setUnion(Field, APValue());
4360 } else {
4361 // Pointer to/into inactive union member: Not within lifetime
4362 if (handler.AccessKind == AK_IsWithinLifetime)
4363 return false;
4364 // FIXME: If O->getUnionValue() is absent, report that there's no
4365 // active union member rather than reporting the prior active union
4366 // member. We'll need to fix nullptr_t to not use APValue() as its
4367 // representation first.
4368 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4369 << handler.AccessKind << Field << !UnionField << UnionField;
4370 return handler.failed();
4371 }
4372 }
4373 O = &O->getUnionValue();
4374 } else
4375 O = &O->getStructField(Field->getFieldIndex());
4376
4377 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4378 LastField = Field;
4379 if (Field->getType().isVolatileQualified())
4380 VolatileField = Field;
4381 } else {
4382 // Next subobject is a base class.
4383 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4384 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4385 O = &O->getStructBase(getBaseIndex(Derived, Base));
4386
4387 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4388 }
4389 }
4390}
4391
4392namespace {
4393struct ExtractSubobjectHandler {
4394 EvalInfo &Info;
4395 const Expr *E;
4396 APValue &Result;
4397 const AccessKinds AccessKind;
4398
4399 typedef bool result_type;
4400 bool failed() { return false; }
4401 bool found(APValue &Subobj, QualType SubobjType) {
4402 Result = Subobj;
4403 if (AccessKind == AK_ReadObjectRepresentation)
4404 return true;
4405 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4406 }
4407 bool found(APSInt &Value, QualType SubobjType) {
4408 Result = APValue(Value);
4409 return true;
4410 }
4411 bool found(APFloat &Value, QualType SubobjType) {
4412 Result = APValue(Value);
4413 return true;
4414 }
4415};
4416} // end anonymous namespace
4417
4418/// Extract the designated sub-object of an rvalue.
4419static bool extractSubobject(EvalInfo &Info, const Expr *E,
4420 const CompleteObject &Obj,
4421 const SubobjectDesignator &Sub, APValue &Result,
4422 AccessKinds AK = AK_Read) {
4423 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4424 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4425 return findSubobject(Info, E, Obj, Sub, Handler);
4426}
4427
4428namespace {
4429struct ModifySubobjectHandler {
4430 EvalInfo &Info;
4431 APValue &NewVal;
4432 const Expr *E;
4433
4434 typedef bool result_type;
4435 static const AccessKinds AccessKind = AK_Assign;
4436
4437 bool checkConst(QualType QT) {
4438 // Assigning to a const object has undefined behavior.
4439 if (QT.isConstQualified()) {
4440 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4441 return false;
4442 }
4443 return true;
4444 }
4445
4446 bool failed() { return false; }
4447 bool found(APValue &Subobj, QualType SubobjType) {
4448 if (!checkConst(SubobjType))
4449 return false;
4450 // We've been given ownership of NewVal, so just swap it in.
4451 Subobj.swap(NewVal);
4452 return true;
4453 }
4454 bool found(APSInt &Value, QualType SubobjType) {
4455 if (!checkConst(SubobjType))
4456 return false;
4457 if (!NewVal.isInt()) {
4458 // Maybe trying to write a cast pointer value into a complex?
4459 Info.FFDiag(E);
4460 return false;
4461 }
4462 Value = NewVal.getInt();
4463 return true;
4464 }
4465 bool found(APFloat &Value, QualType SubobjType) {
4466 if (!checkConst(SubobjType))
4467 return false;
4468 Value = NewVal.getFloat();
4469 return true;
4470 }
4471};
4472} // end anonymous namespace
4473
4474const AccessKinds ModifySubobjectHandler::AccessKind;
4475
4476/// Update the designated sub-object of an rvalue to the given value.
4477static bool modifySubobject(EvalInfo &Info, const Expr *E,
4478 const CompleteObject &Obj,
4479 const SubobjectDesignator &Sub,
4480 APValue &NewVal) {
4481 ModifySubobjectHandler Handler = { Info, NewVal, E };
4482 return findSubobject(Info, E, Obj, Sub, Handler);
4483}
4484
4485/// Find the position where two subobject designators diverge, or equivalently
4486/// the length of the common initial subsequence.
4487static unsigned FindDesignatorMismatch(QualType ObjType,
4488 const SubobjectDesignator &A,
4489 const SubobjectDesignator &B,
4490 bool &WasArrayIndex) {
4491 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4492 for (/**/; I != N; ++I) {
4493 if (!ObjType.isNull() &&
4494 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4495 // Next subobject is an array element.
4496 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4497 WasArrayIndex = true;
4498 return I;
4499 }
4500 if (ObjType->isAnyComplexType())
4501 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4502 else
4503 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4504 } else {
4505 if (A.Entries[I].getAsBaseOrMember() !=
4506 B.Entries[I].getAsBaseOrMember()) {
4507 WasArrayIndex = false;
4508 return I;
4509 }
4510 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4511 // Next subobject is a field.
4512 ObjType = FD->getType();
4513 else
4514 // Next subobject is a base class.
4515 ObjType = QualType();
4516 }
4517 }
4518 WasArrayIndex = false;
4519 return I;
4520}
4521
4522/// Determine whether the given subobject designators refer to elements of the
4523/// same array object.
4525 const SubobjectDesignator &A,
4526 const SubobjectDesignator &B) {
4527 if (A.Entries.size() != B.Entries.size())
4528 return false;
4529
4530 bool IsArray = A.MostDerivedIsArrayElement;
4531 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4532 // A is a subobject of the array element.
4533 return false;
4534
4535 // If A (and B) designates an array element, the last entry will be the array
4536 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4537 // of length 1' case, and the entire path must match.
4538 bool WasArrayIndex;
4539 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4540 return CommonLength >= A.Entries.size() - IsArray;
4541}
4542
4543/// Find the complete object to which an LValue refers.
4544static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4545 AccessKinds AK, const LValue &LVal,
4546 QualType LValType) {
4547 if (LVal.InvalidBase) {
4548 Info.FFDiag(E);
4549 return CompleteObject();
4550 }
4551
4552 if (!LVal.Base) {
4554 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4555 else
4556 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4557 return CompleteObject();
4558 }
4559
4560 CallStackFrame *Frame = nullptr;
4561 unsigned Depth = 0;
4562 if (LVal.getLValueCallIndex()) {
4563 std::tie(Frame, Depth) =
4564 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4565 if (!Frame) {
4566 Info.FFDiag(E, diag::note_constexpr_access_uninit, 1)
4567 << AK << /*Indeterminate=*/false << E->getSourceRange();
4568 NoteLValueLocation(Info, LVal.Base);
4569 return CompleteObject();
4570 }
4571 }
4572
4573 bool IsAccess = isAnyAccess(AK);
4574
4575 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4576 // is not a constant expression (even if the object is non-volatile). We also
4577 // apply this rule to C++98, in order to conform to the expected 'volatile'
4578 // semantics.
4579 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4580 if (Info.getLangOpts().CPlusPlus)
4581 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4582 << AK << LValType;
4583 else
4584 Info.FFDiag(E);
4585 return CompleteObject();
4586 }
4587
4588 // Compute value storage location and type of base object.
4589 APValue *BaseVal = nullptr;
4590 QualType BaseType = getType(LVal.Base);
4591
4592 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4593 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4594 // This is the object whose initializer we're evaluating, so its lifetime
4595 // started in the current evaluation.
4596 BaseVal = Info.EvaluatingDeclValue;
4597 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4598 // Allow reading from a GUID declaration.
4599 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4600 if (isModification(AK)) {
4601 // All the remaining cases do not permit modification of the object.
4602 Info.FFDiag(E, diag::note_constexpr_modify_global);
4603 return CompleteObject();
4604 }
4605 APValue &V = GD->getAsAPValue();
4606 if (V.isAbsent()) {
4607 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4608 << GD->getType();
4609 return CompleteObject();
4610 }
4611 return CompleteObject(LVal.Base, &V, GD->getType());
4612 }
4613
4614 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4615 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4616 if (isModification(AK)) {
4617 Info.FFDiag(E, diag::note_constexpr_modify_global);
4618 return CompleteObject();
4619 }
4620 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4621 GCD->getType());
4622 }
4623
4624 // Allow reading from template parameter objects.
4625 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4626 if (isModification(AK)) {
4627 Info.FFDiag(E, diag::note_constexpr_modify_global);
4628 return CompleteObject();
4629 }
4630 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4631 TPO->getType());
4632 }
4633
4634 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4635 // In C++11, constexpr, non-volatile variables initialized with constant
4636 // expressions are constant expressions too. Inside constexpr functions,
4637 // parameters are constant expressions even if they're non-const.
4638 // In C++1y, objects local to a constant expression (those with a Frame) are
4639 // both readable and writable inside constant expressions.
4640 // In C, such things can also be folded, although they are not ICEs.
4641 const VarDecl *VD = dyn_cast<VarDecl>(D);
4642 if (VD) {
4643 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4644 VD = VDef;
4645 }
4646 if (!VD || VD->isInvalidDecl()) {
4647 Info.FFDiag(E);
4648 return CompleteObject();
4649 }
4650
4651 bool IsConstant = BaseType.isConstant(Info.Ctx);
4652 bool ConstexprVar = false;
4653 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4654 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4655 ConstexprVar = VD->isConstexpr();
4656
4657 // Unless we're looking at a local variable or argument in a constexpr call,
4658 // the variable we're reading must be const (unless we are binding to a
4659 // reference).
4660 if (AK != clang::AK_Dereference && !Frame) {
4661 if (IsAccess && isa<ParmVarDecl>(VD)) {
4662 // Access of a parameter that's not associated with a frame isn't going
4663 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4664 // suitable diagnostic.
4665 } else if (Info.getLangOpts().CPlusPlus14 &&
4666 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4667 // OK, we can read and modify an object if we're in the process of
4668 // evaluating its initializer, because its lifetime began in this
4669 // evaluation.
4670 } else 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 } else if (VD->isConstexpr()) {
4675 // OK, we can read this variable.
4676 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4677 Info.FFDiag(E);
4678 return CompleteObject();
4679 } else if (BaseType->isIntegralOrEnumerationType()) {
4680 if (!IsConstant) {
4681 if (!IsAccess)
4682 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4683 if (Info.getLangOpts().CPlusPlus) {
4684 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4685 Info.Note(VD->getLocation(), diag::note_declared_at);
4686 } else {
4687 Info.FFDiag(E);
4688 }
4689 return CompleteObject();
4690 }
4691 } else if (!IsAccess) {
4692 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4693 } else if ((IsConstant || BaseType->isReferenceType()) &&
4694 Info.checkingPotentialConstantExpression() &&
4695 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4696 // This variable might end up being constexpr. Don't diagnose it yet.
4697 } else if (IsConstant) {
4698 // Keep evaluating to see what we can do. In particular, we support
4699 // folding of const floating-point types, in order to make static const
4700 // data members of such types (supported as an extension) more useful.
4701 if (Info.getLangOpts().CPlusPlus) {
4702 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4703 ? diag::note_constexpr_ltor_non_constexpr
4704 : diag::note_constexpr_ltor_non_integral, 1)
4705 << VD << BaseType;
4706 Info.Note(VD->getLocation(), diag::note_declared_at);
4707 } else {
4708 Info.CCEDiag(E);
4709 }
4710 } else {
4711 // Never allow reading a non-const value.
4712 if (Info.getLangOpts().CPlusPlus) {
4713 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4714 ? diag::note_constexpr_ltor_non_constexpr
4715 : diag::note_constexpr_ltor_non_integral, 1)
4716 << VD << BaseType;
4717 Info.Note(VD->getLocation(), diag::note_declared_at);
4718 } else {
4719 Info.FFDiag(E);
4720 }
4721 return CompleteObject();
4722 }
4723 }
4724
4725 // When binding to a reference, the variable does not need to be constexpr
4726 // or have constant initalization.
4727 if (AK != clang::AK_Dereference &&
4728 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4729 BaseVal))
4730 return CompleteObject();
4731 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4732 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4733 // we can't access a constexpr-unknown object.
4734 if (AK != clang::AK_Dereference && !BaseVal) {
4735 if (!Info.checkingPotentialConstantExpression()) {
4736 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4737 << AK << VD;
4738 Info.Note(VD->getLocation(), diag::note_declared_at);
4739 }
4740 return CompleteObject();
4741 }
4742 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4743 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4744 if (!Alloc) {
4745 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4746 return CompleteObject();
4747 }
4748 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4749 LVal.Base.getDynamicAllocType());
4750 }
4751 // When binding to a reference, the variable does not need to be
4752 // within its lifetime.
4753 else if (AK != clang::AK_Dereference) {
4754 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4755
4756 if (!Frame) {
4757 if (const MaterializeTemporaryExpr *MTE =
4758 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4759 assert(MTE->getStorageDuration() == SD_Static &&
4760 "should have a frame for a non-global materialized temporary");
4761
4762 // C++20 [expr.const]p4: [DR2126]
4763 // An object or reference is usable in constant expressions if it is
4764 // - a temporary object of non-volatile const-qualified literal type
4765 // whose lifetime is extended to that of a variable that is usable
4766 // in constant expressions
4767 //
4768 // C++20 [expr.const]p5:
4769 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4770 // - a non-volatile glvalue that refers to an object that is usable
4771 // in constant expressions, or
4772 // - a non-volatile glvalue of literal type that refers to a
4773 // non-volatile object whose lifetime began within the evaluation
4774 // of E;
4775 //
4776 // C++11 misses the 'began within the evaluation of e' check and
4777 // instead allows all temporaries, including things like:
4778 // int &&r = 1;
4779 // int x = ++r;
4780 // constexpr int k = r;
4781 // Therefore we use the C++14-onwards rules in C++11 too.
4782 //
4783 // Note that temporaries whose lifetimes began while evaluating a
4784 // variable's constructor are not usable while evaluating the
4785 // corresponding destructor, not even if they're of const-qualified
4786 // types.
4787 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4788 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4789 if (!IsAccess)
4790 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4791 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4792 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4793 return CompleteObject();
4794 }
4795
4796 BaseVal = MTE->getOrCreateValue(false);
4797 assert(BaseVal && "got reference to unevaluated temporary");
4798 } else if (const CompoundLiteralExpr *CLE =
4799 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4800 // According to GCC info page:
4801 //
4802 // 6.28 Compound Literals
4803 //
4804 // As an optimization, G++ sometimes gives array compound literals
4805 // longer lifetimes: when the array either appears outside a function or
4806 // has a const-qualified type. If foo and its initializer had elements
4807 // of type char *const rather than char *, or if foo were a global
4808 // variable, the array would have static storage duration. But it is
4809 // probably safest just to avoid the use of array compound literals in
4810 // C++ code.
4811 //
4812 // Obey that rule by checking constness for converted array types.
4813 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4814 !LValType->isArrayType() &&
4815 !CLETy.isConstant(Info.Ctx)) {
4816 Info.FFDiag(E);
4817 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4818 return CompleteObject();
4819 }
4820
4821 BaseVal = &CLE->getStaticValue();
4822 } else {
4823 if (!IsAccess)
4824 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4825 APValue Val;
4826 LVal.moveInto(Val);
4827 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4828 << AK
4829 << Val.getAsString(Info.Ctx,
4830 Info.Ctx.getLValueReferenceType(LValType));
4831 NoteLValueLocation(Info, LVal.Base);
4832 return CompleteObject();
4833 }
4834 } else if (AK != clang::AK_Dereference) {
4835 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4836 assert(BaseVal && "missing value for temporary");
4837 }
4838 }
4839
4840 // In C++14, we can't safely access any mutable state when we might be
4841 // evaluating after an unmodeled side effect. Parameters are modeled as state
4842 // in the caller, but aren't visible once the call returns, so they can be
4843 // modified in a speculatively-evaluated call.
4844 //
4845 // FIXME: Not all local state is mutable. Allow local constant subobjects
4846 // to be read here (but take care with 'mutable' fields).
4847 unsigned VisibleDepth = Depth;
4848 if (llvm::isa_and_nonnull<ParmVarDecl>(
4849 LVal.Base.dyn_cast<const ValueDecl *>()))
4850 ++VisibleDepth;
4851 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4852 Info.EvalStatus.HasSideEffects) ||
4853 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4854 return CompleteObject();
4855
4856 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4857}
4858
4859/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4860/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4861/// glvalue referred to by an entity of reference type.
4862///
4863/// \param Info - Information about the ongoing evaluation.
4864/// \param Conv - The expression for which we are performing the conversion.
4865/// Used for diagnostics.
4866/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4867/// case of a non-class type).
4868/// \param LVal - The glvalue on which we are attempting to perform this action.
4869/// \param RVal - The produced value will be placed here.
4870/// \param WantObjectRepresentation - If true, we're looking for the object
4871/// representation rather than the value, and in particular,
4872/// there is no requirement that the result be fully initialized.
4873static bool
4875 const LValue &LVal, APValue &RVal,
4876 bool WantObjectRepresentation = false) {
4877 if (LVal.Designator.Invalid)
4878 return false;
4879
4880 // Check for special cases where there is no existing APValue to look at.
4881 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4882
4883 AccessKinds AK =
4884 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4885
4886 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4888 // Special-case character extraction so we don't have to construct an
4889 // APValue for the whole string.
4890 assert(LVal.Designator.Entries.size() <= 1 &&
4891 "Can only read characters from string literals");
4892 if (LVal.Designator.Entries.empty()) {
4893 // Fail for now for LValue to RValue conversion of an array.
4894 // (This shouldn't show up in C/C++, but it could be triggered by a
4895 // weird EvaluateAsRValue call from a tool.)
4896 Info.FFDiag(Conv);
4897 return false;
4898 }
4899 if (LVal.Designator.isOnePastTheEnd()) {
4900 if (Info.getLangOpts().CPlusPlus11)
4901 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4902 else
4903 Info.FFDiag(Conv);
4904 return false;
4905 }
4906 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4907 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4908 return true;
4909 }
4910 }
4911
4912 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4913 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4914}
4915
4916static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E,
4917 QualType DestTy,
4918 SmallVectorImpl<APValue> &SrcVals,
4919 SmallVectorImpl<QualType> &SrcTypes) {
4920 APValue Val;
4921 if (!Evaluate(Val, Info, E))
4922 return false;
4923
4924 // must be dealing with a record
4925 if (Val.isLValue()) {
4926 LValue LVal;
4927 LVal.setFrom(Info.Ctx, Val);
4928 if (!handleLValueToRValueConversion(Info, E, E->getType(), LVal, Val))
4929 return false;
4930 }
4931
4932 unsigned NEls = elementwiseSize(Info, DestTy);
4933 // flatten the source
4934 if (!flattenAPValue(Info, E, Val, E->getType(), SrcVals, SrcTypes, NEls))
4935 return false;
4936
4937 return true;
4938}
4939
4940/// Perform an assignment of Val to LVal. Takes ownership of Val.
4941static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4942 QualType LValType, APValue &Val) {
4943 if (LVal.Designator.Invalid)
4944 return false;
4945
4946 if (!Info.getLangOpts().CPlusPlus14) {
4947 Info.FFDiag(E);
4948 return false;
4949 }
4950
4951 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4952 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4953}
4954
4955namespace {
4956struct CompoundAssignSubobjectHandler {
4957 EvalInfo &Info;
4958 const CompoundAssignOperator *E;
4959 QualType PromotedLHSType;
4961 const APValue &RHS;
4962
4963 static const AccessKinds AccessKind = AK_Assign;
4964
4965 typedef bool result_type;
4966
4967 bool checkConst(QualType QT) {
4968 // Assigning to a const object has undefined behavior.
4969 if (QT.isConstQualified()) {
4970 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4971 return false;
4972 }
4973 return true;
4974 }
4975
4976 bool failed() { return false; }
4977 bool found(APValue &Subobj, QualType SubobjType) {
4978 switch (Subobj.getKind()) {
4979 case APValue::Int:
4980 return found(Subobj.getInt(), SubobjType);
4981 case APValue::Float:
4982 return found(Subobj.getFloat(), SubobjType);
4985 // FIXME: Implement complex compound assignment.
4986 Info.FFDiag(E);
4987 return false;
4988 case APValue::LValue:
4989 return foundPointer(Subobj, SubobjType);
4990 case APValue::Vector:
4991 return foundVector(Subobj, SubobjType);
4993 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4994 << /*read of=*/0 << /*uninitialized object=*/1
4995 << E->getLHS()->getSourceRange();
4996 return false;
4997 default:
4998 // FIXME: can this happen?
4999 Info.FFDiag(E);
5000 return false;
5001 }
5002 }
5003
5004 bool foundVector(APValue &Value, QualType SubobjType) {
5005 if (!checkConst(SubobjType))
5006 return false;
5007
5008 if (!SubobjType->isVectorType()) {
5009 Info.FFDiag(E);
5010 return false;
5011 }
5012 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
5013 }
5014
5015 bool found(APSInt &Value, QualType SubobjType) {
5016 if (!checkConst(SubobjType))
5017 return false;
5018
5019 if (!SubobjType->isIntegerType()) {
5020 // We don't support compound assignment on integer-cast-to-pointer
5021 // values.
5022 Info.FFDiag(E);
5023 return false;
5024 }
5025
5026 if (RHS.isInt()) {
5027 APSInt LHS =
5028 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
5029 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
5030 return false;
5031 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
5032 return true;
5033 } else if (RHS.isFloat()) {
5034 const FPOptions FPO = E->getFPFeaturesInEffect(
5035 Info.Ctx.getLangOpts());
5036 APFloat FValue(0.0);
5037 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
5038 PromotedLHSType, FValue) &&
5039 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
5040 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
5041 Value);
5042 }
5043
5044 Info.FFDiag(E);
5045 return false;
5046 }
5047 bool found(APFloat &Value, QualType SubobjType) {
5048 return checkConst(SubobjType) &&
5049 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
5050 Value) &&
5051 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
5052 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
5053 }
5054 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5055 if (!checkConst(SubobjType))
5056 return false;
5057
5058 QualType PointeeType;
5059 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5060 PointeeType = PT->getPointeeType();
5061
5062 if (PointeeType.isNull() || !RHS.isInt() ||
5063 (Opcode != BO_Add && Opcode != BO_Sub)) {
5064 Info.FFDiag(E);
5065 return false;
5066 }
5067
5068 APSInt Offset = RHS.getInt();
5069 if (Opcode == BO_Sub)
5070 negateAsSigned(Offset);
5071
5072 LValue LVal;
5073 LVal.setFrom(Info.Ctx, Subobj);
5074 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
5075 return false;
5076 LVal.moveInto(Subobj);
5077 return true;
5078 }
5079};
5080} // end anonymous namespace
5081
5082const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5083
5084/// Perform a compound assignment of LVal <op>= RVal.
5085static bool handleCompoundAssignment(EvalInfo &Info,
5086 const CompoundAssignOperator *E,
5087 const LValue &LVal, QualType LValType,
5088 QualType PromotedLValType,
5089 BinaryOperatorKind Opcode,
5090 const APValue &RVal) {
5091 if (LVal.Designator.Invalid)
5092 return false;
5093
5094 if (!Info.getLangOpts().CPlusPlus14) {
5095 Info.FFDiag(E);
5096 return false;
5097 }
5098
5099 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5100 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5101 RVal };
5102 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5103}
5104
5105namespace {
5106struct IncDecSubobjectHandler {
5107 EvalInfo &Info;
5108 const UnaryOperator *E;
5110 APValue *Old;
5111
5112 typedef bool result_type;
5113
5114 bool checkConst(QualType QT) {
5115 // Assigning to a const object has undefined behavior.
5116 if (QT.isConstQualified()) {
5117 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5118 return false;
5119 }
5120 return true;
5121 }
5122
5123 bool failed() { return false; }
5124 bool found(APValue &Subobj, QualType SubobjType) {
5125 // Stash the old value. Also clear Old, so we don't clobber it later
5126 // if we're post-incrementing a complex.
5127 if (Old) {
5128 *Old = Subobj;
5129 Old = nullptr;
5130 }
5131
5132 switch (Subobj.getKind()) {
5133 case APValue::Int:
5134 return found(Subobj.getInt(), SubobjType);
5135 case APValue::Float:
5136 return found(Subobj.getFloat(), SubobjType);
5138 return found(Subobj.getComplexIntReal(),
5139 SubobjType->castAs<ComplexType>()->getElementType()
5140 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5142 return found(Subobj.getComplexFloatReal(),
5143 SubobjType->castAs<ComplexType>()->getElementType()
5144 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5145 case APValue::LValue:
5146 return foundPointer(Subobj, SubobjType);
5147 default:
5148 // FIXME: can this happen?
5149 Info.FFDiag(E);
5150 return false;
5151 }
5152 }
5153 bool found(APSInt &Value, QualType SubobjType) {
5154 if (!checkConst(SubobjType))
5155 return false;
5156
5157 if (!SubobjType->isIntegerType()) {
5158 // We don't support increment / decrement on integer-cast-to-pointer
5159 // values.
5160 Info.FFDiag(E);
5161 return false;
5162 }
5163
5164 if (Old) *Old = APValue(Value);
5165
5166 // bool arithmetic promotes to int, and the conversion back to bool
5167 // doesn't reduce mod 2^n, so special-case it.
5168 if (SubobjType->isBooleanType()) {
5169 if (AccessKind == AK_Increment)
5170 Value = 1;
5171 else
5172 Value = !Value;
5173 return true;
5174 }
5175
5176 bool WasNegative = Value.isNegative();
5177 if (AccessKind == AK_Increment) {
5178 ++Value;
5179
5180 if (!WasNegative && Value.isNegative() && E->canOverflow() &&
5181 !SubobjType.isWrapType()) {
5182 APSInt ActualValue(Value, /*IsUnsigned*/true);
5183 return HandleOverflow(Info, E, ActualValue, SubobjType);
5184 }
5185 } else {
5186 --Value;
5187
5188 if (WasNegative && !Value.isNegative() && E->canOverflow() &&
5189 !SubobjType.isWrapType()) {
5190 unsigned BitWidth = Value.getBitWidth();
5191 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
5192 ActualValue.setBit(BitWidth);
5193 return HandleOverflow(Info, E, ActualValue, SubobjType);
5194 }
5195 }
5196 return true;
5197 }
5198 bool found(APFloat &Value, QualType SubobjType) {
5199 if (!checkConst(SubobjType))
5200 return false;
5201
5202 if (Old) *Old = APValue(Value);
5203
5204 APFloat One(Value.getSemantics(), 1);
5205 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
5206 APFloat::opStatus St;
5207 if (AccessKind == AK_Increment)
5208 St = Value.add(One, RM);
5209 else
5210 St = Value.subtract(One, RM);
5211 return checkFloatingPointResult(Info, E, St);
5212 }
5213 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5214 if (!checkConst(SubobjType))
5215 return false;
5216
5217 QualType PointeeType;
5218 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5219 PointeeType = PT->getPointeeType();
5220 else {
5221 Info.FFDiag(E);
5222 return false;
5223 }
5224
5225 LValue LVal;
5226 LVal.setFrom(Info.Ctx, Subobj);
5227 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
5228 AccessKind == AK_Increment ? 1 : -1))
5229 return false;
5230 LVal.moveInto(Subobj);
5231 return true;
5232 }
5233};
5234} // end anonymous namespace
5235
5236/// Perform an increment or decrement on LVal.
5237static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
5238 QualType LValType, bool IsIncrement, APValue *Old) {
5239 if (LVal.Designator.Invalid)
5240 return false;
5241
5242 if (!Info.getLangOpts().CPlusPlus14) {
5243 Info.FFDiag(E);
5244 return false;
5245 }
5246
5247 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
5248 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
5249 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
5250 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5251}
5252
5253/// Build an lvalue for the object argument of a member function call.
5254static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
5255 LValue &This) {
5256 if (Object->getType()->isPointerType() && Object->isPRValue())
5257 return EvaluatePointer(Object, This, Info);
5258
5259 if (Object->isGLValue())
5260 return EvaluateLValue(Object, This, Info);
5261
5262 if (Object->getType()->isLiteralType(Info.Ctx))
5263 return EvaluateTemporary(Object, This, Info);
5264
5265 if (Object->getType()->isRecordType() && Object->isPRValue())
5266 return EvaluateTemporary(Object, This, Info);
5267
5268 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5269 return false;
5270}
5271
5272/// HandleMemberPointerAccess - Evaluate a member access operation and build an
5273/// lvalue referring to the result.
5274///
5275/// \param Info - Information about the ongoing evaluation.
5276/// \param LV - An lvalue referring to the base of the member pointer.
5277/// \param RHS - The member pointer expression.
5278/// \param IncludeMember - Specifies whether the member itself is included in
5279/// the resulting LValue subobject designator. This is not possible when
5280/// creating a bound member function.
5281/// \return The field or method declaration to which the member pointer refers,
5282/// or 0 if evaluation fails.
5283static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5284 QualType LVType,
5285 LValue &LV,
5286 const Expr *RHS,
5287 bool IncludeMember = true) {
5288 MemberPtr MemPtr;
5289 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5290 return nullptr;
5291
5292 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5293 // member value, the behavior is undefined.
5294 if (!MemPtr.getDecl()) {
5295 // FIXME: Specific diagnostic.
5296 Info.FFDiag(RHS);
5297 return nullptr;
5298 }
5299
5300 if (MemPtr.isDerivedMember()) {
5301 // This is a member of some derived class. Truncate LV appropriately.
5302 // The end of the derived-to-base path for the base object must match the
5303 // derived-to-base path for the member pointer.
5304 // C++23 [expr.mptr.oper]p4:
5305 // If the result of E1 is an object [...] whose most derived object does
5306 // not contain the member to which E2 refers, the behavior is undefined.
5307 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5308 LV.Designator.Entries.size()) {
5309 Info.FFDiag(RHS);
5310 return nullptr;
5311 }
5312 unsigned PathLengthToMember =
5313 LV.Designator.Entries.size() - MemPtr.Path.size();
5314 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5315 const CXXRecordDecl *LVDecl = getAsBaseClass(
5316 LV.Designator.Entries[PathLengthToMember + I]);
5317 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5318 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5319 Info.FFDiag(RHS);
5320 return nullptr;
5321 }
5322 }
5323 // MemPtr.Path only contains the base classes of the class directly
5324 // containing the member E2. It is still necessary to check that the class
5325 // directly containing the member E2 lies on the derived-to-base path of E1
5326 // to avoid incorrectly permitting member pointer access into a sibling
5327 // class of the class containing the member E2. If this class would
5328 // correspond to the most-derived class of E1, it either isn't contained in
5329 // LV.Designator.Entries or the corresponding entry refers to an array
5330 // element instead. Therefore get the most derived class directly in this
5331 // case. Otherwise the previous entry should correpond to this class.
5332 const CXXRecordDecl *LastLVDecl =
5333 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5334 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5335 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5336 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5337 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5338 Info.FFDiag(RHS);
5339 return nullptr;
5340 }
5341
5342 // Truncate the lvalue to the appropriate derived class.
5343 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5344 PathLengthToMember))
5345 return nullptr;
5346 } else if (!MemPtr.Path.empty()) {
5347 // Extend the LValue path with the member pointer's path.
5348 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5349 MemPtr.Path.size() + IncludeMember);
5350
5351 // Walk down to the appropriate base class.
5352 if (const PointerType *PT = LVType->getAs<PointerType>())
5353 LVType = PT->getPointeeType();
5354 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5355 assert(RD && "member pointer access on non-class-type expression");
5356 // The first class in the path is that of the lvalue.
5357 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5358 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5359 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5360 return nullptr;
5361 RD = Base;
5362 }
5363 // Finally cast to the class containing the member.
5364 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5365 MemPtr.getContainingRecord()))
5366 return nullptr;
5367 }
5368
5369 // Add the member. Note that we cannot build bound member functions here.
5370 if (IncludeMember) {
5371 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5372 if (!HandleLValueMember(Info, RHS, LV, FD))
5373 return nullptr;
5374 } else if (const IndirectFieldDecl *IFD =
5375 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5376 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5377 return nullptr;
5378 } else {
5379 llvm_unreachable("can't construct reference to bound member function");
5380 }
5381 }
5382
5383 return MemPtr.getDecl();
5384}
5385
5386static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5387 const BinaryOperator *BO,
5388 LValue &LV,
5389 bool IncludeMember = true) {
5390 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5391
5392 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5393 if (Info.noteFailure()) {
5394 MemberPtr MemPtr;
5395 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5396 }
5397 return nullptr;
5398 }
5399
5400 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5401 BO->getRHS(), IncludeMember);
5402}
5403
5404/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5405/// the provided lvalue, which currently refers to the base object.
5406static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5407 LValue &Result) {
5408 SubobjectDesignator &D = Result.Designator;
5409 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5410 return false;
5411
5412 QualType TargetQT = E->getType();
5413 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5414 TargetQT = PT->getPointeeType();
5415
5416 auto InvalidCast = [&]() {
5417 if (!Info.checkingPotentialConstantExpression() ||
5418 !Result.AllowConstexprUnknown) {
5419 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5420 << D.MostDerivedType << TargetQT;
5421 }
5422 return false;
5423 };
5424
5425 // Check this cast lands within the final derived-to-base subobject path.
5426 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5427 return InvalidCast();
5428
5429 // Check the type of the final cast. We don't need to check the path,
5430 // since a cast can only be formed if the path is unique.
5431 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5432 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5433 const CXXRecordDecl *FinalType;
5434 if (NewEntriesSize == D.MostDerivedPathLength)
5435 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5436 else
5437 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5438 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5439 return InvalidCast();
5440
5441 // Truncate the lvalue to the appropriate derived class.
5442 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5443}
5444
5445/// Get the value to use for a default-initialized object of type T.
5446/// Return false if it encounters something invalid.
5447static bool handleDefaultInitValue(QualType T, APValue &Result) {
5448 bool Success = true;
5449
5450 // If there is already a value present don't overwrite it.
5451 if (!Result.isAbsent())
5452 return true;
5453
5454 if (auto *RD = T->getAsCXXRecordDecl()) {
5455 if (RD->isInvalidDecl()) {
5456 Result = APValue();
5457 return false;
5458 }
5459 if (RD->isUnion()) {
5460 Result = APValue((const FieldDecl *)nullptr);
5461 return true;
5462 }
5463 Result =
5464 APValue(APValue::UninitStruct(), RD->getNumBases(), RD->getNumFields());
5465
5466 unsigned Index = 0;
5467 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5468 End = RD->bases_end();
5469 I != End; ++I, ++Index)
5470 Success &=
5471 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5472
5473 for (const auto *I : RD->fields()) {
5474 if (I->isUnnamedBitField())
5475 continue;
5477 I->getType(), Result.getStructField(I->getFieldIndex()));
5478 }
5479 return Success;
5480 }
5481
5482 if (auto *AT =
5483 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5484 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5485 if (Result.hasArrayFiller())
5486 Success &=
5487 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5488
5489 return Success;
5490 }
5491
5492 Result = APValue::IndeterminateValue();
5493 return true;
5494}
5495
5496namespace {
5497enum EvalStmtResult {
5498 /// Evaluation failed.
5499 ESR_Failed,
5500 /// Hit a 'return' statement.
5501 ESR_Returned,
5502 /// Evaluation succeeded.
5503 ESR_Succeeded,
5504 /// Hit a 'continue' statement.
5505 ESR_Continue,
5506 /// Hit a 'break' statement.
5507 ESR_Break,
5508 /// Still scanning for 'case' or 'default' statement.
5509 ESR_CaseNotFound
5510};
5511}
5512/// Evaluates the initializer of a reference.
5513static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5514 const ValueDecl *D,
5515 const Expr *Init, LValue &Result,
5516 APValue &Val) {
5517 assert(Init->isGLValue() && D->getType()->isReferenceType());
5518 // A reference is an lvalue.
5519 if (!EvaluateLValue(Init, Result, Info))
5520 return false;
5521 // [C++26][decl.ref]
5522 // The object designated by such a glvalue can be outside its lifetime
5523 // Because a null pointer value or a pointer past the end of an object
5524 // does not point to an object, a reference in a well-defined program cannot
5525 // refer to such things;
5526 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5527 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5528 return false;
5529 }
5530
5531 // Save the result.
5532 Result.moveInto(Val);
5533 return true;
5534}
5535
5536static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5537 if (VD->isInvalidDecl())
5538 return false;
5539 // We don't need to evaluate the initializer for a static local.
5540 if (!VD->hasLocalStorage())
5541 return true;
5542
5543 LValue Result;
5544 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5545 ScopeKind::Block, Result);
5546
5547 const Expr *InitE = VD->getInit();
5548 if (!InitE) {
5549 if (VD->getType()->isDependentType())
5550 return Info.noteSideEffect();
5551 return handleDefaultInitValue(VD->getType(), Val);
5552 }
5553 if (InitE->isValueDependent())
5554 return false;
5555
5556 // For references to objects, check they do not designate a one-past-the-end
5557 // object.
5558 if (VD->getType()->isReferenceType()) {
5559 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5560 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5561 // Wipe out any partially-computed value, to allow tracking that this
5562 // evaluation failed.
5563 Val = APValue();
5564 return false;
5565 }
5566
5567 return true;
5568}
5569
5570static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5571 const DecompositionDecl *DD);
5572
5573static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5574 bool EvaluateConditionDecl = false) {
5575 bool OK = true;
5576 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5577 OK &= EvaluateVarDecl(Info, VD);
5578
5579 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5580 EvaluateConditionDecl && DD)
5581 OK &= EvaluateDecompositionDeclInit(Info, DD);
5582
5583 return OK;
5584}
5585
5586static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5587 const DecompositionDecl *DD) {
5588 bool OK = true;
5589 for (auto *BD : DD->flat_bindings())
5590 if (auto *VD = BD->getHoldingVar())
5591 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5592
5593 return OK;
5594}
5595
5596static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5597 const VarDecl *VD) {
5598 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5599 if (!EvaluateDecompositionDeclInit(Info, DD))
5600 return false;
5601 }
5602 return true;
5603}
5604
5605static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5606 assert(E->isValueDependent());
5607 if (Info.noteSideEffect())
5608 return true;
5609 assert(E->containsErrors() && "valid value-dependent expression should never "
5610 "reach invalid code path.");
5611 return false;
5612}
5613
5614/// Evaluate a condition (either a variable declaration or an expression).
5615static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5616 const Expr *Cond, bool &Result) {
5617 if (Cond->isValueDependent())
5618 return false;
5619 FullExpressionRAII Scope(Info);
5620 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5621 return false;
5622 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5623 return false;
5624 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5625 return false;
5626 return Scope.destroy();
5627}
5628
5629namespace {
5630/// A location where the result (returned value) of evaluating a
5631/// statement should be stored.
5632struct StmtResult {
5633 /// The APValue that should be filled in with the returned value.
5634 APValue &Value;
5635 /// The location containing the result, if any (used to support RVO).
5636 const LValue *Slot;
5637};
5638
5639struct TempVersionRAII {
5640 CallStackFrame &Frame;
5641
5642 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5643 Frame.pushTempVersion();
5644 }
5645
5646 ~TempVersionRAII() {
5647 Frame.popTempVersion();
5648 }
5649};
5650
5651}
5652
5653static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5654 const Stmt *S,
5655 const SwitchCase *SC = nullptr);
5656
5657/// Helper to implement named break/continue. Returns 'true' if the evaluation
5658/// result should be propagated up. Otherwise, it sets the evaluation result
5659/// to either Continue to continue the current loop, or Succeeded to break it.
5660static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5661 const Stmt *LoopOrSwitch,
5663 EvalStmtResult &ESR) {
5664 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5665
5666 // For loops, map Succeeded to Continue so we don't have to check for both.
5667 if (!IsSwitch && ESR == ESR_Succeeded) {
5668 ESR = ESR_Continue;
5669 return false;
5670 }
5671
5672 if (ESR != ESR_Break && ESR != ESR_Continue)
5673 return false;
5674
5675 // Are we breaking out of or continuing this statement?
5676 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5677 const Stmt *StackTop = Info.BreakContinueStack.back();
5678 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5679 Info.BreakContinueStack.pop_back();
5680 if (ESR == ESR_Break)
5681 ESR = ESR_Succeeded;
5682 return false;
5683 }
5684
5685 // We're not. Propagate the result up.
5686 for (BlockScopeRAII *S : Scopes) {
5687 if (!S->destroy()) {
5688 ESR = ESR_Failed;
5689 break;
5690 }
5691 }
5692 return true;
5693}
5694
5695/// Evaluate the body of a loop, and translate the result as appropriate.
5696static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5697 const Stmt *Body,
5698 const SwitchCase *Case = nullptr) {
5699 BlockScopeRAII Scope(Info);
5700
5701 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5702 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5703 ESR = ESR_Failed;
5704
5705 return ESR;
5706}
5707
5708/// Evaluate a switch statement.
5709static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5710 const SwitchStmt *SS) {
5711 BlockScopeRAII Scope(Info);
5712
5713 // Evaluate the switch condition.
5714 APSInt Value;
5715 {
5716 if (const Stmt *Init = SS->getInit()) {
5717 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5718 if (ESR != ESR_Succeeded) {
5719 if (ESR != ESR_Failed && !Scope.destroy())
5720 ESR = ESR_Failed;
5721 return ESR;
5722 }
5723 }
5724
5725 FullExpressionRAII CondScope(Info);
5726 if (SS->getConditionVariable() &&
5727 !EvaluateDecl(Info, SS->getConditionVariable()))
5728 return ESR_Failed;
5729 if (SS->getCond()->isValueDependent()) {
5730 // We don't know what the value is, and which branch should jump to.
5731 EvaluateDependentExpr(SS->getCond(), Info);
5732 return ESR_Failed;
5733 }
5734 if (!EvaluateInteger(SS->getCond(), Value, Info))
5735 return ESR_Failed;
5736
5738 return ESR_Failed;
5739
5740 if (!CondScope.destroy())
5741 return ESR_Failed;
5742 }
5743
5744 // Find the switch case corresponding to the value of the condition.
5745 // FIXME: Cache this lookup.
5746 const SwitchCase *Found = nullptr;
5747 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5748 SC = SC->getNextSwitchCase()) {
5749 if (isa<DefaultStmt>(SC)) {
5750 Found = SC;
5751 continue;
5752 }
5753
5754 const CaseStmt *CS = cast<CaseStmt>(SC);
5755 const Expr *LHS = CS->getLHS();
5756 const Expr *RHS = CS->getRHS();
5757 if (LHS->isValueDependent() || (RHS && RHS->isValueDependent()))
5758 return ESR_Failed;
5759 APSInt LHSValue = LHS->EvaluateKnownConstInt(Info.Ctx);
5760 APSInt RHSValue = RHS ? RHS->EvaluateKnownConstInt(Info.Ctx) : LHSValue;
5761 if (LHSValue <= Value && Value <= RHSValue) {
5762 Found = SC;
5763 break;
5764 }
5765 }
5766
5767 if (!Found)
5768 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5769
5770 // Search the switch body for the switch case and evaluate it from there.
5771 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5772 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5773 return ESR_Failed;
5774 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5775 return ESR;
5776
5777 switch (ESR) {
5778 case ESR_Break:
5779 llvm_unreachable("Should have been converted to Succeeded");
5780 case ESR_Succeeded:
5781 case ESR_Continue:
5782 case ESR_Failed:
5783 case ESR_Returned:
5784 return ESR;
5785 case ESR_CaseNotFound:
5786 // This can only happen if the switch case is nested within a statement
5787 // expression. We have no intention of supporting that.
5788 Info.FFDiag(Found->getBeginLoc(),
5789 diag::note_constexpr_stmt_expr_unsupported);
5790 return ESR_Failed;
5791 }
5792 llvm_unreachable("Invalid EvalStmtResult!");
5793}
5794
5795static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5796 // An expression E is a core constant expression unless the evaluation of E
5797 // would evaluate one of the following: [C++23] - a control flow that passes
5798 // through a declaration of a variable with static or thread storage duration
5799 // unless that variable is usable in constant expressions.
5800 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5801 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5802 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5803 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5804 return false;
5805 }
5806 return true;
5807}
5808
5809// Evaluate a statement.
5810static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5811 const Stmt *S, const SwitchCase *Case) {
5812 if (!Info.nextStep(S))
5813 return ESR_Failed;
5814
5815 // If we're hunting down a 'case' or 'default' label, recurse through
5816 // substatements until we hit the label.
5817 if (Case) {
5818 switch (S->getStmtClass()) {
5819 case Stmt::CompoundStmtClass:
5820 // FIXME: Precompute which substatement of a compound statement we
5821 // would jump to, and go straight there rather than performing a
5822 // linear scan each time.
5823 case Stmt::LabelStmtClass:
5824 case Stmt::AttributedStmtClass:
5825 case Stmt::DoStmtClass:
5826 break;
5827
5828 case Stmt::CaseStmtClass:
5829 case Stmt::DefaultStmtClass:
5830 if (Case == S)
5831 Case = nullptr;
5832 break;
5833
5834 case Stmt::IfStmtClass: {
5835 // FIXME: Precompute which side of an 'if' we would jump to, and go
5836 // straight there rather than scanning both sides.
5837 const IfStmt *IS = cast<IfStmt>(S);
5838
5839 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5840 // preceded by our switch label.
5841 BlockScopeRAII Scope(Info);
5842
5843 // Step into the init statement in case it brings an (uninitialized)
5844 // variable into scope.
5845 if (const Stmt *Init = IS->getInit()) {
5846 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5847 if (ESR != ESR_CaseNotFound) {
5848 assert(ESR != ESR_Succeeded);
5849 return ESR;
5850 }
5851 }
5852
5853 // Condition variable must be initialized if it exists.
5854 // FIXME: We can skip evaluating the body if there's a condition
5855 // variable, as there can't be any case labels within it.
5856 // (The same is true for 'for' statements.)
5857
5858 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5859 if (ESR == ESR_Failed)
5860 return ESR;
5861 if (ESR != ESR_CaseNotFound)
5862 return Scope.destroy() ? ESR : ESR_Failed;
5863 if (!IS->getElse())
5864 return ESR_CaseNotFound;
5865
5866 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5867 if (ESR == ESR_Failed)
5868 return ESR;
5869 if (ESR != ESR_CaseNotFound)
5870 return Scope.destroy() ? ESR : ESR_Failed;
5871 return ESR_CaseNotFound;
5872 }
5873
5874 case Stmt::WhileStmtClass: {
5875 EvalStmtResult ESR =
5876 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5877 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5878 return ESR;
5879 if (ESR != ESR_Continue)
5880 return ESR;
5881 break;
5882 }
5883
5884 case Stmt::ForStmtClass: {
5885 const ForStmt *FS = cast<ForStmt>(S);
5886 BlockScopeRAII Scope(Info);
5887
5888 // Step into the init statement in case it brings an (uninitialized)
5889 // variable into scope.
5890 if (const Stmt *Init = FS->getInit()) {
5891 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5892 if (ESR != ESR_CaseNotFound) {
5893 assert(ESR != ESR_Succeeded);
5894 return ESR;
5895 }
5896 }
5897
5898 EvalStmtResult ESR =
5899 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5900 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5901 return ESR;
5902 if (ESR != ESR_Continue)
5903 return ESR;
5904 if (const auto *Inc = FS->getInc()) {
5905 if (Inc->isValueDependent()) {
5906 if (!EvaluateDependentExpr(Inc, Info))
5907 return ESR_Failed;
5908 } else {
5909 FullExpressionRAII IncScope(Info);
5910 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5911 return ESR_Failed;
5912 }
5913 }
5914 break;
5915 }
5916
5917 case Stmt::DeclStmtClass: {
5918 // Start the lifetime of any uninitialized variables we encounter. They
5919 // might be used by the selected branch of the switch.
5920 const DeclStmt *DS = cast<DeclStmt>(S);
5921 for (const auto *D : DS->decls()) {
5922 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5923 if (!CheckLocalVariableDeclaration(Info, VD))
5924 return ESR_Failed;
5925 if (VD->hasLocalStorage() && !VD->getInit())
5926 if (!EvaluateVarDecl(Info, VD))
5927 return ESR_Failed;
5928 // FIXME: If the variable has initialization that can't be jumped
5929 // over, bail out of any immediately-surrounding compound-statement
5930 // too. There can't be any case labels here.
5931 }
5932 }
5933 return ESR_CaseNotFound;
5934 }
5935
5936 default:
5937 return ESR_CaseNotFound;
5938 }
5939 }
5940
5941 switch (S->getStmtClass()) {
5942 default:
5943 if (const Expr *E = dyn_cast<Expr>(S)) {
5944 if (E->isValueDependent()) {
5945 if (!EvaluateDependentExpr(E, Info))
5946 return ESR_Failed;
5947 } else {
5948 // Don't bother evaluating beyond an expression-statement which couldn't
5949 // be evaluated.
5950 // FIXME: Do we need the FullExpressionRAII object here?
5951 // VisitExprWithCleanups should create one when necessary.
5952 FullExpressionRAII Scope(Info);
5953 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5954 return ESR_Failed;
5955 }
5956 return ESR_Succeeded;
5957 }
5958
5959 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5960 return ESR_Failed;
5961
5962 case Stmt::NullStmtClass:
5963 return ESR_Succeeded;
5964
5965 case Stmt::DeclStmtClass: {
5966 const DeclStmt *DS = cast<DeclStmt>(S);
5967 for (const auto *D : DS->decls()) {
5968 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5969 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5970 return ESR_Failed;
5971 // Each declaration initialization is its own full-expression.
5972 FullExpressionRAII Scope(Info);
5973 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
5974 !Info.noteFailure())
5975 return ESR_Failed;
5976 if (!Scope.destroy())
5977 return ESR_Failed;
5978 }
5979 return ESR_Succeeded;
5980 }
5981
5982 case Stmt::ReturnStmtClass: {
5983 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5984 FullExpressionRAII Scope(Info);
5985 if (RetExpr && RetExpr->isValueDependent()) {
5986 EvaluateDependentExpr(RetExpr, Info);
5987 // We know we returned, but we don't know what the value is.
5988 return ESR_Failed;
5989 }
5990 if (RetExpr &&
5991 !(Result.Slot
5992 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5993 : Evaluate(Result.Value, Info, RetExpr)))
5994 return ESR_Failed;
5995 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5996 }
5997
5998 case Stmt::CompoundStmtClass: {
5999 BlockScopeRAII Scope(Info);
6000
6001 const CompoundStmt *CS = cast<CompoundStmt>(S);
6002 for (const auto *BI : CS->body()) {
6003 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
6004 if (ESR == ESR_Succeeded)
6005 Case = nullptr;
6006 else if (ESR != ESR_CaseNotFound) {
6007 if (ESR != ESR_Failed && !Scope.destroy())
6008 return ESR_Failed;
6009 return ESR;
6010 }
6011 }
6012 if (Case)
6013 return ESR_CaseNotFound;
6014 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6015 }
6016
6017 case Stmt::IfStmtClass: {
6018 const IfStmt *IS = cast<IfStmt>(S);
6019
6020 // Evaluate the condition, as either a var decl or as an expression.
6021 BlockScopeRAII Scope(Info);
6022 if (const Stmt *Init = IS->getInit()) {
6023 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
6024 if (ESR != ESR_Succeeded) {
6025 if (ESR != ESR_Failed && !Scope.destroy())
6026 return ESR_Failed;
6027 return ESR;
6028 }
6029 }
6030 bool Cond;
6031 if (IS->isConsteval()) {
6033 // If we are not in a constant context, if consteval should not evaluate
6034 // to true.
6035 if (!Info.InConstantContext)
6036 Cond = !Cond;
6037 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
6038 Cond))
6039 return ESR_Failed;
6040
6041 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
6042 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
6043 if (ESR != ESR_Succeeded) {
6044 if (ESR != ESR_Failed && !Scope.destroy())
6045 return ESR_Failed;
6046 return ESR;
6047 }
6048 }
6049 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6050 }
6051
6052 case Stmt::WhileStmtClass: {
6053 const WhileStmt *WS = cast<WhileStmt>(S);
6054 while (true) {
6055 BlockScopeRAII Scope(Info);
6056 bool Continue;
6057 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
6058 Continue))
6059 return ESR_Failed;
6060 if (!Continue)
6061 break;
6062
6063 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
6064 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
6065 return ESR;
6066
6067 if (ESR != ESR_Continue) {
6068 if (ESR != ESR_Failed && !Scope.destroy())
6069 return ESR_Failed;
6070 return ESR;
6071 }
6072 if (!Scope.destroy())
6073 return ESR_Failed;
6074 }
6075 return ESR_Succeeded;
6076 }
6077
6078 case Stmt::DoStmtClass: {
6079 const DoStmt *DS = cast<DoStmt>(S);
6080 bool Continue;
6081 do {
6082 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
6083 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
6084 return ESR;
6085 if (ESR != ESR_Continue)
6086 return ESR;
6087 Case = nullptr;
6088
6089 if (DS->getCond()->isValueDependent()) {
6090 EvaluateDependentExpr(DS->getCond(), Info);
6091 // Bailout as we don't know whether to keep going or terminate the loop.
6092 return ESR_Failed;
6093 }
6094 FullExpressionRAII CondScope(Info);
6095 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
6096 !CondScope.destroy())
6097 return ESR_Failed;
6098 } while (Continue);
6099 return ESR_Succeeded;
6100 }
6101
6102 case Stmt::ForStmtClass: {
6103 const ForStmt *FS = cast<ForStmt>(S);
6104 BlockScopeRAII ForScope(Info);
6105 if (FS->getInit()) {
6106 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6107 if (ESR != ESR_Succeeded) {
6108 if (ESR != ESR_Failed && !ForScope.destroy())
6109 return ESR_Failed;
6110 return ESR;
6111 }
6112 }
6113 while (true) {
6114 BlockScopeRAII IterScope(Info);
6115 bool Continue = true;
6116 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
6117 FS->getCond(), Continue))
6118 return ESR_Failed;
6119
6120 if (!Continue) {
6121 if (!IterScope.destroy())
6122 return ESR_Failed;
6123 break;
6124 }
6125
6126 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6127 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
6128 return ESR;
6129 if (ESR != ESR_Continue) {
6130 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6131 return ESR_Failed;
6132 return ESR;
6133 }
6134
6135 if (const auto *Inc = FS->getInc()) {
6136 if (Inc->isValueDependent()) {
6137 if (!EvaluateDependentExpr(Inc, Info))
6138 return ESR_Failed;
6139 } else {
6140 FullExpressionRAII IncScope(Info);
6141 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6142 return ESR_Failed;
6143 }
6144 }
6145
6146 if (!IterScope.destroy())
6147 return ESR_Failed;
6148 }
6149 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6150 }
6151
6152 case Stmt::CXXForRangeStmtClass: {
6154 BlockScopeRAII Scope(Info);
6155
6156 // Evaluate the init-statement if present.
6157 if (FS->getInit()) {
6158 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6159 if (ESR != ESR_Succeeded) {
6160 if (ESR != ESR_Failed && !Scope.destroy())
6161 return ESR_Failed;
6162 return ESR;
6163 }
6164 }
6165
6166 // Initialize the __range variable.
6167 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
6168 if (ESR != ESR_Succeeded) {
6169 if (ESR != ESR_Failed && !Scope.destroy())
6170 return ESR_Failed;
6171 return ESR;
6172 }
6173
6174 // In error-recovery cases it's possible to get here even if we failed to
6175 // synthesize the __begin and __end variables.
6176 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
6177 return ESR_Failed;
6178
6179 // Create the __begin and __end iterators.
6180 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
6181 if (ESR != ESR_Succeeded) {
6182 if (ESR != ESR_Failed && !Scope.destroy())
6183 return ESR_Failed;
6184 return ESR;
6185 }
6186 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
6187 if (ESR != ESR_Succeeded) {
6188 if (ESR != ESR_Failed && !Scope.destroy())
6189 return ESR_Failed;
6190 return ESR;
6191 }
6192
6193 while (true) {
6194 // Condition: __begin != __end.
6195 {
6196 if (FS->getCond()->isValueDependent()) {
6197 EvaluateDependentExpr(FS->getCond(), Info);
6198 // We don't know whether to keep going or terminate the loop.
6199 return ESR_Failed;
6200 }
6201 bool Continue = true;
6202 FullExpressionRAII CondExpr(Info);
6203 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
6204 return ESR_Failed;
6205 if (!Continue)
6206 break;
6207 }
6208
6209 // User's variable declaration, initialized by *__begin.
6210 BlockScopeRAII InnerScope(Info);
6211 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
6212 if (ESR != ESR_Succeeded) {
6213 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6214 return ESR_Failed;
6215 return ESR;
6216 }
6217
6218 // Loop body.
6219 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6220 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
6221 return ESR;
6222 if (ESR != ESR_Continue) {
6223 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6224 return ESR_Failed;
6225 return ESR;
6226 }
6227 if (FS->getInc()->isValueDependent()) {
6228 if (!EvaluateDependentExpr(FS->getInc(), Info))
6229 return ESR_Failed;
6230 } else {
6231 // Increment: ++__begin
6232 if (!EvaluateIgnoredValue(Info, FS->getInc()))
6233 return ESR_Failed;
6234 }
6235
6236 if (!InnerScope.destroy())
6237 return ESR_Failed;
6238 }
6239
6240 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6241 }
6242
6243 case Stmt::SwitchStmtClass:
6244 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
6245
6246 case Stmt::ContinueStmtClass:
6247 case Stmt::BreakStmtClass: {
6248 auto *B = cast<LoopControlStmt>(S);
6249 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
6250 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
6251 }
6252
6253 case Stmt::LabelStmtClass:
6254 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
6255
6256 case Stmt::AttributedStmtClass: {
6257 const auto *AS = cast<AttributedStmt>(S);
6258 const auto *SS = AS->getSubStmt();
6259 MSConstexprContextRAII ConstexprContext(
6260 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
6261 isa<ReturnStmt>(SS));
6262
6263 auto LO = Info.Ctx.getLangOpts();
6264 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6265 for (auto *Attr : AS->getAttrs()) {
6266 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6267 if (!AA)
6268 continue;
6269
6270 auto *Assumption = AA->getAssumption();
6271 if (Assumption->isValueDependent())
6272 return ESR_Failed;
6273
6274 if (Assumption->HasSideEffects(Info.Ctx))
6275 continue;
6276
6277 bool Value;
6278 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6279 return ESR_Failed;
6280 if (!Value) {
6281 Info.CCEDiag(Assumption->getExprLoc(),
6282 diag::note_constexpr_assumption_failed);
6283 return ESR_Failed;
6284 }
6285 }
6286 }
6287
6288 return EvaluateStmt(Result, Info, SS, Case);
6289 }
6290
6291 case Stmt::CaseStmtClass:
6292 case Stmt::DefaultStmtClass:
6293 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6294 case Stmt::CXXTryStmtClass:
6295 // Evaluate try blocks by evaluating all sub statements.
6296 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6297 }
6298}
6299
6300/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6301/// default constructor. If so, we'll fold it whether or not it's marked as
6302/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6303/// so we need special handling.
6304static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6305 const CXXConstructorDecl *CD,
6306 bool IsValueInitialization) {
6307 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6308 return false;
6309
6310 // Value-initialization does not call a trivial default constructor, so such a
6311 // call is a core constant expression whether or not the constructor is
6312 // constexpr.
6313 if (!CD->isConstexpr() && !IsValueInitialization) {
6314 if (Info.getLangOpts().CPlusPlus11) {
6315 // FIXME: If DiagDecl is an implicitly-declared special member function,
6316 // we should be much more explicit about why it's not constexpr.
6317 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6318 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6319 Info.Note(CD->getLocation(), diag::note_declared_at);
6320 } else {
6321 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6322 }
6323 }
6324 return true;
6325}
6326
6327/// CheckConstexprFunction - Check that a function can be called in a constant
6328/// expression.
6329static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6331 const FunctionDecl *Definition,
6332 const Stmt *Body) {
6333 // Potential constant expressions can contain calls to declared, but not yet
6334 // defined, constexpr functions.
6335 if (Info.checkingPotentialConstantExpression() && !Definition &&
6336 Declaration->isConstexpr())
6337 return false;
6338
6339 // Bail out if the function declaration itself is invalid. We will
6340 // have produced a relevant diagnostic while parsing it, so just
6341 // note the problematic sub-expression.
6342 if (Declaration->isInvalidDecl()) {
6343 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6344 return false;
6345 }
6346
6347 // DR1872: An instantiated virtual constexpr function can't be called in a
6348 // constant expression (prior to C++20). We can still constant-fold such a
6349 // call.
6350 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6351 cast<CXXMethodDecl>(Declaration)->isVirtual())
6352 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6353
6354 if (Definition && Definition->isInvalidDecl()) {
6355 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6356 return false;
6357 }
6358
6359 // Can we evaluate this function call?
6360 if (Definition && Body &&
6361 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6362 Definition->hasAttr<MSConstexprAttr>())))
6363 return true;
6364
6365 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6366 // Special note for the assert() macro, as the normal error message falsely
6367 // implies we cannot use an assertion during constant evaluation.
6368 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6369 // FIXME: Instead of checking for an implementation-defined function,
6370 // check and evaluate the assert() macro.
6371 StringRef Name = DiagDecl->getName();
6372 bool AssertFailed =
6373 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6374 if (AssertFailed) {
6375 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6376 return false;
6377 }
6378 }
6379
6380 if (Info.getLangOpts().CPlusPlus11) {
6381 // If this function is not constexpr because it is an inherited
6382 // non-constexpr constructor, diagnose that directly.
6383 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6384 if (CD && CD->isInheritingConstructor()) {
6385 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6386 if (!Inherited->isConstexpr())
6387 DiagDecl = CD = Inherited;
6388 }
6389
6390 // FIXME: If DiagDecl is an implicitly-declared special member function
6391 // or an inheriting constructor, we should be much more explicit about why
6392 // it's not constexpr.
6393 if (CD && CD->isInheritingConstructor())
6394 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6395 << CD->getInheritedConstructor().getConstructor()->getParent();
6396 else
6397 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6398 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6399 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6400 } else {
6401 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6402 }
6403 return false;
6404}
6405
6406namespace {
6407struct CheckDynamicTypeHandler {
6409 typedef bool result_type;
6410 bool failed() { return false; }
6411 bool found(APValue &Subobj, QualType SubobjType) { return true; }
6412 bool found(APSInt &Value, QualType SubobjType) { return true; }
6413 bool found(APFloat &Value, QualType SubobjType) { return true; }
6414};
6415} // end anonymous namespace
6416
6417/// Check that we can access the notional vptr of an object / determine its
6418/// dynamic type.
6419static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6420 AccessKinds AK, bool Polymorphic) {
6421 if (This.Designator.Invalid)
6422 return false;
6423
6424 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6425
6426 if (!Obj)
6427 return false;
6428
6429 if (!Obj.Value) {
6430 // The object is not usable in constant expressions, so we can't inspect
6431 // its value to see if it's in-lifetime or what the active union members
6432 // are. We can still check for a one-past-the-end lvalue.
6433 if (This.Designator.isOnePastTheEnd() ||
6434 This.Designator.isMostDerivedAnUnsizedArray()) {
6435 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6436 ? diag::note_constexpr_access_past_end
6437 : diag::note_constexpr_access_unsized_array)
6438 << AK;
6439 return false;
6440 } else if (Polymorphic) {
6441 // Conservatively refuse to perform a polymorphic operation if we would
6442 // not be able to read a notional 'vptr' value.
6443 if (!Info.checkingPotentialConstantExpression() ||
6444 !This.AllowConstexprUnknown) {
6445 APValue Val;
6446 This.moveInto(Val);
6447 QualType StarThisType =
6448 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6449 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6450 << AK << Val.getAsString(Info.Ctx, StarThisType);
6451 }
6452 return false;
6453 }
6454 return true;
6455 }
6456
6457 CheckDynamicTypeHandler Handler{AK};
6458 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6459}
6460
6461/// Check that the pointee of the 'this' pointer in a member function call is
6462/// either within its lifetime or in its period of construction or destruction.
6463static bool
6465 const LValue &This,
6466 const CXXMethodDecl *NamedMember) {
6467 return checkDynamicType(
6468 Info, E, This,
6469 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6470}
6471
6473 /// The dynamic class type of the object.
6475 /// The corresponding path length in the lvalue.
6476 unsigned PathLength;
6477};
6478
6479static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6480 unsigned PathLength) {
6481 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6482 Designator.Entries.size() && "invalid path length");
6483 return (PathLength == Designator.MostDerivedPathLength)
6484 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6485 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6486}
6487
6488/// Determine the dynamic type of an object.
6489static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6490 const Expr *E,
6491 LValue &This,
6492 AccessKinds AK) {
6493 // If we don't have an lvalue denoting an object of class type, there is no
6494 // meaningful dynamic type. (We consider objects of non-class type to have no
6495 // dynamic type.)
6496 if (!checkDynamicType(Info, E, This, AK,
6497 AK != AK_TypeId || This.AllowConstexprUnknown))
6498 return std::nullopt;
6499
6500 if (This.Designator.Invalid)
6501 return std::nullopt;
6502
6503 // Refuse to compute a dynamic type in the presence of virtual bases. This
6504 // shouldn't happen other than in constant-folding situations, since literal
6505 // types can't have virtual bases.
6506 //
6507 // Note that consumers of DynamicType assume that the type has no virtual
6508 // bases, and will need modifications if this restriction is relaxed.
6509 const CXXRecordDecl *Class =
6510 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6511 if (!Class || Class->getNumVBases()) {
6512 Info.FFDiag(E);
6513 return std::nullopt;
6514 }
6515
6516 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6517 // binary search here instead. But the overwhelmingly common case is that
6518 // we're not in the middle of a constructor, so it probably doesn't matter
6519 // in practice.
6520 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6521 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6522 PathLength <= Path.size(); ++PathLength) {
6523 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6524 Path.slice(0, PathLength))) {
6525 case ConstructionPhase::Bases:
6526 case ConstructionPhase::DestroyingBases:
6527 // We're constructing or destroying a base class. This is not the dynamic
6528 // type.
6529 break;
6530
6531 case ConstructionPhase::None:
6532 case ConstructionPhase::AfterBases:
6533 case ConstructionPhase::AfterFields:
6534 case ConstructionPhase::Destroying:
6535 // We've finished constructing the base classes and not yet started
6536 // destroying them again, so this is the dynamic type.
6537 return DynamicType{getBaseClassType(This.Designator, PathLength),
6538 PathLength};
6539 }
6540 }
6541
6542 // CWG issue 1517: we're constructing a base class of the object described by
6543 // 'This', so that object has not yet begun its period of construction and
6544 // any polymorphic operation on it results in undefined behavior.
6545 Info.FFDiag(E);
6546 return std::nullopt;
6547}
6548
6549/// Perform virtual dispatch.
6551 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6552 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6553 std::optional<DynamicType> DynType = ComputeDynamicType(
6554 Info, E, This,
6556 if (!DynType)
6557 return nullptr;
6558
6559 // Find the final overrider. It must be declared in one of the classes on the
6560 // path from the dynamic type to the static type.
6561 // FIXME: If we ever allow literal types to have virtual base classes, that
6562 // won't be true.
6563 const CXXMethodDecl *Callee = Found;
6564 unsigned PathLength = DynType->PathLength;
6565 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6566 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6567 const CXXMethodDecl *Overrider =
6568 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6569 if (Overrider) {
6570 Callee = Overrider;
6571 break;
6572 }
6573 }
6574
6575 // C++2a [class.abstract]p6:
6576 // the effect of making a virtual call to a pure virtual function [...] is
6577 // undefined
6578 if (Callee->isPureVirtual()) {
6579 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6580 Info.Note(Callee->getLocation(), diag::note_declared_at);
6581 return nullptr;
6582 }
6583
6584 // If necessary, walk the rest of the path to determine the sequence of
6585 // covariant adjustment steps to apply.
6586 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6587 Found->getReturnType())) {
6588 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6589 for (unsigned CovariantPathLength = PathLength + 1;
6590 CovariantPathLength != This.Designator.Entries.size();
6591 ++CovariantPathLength) {
6592 const CXXRecordDecl *NextClass =
6593 getBaseClassType(This.Designator, CovariantPathLength);
6594 const CXXMethodDecl *Next =
6595 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6596 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6597 Next->getReturnType(), CovariantAdjustmentPath.back()))
6598 CovariantAdjustmentPath.push_back(Next->getReturnType());
6599 }
6600 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6601 CovariantAdjustmentPath.back()))
6602 CovariantAdjustmentPath.push_back(Found->getReturnType());
6603 }
6604
6605 // Perform 'this' adjustment.
6606 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6607 return nullptr;
6608
6609 return Callee;
6610}
6611
6612/// Perform the adjustment from a value returned by a virtual function to
6613/// a value of the statically expected type, which may be a pointer or
6614/// reference to a base class of the returned type.
6615static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6616 APValue &Result,
6617 ArrayRef<QualType> Path) {
6618 assert(Result.isLValue() &&
6619 "unexpected kind of APValue for covariant return");
6620 if (Result.isNullPointer())
6621 return true;
6622
6623 LValue LVal;
6624 LVal.setFrom(Info.Ctx, Result);
6625
6626 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6627 for (unsigned I = 1; I != Path.size(); ++I) {
6628 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6629 assert(OldClass && NewClass && "unexpected kind of covariant return");
6630 if (OldClass != NewClass &&
6631 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6632 return false;
6633 OldClass = NewClass;
6634 }
6635
6636 LVal.moveInto(Result);
6637 return true;
6638}
6639
6640/// Determine whether \p Base, which is known to be a direct base class of
6641/// \p Derived, is a public base class.
6642static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6643 const CXXRecordDecl *Base) {
6644 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6645 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6646 if (BaseClass && declaresSameEntity(BaseClass, Base))
6647 return BaseSpec.getAccessSpecifier() == AS_public;
6648 }
6649 llvm_unreachable("Base is not a direct base of Derived");
6650}
6651
6652/// Apply the given dynamic cast operation on the provided lvalue.
6653///
6654/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6655/// to find a suitable target subobject.
6656static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6657 LValue &Ptr) {
6658 // We can't do anything with a non-symbolic pointer value.
6659 SubobjectDesignator &D = Ptr.Designator;
6660 if (D.Invalid)
6661 return false;
6662
6663 // C++ [expr.dynamic.cast]p6:
6664 // If v is a null pointer value, the result is a null pointer value.
6665 if (Ptr.isNullPointer() && !E->isGLValue())
6666 return true;
6667
6668 // For all the other cases, we need the pointer to point to an object within
6669 // its lifetime / period of construction / destruction, and we need to know
6670 // its dynamic type.
6671 std::optional<DynamicType> DynType =
6672 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6673 if (!DynType)
6674 return false;
6675
6676 // C++ [expr.dynamic.cast]p7:
6677 // If T is "pointer to cv void", then the result is a pointer to the most
6678 // derived object
6679 if (E->getType()->isVoidPointerType())
6680 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6681
6683 assert(C && "dynamic_cast target is not void pointer nor class");
6684 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6685
6686 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6687 // C++ [expr.dynamic.cast]p9:
6688 if (!E->isGLValue()) {
6689 // The value of a failed cast to pointer type is the null pointer value
6690 // of the required result type.
6691 Ptr.setNull(Info.Ctx, E->getType());
6692 return true;
6693 }
6694
6695 // A failed cast to reference type throws [...] std::bad_cast.
6696 unsigned DiagKind;
6697 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6698 DynType->Type->isDerivedFrom(C)))
6699 DiagKind = 0;
6700 else if (!Paths || Paths->begin() == Paths->end())
6701 DiagKind = 1;
6702 else if (Paths->isAmbiguous(CQT))
6703 DiagKind = 2;
6704 else {
6705 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6706 DiagKind = 3;
6707 }
6708 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6709 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6710 << Info.Ctx.getCanonicalTagType(DynType->Type)
6711 << E->getType().getUnqualifiedType();
6712 return false;
6713 };
6714
6715 // Runtime check, phase 1:
6716 // Walk from the base subobject towards the derived object looking for the
6717 // target type.
6718 for (int PathLength = Ptr.Designator.Entries.size();
6719 PathLength >= (int)DynType->PathLength; --PathLength) {
6720 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6721 if (declaresSameEntity(Class, C))
6722 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6723 // We can only walk across public inheritance edges.
6724 if (PathLength > (int)DynType->PathLength &&
6725 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6726 Class))
6727 return RuntimeCheckFailed(nullptr);
6728 }
6729
6730 // Runtime check, phase 2:
6731 // Search the dynamic type for an unambiguous public base of type C.
6732 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6733 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6734 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6735 Paths.front().Access == AS_public) {
6736 // Downcast to the dynamic type...
6737 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6738 return false;
6739 // ... then upcast to the chosen base class subobject.
6740 for (CXXBasePathElement &Elem : Paths.front())
6741 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6742 return false;
6743 return true;
6744 }
6745
6746 // Otherwise, the runtime check fails.
6747 return RuntimeCheckFailed(&Paths);
6748}
6749
6750namespace {
6751struct StartLifetimeOfUnionMemberHandler {
6752 EvalInfo &Info;
6753 const Expr *LHSExpr;
6754 const FieldDecl *Field;
6755 bool DuringInit;
6756 bool Failed = false;
6757 static const AccessKinds AccessKind = AK_Assign;
6758
6759 typedef bool result_type;
6760 bool failed() { return Failed; }
6761 bool found(APValue &Subobj, QualType SubobjType) {
6762 // We are supposed to perform no initialization but begin the lifetime of
6763 // the object. We interpret that as meaning to do what default
6764 // initialization of the object would do if all constructors involved were
6765 // trivial:
6766 // * All base, non-variant member, and array element subobjects' lifetimes
6767 // begin
6768 // * No variant members' lifetimes begin
6769 // * All scalar subobjects whose lifetimes begin have indeterminate values
6770 assert(SubobjType->isUnionType());
6771 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6772 // This union member is already active. If it's also in-lifetime, there's
6773 // nothing to do.
6774 if (Subobj.getUnionValue().hasValue())
6775 return true;
6776 } else if (DuringInit) {
6777 // We're currently in the process of initializing a different union
6778 // member. If we carried on, that initialization would attempt to
6779 // store to an inactive union member, resulting in undefined behavior.
6780 Info.FFDiag(LHSExpr,
6781 diag::note_constexpr_union_member_change_during_init);
6782 return false;
6783 }
6785 Failed = !handleDefaultInitValue(Field->getType(), Result);
6786 Subobj.setUnion(Field, Result);
6787 return true;
6788 }
6789 bool found(APSInt &Value, QualType SubobjType) {
6790 llvm_unreachable("wrong value kind for union object");
6791 }
6792 bool found(APFloat &Value, QualType SubobjType) {
6793 llvm_unreachable("wrong value kind for union object");
6794 }
6795};
6796} // end anonymous namespace
6797
6798const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6799
6800/// Handle a builtin simple-assignment or a call to a trivial assignment
6801/// operator whose left-hand side might involve a union member access. If it
6802/// does, implicitly start the lifetime of any accessed union elements per
6803/// C++20 [class.union]5.
6804static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6805 const Expr *LHSExpr,
6806 const LValue &LHS) {
6807 if (LHS.InvalidBase || LHS.Designator.Invalid)
6808 return false;
6809
6811 // C++ [class.union]p5:
6812 // define the set S(E) of subexpressions of E as follows:
6813 unsigned PathLength = LHS.Designator.Entries.size();
6814 for (const Expr *E = LHSExpr; E != nullptr;) {
6815 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6816 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6817 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6818 // Note that we can't implicitly start the lifetime of a reference,
6819 // so we don't need to proceed any further if we reach one.
6820 if (!FD || FD->getType()->isReferenceType())
6821 break;
6822
6823 // ... and also contains A.B if B names a union member ...
6824 if (FD->getParent()->isUnion()) {
6825 // ... of a non-class, non-array type, or of a class type with a
6826 // trivial default constructor that is not deleted, or an array of
6827 // such types.
6828 auto *RD =
6829 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6830 if (!RD || RD->hasTrivialDefaultConstructor())
6831 UnionPathLengths.push_back({PathLength - 1, FD});
6832 }
6833
6834 E = ME->getBase();
6835 --PathLength;
6836 assert(declaresSameEntity(FD,
6837 LHS.Designator.Entries[PathLength]
6838 .getAsBaseOrMember().getPointer()));
6839
6840 // -- If E is of the form A[B] and is interpreted as a built-in array
6841 // subscripting operator, S(E) is [S(the array operand, if any)].
6842 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6843 // Step over an ArrayToPointerDecay implicit cast.
6844 auto *Base = ASE->getBase()->IgnoreImplicit();
6845 if (!Base->getType()->isArrayType())
6846 break;
6847
6848 E = Base;
6849 --PathLength;
6850
6851 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6852 // Step over a derived-to-base conversion.
6853 E = ICE->getSubExpr();
6854 if (ICE->getCastKind() == CK_NoOp)
6855 continue;
6856 if (ICE->getCastKind() != CK_DerivedToBase &&
6857 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6858 break;
6859 // Walk path backwards as we walk up from the base to the derived class.
6860 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6861 if (Elt->isVirtual()) {
6862 // A class with virtual base classes never has a trivial default
6863 // constructor, so S(E) is empty in this case.
6864 E = nullptr;
6865 break;
6866 }
6867
6868 --PathLength;
6869 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6870 LHS.Designator.Entries[PathLength]
6871 .getAsBaseOrMember().getPointer()));
6872 }
6873
6874 // -- Otherwise, S(E) is empty.
6875 } else {
6876 break;
6877 }
6878 }
6879
6880 // Common case: no unions' lifetimes are started.
6881 if (UnionPathLengths.empty())
6882 return true;
6883
6884 // if modification of X [would access an inactive union member], an object
6885 // of the type of X is implicitly created
6886 CompleteObject Obj =
6887 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6888 if (!Obj)
6889 return false;
6890 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6891 llvm::reverse(UnionPathLengths)) {
6892 // Form a designator for the union object.
6893 SubobjectDesignator D = LHS.Designator;
6894 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6895
6896 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6897 ConstructionPhase::AfterBases;
6898 StartLifetimeOfUnionMemberHandler StartLifetime{
6899 Info, LHSExpr, LengthAndField.second, DuringInit};
6900 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6901 return false;
6902 }
6903
6904 return true;
6905}
6906
6907static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6908 CallRef Call, EvalInfo &Info, bool NonNull = false,
6909 APValue **EvaluatedArg = nullptr) {
6910 LValue LV;
6911 // Create the parameter slot and register its destruction. For a vararg
6912 // argument, create a temporary.
6913 // FIXME: For calling conventions that destroy parameters in the callee,
6914 // should we consider performing destruction when the function returns
6915 // instead?
6916 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6917 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6918 ScopeKind::Call, LV);
6919 if (!EvaluateInPlace(V, Info, LV, Arg))
6920 return false;
6921
6922 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6923 // undefined behavior, so is non-constant.
6924 if (NonNull && V.isLValue() && V.isNullPointer()) {
6925 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6926 return false;
6927 }
6928
6929 if (EvaluatedArg)
6930 *EvaluatedArg = &V;
6931
6932 return true;
6933}
6934
6935/// Evaluate the arguments to a function call.
6936static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6937 EvalInfo &Info, const FunctionDecl *Callee,
6938 bool RightToLeft = false,
6939 LValue *ObjectArg = nullptr) {
6940 bool Success = true;
6941 llvm::SmallBitVector ForbiddenNullArgs;
6942 if (Callee->hasAttr<NonNullAttr>()) {
6943 ForbiddenNullArgs.resize(Args.size());
6944 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6945 if (!Attr->args_size()) {
6946 ForbiddenNullArgs.set();
6947 break;
6948 } else
6949 for (auto Idx : Attr->args()) {
6950 unsigned ASTIdx = Idx.getASTIndex();
6951 if (ASTIdx >= Args.size())
6952 continue;
6953 ForbiddenNullArgs[ASTIdx] = true;
6954 }
6955 }
6956 }
6957 for (unsigned I = 0; I < Args.size(); I++) {
6958 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6959 const ParmVarDecl *PVD =
6960 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6961 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6962 APValue *That = nullptr;
6963 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
6964 // If we're checking for a potential constant expression, evaluate all
6965 // initializers even if some of them fail.
6966 if (!Info.noteFailure())
6967 return false;
6968 Success = false;
6969 }
6970 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
6971 ObjectArg->setFrom(Info.Ctx, *That);
6972 }
6973 return Success;
6974}
6975
6976/// Perform a trivial copy from Param, which is the parameter of a copy or move
6977/// constructor or assignment operator.
6978static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6979 const Expr *E, APValue &Result,
6980 bool CopyObjectRepresentation) {
6981 // Find the reference argument.
6982 CallStackFrame *Frame = Info.CurrentCall;
6983 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6984 if (!RefValue) {
6985 Info.FFDiag(E);
6986 return false;
6987 }
6988
6989 // Copy out the contents of the RHS object.
6990 LValue RefLValue;
6991 RefLValue.setFrom(Info.Ctx, *RefValue);
6993 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6994 CopyObjectRepresentation);
6995}
6996
6997/// Evaluate a function call.
6999 const FunctionDecl *Callee,
7000 const LValue *ObjectArg, const Expr *E,
7001 ArrayRef<const Expr *> Args, CallRef Call,
7002 const Stmt *Body, EvalInfo &Info,
7003 APValue &Result, const LValue *ResultSlot) {
7004 if (!Info.CheckCallLimit(CallLoc))
7005 return false;
7006
7007 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
7008
7009 // For a trivial copy or move assignment, perform an APValue copy. This is
7010 // essential for unions, where the operations performed by the assignment
7011 // operator cannot be represented as statements.
7012 //
7013 // Skip this for non-union classes with no fields; in that case, the defaulted
7014 // copy/move does not actually read the object.
7015 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
7016 if (MD && MD->isDefaulted() &&
7017 (MD->getParent()->isUnion() ||
7018 (MD->isTrivial() &&
7020 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
7021 assert(ObjectArg &&
7023 APValue RHSValue;
7024 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
7025 MD->getParent()->isUnion()))
7026 return false;
7027
7028 LValue Obj;
7029 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
7031 RHSValue))
7032 return false;
7033 ObjectArg->moveInto(Result);
7034 return true;
7035 } else if (MD && isLambdaCallOperator(MD)) {
7036 // We're in a lambda; determine the lambda capture field maps unless we're
7037 // just constexpr checking a lambda's call operator. constexpr checking is
7038 // done before the captures have been added to the closure object (unless
7039 // we're inferring constexpr-ness), so we don't have access to them in this
7040 // case. But since we don't need the captures to constexpr check, we can
7041 // just ignore them.
7042 if (!Info.checkingPotentialConstantExpression())
7043 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
7044 Frame.LambdaThisCaptureField);
7045 }
7046
7047 StmtResult Ret = {Result, ResultSlot};
7048 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
7049 if (ESR == ESR_Succeeded) {
7050 if (Callee->getReturnType()->isVoidType())
7051 return true;
7052 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7053 }
7054 return ESR == ESR_Returned;
7055}
7056
7057/// Evaluate a constructor call.
7058static bool HandleConstructorCall(const Expr *E, const LValue &This,
7059 CallRef Call,
7061 EvalInfo &Info, APValue &Result) {
7062 SourceLocation CallLoc = E->getExprLoc();
7063 if (!Info.CheckCallLimit(CallLoc))
7064 return false;
7065
7066 const CXXRecordDecl *RD = Definition->getParent();
7067 if (RD->getNumVBases()) {
7068 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7069 return false;
7070 }
7071
7072 EvalInfo::EvaluatingConstructorRAII EvalObj(
7073 Info,
7074 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7075 RD->getNumBases());
7076 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
7077
7078 // FIXME: Creating an APValue just to hold a nonexistent return value is
7079 // wasteful.
7080 APValue RetVal;
7081 StmtResult Ret = {RetVal, nullptr};
7082
7083 // If it's a delegating constructor, delegate.
7084 if (Definition->isDelegatingConstructor()) {
7086 if ((*I)->getInit()->isValueDependent()) {
7087 if (!EvaluateDependentExpr((*I)->getInit(), Info))
7088 return false;
7089 } else {
7090 FullExpressionRAII InitScope(Info);
7091 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
7092 !InitScope.destroy())
7093 return false;
7094 }
7095 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
7096 }
7097
7098 // For a trivial copy or move constructor, perform an APValue copy. This is
7099 // essential for unions (or classes with anonymous union members), where the
7100 // operations performed by the constructor cannot be represented by
7101 // ctor-initializers.
7102 //
7103 // Skip this for empty non-union classes; we should not perform an
7104 // lvalue-to-rvalue conversion on them because their copy constructor does not
7105 // actually read them.
7106 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
7107 (Definition->getParent()->isUnion() ||
7108 (Definition->isTrivial() &&
7110 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
7111 Definition->getParent()->isUnion());
7112 }
7113
7114 // Reserve space for the struct members.
7115 if (!Result.hasValue()) {
7116 if (!RD->isUnion())
7117 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
7118 RD->getNumFields());
7119 else
7120 // A union starts with no active member.
7121 Result = APValue((const FieldDecl*)nullptr);
7122 }
7123
7124 if (RD->isInvalidDecl()) return false;
7125 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7126
7127 // A scope for temporaries lifetime-extended by reference members.
7128 BlockScopeRAII LifetimeExtendedScope(Info);
7129
7130 bool Success = true;
7131 unsigned BasesSeen = 0;
7132#ifndef NDEBUG
7134#endif
7136 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
7137 // We might be initializing the same field again if this is an indirect
7138 // field initialization.
7139 if (FieldIt == RD->field_end() ||
7140 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
7141 assert(Indirect && "fields out of order?");
7142 return;
7143 }
7144
7145 // Default-initialize any fields with no explicit initializer.
7146 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
7147 assert(FieldIt != RD->field_end() && "missing field?");
7148 if (!FieldIt->isUnnamedBitField())
7150 FieldIt->getType(),
7151 Result.getStructField(FieldIt->getFieldIndex()));
7152 }
7153 ++FieldIt;
7154 };
7155 for (const auto *I : Definition->inits()) {
7156 LValue Subobject = This;
7157 LValue SubobjectParent = This;
7158 APValue *Value = &Result;
7159
7160 // Determine the subobject to initialize.
7161 FieldDecl *FD = nullptr;
7162 if (I->isBaseInitializer()) {
7163 QualType BaseType(I->getBaseClass(), 0);
7164#ifndef NDEBUG
7165 // Non-virtual base classes are initialized in the order in the class
7166 // definition. We have already checked for virtual base classes.
7167 assert(!BaseIt->isVirtual() && "virtual base for literal type");
7168 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
7169 "base class initializers not in expected order");
7170 ++BaseIt;
7171#endif
7172 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
7173 BaseType->getAsCXXRecordDecl(), &Layout))
7174 return false;
7175 Value = &Result.getStructBase(BasesSeen++);
7176 } else if ((FD = I->getMember())) {
7177 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
7178 return false;
7179 if (RD->isUnion()) {
7180 Result = APValue(FD);
7181 Value = &Result.getUnionValue();
7182 } else {
7183 SkipToField(FD, false);
7184 Value = &Result.getStructField(FD->getFieldIndex());
7185 }
7186 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
7187 // Walk the indirect field decl's chain to find the object to initialize,
7188 // and make sure we've initialized every step along it.
7189 auto IndirectFieldChain = IFD->chain();
7190 for (auto *C : IndirectFieldChain) {
7191 FD = cast<FieldDecl>(C);
7193 // Switch the union field if it differs. This happens if we had
7194 // preceding zero-initialization, and we're now initializing a union
7195 // subobject other than the first.
7196 // FIXME: In this case, the values of the other subobjects are
7197 // specified, since zero-initialization sets all padding bits to zero.
7198 if (!Value->hasValue() ||
7199 (Value->isUnion() &&
7200 !declaresSameEntity(Value->getUnionField(), FD))) {
7201 if (CD->isUnion())
7202 *Value = APValue(FD);
7203 else
7204 // FIXME: This immediately starts the lifetime of all members of
7205 // an anonymous struct. It would be preferable to strictly start
7206 // member lifetime in initialization order.
7207 Success &= handleDefaultInitValue(Info.Ctx.getCanonicalTagType(CD),
7208 *Value);
7209 }
7210 // Store Subobject as its parent before updating it for the last element
7211 // in the chain.
7212 if (C == IndirectFieldChain.back())
7213 SubobjectParent = Subobject;
7214 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
7215 return false;
7216 if (CD->isUnion())
7217 Value = &Value->getUnionValue();
7218 else {
7219 if (C == IndirectFieldChain.front() && !RD->isUnion())
7220 SkipToField(FD, true);
7221 Value = &Value->getStructField(FD->getFieldIndex());
7222 }
7223 }
7224 } else {
7225 llvm_unreachable("unknown base initializer kind");
7226 }
7227
7228 // Need to override This for implicit field initializers as in this case
7229 // This refers to innermost anonymous struct/union containing initializer,
7230 // not to currently constructed class.
7231 const Expr *Init = I->getInit();
7232 if (Init->isValueDependent()) {
7233 if (!EvaluateDependentExpr(Init, Info))
7234 return false;
7235 } else {
7236 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7238 FullExpressionRAII InitScope(Info);
7239 if (FD && FD->getType()->isReferenceType() &&
7240 !FD->getType()->isFunctionReferenceType()) {
7241 LValue Result;
7242 if (!EvaluateInitForDeclOfReferenceType(Info, FD, Init, Result,
7243 *Value)) {
7244 if (!Info.noteFailure())
7245 return false;
7246 Success = false;
7247 }
7248 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
7249 (FD && FD->isBitField() &&
7250 !truncateBitfieldValue(Info, Init, *Value, FD))) {
7251 // If we're checking for a potential constant expression, evaluate all
7252 // initializers even if some of them fail.
7253 if (!Info.noteFailure())
7254 return false;
7255 Success = false;
7256 }
7257 }
7258
7259 // This is the point at which the dynamic type of the object becomes this
7260 // class type.
7261 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
7262 EvalObj.finishedConstructingBases();
7263 }
7264
7265 // Default-initialize any remaining fields.
7266 if (!RD->isUnion()) {
7267 for (; FieldIt != RD->field_end(); ++FieldIt) {
7268 if (!FieldIt->isUnnamedBitField())
7270 FieldIt->getType(),
7271 Result.getStructField(FieldIt->getFieldIndex()));
7272 }
7273 }
7274
7275 EvalObj.finishedConstructingFields();
7276
7277 return Success &&
7278 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7279 LifetimeExtendedScope.destroy();
7280}
7281
7282static bool HandleConstructorCall(const Expr *E, const LValue &This,
7285 EvalInfo &Info, APValue &Result) {
7286 CallScopeRAII CallScope(Info);
7287 CallRef Call = Info.CurrentCall->createCall(Definition);
7288 if (!EvaluateArgs(Args, Call, Info, Definition))
7289 return false;
7290
7291 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
7292 CallScope.destroy();
7293}
7294
7295static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7296 const LValue &This, APValue &Value,
7297 QualType T) {
7298 // Objects can only be destroyed while they're within their lifetimes.
7299 // FIXME: We have no representation for whether an object of type nullptr_t
7300 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7301 // as indeterminate instead?
7302 if (Value.isAbsent() && !T->isNullPtrType()) {
7303 APValue Printable;
7304 This.moveInto(Printable);
7305 Info.FFDiag(CallRange.getBegin(),
7306 diag::note_constexpr_destroy_out_of_lifetime)
7307 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7308 return false;
7309 }
7310
7311 // Invent an expression for location purposes.
7312 // FIXME: We shouldn't need to do this.
7313 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7314
7315 // For arrays, destroy elements right-to-left.
7316 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7317 uint64_t Size = CAT->getZExtSize();
7318 QualType ElemT = CAT->getElementType();
7319
7320 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7321 return false;
7322
7323 LValue ElemLV = This;
7324 ElemLV.addArray(Info, &LocE, CAT);
7325 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7326 return false;
7327
7328 // Ensure that we have actual array elements available to destroy; the
7329 // destructors might mutate the value, so we can't run them on the array
7330 // filler.
7331 if (Size && Size > Value.getArrayInitializedElts())
7332 expandArray(Value, Value.getArraySize() - 1);
7333
7334 // The size of the array might have been reduced by
7335 // a placement new.
7336 for (Size = Value.getArraySize(); Size != 0; --Size) {
7337 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7338 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7339 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7340 return false;
7341 }
7342
7343 // End the lifetime of this array now.
7344 Value = APValue();
7345 return true;
7346 }
7347
7348 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7349 if (!RD) {
7350 if (T.isDestructedType()) {
7351 Info.FFDiag(CallRange.getBegin(),
7352 diag::note_constexpr_unsupported_destruction)
7353 << T;
7354 return false;
7355 }
7356
7357 Value = APValue();
7358 return true;
7359 }
7360
7361 if (RD->getNumVBases()) {
7362 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7363 return false;
7364 }
7365
7366 const CXXDestructorDecl *DD = RD->getDestructor();
7367 if (!DD && !RD->hasTrivialDestructor()) {
7368 Info.FFDiag(CallRange.getBegin());
7369 return false;
7370 }
7371
7372 if (!DD || DD->isTrivial() ||
7373 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7374 // A trivial destructor just ends the lifetime of the object. Check for
7375 // this case before checking for a body, because we might not bother
7376 // building a body for a trivial destructor. Note that it doesn't matter
7377 // whether the destructor is constexpr in this case; all trivial
7378 // destructors are constexpr.
7379 //
7380 // If an anonymous union would be destroyed, some enclosing destructor must
7381 // have been explicitly defined, and the anonymous union destruction should
7382 // have no effect.
7383 Value = APValue();
7384 return true;
7385 }
7386
7387 if (!Info.CheckCallLimit(CallRange.getBegin()))
7388 return false;
7389
7390 const FunctionDecl *Definition = nullptr;
7391 const Stmt *Body = DD->getBody(Definition);
7392
7393 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7394 return false;
7395
7396 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7397 CallRef());
7398
7399 // We're now in the period of destruction of this object.
7400 unsigned BasesLeft = RD->getNumBases();
7401 EvalInfo::EvaluatingDestructorRAII EvalObj(
7402 Info,
7403 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7404 if (!EvalObj.DidInsert) {
7405 // C++2a [class.dtor]p19:
7406 // the behavior is undefined if the destructor is invoked for an object
7407 // whose lifetime has ended
7408 // (Note that formally the lifetime ends when the period of destruction
7409 // begins, even though certain uses of the object remain valid until the
7410 // period of destruction ends.)
7411 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7412 return false;
7413 }
7414
7415 // FIXME: Creating an APValue just to hold a nonexistent return value is
7416 // wasteful.
7417 APValue RetVal;
7418 StmtResult Ret = {RetVal, nullptr};
7419 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7420 return false;
7421
7422 // A union destructor does not implicitly destroy its members.
7423 if (RD->isUnion())
7424 return true;
7425
7426 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7427
7428 // We don't have a good way to iterate fields in reverse, so collect all the
7429 // fields first and then walk them backwards.
7430 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7431 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7432 if (FD->isUnnamedBitField())
7433 continue;
7434
7435 LValue Subobject = This;
7436 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7437 return false;
7438
7439 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7440 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7441 FD->getType()))
7442 return false;
7443 }
7444
7445 if (BasesLeft != 0)
7446 EvalObj.startedDestroyingBases();
7447
7448 // Destroy base classes in reverse order.
7449 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7450 --BasesLeft;
7451
7452 QualType BaseType = Base.getType();
7453 LValue Subobject = This;
7454 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7455 BaseType->getAsCXXRecordDecl(), &Layout))
7456 return false;
7457
7458 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7459 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7460 BaseType))
7461 return false;
7462 }
7463 assert(BasesLeft == 0 && "NumBases was wrong?");
7464
7465 // The period of destruction ends now. The object is gone.
7466 Value = APValue();
7467 return true;
7468}
7469
7470namespace {
7471struct DestroyObjectHandler {
7472 EvalInfo &Info;
7473 const Expr *E;
7474 const LValue &This;
7475 const AccessKinds AccessKind;
7476
7477 typedef bool result_type;
7478 bool failed() { return false; }
7479 bool found(APValue &Subobj, QualType SubobjType) {
7480 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7481 SubobjType);
7482 }
7483 bool found(APSInt &Value, QualType SubobjType) {
7484 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7485 return false;
7486 }
7487 bool found(APFloat &Value, QualType SubobjType) {
7488 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7489 return false;
7490 }
7491};
7492}
7493
7494/// Perform a destructor or pseudo-destructor call on the given object, which
7495/// might in general not be a complete object.
7496static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7497 const LValue &This, QualType ThisType) {
7498 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7499 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7500 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7501}
7502
7503/// Destroy and end the lifetime of the given complete object.
7504static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7506 QualType T) {
7507 // If we've had an unmodeled side-effect, we can't rely on mutable state
7508 // (such as the object we're about to destroy) being correct.
7509 if (Info.EvalStatus.HasSideEffects)
7510 return false;
7511
7512 LValue LV;
7513 LV.set({LVBase});
7514 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7515}
7516
7517/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7518static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7519 LValue &Result) {
7520 if (Info.checkingPotentialConstantExpression() ||
7521 Info.SpeculativeEvaluationDepth)
7522 return false;
7523
7524 // This is permitted only within a call to std::allocator<T>::allocate.
7525 auto Caller = Info.getStdAllocatorCaller("allocate");
7526 if (!Caller) {
7527 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7528 ? diag::note_constexpr_new_untyped
7529 : diag::note_constexpr_new);
7530 return false;
7531 }
7532
7533 QualType ElemType = Caller.ElemType;
7534 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7535 Info.FFDiag(E->getExprLoc(),
7536 diag::note_constexpr_new_not_complete_object_type)
7537 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7538 return false;
7539 }
7540
7541 APSInt ByteSize;
7542 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7543 return false;
7544 bool IsNothrow = false;
7545 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7546 EvaluateIgnoredValue(Info, E->getArg(I));
7547 IsNothrow |= E->getType()->isNothrowT();
7548 }
7549
7550 CharUnits ElemSize;
7551 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7552 return false;
7553 APInt Size, Remainder;
7554 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7555 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7556 if (Remainder != 0) {
7557 // This likely indicates a bug in the implementation of 'std::allocator'.
7558 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7559 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7560 return false;
7561 }
7562
7563 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7564 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7565 if (IsNothrow) {
7566 Result.setNull(Info.Ctx, E->getType());
7567 return true;
7568 }
7569 return false;
7570 }
7571
7572 QualType AllocType = Info.Ctx.getConstantArrayType(
7573 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7574 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7575 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7576 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7577 return true;
7578}
7579
7581 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7582 if (CXXDestructorDecl *DD = RD->getDestructor())
7583 return DD->isVirtual();
7584 return false;
7585}
7586
7588 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7589 if (CXXDestructorDecl *DD = RD->getDestructor())
7590 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7591 return nullptr;
7592}
7593
7594/// Check that the given object is a suitable pointer to a heap allocation that
7595/// still exists and is of the right kind for the purpose of a deletion.
7596///
7597/// On success, returns the heap allocation to deallocate. On failure, produces
7598/// a diagnostic and returns std::nullopt.
7599static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7600 const LValue &Pointer,
7601 DynAlloc::Kind DeallocKind) {
7602 auto PointerAsString = [&] {
7603 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7604 };
7605
7606 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7607 if (!DA) {
7608 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7609 << PointerAsString();
7610 if (Pointer.Base)
7611 NoteLValueLocation(Info, Pointer.Base);
7612 return std::nullopt;
7613 }
7614
7615 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7616 if (!Alloc) {
7617 Info.FFDiag(E, diag::note_constexpr_double_delete);
7618 return std::nullopt;
7619 }
7620
7621 if (DeallocKind != (*Alloc)->getKind()) {
7622 QualType AllocType = Pointer.Base.getDynamicAllocType();
7623 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7624 << DeallocKind << (*Alloc)->getKind() << AllocType;
7625 NoteLValueLocation(Info, Pointer.Base);
7626 return std::nullopt;
7627 }
7628
7629 bool Subobject = false;
7630 if (DeallocKind == DynAlloc::New) {
7631 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7632 Pointer.Designator.isOnePastTheEnd();
7633 } else {
7634 Subobject = Pointer.Designator.Entries.size() != 1 ||
7635 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7636 }
7637 if (Subobject) {
7638 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7639 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7640 return std::nullopt;
7641 }
7642
7643 return Alloc;
7644}
7645
7646// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7647static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7648 if (Info.checkingPotentialConstantExpression() ||
7649 Info.SpeculativeEvaluationDepth)
7650 return false;
7651
7652 // This is permitted only within a call to std::allocator<T>::deallocate.
7653 if (!Info.getStdAllocatorCaller("deallocate")) {
7654 Info.FFDiag(E->getExprLoc());
7655 return true;
7656 }
7657
7658 LValue Pointer;
7659 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7660 return false;
7661 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7662 EvaluateIgnoredValue(Info, E->getArg(I));
7663
7664 if (Pointer.Designator.Invalid)
7665 return false;
7666
7667 // Deleting a null pointer would have no effect, but it's not permitted by
7668 // std::allocator<T>::deallocate's contract.
7669 if (Pointer.isNullPointer()) {
7670 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7671 return true;
7672 }
7673
7674 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7675 return false;
7676
7677 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7678 return true;
7679}
7680
7681//===----------------------------------------------------------------------===//
7682// Generic Evaluation
7683//===----------------------------------------------------------------------===//
7684namespace {
7685
7686class BitCastBuffer {
7687 // FIXME: We're going to need bit-level granularity when we support
7688 // bit-fields.
7689 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7690 // we don't support a host or target where that is the case. Still, we should
7691 // use a more generic type in case we ever do.
7692 SmallVector<std::optional<unsigned char>, 32> Bytes;
7693
7694 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7695 "Need at least 8 bit unsigned char");
7696
7697 bool TargetIsLittleEndian;
7698
7699public:
7700 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7701 : Bytes(Width.getQuantity()),
7702 TargetIsLittleEndian(TargetIsLittleEndian) {}
7703
7704 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7705 SmallVectorImpl<unsigned char> &Output) const {
7706 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7707 // If a byte of an integer is uninitialized, then the whole integer is
7708 // uninitialized.
7709 if (!Bytes[I.getQuantity()])
7710 return false;
7711 Output.push_back(*Bytes[I.getQuantity()]);
7712 }
7713 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7714 std::reverse(Output.begin(), Output.end());
7715 return true;
7716 }
7717
7718 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7719 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7720 std::reverse(Input.begin(), Input.end());
7721
7722 size_t Index = 0;
7723 for (unsigned char Byte : Input) {
7724 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7725 Bytes[Offset.getQuantity() + Index] = Byte;
7726 ++Index;
7727 }
7728 }
7729
7730 size_t size() { return Bytes.size(); }
7731};
7732
7733/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7734/// target would represent the value at runtime.
7735class APValueToBufferConverter {
7736 EvalInfo &Info;
7737 BitCastBuffer Buffer;
7738 const CastExpr *BCE;
7739
7740 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7741 const CastExpr *BCE)
7742 : Info(Info),
7743 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7744 BCE(BCE) {}
7745
7746 bool visit(const APValue &Val, QualType Ty) {
7747 return visit(Val, Ty, CharUnits::fromQuantity(0));
7748 }
7749
7750 // Write out Val with type Ty into Buffer starting at Offset.
7751 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7752 assert((size_t)Offset.getQuantity() <= Buffer.size());
7753
7754 // As a special case, nullptr_t has an indeterminate value.
7755 if (Ty->isNullPtrType())
7756 return true;
7757
7758 // Dig through Src to find the byte at SrcOffset.
7759 switch (Val.getKind()) {
7761 case APValue::None:
7762 return true;
7763
7764 case APValue::Int:
7765 return visitInt(Val.getInt(), Ty, Offset);
7766 case APValue::Float:
7767 return visitFloat(Val.getFloat(), Ty, Offset);
7768 case APValue::Array:
7769 return visitArray(Val, Ty, Offset);
7770 case APValue::Struct:
7771 return visitRecord(Val, Ty, Offset);
7772 case APValue::Vector:
7773 return visitVector(Val, Ty, Offset);
7774
7777 return visitComplex(Val, Ty, Offset);
7779 // FIXME: We should support these.
7780
7781 case APValue::LValue:
7782 case APValue::Matrix:
7783 case APValue::Union:
7786 Info.FFDiag(BCE->getBeginLoc(),
7787 diag::note_constexpr_bit_cast_unsupported_type)
7788 << Ty;
7789 return false;
7790 }
7791 }
7792 llvm_unreachable("Unhandled APValue::ValueKind");
7793 }
7794
7795 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7796 const RecordDecl *RD = Ty->getAsRecordDecl();
7797 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7798
7799 // Visit the base classes.
7800 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7801 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7802 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7803 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7804 const APValue &Base = Val.getStructBase(I);
7805
7806 // Can happen in error cases.
7807 if (!Base.isStruct())
7808 return false;
7809
7810 if (!visitRecord(Base, BS.getType(),
7811 Layout.getBaseClassOffset(BaseDecl) + Offset))
7812 return false;
7813 }
7814 }
7815
7816 // Visit the fields.
7817 unsigned FieldIdx = 0;
7818 for (FieldDecl *FD : RD->fields()) {
7819 if (FD->isBitField()) {
7820 Info.FFDiag(BCE->getBeginLoc(),
7821 diag::note_constexpr_bit_cast_unsupported_bitfield);
7822 return false;
7823 }
7824
7825 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7826
7827 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7828 "only bit-fields can have sub-char alignment");
7829 CharUnits FieldOffset =
7830 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7831 QualType FieldTy = FD->getType();
7832 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7833 return false;
7834 ++FieldIdx;
7835 }
7836
7837 return true;
7838 }
7839
7840 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7841 const auto *CAT =
7842 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7843 if (!CAT)
7844 return false;
7845
7846 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7847 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7848 unsigned ArraySize = Val.getArraySize();
7849 // First, initialize the initialized elements.
7850 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7851 const APValue &SubObj = Val.getArrayInitializedElt(I);
7852 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7853 return false;
7854 }
7855
7856 // Next, initialize the rest of the array using the filler.
7857 if (Val.hasArrayFiller()) {
7858 const APValue &Filler = Val.getArrayFiller();
7859 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7860 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7861 return false;
7862 }
7863 }
7864
7865 return true;
7866 }
7867
7868 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7869 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7870 QualType EltTy = ComplexTy->getElementType();
7871 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7872 bool IsInt = Val.isComplexInt();
7873
7874 if (IsInt) {
7875 if (!visitInt(Val.getComplexIntReal(), EltTy,
7876 Offset + (0 * EltSizeChars)))
7877 return false;
7878 if (!visitInt(Val.getComplexIntImag(), EltTy,
7879 Offset + (1 * EltSizeChars)))
7880 return false;
7881 } else {
7882 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7883 Offset + (0 * EltSizeChars)))
7884 return false;
7885 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7886 Offset + (1 * EltSizeChars)))
7887 return false;
7888 }
7889
7890 return true;
7891 }
7892
7893 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7894 const VectorType *VTy = Ty->castAs<VectorType>();
7895 QualType EltTy = VTy->getElementType();
7896 unsigned NElts = VTy->getNumElements();
7897
7898 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7899 // Special handling for OpenCL bool vectors:
7900 // Since these vectors are stored as packed bits, but we can't write
7901 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7902 // together into an appropriately sized APInt and write them all out at
7903 // once. Because we don't accept vectors where NElts * EltSize isn't a
7904 // multiple of the char size, there will be no padding space, so we don't
7905 // have to worry about writing data which should have been left
7906 // uninitialized.
7907 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7908
7909 llvm::APInt Res = llvm::APInt::getZero(NElts);
7910 for (unsigned I = 0; I < NElts; ++I) {
7911 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7912 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7913 "bool vector element must be 1-bit unsigned integer!");
7914
7915 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7916 }
7917
7918 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7919 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7920 Buffer.writeObject(Offset, Bytes);
7921 } else {
7922 // Iterate over each of the elements and write them out to the buffer at
7923 // the appropriate offset.
7924 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7925 for (unsigned I = 0; I < NElts; ++I) {
7926 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7927 return false;
7928 }
7929 }
7930
7931 return true;
7932 }
7933
7934 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7935 APSInt AdjustedVal = Val;
7936 unsigned Width = AdjustedVal.getBitWidth();
7937 if (Ty->isBooleanType()) {
7938 Width = Info.Ctx.getTypeSize(Ty);
7939 AdjustedVal = AdjustedVal.extend(Width);
7940 }
7941
7942 SmallVector<uint8_t, 8> Bytes(Width / 8);
7943 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7944 Buffer.writeObject(Offset, Bytes);
7945 return true;
7946 }
7947
7948 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7949 APSInt AsInt(Val.bitcastToAPInt());
7950 return visitInt(AsInt, Ty, Offset);
7951 }
7952
7953public:
7954 static std::optional<BitCastBuffer>
7955 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7956 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7957 APValueToBufferConverter Converter(Info, DstSize, BCE);
7958 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7959 return std::nullopt;
7960 return Converter.Buffer;
7961 }
7962};
7963
7964/// Write an BitCastBuffer into an APValue.
7965class BufferToAPValueConverter {
7966 EvalInfo &Info;
7967 const BitCastBuffer &Buffer;
7968 const CastExpr *BCE;
7969
7970 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7971 const CastExpr *BCE)
7972 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7973
7974 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7975 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7976 // Ideally this will be unreachable.
7977 std::nullopt_t unsupportedType(QualType Ty) {
7978 Info.FFDiag(BCE->getBeginLoc(),
7979 diag::note_constexpr_bit_cast_unsupported_type)
7980 << Ty;
7981 return std::nullopt;
7982 }
7983
7984 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7985 Info.FFDiag(BCE->getBeginLoc(),
7986 diag::note_constexpr_bit_cast_unrepresentable_value)
7987 << Ty << toString(Val, /*Radix=*/10);
7988 return std::nullopt;
7989 }
7990
7991 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7992 const EnumType *EnumSugar = nullptr) {
7993 if (T->isNullPtrType()) {
7994 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7995 return APValue((Expr *)nullptr,
7996 /*Offset=*/CharUnits::fromQuantity(NullValue),
7997 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7998 }
7999
8000 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
8001
8002 // Work around floating point types that contain unused padding bytes. This
8003 // is really just `long double` on x86, which is the only fundamental type
8004 // with padding bytes.
8005 if (T->isRealFloatingType()) {
8006 const llvm::fltSemantics &Semantics =
8007 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8008 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8009 assert(NumBits % 8 == 0);
8010 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
8011 if (NumBytes != SizeOf)
8012 SizeOf = NumBytes;
8013 }
8014
8015 SmallVector<uint8_t, 8> Bytes;
8016 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
8017 // If this is std::byte or unsigned char, then its okay to store an
8018 // indeterminate value.
8019 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8020 bool IsUChar =
8021 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
8022 T->isSpecificBuiltinType(BuiltinType::Char_U));
8023 if (!IsStdByte && !IsUChar) {
8024 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
8025 Info.FFDiag(BCE->getExprLoc(),
8026 diag::note_constexpr_bit_cast_indet_dest)
8027 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8028 return std::nullopt;
8029 }
8030
8032 }
8033
8034 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
8035 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8036
8037 if (T->isIntegralOrEnumerationType()) {
8038 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
8039
8040 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
8041 if (IntWidth != Val.getBitWidth()) {
8042 APSInt Truncated = Val.trunc(IntWidth);
8043 if (Truncated.extend(Val.getBitWidth()) != Val)
8044 return unrepresentableValue(QualType(T, 0), Val);
8045 Val = Truncated;
8046 }
8047
8048 return APValue(Val);
8049 }
8050
8051 if (T->isRealFloatingType()) {
8052 const llvm::fltSemantics &Semantics =
8053 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8054 return APValue(APFloat(Semantics, Val));
8055 }
8056
8057 return unsupportedType(QualType(T, 0));
8058 }
8059
8060 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
8061 const RecordDecl *RD = RTy->getAsRecordDecl();
8062 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8063
8064 unsigned NumBases = 0;
8065 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8066 NumBases = CXXRD->getNumBases();
8067
8068 APValue ResultVal(APValue::UninitStruct(), NumBases, RD->getNumFields());
8069
8070 // Visit the base classes.
8071 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8072 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8073 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8074 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8075
8076 std::optional<APValue> SubObj = visitType(
8077 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
8078 if (!SubObj)
8079 return std::nullopt;
8080 ResultVal.getStructBase(I) = *SubObj;
8081 }
8082 }
8083
8084 // Visit the fields.
8085 unsigned FieldIdx = 0;
8086 for (FieldDecl *FD : RD->fields()) {
8087 // FIXME: We don't currently support bit-fields. A lot of the logic for
8088 // this is in CodeGen, so we need to factor it around.
8089 if (FD->isBitField()) {
8090 Info.FFDiag(BCE->getBeginLoc(),
8091 diag::note_constexpr_bit_cast_unsupported_bitfield);
8092 return std::nullopt;
8093 }
8094
8095 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8096 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8097
8098 CharUnits FieldOffset =
8099 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
8100 Offset;
8101 QualType FieldTy = FD->getType();
8102 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8103 if (!SubObj)
8104 return std::nullopt;
8105 ResultVal.getStructField(FieldIdx) = *SubObj;
8106 ++FieldIdx;
8107 }
8108
8109 return ResultVal;
8110 }
8111
8112 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
8113 QualType RepresentationType =
8114 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8115 assert(!RepresentationType.isNull() &&
8116 "enum forward decl should be caught by Sema");
8117 const auto *AsBuiltin =
8118 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
8119 // Recurse into the underlying type. Treat std::byte transparently as
8120 // unsigned char.
8121 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
8122 }
8123
8124 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
8125 size_t Size = Ty->getLimitedSize();
8126 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
8127
8128 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8129 for (size_t I = 0; I != Size; ++I) {
8130 std::optional<APValue> ElementValue =
8131 visitType(Ty->getElementType(), Offset + I * ElementWidth);
8132 if (!ElementValue)
8133 return std::nullopt;
8134 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8135 }
8136
8137 return ArrayValue;
8138 }
8139
8140 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
8141 QualType ElementType = Ty->getElementType();
8142 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8143 bool IsInt = ElementType->isIntegerType();
8144
8145 std::optional<APValue> Values[2];
8146 for (unsigned I = 0; I != 2; ++I) {
8147 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
8148 if (!Values[I])
8149 return std::nullopt;
8150 }
8151
8152 if (IsInt)
8153 return APValue(Values[0]->getInt(), Values[1]->getInt());
8154 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8155 }
8156
8157 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
8158 QualType EltTy = VTy->getElementType();
8159 unsigned NElts = VTy->getNumElements();
8160 unsigned EltSize =
8161 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
8162
8163 SmallVector<APValue, 4> Elts;
8164 Elts.reserve(NElts);
8165 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8166 // Special handling for OpenCL bool vectors:
8167 // Since these vectors are stored as packed bits, but we can't read
8168 // individual bits from the BitCastBuffer, we'll buffer all of the
8169 // elements together into an appropriately sized APInt and write them all
8170 // out at once. Because we don't accept vectors where NElts * EltSize
8171 // isn't a multiple of the char size, there will be no padding space, so
8172 // we don't have to worry about reading any padding data which didn't
8173 // actually need to be accessed.
8174 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8175
8176 SmallVector<uint8_t, 8> Bytes;
8177 Bytes.reserve(NElts / 8);
8178 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
8179 return std::nullopt;
8180
8181 APSInt SValInt(NElts, true);
8182 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8183
8184 for (unsigned I = 0; I < NElts; ++I) {
8185 llvm::APInt Elt =
8186 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8187 Elts.emplace_back(
8188 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
8189 }
8190 } else {
8191 // Iterate over each of the elements and read them from the buffer at
8192 // the appropriate offset.
8193 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8194 for (unsigned I = 0; I < NElts; ++I) {
8195 std::optional<APValue> EltValue =
8196 visitType(EltTy, Offset + I * EltSizeChars);
8197 if (!EltValue)
8198 return std::nullopt;
8199 Elts.push_back(std::move(*EltValue));
8200 }
8201 }
8202
8203 return APValue(Elts.data(), Elts.size());
8204 }
8205
8206 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
8207 return unsupportedType(QualType(Ty, 0));
8208 }
8209
8210 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8211 QualType Can = Ty.getCanonicalType();
8212
8213 switch (Can->getTypeClass()) {
8214#define TYPE(Class, Base) \
8215 case Type::Class: \
8216 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8217#define ABSTRACT_TYPE(Class, Base)
8218#define NON_CANONICAL_TYPE(Class, Base) \
8219 case Type::Class: \
8220 llvm_unreachable("non-canonical type should be impossible!");
8221#define DEPENDENT_TYPE(Class, Base) \
8222 case Type::Class: \
8223 llvm_unreachable( \
8224 "dependent types aren't supported in the constant evaluator!");
8225#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8226 case Type::Class: \
8227 llvm_unreachable("either dependent or not canonical!");
8228#include "clang/AST/TypeNodes.inc"
8229 }
8230 llvm_unreachable("Unhandled Type::TypeClass");
8231 }
8232
8233public:
8234 // Pull out a full value of type DstType.
8235 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8236 const CastExpr *BCE) {
8237 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8238 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
8239 }
8240};
8241
8242static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8243 QualType Ty, EvalInfo *Info,
8244 const ASTContext &Ctx,
8245 bool CheckingDest) {
8246 Ty = Ty.getCanonicalType();
8247
8248 auto diag = [&](int Reason) {
8249 if (Info)
8250 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8251 << CheckingDest << (Reason == 4) << Reason;
8252 return false;
8253 };
8254 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8255 if (Info)
8256 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8257 << NoteTy << Construct << Ty;
8258 return false;
8259 };
8260
8261 if (Ty->isUnionType())
8262 return diag(0);
8263 if (Ty->isPointerType())
8264 return diag(1);
8265 if (Ty->isMemberPointerType())
8266 return diag(2);
8267 if (Ty.isVolatileQualified())
8268 return diag(3);
8269
8270 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8271 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8272 for (CXXBaseSpecifier &BS : CXXRD->bases())
8273 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8274 CheckingDest))
8275 return note(1, BS.getType(), BS.getBeginLoc());
8276 }
8277 for (FieldDecl *FD : Record->fields()) {
8278 if (FD->getType()->isReferenceType())
8279 return diag(4);
8280 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8281 CheckingDest))
8282 return note(0, FD->getType(), FD->getBeginLoc());
8283 }
8284 }
8285
8286 if (Ty->isArrayType() &&
8287 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8288 Info, Ctx, CheckingDest))
8289 return false;
8290
8291 if (const auto *VTy = Ty->getAs<VectorType>()) {
8292 QualType EltTy = VTy->getElementType();
8293 unsigned NElts = VTy->getNumElements();
8294 unsigned EltSize =
8295 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8296
8297 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8298 // The vector's size in bits is not a multiple of the target's byte size,
8299 // so its layout is unspecified. For now, we'll simply treat these cases
8300 // as unsupported (this should only be possible with OpenCL bool vectors
8301 // whose element count isn't a multiple of the byte size).
8302 if (Info)
8303 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8304 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8305 return false;
8306 }
8307
8308 if (EltTy->isRealFloatingType() &&
8309 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8310 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8311 // by both clang and LLVM, so for now we won't allow bit_casts involving
8312 // it in a constexpr context.
8313 if (Info)
8314 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8315 << EltTy;
8316 return false;
8317 }
8318 }
8319
8320 return true;
8321}
8322
8323static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8324 const ASTContext &Ctx,
8325 const CastExpr *BCE) {
8326 bool DestOK = checkBitCastConstexprEligibilityType(
8327 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8328 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8329 BCE->getBeginLoc(),
8330 BCE->getSubExpr()->getType(), Info, Ctx, false);
8331 return SourceOK;
8332}
8333
8334static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8335 const APValue &SourceRValue,
8336 const CastExpr *BCE) {
8337 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8338 "no host or target supports non 8-bit chars");
8339
8340 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8341 return false;
8342
8343 // Read out SourceValue into a char buffer.
8344 std::optional<BitCastBuffer> Buffer =
8345 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8346 if (!Buffer)
8347 return false;
8348
8349 // Write out the buffer into a new APValue.
8350 std::optional<APValue> MaybeDestValue =
8351 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8352 if (!MaybeDestValue)
8353 return false;
8354
8355 DestValue = std::move(*MaybeDestValue);
8356 return true;
8357}
8358
8359static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8360 APValue &SourceValue,
8361 const CastExpr *BCE) {
8362 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8363 "no host or target supports non 8-bit chars");
8364 assert(SourceValue.isLValue() &&
8365 "LValueToRValueBitcast requires an lvalue operand!");
8366
8367 LValue SourceLValue;
8368 APValue SourceRValue;
8369 SourceLValue.setFrom(Info.Ctx, SourceValue);
8371 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8372 SourceRValue, /*WantObjectRepresentation=*/true))
8373 return false;
8374
8375 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8376}
8377
8378template <class Derived>
8379class ExprEvaluatorBase
8380 : public ConstStmtVisitor<Derived, bool> {
8381private:
8382 Derived &getDerived() { return static_cast<Derived&>(*this); }
8383 bool DerivedSuccess(const APValue &V, const Expr *E) {
8384 return getDerived().Success(V, E);
8385 }
8386 bool DerivedZeroInitialization(const Expr *E) {
8387 return getDerived().ZeroInitialization(E);
8388 }
8389
8390 // Check whether a conditional operator with a non-constant condition is a
8391 // potential constant expression. If neither arm is a potential constant
8392 // expression, then the conditional operator is not either.
8393 template<typename ConditionalOperator>
8394 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8395 assert(Info.checkingPotentialConstantExpression());
8396
8397 // Speculatively evaluate both arms.
8398 SmallVector<PartialDiagnosticAt, 8> Diag;
8399 {
8400 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8401 StmtVisitorTy::Visit(E->getFalseExpr());
8402 if (Diag.empty())
8403 return;
8404 }
8405
8406 {
8407 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8408 Diag.clear();
8409 StmtVisitorTy::Visit(E->getTrueExpr());
8410 if (Diag.empty())
8411 return;
8412 }
8413
8414 Error(E, diag::note_constexpr_conditional_never_const);
8415 }
8416
8417
8418 template<typename ConditionalOperator>
8419 bool HandleConditionalOperator(const ConditionalOperator *E) {
8420 bool BoolResult;
8421 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8422 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8423 CheckPotentialConstantConditional(E);
8424 return false;
8425 }
8426 if (Info.noteFailure()) {
8427 StmtVisitorTy::Visit(E->getTrueExpr());
8428 StmtVisitorTy::Visit(E->getFalseExpr());
8429 }
8430 return false;
8431 }
8432
8433 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8434 return StmtVisitorTy::Visit(EvalExpr);
8435 }
8436
8437protected:
8438 EvalInfo &Info;
8439 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8440 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8441
8442 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8443 return Info.CCEDiag(E, D);
8444 }
8445
8446 bool ZeroInitialization(const Expr *E) { return Error(E); }
8447
8448 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8449 unsigned BuiltinOp = E->getBuiltinCallee();
8450 return BuiltinOp != 0 &&
8451 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8452 }
8453
8454public:
8455 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8456
8457 EvalInfo &getEvalInfo() { return Info; }
8458
8459 /// Report an evaluation error. This should only be called when an error is
8460 /// first discovered. When propagating an error, just return false.
8461 bool Error(const Expr *E, diag::kind D) {
8462 Info.FFDiag(E, D) << E->getSourceRange();
8463 return false;
8464 }
8465 bool Error(const Expr *E) {
8466 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8467 }
8468
8469 bool VisitStmt(const Stmt *) {
8470 llvm_unreachable("Expression evaluator should not be called on stmts");
8471 }
8472 bool VisitExpr(const Expr *E) {
8473 return Error(E);
8474 }
8475
8476 bool VisitEmbedExpr(const EmbedExpr *E) {
8477 const auto It = E->begin();
8478 return StmtVisitorTy::Visit(*It);
8479 }
8480
8481 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8482 return StmtVisitorTy::Visit(E->getFunctionName());
8483 }
8484 bool VisitConstantExpr(const ConstantExpr *E) {
8485 if (E->hasAPValueResult())
8486 return DerivedSuccess(E->getAPValueResult(), E);
8487
8488 return StmtVisitorTy::Visit(E->getSubExpr());
8489 }
8490
8491 bool VisitParenExpr(const ParenExpr *E)
8492 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8493 bool VisitUnaryExtension(const UnaryOperator *E)
8494 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8495 bool VisitUnaryPlus(const UnaryOperator *E)
8496 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8497 bool VisitChooseExpr(const ChooseExpr *E)
8498 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8499 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8500 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8501 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8502 { return StmtVisitorTy::Visit(E->getReplacement()); }
8503 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8504 TempVersionRAII RAII(*Info.CurrentCall);
8505 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8506 return StmtVisitorTy::Visit(E->getExpr());
8507 }
8508 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8509 TempVersionRAII RAII(*Info.CurrentCall);
8510 // The initializer may not have been parsed yet, or might be erroneous.
8511 if (!E->getExpr())
8512 return Error(E);
8513 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8514 return StmtVisitorTy::Visit(E->getExpr());
8515 }
8516
8517 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8518 FullExpressionRAII Scope(Info);
8519 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8520 }
8521
8522 // Temporaries are registered when created, so we don't care about
8523 // CXXBindTemporaryExpr.
8524 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8525 return StmtVisitorTy::Visit(E->getSubExpr());
8526 }
8527
8528 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8529 CCEDiag(E, diag::note_constexpr_invalid_cast)
8530 << diag::ConstexprInvalidCastKind::Reinterpret;
8531 return static_cast<Derived*>(this)->VisitCastExpr(E);
8532 }
8533 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8534 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8535 CCEDiag(E, diag::note_constexpr_invalid_cast)
8536 << diag::ConstexprInvalidCastKind::Dynamic;
8537 return static_cast<Derived*>(this)->VisitCastExpr(E);
8538 }
8539 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8540 return static_cast<Derived*>(this)->VisitCastExpr(E);
8541 }
8542
8543 bool VisitBinaryOperator(const BinaryOperator *E) {
8544 switch (E->getOpcode()) {
8545 default:
8546 return Error(E);
8547
8548 case BO_Comma:
8549 VisitIgnoredValue(E->getLHS());
8550 return StmtVisitorTy::Visit(E->getRHS());
8551
8552 case BO_PtrMemD:
8553 case BO_PtrMemI: {
8554 LValue Obj;
8555 if (!HandleMemberPointerAccess(Info, E, Obj))
8556 return false;
8558 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8559 return false;
8560 return DerivedSuccess(Result, E);
8561 }
8562 }
8563 }
8564
8565 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8566 return StmtVisitorTy::Visit(E->getSemanticForm());
8567 }
8568
8569 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8570 // Evaluate and cache the common expression. We treat it as a temporary,
8571 // even though it's not quite the same thing.
8572 LValue CommonLV;
8573 if (!Evaluate(Info.CurrentCall->createTemporary(
8574 E->getOpaqueValue(),
8575 getStorageType(Info.Ctx, E->getOpaqueValue()),
8576 ScopeKind::FullExpression, CommonLV),
8577 Info, E->getCommon()))
8578 return false;
8579
8580 return HandleConditionalOperator(E);
8581 }
8582
8583 bool VisitConditionalOperator(const ConditionalOperator *E) {
8584 bool IsBcpCall = false;
8585 // If the condition (ignoring parens) is a __builtin_constant_p call,
8586 // the result is a constant expression if it can be folded without
8587 // side-effects. This is an important GNU extension. See GCC PR38377
8588 // for discussion.
8589 if (const CallExpr *CallCE =
8590 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8591 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8592 IsBcpCall = true;
8593
8594 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8595 // constant expression; we can't check whether it's potentially foldable.
8596 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8597 // it would return 'false' in this mode.
8598 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8599 return false;
8600
8601 FoldConstant Fold(Info, IsBcpCall);
8602 if (!HandleConditionalOperator(E)) {
8603 Fold.keepDiagnostics();
8604 return false;
8605 }
8606
8607 return true;
8608 }
8609
8610 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8611 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8612 Value && !Value->isAbsent())
8613 return DerivedSuccess(*Value, E);
8614
8615 const Expr *Source = E->getSourceExpr();
8616 if (!Source)
8617 return Error(E);
8618 if (Source == E) {
8619 assert(0 && "OpaqueValueExpr recursively refers to itself");
8620 return Error(E);
8621 }
8622 return StmtVisitorTy::Visit(Source);
8623 }
8624
8625 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8626 for (const Expr *SemE : E->semantics()) {
8627 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8628 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8629 // result expression: there could be two different LValues that would
8630 // refer to the same object in that case, and we can't model that.
8631 if (SemE == E->getResultExpr())
8632 return Error(E);
8633
8634 // Unique OVEs get evaluated if and when we encounter them when
8635 // emitting the rest of the semantic form, rather than eagerly.
8636 if (OVE->isUnique())
8637 continue;
8638
8639 LValue LV;
8640 if (!Evaluate(Info.CurrentCall->createTemporary(
8641 OVE, getStorageType(Info.Ctx, OVE),
8642 ScopeKind::FullExpression, LV),
8643 Info, OVE->getSourceExpr()))
8644 return false;
8645 } else if (SemE == E->getResultExpr()) {
8646 if (!StmtVisitorTy::Visit(SemE))
8647 return false;
8648 } else {
8649 if (!EvaluateIgnoredValue(Info, SemE))
8650 return false;
8651 }
8652 }
8653 return true;
8654 }
8655
8656 bool VisitCallExpr(const CallExpr *E) {
8658 if (!handleCallExpr(E, Result, nullptr))
8659 return false;
8660 return DerivedSuccess(Result, E);
8661 }
8662
8663 bool handleCallExpr(const CallExpr *E, APValue &Result,
8664 const LValue *ResultSlot) {
8665 CallScopeRAII CallScope(Info);
8666
8667 const Expr *Callee = E->getCallee()->IgnoreParens();
8668 QualType CalleeType = Callee->getType();
8669
8670 const FunctionDecl *FD = nullptr;
8671 LValue *This = nullptr, ObjectArg;
8672 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8673 bool HasQualifier = false;
8674
8675 CallRef Call;
8676
8677 // Extract function decl and 'this' pointer from the callee.
8678 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8679 const CXXMethodDecl *Member = nullptr;
8680 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8681 // Explicit bound member calls, such as x.f() or p->g();
8682 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8683 return false;
8684 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8685 if (!Member)
8686 return Error(Callee);
8687 This = &ObjectArg;
8688 HasQualifier = ME->hasQualifier();
8689 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8690 // Indirect bound member calls ('.*' or '->*').
8691 const ValueDecl *D =
8692 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8693 if (!D)
8694 return false;
8695 Member = dyn_cast<CXXMethodDecl>(D);
8696 if (!Member)
8697 return Error(Callee);
8698 This = &ObjectArg;
8699 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8700 if (!Info.getLangOpts().CPlusPlus20)
8701 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8702 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8703 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8704 } else
8705 return Error(Callee);
8706 FD = Member;
8707 } else if (CalleeType->isFunctionPointerType()) {
8708 LValue CalleeLV;
8709 if (!EvaluatePointer(Callee, CalleeLV, Info))
8710 return false;
8711
8712 if (!CalleeLV.getLValueOffset().isZero())
8713 return Error(Callee);
8714 if (CalleeLV.isNullPointer()) {
8715 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8716 << const_cast<Expr *>(Callee);
8717 return false;
8718 }
8719 FD = dyn_cast_or_null<FunctionDecl>(
8720 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8721 if (!FD)
8722 return Error(Callee);
8723 // Don't call function pointers which have been cast to some other type.
8724 // Per DR (no number yet), the caller and callee can differ in noexcept.
8725 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8726 CalleeType->getPointeeType(), FD->getType())) {
8727 return Error(E);
8728 }
8729
8730 // For an (overloaded) assignment expression, evaluate the RHS before the
8731 // LHS.
8732 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8733 if (OCE && OCE->isAssignmentOp()) {
8734 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8735 Call = Info.CurrentCall->createCall(FD);
8736 bool HasThis = false;
8737 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8738 HasThis = MD->isImplicitObjectMemberFunction();
8739 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8740 /*RightToLeft=*/true, &ObjectArg))
8741 return false;
8742 }
8743
8744 // Overloaded operator calls to member functions are represented as normal
8745 // calls with '*this' as the first argument.
8746 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8747 if (MD &&
8748 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8749 // FIXME: When selecting an implicit conversion for an overloaded
8750 // operator delete, we sometimes try to evaluate calls to conversion
8751 // operators without a 'this' parameter!
8752 if (Args.empty())
8753 return Error(E);
8754
8755 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8756 return false;
8757
8758 // If we are calling a static operator, the 'this' argument needs to be
8759 // ignored after being evaluated.
8760 if (MD->isInstance())
8761 This = &ObjectArg;
8762
8763 // If this is syntactically a simple assignment using a trivial
8764 // assignment operator, start the lifetimes of union members as needed,
8765 // per C++20 [class.union]5.
8766 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8767 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8768 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8769 return false;
8770
8771 Args = Args.slice(1);
8772 } else if (MD && MD->isLambdaStaticInvoker()) {
8773 // Map the static invoker for the lambda back to the call operator.
8774 // Conveniently, we don't have to slice out the 'this' argument (as is
8775 // being done for the non-static case), since a static member function
8776 // doesn't have an implicit argument passed in.
8777 const CXXRecordDecl *ClosureClass = MD->getParent();
8778 assert(
8779 ClosureClass->captures().empty() &&
8780 "Number of captures must be zero for conversion to function-ptr");
8781
8782 const CXXMethodDecl *LambdaCallOp =
8783 ClosureClass->getLambdaCallOperator();
8784
8785 // Set 'FD', the function that will be called below, to the call
8786 // operator. If the closure object represents a generic lambda, find
8787 // the corresponding specialization of the call operator.
8788
8789 if (ClosureClass->isGenericLambda()) {
8790 assert(MD->isFunctionTemplateSpecialization() &&
8791 "A generic lambda's static-invoker function must be a "
8792 "template specialization");
8793 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8794 FunctionTemplateDecl *CallOpTemplate =
8795 LambdaCallOp->getDescribedFunctionTemplate();
8796 void *InsertPos = nullptr;
8797 FunctionDecl *CorrespondingCallOpSpecialization =
8798 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8799 assert(CorrespondingCallOpSpecialization &&
8800 "We must always have a function call operator specialization "
8801 "that corresponds to our static invoker specialization");
8802 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8803 FD = CorrespondingCallOpSpecialization;
8804 } else
8805 FD = LambdaCallOp;
8807 if (FD->getDeclName().isAnyOperatorNew()) {
8808 LValue Ptr;
8809 if (!HandleOperatorNewCall(Info, E, Ptr))
8810 return false;
8811 Ptr.moveInto(Result);
8812 return CallScope.destroy();
8813 } else {
8814 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8815 }
8816 }
8817 } else
8818 return Error(E);
8819
8820 // Evaluate the arguments now if we've not already done so.
8821 if (!Call) {
8822 Call = Info.CurrentCall->createCall(FD);
8823 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8824 &ObjectArg))
8825 return false;
8826 }
8827
8828 SmallVector<QualType, 4> CovariantAdjustmentPath;
8829 if (This) {
8830 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8831 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8832 // Perform virtual dispatch, if necessary.
8833 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8834 CovariantAdjustmentPath);
8835 if (!FD)
8836 return false;
8837 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8838 // Check that the 'this' pointer points to an object of the right type.
8839 // FIXME: If this is an assignment operator call, we may need to change
8840 // the active union member before we check this.
8841 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8842 return false;
8843 }
8844 }
8845
8846 // Destructor calls are different enough that they have their own codepath.
8847 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8848 assert(This && "no 'this' pointer for destructor call");
8849 return HandleDestruction(Info, E, *This,
8850 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8851 CallScope.destroy();
8852 }
8853
8854 const FunctionDecl *Definition = nullptr;
8855 Stmt *Body = FD->getBody(Definition);
8856 SourceLocation Loc = E->getExprLoc();
8857
8858 // Treat the object argument as `this` when evaluating defaulted
8859 // special menmber functions
8861 This = &ObjectArg;
8862
8863 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8864 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8865 Result, ResultSlot))
8866 return false;
8867
8868 if (!CovariantAdjustmentPath.empty() &&
8870 CovariantAdjustmentPath))
8871 return false;
8872
8873 return CallScope.destroy();
8874 }
8875
8876 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8877 return StmtVisitorTy::Visit(E->getInitializer());
8878 }
8879 bool VisitInitListExpr(const InitListExpr *E) {
8880 if (E->getNumInits() == 0)
8881 return DerivedZeroInitialization(E);
8882 if (E->getNumInits() == 1)
8883 return StmtVisitorTy::Visit(E->getInit(0));
8884 return Error(E);
8885 }
8886 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8887 return DerivedZeroInitialization(E);
8888 }
8889 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8890 return DerivedZeroInitialization(E);
8891 }
8892 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8893 return DerivedZeroInitialization(E);
8894 }
8895
8896 /// A member expression where the object is a prvalue is itself a prvalue.
8897 bool VisitMemberExpr(const MemberExpr *E) {
8898 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8899 "missing temporary materialization conversion");
8900 assert(!E->isArrow() && "missing call to bound member function?");
8901
8902 APValue Val;
8903 if (!Evaluate(Val, Info, E->getBase()))
8904 return false;
8905
8906 QualType BaseTy = E->getBase()->getType();
8907
8908 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8909 if (!FD) return Error(E);
8910 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8911 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
8912 FD->getParent()->getCanonicalDecl() &&
8913 "record / field mismatch");
8914
8915 // Note: there is no lvalue base here. But this case should only ever
8916 // happen in C or in C++98, where we cannot be evaluating a constexpr
8917 // constructor, which is the only case the base matters.
8918 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8919 SubobjectDesignator Designator(BaseTy);
8920 Designator.addDeclUnchecked(FD);
8921
8923 return extractSubobject(Info, E, Obj, Designator, Result) &&
8924 DerivedSuccess(Result, E);
8925 }
8926
8927 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8928 APValue Val;
8929 if (!Evaluate(Val, Info, E->getBase()))
8930 return false;
8931
8932 if (Val.isVector()) {
8933 SmallVector<uint32_t, 4> Indices;
8934 E->getEncodedElementAccess(Indices);
8935 if (Indices.size() == 1) {
8936 // Return scalar.
8937 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8938 } else {
8939 // Construct new APValue vector.
8940 SmallVector<APValue, 4> Elts;
8941 for (unsigned I = 0; I < Indices.size(); ++I) {
8942 Elts.push_back(Val.getVectorElt(Indices[I]));
8943 }
8944 APValue VecResult(Elts.data(), Indices.size());
8945 return DerivedSuccess(VecResult, E);
8946 }
8947 }
8948
8949 return false;
8950 }
8951
8952 bool VisitCastExpr(const CastExpr *E) {
8953 switch (E->getCastKind()) {
8954 default:
8955 break;
8956
8957 case CK_AtomicToNonAtomic: {
8958 APValue AtomicVal;
8959 // This does not need to be done in place even for class/array types:
8960 // atomic-to-non-atomic conversion implies copying the object
8961 // representation.
8962 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8963 return false;
8964 return DerivedSuccess(AtomicVal, E);
8965 }
8966
8967 case CK_NoOp:
8968 case CK_UserDefinedConversion:
8969 return StmtVisitorTy::Visit(E->getSubExpr());
8970
8971 case CK_HLSLArrayRValue: {
8972 const Expr *SubExpr = E->getSubExpr();
8973 if (!SubExpr->isGLValue()) {
8974 APValue Val;
8975 if (!Evaluate(Val, Info, SubExpr))
8976 return false;
8977 return DerivedSuccess(Val, E);
8978 }
8979
8980 LValue LVal;
8981 if (!EvaluateLValue(SubExpr, LVal, Info))
8982 return false;
8983 APValue RVal;
8984 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8985 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(), LVal,
8986 RVal))
8987 return false;
8988 return DerivedSuccess(RVal, E);
8989 }
8990 case CK_LValueToRValue: {
8991 LValue LVal;
8992 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8993 return false;
8994 APValue RVal;
8995 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8997 LVal, RVal))
8998 return false;
8999 return DerivedSuccess(RVal, E);
9000 }
9001 case CK_LValueToRValueBitCast: {
9002 APValue DestValue, SourceValue;
9003 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
9004 return false;
9005 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9006 return false;
9007 return DerivedSuccess(DestValue, E);
9008 }
9009
9010 case CK_AddressSpaceConversion: {
9011 APValue Value;
9012 if (!Evaluate(Value, Info, E->getSubExpr()))
9013 return false;
9014 return DerivedSuccess(Value, E);
9015 }
9016 }
9017
9018 return Error(E);
9019 }
9020
9021 bool VisitUnaryPostInc(const UnaryOperator *UO) {
9022 return VisitUnaryPostIncDec(UO);
9023 }
9024 bool VisitUnaryPostDec(const UnaryOperator *UO) {
9025 return VisitUnaryPostIncDec(UO);
9026 }
9027 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
9028 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9029 return Error(UO);
9030
9031 LValue LVal;
9032 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
9033 return false;
9034 APValue RVal;
9035 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
9036 UO->isIncrementOp(), &RVal))
9037 return false;
9038 return DerivedSuccess(RVal, UO);
9039 }
9040
9041 bool VisitStmtExpr(const StmtExpr *E) {
9042 // We will have checked the full-expressions inside the statement expression
9043 // when they were completed, and don't need to check them again now.
9044 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9045 false);
9046
9047 const CompoundStmt *CS = E->getSubStmt();
9048 if (CS->body_empty())
9049 return true;
9050
9051 BlockScopeRAII Scope(Info);
9053 BE = CS->body_end();
9054 /**/; ++BI) {
9055 if (BI + 1 == BE) {
9056 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9057 if (!FinalExpr) {
9058 Info.FFDiag((*BI)->getBeginLoc(),
9059 diag::note_constexpr_stmt_expr_unsupported);
9060 return false;
9061 }
9062 return this->Visit(FinalExpr) && Scope.destroy();
9063 }
9064
9066 StmtResult Result = { ReturnValue, nullptr };
9067 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
9068 if (ESR != ESR_Succeeded) {
9069 // FIXME: If the statement-expression terminated due to 'return',
9070 // 'break', or 'continue', it would be nice to propagate that to
9071 // the outer statement evaluation rather than bailing out.
9072 if (ESR != ESR_Failed)
9073 Info.FFDiag((*BI)->getBeginLoc(),
9074 diag::note_constexpr_stmt_expr_unsupported);
9075 return false;
9076 }
9077 }
9078
9079 llvm_unreachable("Return from function from the loop above.");
9080 }
9081
9082 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
9083 return StmtVisitorTy::Visit(E->getSelectedExpr());
9084 }
9085
9086 /// Visit a value which is evaluated, but whose value is ignored.
9087 void VisitIgnoredValue(const Expr *E) {
9088 EvaluateIgnoredValue(Info, E);
9089 }
9090
9091 /// Potentially visit a MemberExpr's base expression.
9092 void VisitIgnoredBaseExpression(const Expr *E) {
9093 // While MSVC doesn't evaluate the base expression, it does diagnose the
9094 // presence of side-effecting behavior.
9095 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
9096 return;
9097 VisitIgnoredValue(E);
9098 }
9099};
9100
9101} // namespace
9102
9103//===----------------------------------------------------------------------===//
9104// Common base class for lvalue and temporary evaluation.
9105//===----------------------------------------------------------------------===//
9106namespace {
9107template<class Derived>
9108class LValueExprEvaluatorBase
9109 : public ExprEvaluatorBase<Derived> {
9110protected:
9111 LValue &Result;
9112 bool InvalidBaseOK;
9113 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9114 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9115
9116 bool Success(APValue::LValueBase B) {
9117 Result.set(B);
9118 return true;
9119 }
9120
9121 bool evaluatePointer(const Expr *E, LValue &Result) {
9122 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
9123 }
9124
9125public:
9126 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
9127 : ExprEvaluatorBaseTy(Info), Result(Result),
9128 InvalidBaseOK(InvalidBaseOK) {}
9129
9130 bool Success(const APValue &V, const Expr *E) {
9131 Result.setFrom(this->Info.Ctx, V);
9132 return true;
9133 }
9134
9135 bool VisitMemberExpr(const MemberExpr *E) {
9136 // Handle non-static data members.
9137 QualType BaseTy;
9138 bool EvalOK;
9139 if (E->isArrow()) {
9140 EvalOK = evaluatePointer(E->getBase(), Result);
9141 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
9142 } else if (E->getBase()->isPRValue()) {
9143 assert(E->getBase()->getType()->isRecordType());
9144 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
9145 BaseTy = E->getBase()->getType();
9146 } else {
9147 EvalOK = this->Visit(E->getBase());
9148 BaseTy = E->getBase()->getType();
9149 }
9150 if (!EvalOK) {
9151 if (!InvalidBaseOK)
9152 return false;
9153 Result.setInvalid(E);
9154 return true;
9155 }
9156
9157 const ValueDecl *MD = E->getMemberDecl();
9158 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
9159 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9160 FD->getParent()->getCanonicalDecl() &&
9161 "record / field mismatch");
9162 (void)BaseTy;
9163 if (!HandleLValueMember(this->Info, E, Result, FD))
9164 return false;
9165 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9166 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
9167 return false;
9168 } else
9169 return this->Error(E);
9170
9171 if (MD->getType()->isReferenceType()) {
9172 APValue RefValue;
9173 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
9174 RefValue))
9175 return false;
9176 return Success(RefValue, E);
9177 }
9178 return true;
9179 }
9180
9181 bool VisitBinaryOperator(const BinaryOperator *E) {
9182 switch (E->getOpcode()) {
9183 default:
9184 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9185
9186 case BO_PtrMemD:
9187 case BO_PtrMemI:
9188 return HandleMemberPointerAccess(this->Info, E, Result);
9189 }
9190 }
9191
9192 bool VisitCastExpr(const CastExpr *E) {
9193 switch (E->getCastKind()) {
9194 default:
9195 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9196
9197 case CK_DerivedToBase:
9198 case CK_UncheckedDerivedToBase:
9199 if (!this->Visit(E->getSubExpr()))
9200 return false;
9201
9202 // Now figure out the necessary offset to add to the base LV to get from
9203 // the derived class to the base class.
9204 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
9205 Result);
9206 }
9207 }
9208};
9209}
9210
9211//===----------------------------------------------------------------------===//
9212// LValue Evaluation
9213//
9214// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
9215// function designators (in C), decl references to void objects (in C), and
9216// temporaries (if building with -Wno-address-of-temporary).
9217//
9218// LValue evaluation produces values comprising a base expression of one of the
9219// following types:
9220// - Declarations
9221// * VarDecl
9222// * FunctionDecl
9223// - Literals
9224// * CompoundLiteralExpr in C (and in global scope in C++)
9225// * StringLiteral
9226// * PredefinedExpr
9227// * ObjCStringLiteralExpr
9228// * ObjCEncodeExpr
9229// * AddrLabelExpr
9230// * BlockExpr
9231// * CallExpr for a MakeStringConstant builtin
9232// - typeid(T) expressions, as TypeInfoLValues
9233// - Locals and temporaries
9234// * MaterializeTemporaryExpr
9235// * Any Expr, with a CallIndex indicating the function in which the temporary
9236// was evaluated, for cases where the MaterializeTemporaryExpr is missing
9237// from the AST (FIXME).
9238// * A MaterializeTemporaryExpr that has static storage duration, with no
9239// CallIndex, for a lifetime-extended temporary.
9240// * The ConstantExpr that is currently being evaluated during evaluation of an
9241// immediate invocation.
9242// plus an offset in bytes.
9243//===----------------------------------------------------------------------===//
9244namespace {
9245class LValueExprEvaluator
9246 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
9247public:
9248 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
9249 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
9250
9251 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
9252 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
9253
9254 bool VisitCallExpr(const CallExpr *E);
9255 bool VisitDeclRefExpr(const DeclRefExpr *E);
9256 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
9257 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
9258 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
9259 bool VisitMemberExpr(const MemberExpr *E);
9260 bool VisitStringLiteral(const StringLiteral *E) {
9261 return Success(
9262 APValue::LValueBase(E, 0, Info.Ctx.getNextStringLiteralVersion()));
9263 }
9264 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
9265 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
9266 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
9267 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
9268 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
9269 bool VisitUnaryDeref(const UnaryOperator *E);
9270 bool VisitUnaryReal(const UnaryOperator *E);
9271 bool VisitUnaryImag(const UnaryOperator *E);
9272 bool VisitUnaryPreInc(const UnaryOperator *UO) {
9273 return VisitUnaryPreIncDec(UO);
9274 }
9275 bool VisitUnaryPreDec(const UnaryOperator *UO) {
9276 return VisitUnaryPreIncDec(UO);
9277 }
9278 bool VisitBinAssign(const BinaryOperator *BO);
9279 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
9280
9281 bool VisitCastExpr(const CastExpr *E) {
9282 switch (E->getCastKind()) {
9283 default:
9284 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9285
9286 case CK_LValueBitCast:
9287 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9288 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9289 << Info.Ctx.getLangOpts().CPlusPlus;
9290 if (!Visit(E->getSubExpr()))
9291 return false;
9292 Result.Designator.setInvalid();
9293 return true;
9294
9295 case CK_BaseToDerived:
9296 if (!Visit(E->getSubExpr()))
9297 return false;
9298 return HandleBaseToDerivedCast(Info, E, Result);
9299
9300 case CK_Dynamic:
9301 if (!Visit(E->getSubExpr()))
9302 return false;
9304 }
9305 }
9306};
9307} // end anonymous namespace
9308
9309/// Get an lvalue to a field of a lambda's closure type.
9310static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9311 const CXXMethodDecl *MD, const FieldDecl *FD,
9312 bool LValueToRValueConversion) {
9313 // Static lambda function call operators can't have captures. We already
9314 // diagnosed this, so bail out here.
9315 if (MD->isStatic()) {
9316 assert(Info.CurrentCall->This == nullptr &&
9317 "This should not be set for a static call operator");
9318 return false;
9319 }
9320
9321 // Start with 'Result' referring to the complete closure object...
9323 // Self may be passed by reference or by value.
9324 const ParmVarDecl *Self = MD->getParamDecl(0);
9325 if (Self->getType()->isReferenceType()) {
9326 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9327 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9328 Result.setFrom(Info.Ctx, *RefValue);
9329 } else {
9330 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9331 CallStackFrame *Frame =
9332 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9333 .first;
9334 unsigned Version = Info.CurrentCall->Arguments.Version;
9335 Result.set({VD, Frame->Index, Version});
9336 }
9337 } else
9338 Result = *Info.CurrentCall->This;
9339
9340 // ... then update it to refer to the field of the closure object
9341 // that represents the capture.
9342 if (!HandleLValueMember(Info, E, Result, FD))
9343 return false;
9344
9345 // And if the field is of reference type (or if we captured '*this' by
9346 // reference), update 'Result' to refer to what
9347 // the field refers to.
9348 if (LValueToRValueConversion) {
9349 APValue RVal;
9350 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9351 return false;
9352 Result.setFrom(Info.Ctx, RVal);
9353 }
9354 return true;
9355}
9356
9357/// Evaluate an expression as an lvalue. This can be legitimately called on
9358/// expressions which are not glvalues, in three cases:
9359/// * function designators in C, and
9360/// * "extern void" objects
9361/// * @selector() expressions in Objective-C
9362static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9363 bool InvalidBaseOK) {
9364 assert(!E->isValueDependent());
9365 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9367 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9368}
9369
9370bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9371 const ValueDecl *D = E->getDecl();
9372
9373 // If we are within a lambda's call operator, check whether the 'VD' referred
9374 // to within 'E' actually represents a lambda-capture that maps to a
9375 // data-member/field within the closure object, and if so, evaluate to the
9376 // field or what the field refers to.
9377 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9379 // We don't always have a complete capture-map when checking or inferring if
9380 // the function call operator meets the requirements of a constexpr function
9381 // - but we don't need to evaluate the captures to determine constexprness
9382 // (dcl.constexpr C++17).
9383 if (Info.checkingPotentialConstantExpression())
9384 return false;
9385
9386 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9387 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9388 return HandleLambdaCapture(Info, E, Result, MD, FD,
9389 FD->getType()->isReferenceType());
9390 }
9391 }
9392
9393 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9394 UnnamedGlobalConstantDecl>(D))
9395 return Success(cast<ValueDecl>(D));
9396 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9397 return VisitVarDecl(E, VD);
9398 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9399 return Visit(BD->getBinding());
9400 return Error(E);
9401}
9402
9403bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9404 CallStackFrame *Frame = nullptr;
9405 unsigned Version = 0;
9406 if (VD->hasLocalStorage()) {
9407 // Only if a local variable was declared in the function currently being
9408 // evaluated, do we expect to be able to find its value in the current
9409 // frame. (Otherwise it was likely declared in an enclosing context and
9410 // could either have a valid evaluatable value (for e.g. a constexpr
9411 // variable) or be ill-formed (and trigger an appropriate evaluation
9412 // diagnostic)).
9413 CallStackFrame *CurrFrame = Info.CurrentCall;
9414 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9415 // Function parameters are stored in some caller's frame. (Usually the
9416 // immediate caller, but for an inherited constructor they may be more
9417 // distant.)
9418 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9419 if (CurrFrame->Arguments) {
9420 VD = CurrFrame->Arguments.getOrigParam(PVD);
9421 Frame =
9422 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9423 Version = CurrFrame->Arguments.Version;
9424 }
9425 } else {
9426 Frame = CurrFrame;
9427 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9428 }
9429 }
9430 }
9431
9432 if (!VD->getType()->isReferenceType()) {
9433 if (Frame) {
9434 Result.set({VD, Frame->Index, Version});
9435 return true;
9436 }
9437 return Success(VD);
9438 }
9439
9440 if (!Info.getLangOpts().CPlusPlus11) {
9441 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9442 << VD << VD->getType();
9443 Info.Note(VD->getLocation(), diag::note_declared_at);
9444 }
9445
9446 APValue *V;
9447 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9448 return false;
9449
9450 if (!V) {
9451 Result.set(VD);
9452 Result.AllowConstexprUnknown = true;
9453 return true;
9454 }
9455
9456 return Success(*V, E);
9457}
9458
9459bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9460 if (!IsConstantEvaluatedBuiltinCall(E))
9461 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9462
9463 switch (E->getBuiltinCallee()) {
9464 default:
9465 return false;
9466 case Builtin::BIas_const:
9467 case Builtin::BIforward:
9468 case Builtin::BIforward_like:
9469 case Builtin::BImove:
9470 case Builtin::BImove_if_noexcept:
9471 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9472 return Visit(E->getArg(0));
9473 break;
9474 }
9475
9476 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9477}
9478
9479bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9480 const MaterializeTemporaryExpr *E) {
9481 // Walk through the expression to find the materialized temporary itself.
9484 const Expr *Inner =
9485 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9486
9487 // If we passed any comma operators, evaluate their LHSs.
9488 for (const Expr *E : CommaLHSs)
9489 if (!EvaluateIgnoredValue(Info, E))
9490 return false;
9491
9492 // A materialized temporary with static storage duration can appear within the
9493 // result of a constant expression evaluation, so we need to preserve its
9494 // value for use outside this evaluation.
9495 APValue *Value;
9496 if (E->getStorageDuration() == SD_Static) {
9497 if (Info.EvalMode == EvaluationMode::ConstantFold)
9498 return false;
9499 // FIXME: What about SD_Thread?
9500 Value = E->getOrCreateValue(true);
9501 *Value = APValue();
9502 Result.set(E);
9503 } else {
9504 Value = &Info.CurrentCall->createTemporary(
9505 E, Inner->getType(),
9506 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9507 : ScopeKind::Block,
9508 Result);
9509 }
9510
9511 QualType Type = Inner->getType();
9512
9513 // Materialize the temporary itself.
9514 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9515 *Value = APValue();
9516 return false;
9517 }
9518
9519 // Adjust our lvalue to refer to the desired subobject.
9520 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9521 --I;
9522 switch (Adjustments[I].Kind) {
9524 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9525 Type, Result))
9526 return false;
9527 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9528 break;
9529
9531 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9532 return false;
9533 Type = Adjustments[I].Field->getType();
9534 break;
9535
9537 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9538 Adjustments[I].Ptr.RHS))
9539 return false;
9540 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9541 break;
9542 }
9543 }
9544
9545 return true;
9546}
9547
9548bool
9549LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9550 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9551 "lvalue compound literal in c++?");
9552 APValue *Lit;
9553 // If CompountLiteral has static storage, its value can be used outside
9554 // this expression. So evaluate it once and store it in ASTContext.
9555 if (E->hasStaticStorage()) {
9556 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9557 Result.set(E);
9558 // Reset any previously evaluated state, otherwise evaluation below might
9559 // fail.
9560 // FIXME: Should we just re-use the previously evaluated value instead?
9561 *Lit = APValue();
9562 } else {
9563 assert(!Info.getLangOpts().CPlusPlus);
9564 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9565 ScopeKind::Block, Result);
9566 }
9567 // FIXME: Evaluating in place isn't always right. We should figure out how to
9568 // use appropriate evaluation context here, see
9569 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9570 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9571 *Lit = APValue();
9572 return false;
9573 }
9574 return true;
9575}
9576
9577bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9578 TypeInfoLValue TypeInfo;
9579
9580 if (!E->isPotentiallyEvaluated()) {
9581 if (E->isTypeOperand())
9582 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9583 else
9584 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9585 } else {
9586 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9587 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9588 << E->getExprOperand()->getType()
9589 << E->getExprOperand()->getSourceRange();
9590 }
9591
9592 if (!Visit(E->getExprOperand()))
9593 return false;
9594
9595 std::optional<DynamicType> DynType =
9597 if (!DynType)
9598 return false;
9599
9600 TypeInfo = TypeInfoLValue(
9601 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9602 }
9603
9604 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9605}
9606
9607bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9608 return Success(E->getGuidDecl());
9609}
9610
9611bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9612 // Handle static data members.
9613 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9614 VisitIgnoredBaseExpression(E->getBase());
9615 return VisitVarDecl(E, VD);
9616 }
9617
9618 // Handle static member functions.
9619 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9620 if (MD->isStatic()) {
9621 VisitIgnoredBaseExpression(E->getBase());
9622 return Success(MD);
9623 }
9624 }
9625
9626 // Handle non-static data members.
9627 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9628}
9629
9630bool LValueExprEvaluator::VisitExtVectorElementExpr(
9631 const ExtVectorElementExpr *E) {
9632 bool Success = true;
9633
9634 APValue Val;
9635 if (!Evaluate(Val, Info, E->getBase())) {
9636 if (!Info.noteFailure())
9637 return false;
9638 Success = false;
9639 }
9640
9642 E->getEncodedElementAccess(Indices);
9643 // FIXME: support accessing more than one element
9644 if (Indices.size() > 1)
9645 return false;
9646
9647 if (Success) {
9648 Result.setFrom(Info.Ctx, Val);
9649 QualType BaseType = E->getBase()->getType();
9650 if (E->isArrow())
9651 BaseType = BaseType->getPointeeType();
9652 const auto *VT = BaseType->castAs<VectorType>();
9653 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9654 VT->getNumElements(), Indices[0]);
9655 }
9656
9657 return Success;
9658}
9659
9660bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9661 if (E->getBase()->getType()->isSveVLSBuiltinType())
9662 return Error(E);
9663
9664 APSInt Index;
9665 bool Success = true;
9666
9667 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9668 APValue Val;
9669 if (!Evaluate(Val, Info, E->getBase())) {
9670 if (!Info.noteFailure())
9671 return false;
9672 Success = false;
9673 }
9674
9675 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9676 if (!Info.noteFailure())
9677 return false;
9678 Success = false;
9679 }
9680
9681 if (Success) {
9682 Result.setFrom(Info.Ctx, Val);
9683 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9684 VT->getNumElements(), Index.getZExtValue());
9685 }
9686
9687 return Success;
9688 }
9689
9690 // C++17's rules require us to evaluate the LHS first, regardless of which
9691 // side is the base.
9692 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9693 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9694 : !EvaluateInteger(SubExpr, Index, Info)) {
9695 if (!Info.noteFailure())
9696 return false;
9697 Success = false;
9698 }
9699 }
9700
9701 return Success &&
9702 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9703}
9704
9705bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9706 bool Success = evaluatePointer(E->getSubExpr(), Result);
9707 // [C++26][expr.unary.op]
9708 // If the operand points to an object or function, the result
9709 // denotes that object or function; otherwise, the behavior is undefined.
9710 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9711 // immediately.
9713 return Success;
9715 E->getType())) ||
9716 Info.noteUndefinedBehavior();
9717}
9718
9719bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9720 if (!Visit(E->getSubExpr()))
9721 return false;
9722 // __real is a no-op on scalar lvalues.
9723 if (E->getSubExpr()->getType()->isAnyComplexType())
9724 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9725 return true;
9726}
9727
9728bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9729 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9730 "lvalue __imag__ on scalar?");
9731 if (!Visit(E->getSubExpr()))
9732 return false;
9733 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9734 return true;
9735}
9736
9737bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9738 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9739 return Error(UO);
9740
9741 if (!this->Visit(UO->getSubExpr()))
9742 return false;
9743
9744 return handleIncDec(
9745 this->Info, UO, Result, UO->getSubExpr()->getType(),
9746 UO->isIncrementOp(), nullptr);
9747}
9748
9749bool LValueExprEvaluator::VisitCompoundAssignOperator(
9750 const CompoundAssignOperator *CAO) {
9751 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9752 return Error(CAO);
9753
9754 bool Success = true;
9755
9756 // C++17 onwards require that we evaluate the RHS first.
9757 APValue RHS;
9758 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9759 if (!Info.noteFailure())
9760 return false;
9761 Success = false;
9762 }
9763
9764 // The overall lvalue result is the result of evaluating the LHS.
9765 if (!this->Visit(CAO->getLHS()) || !Success)
9766 return false;
9767
9769 this->Info, CAO,
9770 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9771 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9772}
9773
9774bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9775 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9776 return Error(E);
9777
9778 bool Success = true;
9779
9780 // C++17 onwards require that we evaluate the RHS first.
9781 APValue NewVal;
9782 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9783 if (!Info.noteFailure())
9784 return false;
9785 Success = false;
9786 }
9787
9788 if (!this->Visit(E->getLHS()) || !Success)
9789 return false;
9790
9791 if (Info.getLangOpts().CPlusPlus20 &&
9793 return false;
9794
9795 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9796 NewVal);
9797}
9798
9799//===----------------------------------------------------------------------===//
9800// Pointer Evaluation
9801//===----------------------------------------------------------------------===//
9802
9803/// Convenience function. LVal's base must be a call to an alloc_size
9804/// function.
9806 const LValue &LVal,
9807 llvm::APInt &Result) {
9808 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9809 "Can't get the size of a non alloc_size function");
9810 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9811 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9812 std::optional<llvm::APInt> Size =
9813 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9814 if (!Size)
9815 return false;
9816
9817 Result = std::move(*Size);
9818 return true;
9819}
9820
9821/// Attempts to evaluate the given LValueBase as the result of a call to
9822/// a function with the alloc_size attribute. If it was possible to do so, this
9823/// function will return true, make Result's Base point to said function call,
9824/// and mark Result's Base as invalid.
9826 LValue &Result) {
9827 if (Base.isNull())
9828 return false;
9829
9830 // Because we do no form of static analysis, we only support const variables.
9831 //
9832 // Additionally, we can't support parameters, nor can we support static
9833 // variables (in the latter case, use-before-assign isn't UB; in the former,
9834 // we have no clue what they'll be assigned to).
9835 const auto *VD =
9836 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9837 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9838 return false;
9839
9840 const Expr *Init = VD->getAnyInitializer();
9841 if (!Init || Init->getType().isNull())
9842 return false;
9843
9844 const Expr *E = Init->IgnoreParens();
9845 if (!tryUnwrapAllocSizeCall(E))
9846 return false;
9847
9848 // Store E instead of E unwrapped so that the type of the LValue's base is
9849 // what the user wanted.
9850 Result.setInvalid(E);
9851
9852 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9853 Result.addUnsizedArray(Info, E, Pointee);
9854 return true;
9855}
9856
9857namespace {
9858class PointerExprEvaluator
9859 : public ExprEvaluatorBase<PointerExprEvaluator> {
9860 LValue &Result;
9861 bool InvalidBaseOK;
9862
9863 bool Success(const Expr *E) {
9864 Result.set(E);
9865 return true;
9866 }
9867
9868 bool evaluateLValue(const Expr *E, LValue &Result) {
9869 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9870 }
9871
9872 bool evaluatePointer(const Expr *E, LValue &Result) {
9873 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9874 }
9875
9876 bool visitNonBuiltinCallExpr(const CallExpr *E);
9877public:
9878
9879 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9880 : ExprEvaluatorBaseTy(info), Result(Result),
9881 InvalidBaseOK(InvalidBaseOK) {}
9882
9883 bool Success(const APValue &V, const Expr *E) {
9884 Result.setFrom(Info.Ctx, V);
9885 return true;
9886 }
9887 bool ZeroInitialization(const Expr *E) {
9888 Result.setNull(Info.Ctx, E->getType());
9889 return true;
9890 }
9891
9892 bool VisitBinaryOperator(const BinaryOperator *E);
9893 bool VisitCastExpr(const CastExpr* E);
9894 bool VisitUnaryAddrOf(const UnaryOperator *E);
9895 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9896 { return Success(E); }
9897 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9899 return Success(E);
9900 if (Info.noteFailure())
9901 EvaluateIgnoredValue(Info, E->getSubExpr());
9902 return Error(E);
9903 }
9904 bool VisitObjCArrayLiteral(const ObjCArrayLiteral *E) {
9905 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
9906 }
9907 bool VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E) {
9908 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
9909 }
9910 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9911 { return Success(E); }
9912 bool VisitCallExpr(const CallExpr *E);
9913 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9914 bool VisitBlockExpr(const BlockExpr *E) {
9915 if (!E->getBlockDecl()->hasCaptures())
9916 return Success(E);
9917 return Error(E);
9918 }
9919 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9920 auto DiagnoseInvalidUseOfThis = [&] {
9921 if (Info.getLangOpts().CPlusPlus11)
9922 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9923 else
9924 Info.FFDiag(E);
9925 };
9926
9927 // Can't look at 'this' when checking a potential constant expression.
9928 if (Info.checkingPotentialConstantExpression())
9929 return false;
9930
9931 bool IsExplicitLambda =
9932 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9933 if (!IsExplicitLambda) {
9934 if (!Info.CurrentCall->This) {
9935 DiagnoseInvalidUseOfThis();
9936 return false;
9937 }
9938
9939 Result = *Info.CurrentCall->This;
9940 }
9941
9942 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9943 // Ensure we actually have captured 'this'. If something was wrong with
9944 // 'this' capture, the error would have been previously reported.
9945 // Otherwise we can be inside of a default initialization of an object
9946 // declared by lambda's body, so no need to return false.
9947 if (!Info.CurrentCall->LambdaThisCaptureField) {
9948 if (IsExplicitLambda && !Info.CurrentCall->This) {
9949 DiagnoseInvalidUseOfThis();
9950 return false;
9951 }
9952
9953 return true;
9954 }
9955
9956 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9957 return HandleLambdaCapture(
9958 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9959 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9960 }
9961 return true;
9962 }
9963
9964 bool VisitCXXNewExpr(const CXXNewExpr *E);
9965
9966 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9967 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9968 APValue LValResult = E->EvaluateInContext(
9969 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9970 Result.setFrom(Info.Ctx, LValResult);
9971 return true;
9972 }
9973
9974 bool VisitEmbedExpr(const EmbedExpr *E) {
9975 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9976 return true;
9977 }
9978
9979 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9980 std::string ResultStr = E->ComputeName(Info.Ctx);
9981
9982 QualType CharTy = Info.Ctx.CharTy.withConst();
9983 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9984 ResultStr.size() + 1);
9985 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9986 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9987
9988 StringLiteral *SL =
9989 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9990 /*Pascal*/ false, ArrayTy, E->getLocation());
9991
9992 evaluateLValue(SL, Result);
9993 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9994 return true;
9995 }
9996
9997 // FIXME: Missing: @protocol, @selector
9998};
9999} // end anonymous namespace
10000
10001static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
10002 bool InvalidBaseOK) {
10003 assert(!E->isValueDependent());
10004 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
10005 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
10006}
10007
10008bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10009 if (E->getOpcode() != BO_Add &&
10010 E->getOpcode() != BO_Sub)
10011 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10012
10013 const Expr *PExp = E->getLHS();
10014 const Expr *IExp = E->getRHS();
10015 if (IExp->getType()->isPointerType())
10016 std::swap(PExp, IExp);
10017
10018 bool EvalPtrOK = evaluatePointer(PExp, Result);
10019 if (!EvalPtrOK && !Info.noteFailure())
10020 return false;
10021
10022 llvm::APSInt Offset;
10023 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
10024 return false;
10025
10026 if (E->getOpcode() == BO_Sub)
10027 negateAsSigned(Offset);
10028
10029 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
10030 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
10031}
10032
10033bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10034 return evaluateLValue(E->getSubExpr(), Result);
10035}
10036
10037// Is the provided decl 'std::source_location::current'?
10039 if (!FD)
10040 return false;
10041 const IdentifierInfo *FnII = FD->getIdentifier();
10042 if (!FnII || !FnII->isStr("current"))
10043 return false;
10044
10045 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
10046 if (!RD)
10047 return false;
10048
10049 const IdentifierInfo *ClassII = RD->getIdentifier();
10050 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
10051}
10052
10053bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10054 const Expr *SubExpr = E->getSubExpr();
10055
10056 switch (E->getCastKind()) {
10057 default:
10058 break;
10059 case CK_BitCast:
10060 case CK_CPointerToObjCPointerCast:
10061 case CK_BlockPointerToObjCPointerCast:
10062 case CK_AnyPointerToBlockPointerCast:
10063 case CK_AddressSpaceConversion:
10064 if (!Visit(SubExpr))
10065 return false;
10066 if (E->getType()->isFunctionPointerType() ||
10067 SubExpr->getType()->isFunctionPointerType()) {
10068 // Casting between two function pointer types, or between a function
10069 // pointer and an object pointer, is always a reinterpret_cast.
10070 CCEDiag(E, diag::note_constexpr_invalid_cast)
10071 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10072 << Info.Ctx.getLangOpts().CPlusPlus;
10073 Result.Designator.setInvalid();
10074 } else if (!E->getType()->isVoidPointerType()) {
10075 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
10076 // permitted in constant expressions in C++11. Bitcasts from cv void* are
10077 // also static_casts, but we disallow them as a resolution to DR1312.
10078 //
10079 // In some circumstances, we permit casting from void* to cv1 T*, when the
10080 // actual pointee object is actually a cv2 T.
10081 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
10082 !Result.IsNullPtr;
10083 bool VoidPtrCastMaybeOK =
10084 Result.IsNullPtr ||
10085 (HasValidResult &&
10086 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
10087 E->getType()->getPointeeType()));
10088 // 1. We'll allow it in std::allocator::allocate, and anything which that
10089 // calls.
10090 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
10091 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
10092 // We'll allow it in the body of std::source_location::current. GCC's
10093 // implementation had a parameter of type `void*`, and casts from
10094 // that back to `const __impl*` in its body.
10095 if (VoidPtrCastMaybeOK &&
10096 (Info.getStdAllocatorCaller("allocate") ||
10097 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
10098 Info.getLangOpts().CPlusPlus26)) {
10099 // Permitted.
10100 } else {
10101 if (SubExpr->getType()->isVoidPointerType() &&
10102 Info.getLangOpts().CPlusPlus) {
10103 if (HasValidResult)
10104 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10105 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
10106 << Result.Designator.getType(Info.Ctx).getCanonicalType()
10107 << E->getType()->getPointeeType();
10108 else
10109 CCEDiag(E, diag::note_constexpr_invalid_cast)
10110 << diag::ConstexprInvalidCastKind::CastFrom
10111 << SubExpr->getType();
10112 } else
10113 CCEDiag(E, diag::note_constexpr_invalid_cast)
10114 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10115 << Info.Ctx.getLangOpts().CPlusPlus;
10116 Result.Designator.setInvalid();
10117 }
10118 }
10119 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
10120 ZeroInitialization(E);
10121 return true;
10122
10123 case CK_DerivedToBase:
10124 case CK_UncheckedDerivedToBase:
10125 if (!evaluatePointer(E->getSubExpr(), Result))
10126 return false;
10127 if (!Result.Base && Result.Offset.isZero())
10128 return true;
10129
10130 // Now figure out the necessary offset to add to the base LV to get from
10131 // the derived class to the base class.
10132 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
10133 castAs<PointerType>()->getPointeeType(),
10134 Result);
10135
10136 case CK_BaseToDerived:
10137 if (!Visit(E->getSubExpr()))
10138 return false;
10139 if (!Result.Base && Result.Offset.isZero())
10140 return true;
10141 return HandleBaseToDerivedCast(Info, E, Result);
10142
10143 case CK_Dynamic:
10144 if (!Visit(E->getSubExpr()))
10145 return false;
10147
10148 case CK_NullToPointer:
10149 VisitIgnoredValue(E->getSubExpr());
10150 return ZeroInitialization(E);
10151
10152 case CK_IntegralToPointer: {
10153 CCEDiag(E, diag::note_constexpr_invalid_cast)
10154 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10155 << Info.Ctx.getLangOpts().CPlusPlus;
10156
10157 APValue Value;
10158 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
10159 break;
10160
10161 if (Value.isInt()) {
10162 unsigned Size = Info.Ctx.getTypeSize(E->getType());
10163 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
10164 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
10165 Result.setNull(Info.Ctx, E->getType());
10166 } else {
10167 Result.Base = (Expr *)nullptr;
10168 Result.InvalidBase = false;
10169 Result.Offset = CharUnits::fromQuantity(N);
10170 Result.Designator.setInvalid();
10171 Result.IsNullPtr = false;
10172 }
10173 return true;
10174 } else {
10175 // In rare instances, the value isn't an lvalue.
10176 // For example, when the value is the difference between the addresses of
10177 // two labels. We reject that as a constant expression because we can't
10178 // compute a valid offset to convert into a pointer.
10179 if (!Value.isLValue())
10180 return false;
10181
10182 // Cast is of an lvalue, no need to change value.
10183 Result.setFrom(Info.Ctx, Value);
10184 return true;
10185 }
10186 }
10187
10188 case CK_ArrayToPointerDecay: {
10189 if (SubExpr->isGLValue()) {
10190 if (!evaluateLValue(SubExpr, Result))
10191 return false;
10192 } else {
10193 APValue &Value = Info.CurrentCall->createTemporary(
10194 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
10195 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
10196 return false;
10197 }
10198 // The result is a pointer to the first element of the array.
10199 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
10200 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
10201 Result.addArray(Info, E, CAT);
10202 else
10203 Result.addUnsizedArray(Info, E, AT->getElementType());
10204 return true;
10205 }
10206
10207 case CK_FunctionToPointerDecay:
10208 return evaluateLValue(SubExpr, Result);
10209
10210 case CK_LValueToRValue: {
10211 LValue LVal;
10212 if (!evaluateLValue(E->getSubExpr(), LVal))
10213 return false;
10214
10215 APValue RVal;
10216 // Note, we use the subexpression's type in order to retain cv-qualifiers.
10218 LVal, RVal))
10219 return InvalidBaseOK &&
10220 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
10221 return Success(RVal, E);
10222 }
10223 }
10224
10225 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10226}
10227
10229 UnaryExprOrTypeTrait ExprKind) {
10230 // C++ [expr.alignof]p3:
10231 // When alignof is applied to a reference type, the result is the
10232 // alignment of the referenced type.
10233 T = T.getNonReferenceType();
10234
10235 if (T.getQualifiers().hasUnaligned())
10236 return CharUnits::One();
10237
10238 const bool AlignOfReturnsPreferred =
10239 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
10240
10241 // __alignof is defined to return the preferred alignment.
10242 // Before 8, clang returned the preferred alignment for alignof and _Alignof
10243 // as well.
10244 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10245 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
10246 // alignof and _Alignof are defined to return the ABI alignment.
10247 else if (ExprKind == UETT_AlignOf)
10248 return Ctx.getTypeAlignInChars(T.getTypePtr());
10249 else
10250 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
10251}
10252
10254 UnaryExprOrTypeTrait ExprKind) {
10255 E = E->IgnoreParens();
10256
10257 // The kinds of expressions that we have special-case logic here for
10258 // should be kept up to date with the special checks for those
10259 // expressions in Sema.
10260
10261 // alignof decl is always accepted, even if it doesn't make sense: we default
10262 // to 1 in those cases.
10263 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10264 return Ctx.getDeclAlign(DRE->getDecl(),
10265 /*RefAsPointee*/ true);
10266
10267 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10268 return Ctx.getDeclAlign(ME->getMemberDecl(),
10269 /*RefAsPointee*/ true);
10270
10271 return GetAlignOfType(Ctx, E->getType(), ExprKind);
10272}
10273
10274static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
10275 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
10276 return Info.Ctx.getDeclAlign(VD);
10277 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
10278 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
10279 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
10280}
10281
10282/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
10283/// __builtin_is_aligned and __builtin_assume_aligned.
10284static bool getAlignmentArgument(const Expr *E, QualType ForType,
10285 EvalInfo &Info, APSInt &Alignment) {
10286 if (!EvaluateInteger(E, Alignment, Info))
10287 return false;
10288 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10289 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10290 return false;
10291 }
10292 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10293 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10294 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10295 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10296 << MaxValue << ForType << Alignment;
10297 return false;
10298 }
10299 // Ensure both alignment and source value have the same bit width so that we
10300 // don't assert when computing the resulting value.
10301 APSInt ExtAlignment =
10302 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10303 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10304 "Alignment should not be changed by ext/trunc");
10305 Alignment = ExtAlignment;
10306 assert(Alignment.getBitWidth() == SrcWidth);
10307 return true;
10308}
10309
10310// To be clear: this happily visits unsupported builtins. Better name welcomed.
10311bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10312 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10313 return true;
10314
10315 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10316 return false;
10317
10318 Result.setInvalid(E);
10319 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10320 Result.addUnsizedArray(Info, E, PointeeTy);
10321 return true;
10322}
10323
10324bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10325 if (!IsConstantEvaluatedBuiltinCall(E))
10326 return visitNonBuiltinCallExpr(E);
10327 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
10328}
10329
10330// Determine if T is a character type for which we guarantee that
10331// sizeof(T) == 1.
10333 return T->isCharType() || T->isChar8Type();
10334}
10335
10336bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10337 unsigned BuiltinOp) {
10338 if (IsOpaqueConstantCall(E))
10339 return Success(E);
10340
10341 switch (BuiltinOp) {
10342 case Builtin::BIaddressof:
10343 case Builtin::BI__addressof:
10344 case Builtin::BI__builtin_addressof:
10345 return evaluateLValue(E->getArg(0), Result);
10346 case Builtin::BI__builtin_assume_aligned: {
10347 // We need to be very careful here because: if the pointer does not have the
10348 // asserted alignment, then the behavior is undefined, and undefined
10349 // behavior is non-constant.
10350 if (!evaluatePointer(E->getArg(0), Result))
10351 return false;
10352
10353 LValue OffsetResult(Result);
10354 APSInt Alignment;
10355 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10356 Alignment))
10357 return false;
10358 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10359
10360 if (E->getNumArgs() > 2) {
10361 APSInt Offset;
10362 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10363 return false;
10364
10365 int64_t AdditionalOffset = -Offset.getZExtValue();
10366 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10367 }
10368
10369 // If there is a base object, then it must have the correct alignment.
10370 if (OffsetResult.Base) {
10371 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10372
10373 if (BaseAlignment < Align) {
10374 Result.Designator.setInvalid();
10375 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10376 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10377 return false;
10378 }
10379 }
10380
10381 // The offset must also have the correct alignment.
10382 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10383 Result.Designator.setInvalid();
10384
10385 (OffsetResult.Base
10386 ? CCEDiag(E->getArg(0),
10387 diag::note_constexpr_baa_insufficient_alignment)
10388 << 1
10389 : CCEDiag(E->getArg(0),
10390 diag::note_constexpr_baa_value_insufficient_alignment))
10391 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10392 return false;
10393 }
10394
10395 return true;
10396 }
10397 case Builtin::BI__builtin_align_up:
10398 case Builtin::BI__builtin_align_down: {
10399 if (!evaluatePointer(E->getArg(0), Result))
10400 return false;
10401 APSInt Alignment;
10402 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10403 Alignment))
10404 return false;
10405 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10406 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10407 // For align_up/align_down, we can return the same value if the alignment
10408 // is known to be greater or equal to the requested value.
10409 if (PtrAlign.getQuantity() >= Alignment)
10410 return true;
10411
10412 // The alignment could be greater than the minimum at run-time, so we cannot
10413 // infer much about the resulting pointer value. One case is possible:
10414 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10415 // can infer the correct index if the requested alignment is smaller than
10416 // the base alignment so we can perform the computation on the offset.
10417 if (BaseAlignment.getQuantity() >= Alignment) {
10418 assert(Alignment.getBitWidth() <= 64 &&
10419 "Cannot handle > 64-bit address-space");
10420 uint64_t Alignment64 = Alignment.getZExtValue();
10421 CharUnits NewOffset = CharUnits::fromQuantity(
10422 BuiltinOp == Builtin::BI__builtin_align_down
10423 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10424 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10425 Result.adjustOffset(NewOffset - Result.Offset);
10426 // TODO: diagnose out-of-bounds values/only allow for arrays?
10427 return true;
10428 }
10429 // Otherwise, we cannot constant-evaluate the result.
10430 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10431 << Alignment;
10432 return false;
10433 }
10434 case Builtin::BI__builtin_operator_new:
10435 return HandleOperatorNewCall(Info, E, Result);
10436 case Builtin::BI__builtin_launder:
10437 return evaluatePointer(E->getArg(0), Result);
10438 case Builtin::BIstrchr:
10439 case Builtin::BIwcschr:
10440 case Builtin::BImemchr:
10441 case Builtin::BIwmemchr:
10442 if (Info.getLangOpts().CPlusPlus11)
10443 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10444 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10445 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10446 else
10447 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10448 [[fallthrough]];
10449 case Builtin::BI__builtin_strchr:
10450 case Builtin::BI__builtin_wcschr:
10451 case Builtin::BI__builtin_memchr:
10452 case Builtin::BI__builtin_char_memchr:
10453 case Builtin::BI__builtin_wmemchr: {
10454 if (!Visit(E->getArg(0)))
10455 return false;
10456 APSInt Desired;
10457 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10458 return false;
10459 uint64_t MaxLength = uint64_t(-1);
10460 if (BuiltinOp != Builtin::BIstrchr &&
10461 BuiltinOp != Builtin::BIwcschr &&
10462 BuiltinOp != Builtin::BI__builtin_strchr &&
10463 BuiltinOp != Builtin::BI__builtin_wcschr) {
10464 APSInt N;
10465 if (!EvaluateInteger(E->getArg(2), N, Info))
10466 return false;
10467 MaxLength = N.getZExtValue();
10468 }
10469 // We cannot find the value if there are no candidates to match against.
10470 if (MaxLength == 0u)
10471 return ZeroInitialization(E);
10472 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10473 Result.Designator.Invalid)
10474 return false;
10475 QualType CharTy = Result.Designator.getType(Info.Ctx);
10476 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10477 BuiltinOp == Builtin::BI__builtin_memchr;
10478 assert(IsRawByte ||
10479 Info.Ctx.hasSameUnqualifiedType(
10480 CharTy, E->getArg(0)->getType()->getPointeeType()));
10481 // Pointers to const void may point to objects of incomplete type.
10482 if (IsRawByte && CharTy->isIncompleteType()) {
10483 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10484 return false;
10485 }
10486 // Give up on byte-oriented matching against multibyte elements.
10487 // FIXME: We can compare the bytes in the correct order.
10488 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10489 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10490 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10491 return false;
10492 }
10493 // Figure out what value we're actually looking for (after converting to
10494 // the corresponding unsigned type if necessary).
10495 uint64_t DesiredVal;
10496 bool StopAtNull = false;
10497 switch (BuiltinOp) {
10498 case Builtin::BIstrchr:
10499 case Builtin::BI__builtin_strchr:
10500 // strchr compares directly to the passed integer, and therefore
10501 // always fails if given an int that is not a char.
10502 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10503 E->getArg(1)->getType(),
10504 Desired),
10505 Desired))
10506 return ZeroInitialization(E);
10507 StopAtNull = true;
10508 [[fallthrough]];
10509 case Builtin::BImemchr:
10510 case Builtin::BI__builtin_memchr:
10511 case Builtin::BI__builtin_char_memchr:
10512 // memchr compares by converting both sides to unsigned char. That's also
10513 // correct for strchr if we get this far (to cope with plain char being
10514 // unsigned in the strchr case).
10515 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10516 break;
10517
10518 case Builtin::BIwcschr:
10519 case Builtin::BI__builtin_wcschr:
10520 StopAtNull = true;
10521 [[fallthrough]];
10522 case Builtin::BIwmemchr:
10523 case Builtin::BI__builtin_wmemchr:
10524 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10525 DesiredVal = Desired.getZExtValue();
10526 break;
10527 }
10528
10529 for (; MaxLength; --MaxLength) {
10530 APValue Char;
10531 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10532 !Char.isInt())
10533 return false;
10534 if (Char.getInt().getZExtValue() == DesiredVal)
10535 return true;
10536 if (StopAtNull && !Char.getInt())
10537 break;
10538 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10539 return false;
10540 }
10541 // Not found: return nullptr.
10542 return ZeroInitialization(E);
10543 }
10544
10545 case Builtin::BImemcpy:
10546 case Builtin::BImemmove:
10547 case Builtin::BIwmemcpy:
10548 case Builtin::BIwmemmove:
10549 if (Info.getLangOpts().CPlusPlus11)
10550 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10551 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10552 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10553 else
10554 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10555 [[fallthrough]];
10556 case Builtin::BI__builtin_memcpy:
10557 case Builtin::BI__builtin_memmove:
10558 case Builtin::BI__builtin_wmemcpy:
10559 case Builtin::BI__builtin_wmemmove: {
10560 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10561 BuiltinOp == Builtin::BIwmemmove ||
10562 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10563 BuiltinOp == Builtin::BI__builtin_wmemmove;
10564 bool Move = BuiltinOp == Builtin::BImemmove ||
10565 BuiltinOp == Builtin::BIwmemmove ||
10566 BuiltinOp == Builtin::BI__builtin_memmove ||
10567 BuiltinOp == Builtin::BI__builtin_wmemmove;
10568
10569 // The result of mem* is the first argument.
10570 if (!Visit(E->getArg(0)))
10571 return false;
10572 LValue Dest = Result;
10573
10574 LValue Src;
10575 if (!EvaluatePointer(E->getArg(1), Src, Info))
10576 return false;
10577
10578 APSInt N;
10579 if (!EvaluateInteger(E->getArg(2), N, Info))
10580 return false;
10581 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10582
10583 // If the size is zero, we treat this as always being a valid no-op.
10584 // (Even if one of the src and dest pointers is null.)
10585 if (!N)
10586 return true;
10587
10588 // Otherwise, if either of the operands is null, we can't proceed. Don't
10589 // try to determine the type of the copied objects, because there aren't
10590 // any.
10591 if (!Src.Base || !Dest.Base) {
10592 APValue Val;
10593 (!Src.Base ? Src : Dest).moveInto(Val);
10594 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10595 << Move << WChar << !!Src.Base
10596 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10597 return false;
10598 }
10599 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10600 return false;
10601
10602 // We require that Src and Dest are both pointers to arrays of
10603 // trivially-copyable type. (For the wide version, the designator will be
10604 // invalid if the designated object is not a wchar_t.)
10605 QualType T = Dest.Designator.getType(Info.Ctx);
10606 QualType SrcT = Src.Designator.getType(Info.Ctx);
10607 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10608 // FIXME: Consider using our bit_cast implementation to support this.
10609 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10610 return false;
10611 }
10612 if (T->isIncompleteType()) {
10613 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10614 return false;
10615 }
10616 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10617 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10618 return false;
10619 }
10620
10621 // Figure out how many T's we're copying.
10622 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10623 if (TSize == 0)
10624 return false;
10625 if (!WChar) {
10626 uint64_t Remainder;
10627 llvm::APInt OrigN = N;
10628 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10629 if (Remainder) {
10630 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10631 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10632 << (unsigned)TSize;
10633 return false;
10634 }
10635 }
10636
10637 // Check that the copying will remain within the arrays, just so that we
10638 // can give a more meaningful diagnostic. This implicitly also checks that
10639 // N fits into 64 bits.
10640 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10641 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10642 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10643 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10644 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10645 << toString(N, 10, /*Signed*/false);
10646 return false;
10647 }
10648 uint64_t NElems = N.getZExtValue();
10649 uint64_t NBytes = NElems * TSize;
10650
10651 // Check for overlap.
10652 int Direction = 1;
10653 if (HasSameBase(Src, Dest)) {
10654 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10655 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10656 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10657 // Dest is inside the source region.
10658 if (!Move) {
10659 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10660 return false;
10661 }
10662 // For memmove and friends, copy backwards.
10663 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10664 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10665 return false;
10666 Direction = -1;
10667 } else if (!Move && SrcOffset >= DestOffset &&
10668 SrcOffset - DestOffset < NBytes) {
10669 // Src is inside the destination region for memcpy: invalid.
10670 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10671 return false;
10672 }
10673 }
10674
10675 while (true) {
10676 APValue Val;
10677 // FIXME: Set WantObjectRepresentation to true if we're copying a
10678 // char-like type?
10679 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10680 !handleAssignment(Info, E, Dest, T, Val))
10681 return false;
10682 // Do not iterate past the last element; if we're copying backwards, that
10683 // might take us off the start of the array.
10684 if (--NElems == 0)
10685 return true;
10686 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10687 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10688 return false;
10689 }
10690 }
10691
10692 default:
10693 return false;
10694 }
10695}
10696
10697static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10698 APValue &Result, const InitListExpr *ILE,
10699 QualType AllocType);
10700static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10701 APValue &Result,
10702 const CXXConstructExpr *CCE,
10703 QualType AllocType);
10704
10705bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10706 if (!Info.getLangOpts().CPlusPlus20)
10707 Info.CCEDiag(E, diag::note_constexpr_new);
10708
10709 // We cannot speculatively evaluate a delete expression.
10710 if (Info.SpeculativeEvaluationDepth)
10711 return false;
10712
10713 FunctionDecl *OperatorNew = E->getOperatorNew();
10714 QualType AllocType = E->getAllocatedType();
10715 QualType TargetType = AllocType;
10716
10717 bool IsNothrow = false;
10718 bool IsPlacement = false;
10719
10720 if (E->getNumPlacementArgs() == 1 &&
10721 E->getPlacementArg(0)->getType()->isNothrowT()) {
10722 // The only new-placement list we support is of the form (std::nothrow).
10723 //
10724 // FIXME: There is no restriction on this, but it's not clear that any
10725 // other form makes any sense. We get here for cases such as:
10726 //
10727 // new (std::align_val_t{N}) X(int)
10728 //
10729 // (which should presumably be valid only if N is a multiple of
10730 // alignof(int), and in any case can't be deallocated unless N is
10731 // alignof(X) and X has new-extended alignment).
10732 LValue Nothrow;
10733 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10734 return false;
10735 IsNothrow = true;
10736 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10737 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10738 (Info.CurrentCall->CanEvalMSConstexpr &&
10739 OperatorNew->hasAttr<MSConstexprAttr>())) {
10740 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10741 return false;
10742 if (Result.Designator.Invalid)
10743 return false;
10744 TargetType = E->getPlacementArg(0)->getType();
10745 IsPlacement = true;
10746 } else {
10747 Info.FFDiag(E, diag::note_constexpr_new_placement)
10748 << /*C++26 feature*/ 1 << E->getSourceRange();
10749 return false;
10750 }
10751 } else if (E->getNumPlacementArgs()) {
10752 Info.FFDiag(E, diag::note_constexpr_new_placement)
10753 << /*Unsupported*/ 0 << E->getSourceRange();
10754 return false;
10755 } else if (!OperatorNew
10756 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10757 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10758 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10759 return false;
10760 }
10761
10762 const Expr *Init = E->getInitializer();
10763 const InitListExpr *ResizedArrayILE = nullptr;
10764 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10765 bool ValueInit = false;
10766
10767 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10768 const Expr *Stripped = *ArraySize;
10769 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10770 Stripped = ICE->getSubExpr())
10771 if (ICE->getCastKind() != CK_NoOp &&
10772 ICE->getCastKind() != CK_IntegralCast)
10773 break;
10774
10775 llvm::APSInt ArrayBound;
10776 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10777 return false;
10778
10779 // C++ [expr.new]p9:
10780 // The expression is erroneous if:
10781 // -- [...] its value before converting to size_t [or] applying the
10782 // second standard conversion sequence is less than zero
10783 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10784 if (IsNothrow)
10785 return ZeroInitialization(E);
10786
10787 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10788 << ArrayBound << (*ArraySize)->getSourceRange();
10789 return false;
10790 }
10791
10792 // -- its value is such that the size of the allocated object would
10793 // exceed the implementation-defined limit
10794 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10796 Info.Ctx, AllocType, ArrayBound),
10797 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10798 if (IsNothrow)
10799 return ZeroInitialization(E);
10800 return false;
10801 }
10802
10803 // -- the new-initializer is a braced-init-list and the number of
10804 // array elements for which initializers are provided [...]
10805 // exceeds the number of elements to initialize
10806 if (!Init) {
10807 // No initialization is performed.
10808 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10810 ValueInit = true;
10811 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10812 ResizedArrayCCE = CCE;
10813 } else {
10814 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10815 assert(CAT && "unexpected type for array initializer");
10816
10817 unsigned Bits =
10818 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10819 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10820 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10821 if (InitBound.ugt(AllocBound)) {
10822 if (IsNothrow)
10823 return ZeroInitialization(E);
10824
10825 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10826 << toString(AllocBound, 10, /*Signed=*/false)
10827 << toString(InitBound, 10, /*Signed=*/false)
10828 << (*ArraySize)->getSourceRange();
10829 return false;
10830 }
10831
10832 // If the sizes differ, we must have an initializer list, and we need
10833 // special handling for this case when we initialize.
10834 if (InitBound != AllocBound)
10835 ResizedArrayILE = cast<InitListExpr>(Init);
10836 }
10837
10838 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10839 ArraySizeModifier::Normal, 0);
10840 } else {
10841 assert(!AllocType->isArrayType() &&
10842 "array allocation with non-array new");
10843 }
10844
10845 APValue *Val;
10846 if (IsPlacement) {
10848 struct FindObjectHandler {
10849 EvalInfo &Info;
10850 const Expr *E;
10851 QualType AllocType;
10852 const AccessKinds AccessKind;
10853 APValue *Value;
10854
10855 typedef bool result_type;
10856 bool failed() { return false; }
10857 bool checkConst(QualType QT) {
10858 if (QT.isConstQualified()) {
10859 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10860 return false;
10861 }
10862 return true;
10863 }
10864 bool found(APValue &Subobj, QualType SubobjType) {
10865 if (!checkConst(SubobjType))
10866 return false;
10867 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10868 // old name of the object to be used to name the new object.
10869 unsigned SubobjectSize = 1;
10870 unsigned AllocSize = 1;
10871 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10872 AllocSize = CAT->getZExtSize();
10873 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10874 SubobjectSize = CAT->getZExtSize();
10875 if (SubobjectSize < AllocSize ||
10876 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10877 Info.Ctx.getBaseElementType(AllocType))) {
10878 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10879 << SubobjType << AllocType;
10880 return false;
10881 }
10882 Value = &Subobj;
10883 return true;
10884 }
10885 bool found(APSInt &Value, QualType SubobjType) {
10886 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10887 return false;
10888 }
10889 bool found(APFloat &Value, QualType SubobjType) {
10890 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10891 return false;
10892 }
10893 } Handler = {Info, E, AllocType, AK, nullptr};
10894
10895 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10896 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10897 return false;
10898
10899 Val = Handler.Value;
10900
10901 // [basic.life]p1:
10902 // The lifetime of an object o of type T ends when [...] the storage
10903 // which the object occupies is [...] reused by an object that is not
10904 // nested within o (6.6.2).
10905 *Val = APValue();
10906 } else {
10907 // Perform the allocation and obtain a pointer to the resulting object.
10908 Val = Info.createHeapAlloc(E, AllocType, Result);
10909 if (!Val)
10910 return false;
10911 }
10912
10913 if (ValueInit) {
10914 ImplicitValueInitExpr VIE(AllocType);
10915 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10916 return false;
10917 } else if (ResizedArrayILE) {
10918 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10919 AllocType))
10920 return false;
10921 } else if (ResizedArrayCCE) {
10922 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10923 AllocType))
10924 return false;
10925 } else if (Init) {
10926 if (!EvaluateInPlace(*Val, Info, Result, Init))
10927 return false;
10928 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10929 return false;
10930 }
10931
10932 // Array new returns a pointer to the first element, not a pointer to the
10933 // array.
10934 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10935 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10936
10937 return true;
10938}
10939//===----------------------------------------------------------------------===//
10940// Member Pointer Evaluation
10941//===----------------------------------------------------------------------===//
10942
10943namespace {
10944class MemberPointerExprEvaluator
10945 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10946 MemberPtr &Result;
10947
10948 bool Success(const ValueDecl *D) {
10949 Result = MemberPtr(D);
10950 return true;
10951 }
10952public:
10953
10954 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10955 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10956
10957 bool Success(const APValue &V, const Expr *E) {
10958 Result.setFrom(V);
10959 return true;
10960 }
10961 bool ZeroInitialization(const Expr *E) {
10962 return Success((const ValueDecl*)nullptr);
10963 }
10964
10965 bool VisitCastExpr(const CastExpr *E);
10966 bool VisitUnaryAddrOf(const UnaryOperator *E);
10967};
10968} // end anonymous namespace
10969
10970static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10971 EvalInfo &Info) {
10972 assert(!E->isValueDependent());
10973 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10974 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10975}
10976
10977bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10978 switch (E->getCastKind()) {
10979 default:
10980 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10981
10982 case CK_NullToMemberPointer:
10983 VisitIgnoredValue(E->getSubExpr());
10984 return ZeroInitialization(E);
10985
10986 case CK_BaseToDerivedMemberPointer: {
10987 if (!Visit(E->getSubExpr()))
10988 return false;
10989 if (E->path_empty())
10990 return true;
10991 // Base-to-derived member pointer casts store the path in derived-to-base
10992 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10993 // the wrong end of the derived->base arc, so stagger the path by one class.
10994 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10995 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10996 PathI != PathE; ++PathI) {
10997 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10998 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10999 if (!Result.castToDerived(Derived))
11000 return Error(E);
11001 }
11002 if (!Result.castToDerived(E->getType()
11003 ->castAs<MemberPointerType>()
11004 ->getMostRecentCXXRecordDecl()))
11005 return Error(E);
11006 return true;
11007 }
11008
11009 case CK_DerivedToBaseMemberPointer:
11010 if (!Visit(E->getSubExpr()))
11011 return false;
11012 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11013 PathE = E->path_end(); PathI != PathE; ++PathI) {
11014 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11015 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11016 if (!Result.castToBase(Base))
11017 return Error(E);
11018 }
11019 return true;
11020 }
11021}
11022
11023bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
11024 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
11025 // member can be formed.
11026 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
11027}
11028
11029//===----------------------------------------------------------------------===//
11030// Record Evaluation
11031//===----------------------------------------------------------------------===//
11032
11033namespace {
11034 class RecordExprEvaluator
11035 : public ExprEvaluatorBase<RecordExprEvaluator> {
11036 const LValue &This;
11037 APValue &Result;
11038 public:
11039
11040 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
11041 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
11042
11043 bool Success(const APValue &V, const Expr *E) {
11044 Result = V;
11045 return true;
11046 }
11047 bool ZeroInitialization(const Expr *E) {
11048 return ZeroInitialization(E, E->getType());
11049 }
11050 bool ZeroInitialization(const Expr *E, QualType T);
11051
11052 bool VisitCallExpr(const CallExpr *E) {
11053 return handleCallExpr(E, Result, &This);
11054 }
11055 bool VisitCastExpr(const CastExpr *E);
11056 bool VisitInitListExpr(const InitListExpr *E);
11057 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11058 return VisitCXXConstructExpr(E, E->getType());
11059 }
11060 bool VisitLambdaExpr(const LambdaExpr *E);
11061 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
11062 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
11063 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
11064 bool VisitBinCmp(const BinaryOperator *E);
11065 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11066 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11067 ArrayRef<Expr *> Args);
11068 };
11069}
11070
11071/// Perform zero-initialization on an object of non-union class type.
11072/// C++11 [dcl.init]p5:
11073/// To zero-initialize an object or reference of type T means:
11074/// [...]
11075/// -- if T is a (possibly cv-qualified) non-union class type,
11076/// each non-static data member and each base-class subobject is
11077/// zero-initialized
11078static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
11079 const RecordDecl *RD,
11080 const LValue &This, APValue &Result) {
11081 assert(!RD->isUnion() && "Expected non-union class type");
11082 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
11083 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
11084 RD->getNumFields());
11085
11086 if (RD->isInvalidDecl()) return false;
11087 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11088
11089 if (CD) {
11090 unsigned Index = 0;
11092 End = CD->bases_end(); I != End; ++I, ++Index) {
11093 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
11094 LValue Subobject = This;
11095 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
11096 return false;
11097 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11098 Result.getStructBase(Index)))
11099 return false;
11100 }
11101 }
11102
11103 for (const auto *I : RD->fields()) {
11104 // -- if T is a reference type, no initialization is performed.
11105 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11106 continue;
11107
11108 LValue Subobject = This;
11109 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
11110 return false;
11111
11112 ImplicitValueInitExpr VIE(I->getType());
11113 if (!EvaluateInPlace(
11114 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11115 return false;
11116 }
11117
11118 return true;
11119}
11120
11121bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
11122 const auto *RD = T->castAsRecordDecl();
11123 if (RD->isInvalidDecl()) return false;
11124 if (RD->isUnion()) {
11125 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
11126 // object's first non-static named data member is zero-initialized
11128 while (I != RD->field_end() && (*I)->isUnnamedBitField())
11129 ++I;
11130 if (I == RD->field_end()) {
11131 Result = APValue((const FieldDecl*)nullptr);
11132 return true;
11133 }
11134
11135 LValue Subobject = This;
11136 if (!HandleLValueMember(Info, E, Subobject, *I))
11137 return false;
11138 Result = APValue(*I);
11139 ImplicitValueInitExpr VIE(I->getType());
11140 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
11141 }
11142
11143 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
11144 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11145 return false;
11146 }
11147
11148 return HandleClassZeroInitialization(Info, E, RD, This, Result);
11149}
11150
11151bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
11152 switch (E->getCastKind()) {
11153 default:
11154 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11155
11156 case CK_ConstructorConversion:
11157 return Visit(E->getSubExpr());
11158
11159 case CK_DerivedToBase:
11160 case CK_UncheckedDerivedToBase: {
11161 APValue DerivedObject;
11162 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
11163 return false;
11164 if (!DerivedObject.isStruct())
11165 return Error(E->getSubExpr());
11166
11167 // Derived-to-base rvalue conversion: just slice off the derived part.
11168 APValue *Value = &DerivedObject;
11169 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
11170 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11171 PathE = E->path_end(); PathI != PathE; ++PathI) {
11172 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
11173 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11174 Value = &Value->getStructBase(getBaseIndex(RD, Base));
11175 RD = Base;
11176 }
11177 Result = *Value;
11178 return true;
11179 }
11180 case CK_HLSLAggregateSplatCast: {
11181 APValue Val;
11182 QualType ValTy;
11183
11184 if (!hlslAggSplatHelper(Info, E->getSubExpr(), Val, ValTy))
11185 return false;
11186
11187 unsigned NEls = elementwiseSize(Info, E->getType());
11188 // splat our Val
11189 SmallVector<APValue> SplatEls(NEls, Val);
11190 SmallVector<QualType> SplatType(NEls, ValTy);
11191
11192 // cast the elements and construct our struct result
11193 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11194 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
11195 SplatType))
11196 return false;
11197
11198 return true;
11199 }
11200 case CK_HLSLElementwiseCast: {
11201 SmallVector<APValue> SrcEls;
11202 SmallVector<QualType> SrcTypes;
11203
11204 if (!hlslElementwiseCastHelper(Info, E->getSubExpr(), E->getType(), SrcEls,
11205 SrcTypes))
11206 return false;
11207
11208 // cast the elements and construct our struct result
11209 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11210 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
11211 SrcTypes))
11212 return false;
11213
11214 return true;
11215 }
11216 }
11217}
11218
11219bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11220 if (E->isTransparent())
11221 return Visit(E->getInit(0));
11222 return VisitCXXParenListOrInitListExpr(E, E->inits());
11223}
11224
11225bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11226 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
11227 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
11228 if (RD->isInvalidDecl()) return false;
11229 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11230 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11231
11232 EvalInfo::EvaluatingConstructorRAII EvalObj(
11233 Info,
11234 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
11235 CXXRD && CXXRD->getNumBases());
11236
11237 if (RD->isUnion()) {
11238 const FieldDecl *Field;
11239 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11240 Field = ILE->getInitializedFieldInUnion();
11241 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11242 Field = PLIE->getInitializedFieldInUnion();
11243 } else {
11244 llvm_unreachable(
11245 "Expression is neither an init list nor a C++ paren list");
11246 }
11247
11248 Result = APValue(Field);
11249 if (!Field)
11250 return true;
11251
11252 // If the initializer list for a union does not contain any elements, the
11253 // first element of the union is value-initialized.
11254 // FIXME: The element should be initialized from an initializer list.
11255 // Is this difference ever observable for initializer lists which
11256 // we don't build?
11257 ImplicitValueInitExpr VIE(Field->getType());
11258 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11259
11260 LValue Subobject = This;
11261 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
11262 return false;
11263
11264 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11265 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11266 isa<CXXDefaultInitExpr>(InitExpr));
11267
11268 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
11269 if (Field->isBitField())
11270 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
11271 Field);
11272 return true;
11273 }
11274
11275 return false;
11276 }
11277
11278 if (!Result.hasValue())
11279 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11280 RD->getNumFields());
11281 unsigned ElementNo = 0;
11282 bool Success = true;
11283
11284 // Initialize base classes.
11285 if (CXXRD && CXXRD->getNumBases()) {
11286 for (const auto &Base : CXXRD->bases()) {
11287 assert(ElementNo < Args.size() && "missing init for base class");
11288 const Expr *Init = Args[ElementNo];
11289
11290 LValue Subobject = This;
11291 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
11292 return false;
11293
11294 APValue &FieldVal = Result.getStructBase(ElementNo);
11295 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
11296 if (!Info.noteFailure())
11297 return false;
11298 Success = false;
11299 }
11300 ++ElementNo;
11301 }
11302
11303 EvalObj.finishedConstructingBases();
11304 }
11305
11306 // Initialize members.
11307 for (const auto *Field : RD->fields()) {
11308 // Anonymous bit-fields are not considered members of the class for
11309 // purposes of aggregate initialization.
11310 if (Field->isUnnamedBitField())
11311 continue;
11312
11313 LValue Subobject = This;
11314
11315 bool HaveInit = ElementNo < Args.size();
11316
11317 // FIXME: Diagnostics here should point to the end of the initializer
11318 // list, not the start.
11319 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
11320 Subobject, Field, &Layout))
11321 return false;
11322
11323 // Perform an implicit value-initialization for members beyond the end of
11324 // the initializer list.
11325 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11326 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11327
11328 if (Field->getType()->isIncompleteArrayType()) {
11329 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11330 if (!CAT->isZeroSize()) {
11331 // Bail out for now. This might sort of "work", but the rest of the
11332 // code isn't really prepared to handle it.
11333 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11334 return false;
11335 }
11336 }
11337 }
11338
11339 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11340 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11342
11343 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11344 if (Field->getType()->isReferenceType()) {
11345 LValue Result;
11347 FieldVal)) {
11348 if (!Info.noteFailure())
11349 return false;
11350 Success = false;
11351 }
11352 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11353 (Field->isBitField() &&
11354 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11355 if (!Info.noteFailure())
11356 return false;
11357 Success = false;
11358 }
11359 }
11360
11361 EvalObj.finishedConstructingFields();
11362
11363 return Success;
11364}
11365
11366bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11367 QualType T) {
11368 // Note that E's type is not necessarily the type of our class here; we might
11369 // be initializing an array element instead.
11370 const CXXConstructorDecl *FD = E->getConstructor();
11371 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11372
11373 bool ZeroInit = E->requiresZeroInitialization();
11374 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11375 if (ZeroInit)
11376 return ZeroInitialization(E, T);
11377
11378 return handleDefaultInitValue(T, Result);
11379 }
11380
11381 const FunctionDecl *Definition = nullptr;
11382 auto Body = FD->getBody(Definition);
11383
11384 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11385 return false;
11386
11387 // Avoid materializing a temporary for an elidable copy/move constructor.
11388 if (E->isElidable() && !ZeroInit) {
11389 // FIXME: This only handles the simplest case, where the source object
11390 // is passed directly as the first argument to the constructor.
11391 // This should also handle stepping though implicit casts and
11392 // and conversion sequences which involve two steps, with a
11393 // conversion operator followed by a converting constructor.
11394 const Expr *SrcObj = E->getArg(0);
11395 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11396 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11397 if (const MaterializeTemporaryExpr *ME =
11398 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11399 return Visit(ME->getSubExpr());
11400 }
11401
11402 if (ZeroInit && !ZeroInitialization(E, T))
11403 return false;
11404
11405 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11406 return HandleConstructorCall(E, This, Args,
11408 Result);
11409}
11410
11411bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11412 const CXXInheritedCtorInitExpr *E) {
11413 if (!Info.CurrentCall) {
11414 assert(Info.checkingPotentialConstantExpression());
11415 return false;
11416 }
11417
11418 const CXXConstructorDecl *FD = E->getConstructor();
11419 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11420 return false;
11421
11422 const FunctionDecl *Definition = nullptr;
11423 auto Body = FD->getBody(Definition);
11424
11425 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11426 return false;
11427
11428 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11430 Result);
11431}
11432
11433bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11434 const CXXStdInitializerListExpr *E) {
11435 const ConstantArrayType *ArrayType =
11436 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11437
11438 LValue Array;
11439 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11440 return false;
11441
11442 assert(ArrayType && "unexpected type for array initializer");
11443
11444 // Get a pointer to the first element of the array.
11445 Array.addArray(Info, E, ArrayType);
11446
11447 // FIXME: What if the initializer_list type has base classes, etc?
11448 Result = APValue(APValue::UninitStruct(), 0, 2);
11449 Array.moveInto(Result.getStructField(0));
11450
11451 auto *Record = E->getType()->castAsRecordDecl();
11452 RecordDecl::field_iterator Field = Record->field_begin();
11453 assert(Field != Record->field_end() &&
11454 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11455 ArrayType->getElementType()) &&
11456 "Expected std::initializer_list first field to be const E *");
11457 ++Field;
11458 assert(Field != Record->field_end() &&
11459 "Expected std::initializer_list to have two fields");
11460
11461 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11462 // Length.
11463 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11464 } else {
11465 // End pointer.
11466 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11467 ArrayType->getElementType()) &&
11468 "Expected std::initializer_list second field to be const E *");
11469 if (!HandleLValueArrayAdjustment(Info, E, Array,
11470 ArrayType->getElementType(),
11471 ArrayType->getZExtSize()))
11472 return false;
11473 Array.moveInto(Result.getStructField(1));
11474 }
11475
11476 assert(++Field == Record->field_end() &&
11477 "Expected std::initializer_list to only have two fields");
11478
11479 return true;
11480}
11481
11482bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11483 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11484 if (ClosureClass->isInvalidDecl())
11485 return false;
11486
11487 const size_t NumFields = ClosureClass->getNumFields();
11488
11489 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11490 E->capture_init_end()) &&
11491 "The number of lambda capture initializers should equal the number of "
11492 "fields within the closure type");
11493
11494 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11495 // Iterate through all the lambda's closure object's fields and initialize
11496 // them.
11497 auto *CaptureInitIt = E->capture_init_begin();
11498 bool Success = true;
11499 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11500 for (const auto *Field : ClosureClass->fields()) {
11501 assert(CaptureInitIt != E->capture_init_end());
11502 // Get the initializer for this field
11503 Expr *const CurFieldInit = *CaptureInitIt++;
11504
11505 // If there is no initializer, either this is a VLA or an error has
11506 // occurred.
11507 if (!CurFieldInit || CurFieldInit->containsErrors())
11508 return Error(E);
11509
11510 LValue Subobject = This;
11511
11512 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11513 return false;
11514
11515 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11516 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11517 if (!Info.keepEvaluatingAfterFailure())
11518 return false;
11519 Success = false;
11520 }
11521 }
11522 return Success;
11523}
11524
11525static bool EvaluateRecord(const Expr *E, const LValue &This,
11526 APValue &Result, EvalInfo &Info) {
11527 assert(!E->isValueDependent());
11528 assert(E->isPRValue() && E->getType()->isRecordType() &&
11529 "can't evaluate expression as a record rvalue");
11530 return RecordExprEvaluator(Info, This, Result).Visit(E);
11531}
11532
11533//===----------------------------------------------------------------------===//
11534// Temporary Evaluation
11535//
11536// Temporaries are represented in the AST as rvalues, but generally behave like
11537// lvalues. The full-object of which the temporary is a subobject is implicitly
11538// materialized so that a reference can bind to it.
11539//===----------------------------------------------------------------------===//
11540namespace {
11541class TemporaryExprEvaluator
11542 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11543public:
11544 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11545 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11546
11547 /// Visit an expression which constructs the value of this temporary.
11548 bool VisitConstructExpr(const Expr *E) {
11549 APValue &Value = Info.CurrentCall->createTemporary(
11550 E, E->getType(), ScopeKind::FullExpression, Result);
11551 return EvaluateInPlace(Value, Info, Result, E);
11552 }
11553
11554 bool VisitCastExpr(const CastExpr *E) {
11555 switch (E->getCastKind()) {
11556 default:
11557 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11558
11559 case CK_ConstructorConversion:
11560 return VisitConstructExpr(E->getSubExpr());
11561 }
11562 }
11563 bool VisitInitListExpr(const InitListExpr *E) {
11564 return VisitConstructExpr(E);
11565 }
11566 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11567 return VisitConstructExpr(E);
11568 }
11569 bool VisitCallExpr(const CallExpr *E) {
11570 return VisitConstructExpr(E);
11571 }
11572 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11573 return VisitConstructExpr(E);
11574 }
11575 bool VisitLambdaExpr(const LambdaExpr *E) {
11576 return VisitConstructExpr(E);
11577 }
11578};
11579} // end anonymous namespace
11580
11581/// Evaluate an expression of record type as a temporary.
11582static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11583 assert(!E->isValueDependent());
11584 assert(E->isPRValue() && E->getType()->isRecordType());
11585 return TemporaryExprEvaluator(Info, Result).Visit(E);
11586}
11587
11588//===----------------------------------------------------------------------===//
11589// Vector Evaluation
11590//===----------------------------------------------------------------------===//
11591
11592namespace {
11593 class VectorExprEvaluator
11594 : public ExprEvaluatorBase<VectorExprEvaluator> {
11595 APValue &Result;
11596 public:
11597
11598 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11599 : ExprEvaluatorBaseTy(info), Result(Result) {}
11600
11601 bool Success(ArrayRef<APValue> V, const Expr *E) {
11602 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11603 // FIXME: remove this APValue copy.
11604 Result = APValue(V.data(), V.size());
11605 return true;
11606 }
11607 bool Success(const APValue &V, const Expr *E) {
11608 assert(V.isVector());
11609 Result = V;
11610 return true;
11611 }
11612 bool ZeroInitialization(const Expr *E);
11613
11614 bool VisitUnaryReal(const UnaryOperator *E)
11615 { return Visit(E->getSubExpr()); }
11616 bool VisitCastExpr(const CastExpr* E);
11617 bool VisitInitListExpr(const InitListExpr *E);
11618 bool VisitUnaryImag(const UnaryOperator *E);
11619 bool VisitBinaryOperator(const BinaryOperator *E);
11620 bool VisitUnaryOperator(const UnaryOperator *E);
11621 bool VisitCallExpr(const CallExpr *E);
11622 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11623 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11624
11625 // FIXME: Missing: conditional operator (for GNU
11626 // conditional select), ExtVectorElementExpr
11627 };
11628} // end anonymous namespace
11629
11630static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11631 assert(E->isPRValue() && E->getType()->isVectorType() &&
11632 "not a vector prvalue");
11633 return VectorExprEvaluator(Info, Result).Visit(E);
11634}
11635
11636static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11637 assert(Val.isVector() && "expected vector APValue");
11638 unsigned NumElts = Val.getVectorLength();
11639
11640 // Each element is one bit, so create an integer with NumElts bits.
11641 llvm::APInt Result(NumElts, 0);
11642
11643 for (unsigned I = 0; I < NumElts; ++I) {
11644 const APValue &Elt = Val.getVectorElt(I);
11645 assert(Elt.isInt() && "expected integer element in bool vector");
11646
11647 if (Elt.getInt().getBoolValue())
11648 Result.setBit(I);
11649 }
11650
11651 return Result;
11652}
11653
11654bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11655 const VectorType *VTy = E->getType()->castAs<VectorType>();
11656 unsigned NElts = VTy->getNumElements();
11657
11658 const Expr *SE = E->getSubExpr();
11659 QualType SETy = SE->getType();
11660
11661 switch (E->getCastKind()) {
11662 case CK_VectorSplat: {
11663 APValue Val = APValue();
11664 if (SETy->isIntegerType()) {
11665 APSInt IntResult;
11666 if (!EvaluateInteger(SE, IntResult, Info))
11667 return false;
11668 Val = APValue(std::move(IntResult));
11669 } else if (SETy->isRealFloatingType()) {
11670 APFloat FloatResult(0.0);
11671 if (!EvaluateFloat(SE, FloatResult, Info))
11672 return false;
11673 Val = APValue(std::move(FloatResult));
11674 } else {
11675 return Error(E);
11676 }
11677
11678 // Splat and create vector APValue.
11679 SmallVector<APValue, 4> Elts(NElts, Val);
11680 return Success(Elts, E);
11681 }
11682 case CK_BitCast: {
11683 APValue SVal;
11684 if (!Evaluate(SVal, Info, SE))
11685 return false;
11686
11687 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11688 // Give up if the input isn't an int, float, or vector. For example, we
11689 // reject "(v4i16)(intptr_t)&a".
11690 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11691 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11692 << Info.Ctx.getLangOpts().CPlusPlus;
11693 return false;
11694 }
11695
11696 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11697 return false;
11698
11699 return true;
11700 }
11701 case CK_HLSLVectorTruncation: {
11702 APValue Val;
11703 SmallVector<APValue, 4> Elements;
11704 if (!EvaluateVector(SE, Val, Info))
11705 return Error(E);
11706 for (unsigned I = 0; I < NElts; I++)
11707 Elements.push_back(Val.getVectorElt(I));
11708 return Success(Elements, E);
11709 }
11710 case CK_HLSLMatrixTruncation: {
11711 // Matrix truncation occurs in row-major order.
11712 APValue Val;
11713 if (!EvaluateMatrix(SE, Val, Info))
11714 return Error(E);
11715 SmallVector<APValue, 16> Elements;
11716 for (unsigned Row = 0;
11717 Row < Val.getMatrixNumRows() && Elements.size() < NElts; Row++)
11718 for (unsigned Col = 0;
11719 Col < Val.getMatrixNumColumns() && Elements.size() < NElts; Col++)
11720 Elements.push_back(Val.getMatrixElt(Row, Col));
11721 return Success(Elements, E);
11722 }
11723 case CK_HLSLAggregateSplatCast: {
11724 APValue Val;
11725 QualType ValTy;
11726
11727 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
11728 return false;
11729
11730 // cast our Val once.
11732 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11733 if (!handleScalarCast(Info, FPO, E, ValTy, VTy->getElementType(), Val,
11734 Result))
11735 return false;
11736
11737 SmallVector<APValue, 4> SplatEls(NElts, Result);
11738 return Success(SplatEls, E);
11739 }
11740 case CK_HLSLElementwiseCast: {
11741 SmallVector<APValue> SrcVals;
11742 SmallVector<QualType> SrcTypes;
11743
11744 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
11745 return false;
11746
11747 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11748 SmallVector<QualType, 4> DestTypes(NElts, VTy->getElementType());
11749 SmallVector<APValue, 4> ResultEls(NElts);
11750 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
11751 ResultEls))
11752 return false;
11753 return Success(ResultEls, E);
11754 }
11755 default:
11756 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11757 }
11758}
11759
11760bool
11761VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11762 const VectorType *VT = E->getType()->castAs<VectorType>();
11763 unsigned NumInits = E->getNumInits();
11764 unsigned NumElements = VT->getNumElements();
11765
11766 QualType EltTy = VT->getElementType();
11767 SmallVector<APValue, 4> Elements;
11768
11769 // MFloat8 type doesn't have constants and thus constant folding
11770 // is impossible.
11771 if (EltTy->isMFloat8Type())
11772 return false;
11773
11774 // The number of initializers can be less than the number of
11775 // vector elements. For OpenCL, this can be due to nested vector
11776 // initialization. For GCC compatibility, missing trailing elements
11777 // should be initialized with zeroes.
11778 unsigned CountInits = 0, CountElts = 0;
11779 while (CountElts < NumElements) {
11780 // Handle nested vector initialization.
11781 if (CountInits < NumInits
11782 && E->getInit(CountInits)->getType()->isVectorType()) {
11783 APValue v;
11784 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11785 return Error(E);
11786 unsigned vlen = v.getVectorLength();
11787 for (unsigned j = 0; j < vlen; j++)
11788 Elements.push_back(v.getVectorElt(j));
11789 CountElts += vlen;
11790 } else if (EltTy->isIntegerType()) {
11791 llvm::APSInt sInt(32);
11792 if (CountInits < NumInits) {
11793 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11794 return false;
11795 } else // trailing integer zero.
11796 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11797 Elements.push_back(APValue(sInt));
11798 CountElts++;
11799 } else {
11800 llvm::APFloat f(0.0);
11801 if (CountInits < NumInits) {
11802 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11803 return false;
11804 } else // trailing float zero.
11805 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11806 Elements.push_back(APValue(f));
11807 CountElts++;
11808 }
11809 CountInits++;
11810 }
11811 return Success(Elements, E);
11812}
11813
11814bool
11815VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11816 const auto *VT = E->getType()->castAs<VectorType>();
11817 QualType EltTy = VT->getElementType();
11818 APValue ZeroElement;
11819 if (EltTy->isIntegerType())
11820 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11821 else
11822 ZeroElement =
11823 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11824
11825 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11826 return Success(Elements, E);
11827}
11828
11829bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11830 VisitIgnoredValue(E->getSubExpr());
11831 return ZeroInitialization(E);
11832}
11833
11834bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11835 BinaryOperatorKind Op = E->getOpcode();
11836 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11837 "Operation not supported on vector types");
11838
11839 if (Op == BO_Comma)
11840 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11841
11842 Expr *LHS = E->getLHS();
11843 Expr *RHS = E->getRHS();
11844
11845 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11846 "Must both be vector types");
11847 // Checking JUST the types are the same would be fine, except shifts don't
11848 // need to have their types be the same (since you always shift by an int).
11849 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11850 E->getType()->castAs<VectorType>()->getNumElements() &&
11851 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11852 E->getType()->castAs<VectorType>()->getNumElements() &&
11853 "All operands must be the same size.");
11854
11855 APValue LHSValue;
11856 APValue RHSValue;
11857 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11858 if (!LHSOK && !Info.noteFailure())
11859 return false;
11860 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11861 return false;
11862
11863 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11864 return false;
11865
11866 return Success(LHSValue, E);
11867}
11868
11869static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11870 QualType ResultTy,
11872 APValue Elt) {
11873 switch (Op) {
11874 case UO_Plus:
11875 // Nothing to do here.
11876 return Elt;
11877 case UO_Minus:
11878 if (Elt.getKind() == APValue::Int) {
11879 Elt.getInt().negate();
11880 } else {
11881 assert(Elt.getKind() == APValue::Float &&
11882 "Vector can only be int or float type");
11883 Elt.getFloat().changeSign();
11884 }
11885 return Elt;
11886 case UO_Not:
11887 // This is only valid for integral types anyway, so we don't have to handle
11888 // float here.
11889 assert(Elt.getKind() == APValue::Int &&
11890 "Vector operator ~ can only be int");
11891 Elt.getInt().flipAllBits();
11892 return Elt;
11893 case UO_LNot: {
11894 if (Elt.getKind() == APValue::Int) {
11895 Elt.getInt() = !Elt.getInt();
11896 // operator ! on vectors returns -1 for 'truth', so negate it.
11897 Elt.getInt().negate();
11898 return Elt;
11899 }
11900 assert(Elt.getKind() == APValue::Float &&
11901 "Vector can only be int or float type");
11902 // Float types result in an int of the same size, but -1 for true, or 0 for
11903 // false.
11904 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11905 ResultTy->isUnsignedIntegerType()};
11906 if (Elt.getFloat().isZero())
11907 EltResult.setAllBits();
11908 else
11909 EltResult.clearAllBits();
11910
11911 return APValue{EltResult};
11912 }
11913 default:
11914 // FIXME: Implement the rest of the unary operators.
11915 return std::nullopt;
11916 }
11917}
11918
11919bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11920 Expr *SubExpr = E->getSubExpr();
11921 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11922 // This result element type differs in the case of negating a floating point
11923 // vector, since the result type is the a vector of the equivilant sized
11924 // integer.
11925 const QualType ResultEltTy = VD->getElementType();
11926 UnaryOperatorKind Op = E->getOpcode();
11927
11928 APValue SubExprValue;
11929 if (!Evaluate(SubExprValue, Info, SubExpr))
11930 return false;
11931
11932 // FIXME: This vector evaluator someday needs to be changed to be LValue
11933 // aware/keep LValue information around, rather than dealing with just vector
11934 // types directly. Until then, we cannot handle cases where the operand to
11935 // these unary operators is an LValue. The only case I've been able to see
11936 // cause this is operator++ assigning to a member expression (only valid in
11937 // altivec compilations) in C mode, so this shouldn't limit us too much.
11938 if (SubExprValue.isLValue())
11939 return false;
11940
11941 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11942 "Vector length doesn't match type?");
11943
11944 SmallVector<APValue, 4> ResultElements;
11945 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11946 std::optional<APValue> Elt = handleVectorUnaryOperator(
11947 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11948 if (!Elt)
11949 return false;
11950 ResultElements.push_back(*Elt);
11951 }
11952 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11953}
11954
11955static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11956 const Expr *E, QualType SourceTy,
11957 QualType DestTy, APValue const &Original,
11958 APValue &Result) {
11959 if (SourceTy->isIntegerType()) {
11960 if (DestTy->isRealFloatingType()) {
11961 Result = APValue(APFloat(0.0));
11962 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11963 DestTy, Result.getFloat());
11964 }
11965 if (DestTy->isIntegerType()) {
11966 Result = APValue(
11967 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11968 return true;
11969 }
11970 } else if (SourceTy->isRealFloatingType()) {
11971 if (DestTy->isRealFloatingType()) {
11972 Result = Original;
11973 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11974 Result.getFloat());
11975 }
11976 if (DestTy->isIntegerType()) {
11977 Result = APValue(APSInt());
11978 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11979 DestTy, Result.getInt());
11980 }
11981 }
11982
11983 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11984 << SourceTy << DestTy;
11985 return false;
11986}
11987
11988static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
11989 llvm::function_ref<APInt(const APSInt &)> PackFn) {
11990 APValue LHS, RHS;
11991 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
11992 !EvaluateAsRValue(Info, E->getArg(1), RHS))
11993 return false;
11994
11995 unsigned LHSVecLen = LHS.getVectorLength();
11996 unsigned RHSVecLen = RHS.getVectorLength();
11997
11998 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
11999 "pack builtin LHSVecLen must equal to RHSVecLen");
12000
12001 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12002 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12003
12004 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12005 QualType DstElemTy = DstVT->getElementType();
12006 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12007
12008 const unsigned SrcPerLane = 128 / SrcBits;
12009 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12010
12012 Out.reserve(LHSVecLen + RHSVecLen);
12013
12014 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12015 unsigned base = Lane * SrcPerLane;
12016 for (unsigned I = 0; I != SrcPerLane; ++I)
12017 Out.emplace_back(APValue(
12018 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12019 for (unsigned I = 0; I != SrcPerLane; ++I)
12020 Out.emplace_back(APValue(
12021 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12022 }
12023
12024 Result = APValue(Out.data(), Out.size());
12025 return true;
12026}
12027
12029 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12030 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12031 GetSourceIndex) {
12032
12033 const auto *VT = Call->getType()->getAs<VectorType>();
12034 if (!VT)
12035 return false;
12036
12037 unsigned ShuffleMask = 0;
12038 APValue A, MaskVector, B;
12039 bool IsVectorMask = false;
12040 bool IsSingleOperand = (Call->getNumArgs() == 2);
12041
12042 if (IsSingleOperand) {
12043 QualType MaskType = Call->getArg(1)->getType();
12044 if (MaskType->isVectorType()) {
12045 IsVectorMask = true;
12046 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12047 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12048 return false;
12049 B = A;
12050 } else if (MaskType->isIntegerType()) {
12051 APSInt MaskImm;
12052 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12053 return false;
12054 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12055 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12056 return false;
12057 B = A;
12058 } else {
12059 return false;
12060 }
12061 } else {
12062 QualType Arg2Type = Call->getArg(2)->getType();
12063 if (Arg2Type->isVectorType()) {
12064 IsVectorMask = true;
12065 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12066 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12067 !EvaluateAsRValue(Info, Call->getArg(2), B))
12068 return false;
12069 } else if (Arg2Type->isIntegerType()) {
12070 APSInt MaskImm;
12071 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12072 return false;
12073 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12074 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12075 !EvaluateAsRValue(Info, Call->getArg(1), B))
12076 return false;
12077 } else {
12078 return false;
12079 }
12080 }
12081
12082 unsigned NumElts = VT->getNumElements();
12083 SmallVector<APValue, 64> ResultElements;
12084 ResultElements.reserve(NumElts);
12085
12086 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12087 if (IsVectorMask) {
12088 ShuffleMask = static_cast<unsigned>(
12089 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12090 }
12091 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12092
12093 if (SrcIdx < 0) {
12094 // Zero out this element
12095 QualType ElemTy = VT->getElementType();
12096 if (ElemTy->isRealFloatingType()) {
12097 ResultElements.push_back(
12098 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12099 } else if (ElemTy->isIntegerType()) {
12100 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12101 ResultElements.push_back(APValue(Zero));
12102 } else {
12103 // Other types of fallback logic
12104 ResultElements.push_back(APValue());
12105 }
12106 } else {
12107 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12108 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12109 }
12110 }
12111
12112 Out = APValue(ResultElements.data(), ResultElements.size());
12113 return true;
12114}
12115static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E,
12116 APFloat OrigVal, APValue &Result) {
12117
12118 if (OrigVal.isInfinity()) {
12119 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 0;
12120 return false;
12121 }
12122 if (OrigVal.isNaN()) {
12123 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 1;
12124 return false;
12125 }
12126
12127 APFloat Val = OrigVal;
12128 bool LosesInfo = false;
12129 APFloat::opStatus Status = Val.convert(
12130 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
12131
12132 if (LosesInfo || Val.isDenormal()) {
12133 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic_strict);
12134 return false;
12135 }
12136
12137 if (Status != APFloat::opOK) {
12138 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12139 return false;
12140 }
12141
12142 Result = APValue(Val);
12143 return true;
12144}
12146 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12147 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
12148 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
12149
12150 APValue Source, Count;
12151 if (!EvaluateAsRValue(Info, Call->getArg(0), Source) ||
12152 !EvaluateAsRValue(Info, Call->getArg(1), Count))
12153 return false;
12154
12155 assert(Call->getNumArgs() == 2);
12156
12157 QualType SourceTy = Call->getArg(0)->getType();
12158 assert(SourceTy->isVectorType() &&
12159 Call->getArg(1)->getType()->isVectorType());
12160
12161 QualType DestEltTy = SourceTy->castAs<VectorType>()->getElementType();
12162 unsigned DestEltWidth = Source.getVectorElt(0).getInt().getBitWidth();
12163 unsigned DestLen = Source.getVectorLength();
12164 bool IsDestUnsigned = DestEltTy->isUnsignedIntegerType();
12165 unsigned CountEltWidth = Count.getVectorElt(0).getInt().getBitWidth();
12166 unsigned NumBitsInQWord = 64;
12167 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
12169 Result.reserve(DestLen);
12170
12171 uint64_t CountLQWord = 0;
12172 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
12173 uint64_t Elt = Count.getVectorElt(EltIdx).getInt().getZExtValue();
12174 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
12175 }
12176
12177 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
12178 APInt Elt = Source.getVectorElt(EltIdx).getInt();
12179 if (CountLQWord < DestEltWidth) {
12180 Result.push_back(
12181 APValue(APSInt(ShiftOp(Elt, CountLQWord), IsDestUnsigned)));
12182 } else {
12183 Result.push_back(
12184 APValue(APSInt(OverflowOp(Elt, DestEltWidth), IsDestUnsigned)));
12185 }
12186 }
12187 Out = APValue(Result.data(), Result.size());
12188 return true;
12189}
12190
12191std::optional<APFloat> EvalScalarMinMaxFp(const APFloat &A, const APFloat &B,
12192 std::optional<APSInt> RoundingMode,
12193 bool IsMin) {
12194 APSInt DefaultMode(APInt(32, 4), /*isUnsigned=*/true);
12195 if (RoundingMode.value_or(DefaultMode) != 4)
12196 return std::nullopt;
12197 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
12198 B.isInfinity() || B.isDenormal())
12199 return std::nullopt;
12200 if (A.isZero() && B.isZero())
12201 return B;
12202 return IsMin ? llvm::minimum(A, B) : llvm::maximum(A, B);
12203}
12204
12205bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12206 if (!IsConstantEvaluatedBuiltinCall(E))
12207 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12208
12209 auto EvaluateBinOpExpr =
12210 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12211 APValue SourceLHS, SourceRHS;
12212 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12213 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12214 return false;
12215
12216 auto *DestTy = E->getType()->castAs<VectorType>();
12217 QualType DestEltTy = DestTy->getElementType();
12218 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12219 unsigned SourceLen = SourceLHS.getVectorLength();
12220 SmallVector<APValue, 4> ResultElements;
12221 ResultElements.reserve(SourceLen);
12222
12223 if (SourceRHS.isInt()) {
12224 const APSInt &RHS = SourceRHS.getInt();
12225 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12226 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12227 ResultElements.push_back(
12228 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12229 }
12230 } else {
12231 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12232 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12233 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12234 ResultElements.push_back(
12235 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12236 }
12237 }
12238 return Success(APValue(ResultElements.data(), SourceLen), E);
12239 };
12240
12241 auto EvaluateFpBinOpExpr =
12242 [&](llvm::function_ref<std::optional<APFloat>(
12243 const APFloat &, const APFloat &, std::optional<APSInt>)>
12244 Fn,
12245 bool IsScalar = false) {
12246 assert(E->getNumArgs() == 2 || E->getNumArgs() == 3);
12247 APValue A, B;
12248 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12249 !EvaluateAsRValue(Info, E->getArg(1), B))
12250 return false;
12251
12252 assert(A.isVector() && B.isVector());
12253 assert(A.getVectorLength() == B.getVectorLength());
12254
12255 std::optional<APSInt> RoundingMode;
12256 if (E->getNumArgs() == 3) {
12257 APSInt Imm;
12258 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12259 return false;
12260 RoundingMode = Imm;
12261 }
12262
12263 unsigned NumElems = A.getVectorLength();
12264 SmallVector<APValue, 4> ResultElements;
12265 ResultElements.reserve(NumElems);
12266
12267 for (unsigned EltNum = 0; EltNum < NumElems; ++EltNum) {
12268 if (IsScalar && EltNum > 0) {
12269 ResultElements.push_back(A.getVectorElt(EltNum));
12270 continue;
12271 }
12272 const APFloat &EltA = A.getVectorElt(EltNum).getFloat();
12273 const APFloat &EltB = B.getVectorElt(EltNum).getFloat();
12274 std::optional<APFloat> Result = Fn(EltA, EltB, RoundingMode);
12275 if (!Result)
12276 return false;
12277 ResultElements.push_back(APValue(*Result));
12278 }
12279 return Success(APValue(ResultElements.data(), NumElems), E);
12280 };
12281
12282 auto EvaluateScalarFpRoundMaskBinOp =
12283 [&](llvm::function_ref<std::optional<APFloat>(
12284 const APFloat &, const APFloat &, std::optional<APSInt>)>
12285 Fn) {
12286 assert(E->getNumArgs() == 5);
12287 APValue VecA, VecB, VecSrc;
12288 APSInt MaskVal, Rounding;
12289
12290 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
12291 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
12292 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
12293 !EvaluateInteger(E->getArg(3), MaskVal, Info) ||
12294 !EvaluateInteger(E->getArg(4), Rounding, Info))
12295 return false;
12296
12297 unsigned NumElems = VecA.getVectorLength();
12298 SmallVector<APValue, 8> ResultElements;
12299 ResultElements.reserve(NumElems);
12300
12301 if (MaskVal.getZExtValue() & 1) {
12302 const APFloat &EltA = VecA.getVectorElt(0).getFloat();
12303 const APFloat &EltB = VecB.getVectorElt(0).getFloat();
12304 std::optional<APFloat> Result = Fn(EltA, EltB, Rounding);
12305 if (!Result)
12306 return false;
12307 ResultElements.push_back(APValue(*Result));
12308 } else {
12309 ResultElements.push_back(VecSrc.getVectorElt(0));
12310 }
12311
12312 for (unsigned I = 1; I < NumElems; ++I)
12313 ResultElements.push_back(VecA.getVectorElt(I));
12314
12315 return Success(APValue(ResultElements.data(), NumElems), E);
12316 };
12317
12318 auto EvalSelectScalar = [&](unsigned Len) -> bool {
12319 APSInt Mask;
12320 APValue AVal, WVal;
12321 if (!EvaluateInteger(E->getArg(0), Mask, Info) ||
12322 !EvaluateAsRValue(Info, E->getArg(1), AVal) ||
12323 !EvaluateAsRValue(Info, E->getArg(2), WVal))
12324 return false;
12325
12326 bool TakeA0 = (Mask.getZExtValue() & 1u) != 0;
12328 Res.reserve(Len);
12329 Res.push_back(TakeA0 ? AVal.getVectorElt(0) : WVal.getVectorElt(0));
12330 for (unsigned I = 1; I < Len; ++I)
12331 Res.push_back(WVal.getVectorElt(I));
12332 APValue V(Res.data(), Res.size());
12333 return Success(V, E);
12334 };
12335
12336 switch (E->getBuiltinCallee()) {
12337 default:
12338 return false;
12339 case Builtin::BI__builtin_elementwise_popcount:
12340 case Builtin::BI__builtin_elementwise_bitreverse: {
12341 APValue Source;
12342 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12343 return false;
12344
12345 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12346 unsigned SourceLen = Source.getVectorLength();
12347 SmallVector<APValue, 4> ResultElements;
12348 ResultElements.reserve(SourceLen);
12349
12350 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12351 APSInt Elt = Source.getVectorElt(EltNum).getInt();
12352 switch (E->getBuiltinCallee()) {
12353 case Builtin::BI__builtin_elementwise_popcount:
12354 ResultElements.push_back(APValue(
12355 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
12356 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12357 break;
12358 case Builtin::BI__builtin_elementwise_bitreverse:
12359 ResultElements.push_back(
12360 APValue(APSInt(Elt.reverseBits(),
12361 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12362 break;
12363 }
12364 }
12365
12366 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12367 }
12368 case Builtin::BI__builtin_elementwise_abs: {
12369 APValue Source;
12370 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12371 return false;
12372
12373 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12374 unsigned SourceLen = Source.getVectorLength();
12375 SmallVector<APValue, 4> ResultElements;
12376 ResultElements.reserve(SourceLen);
12377
12378 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12379 APValue CurrentEle = Source.getVectorElt(EltNum);
12380 APValue Val = DestEltTy->isFloatingType()
12381 ? APValue(llvm::abs(CurrentEle.getFloat()))
12382 : APValue(APSInt(
12383 CurrentEle.getInt().abs(),
12384 DestEltTy->isUnsignedIntegerOrEnumerationType()));
12385 ResultElements.push_back(Val);
12386 }
12387
12388 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12389 }
12390
12391 case Builtin::BI__builtin_elementwise_add_sat:
12392 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12393 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
12394 });
12395
12396 case Builtin::BI__builtin_elementwise_sub_sat:
12397 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12398 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
12399 });
12400
12401 case X86::BI__builtin_ia32_extract128i256:
12402 case X86::BI__builtin_ia32_vextractf128_pd256:
12403 case X86::BI__builtin_ia32_vextractf128_ps256:
12404 case X86::BI__builtin_ia32_vextractf128_si256: {
12405 APValue SourceVec, SourceImm;
12406 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12407 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
12408 return false;
12409
12410 if (!SourceVec.isVector())
12411 return false;
12412
12413 const auto *RetVT = E->getType()->castAs<VectorType>();
12414 unsigned RetLen = RetVT->getNumElements();
12415 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
12416
12417 SmallVector<APValue, 32> ResultElements;
12418 ResultElements.reserve(RetLen);
12419
12420 for (unsigned I = 0; I < RetLen; I++)
12421 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
12422
12423 return Success(APValue(ResultElements.data(), RetLen), E);
12424 }
12425
12426 case clang::X86::BI__builtin_ia32_cvtmask2b128:
12427 case clang::X86::BI__builtin_ia32_cvtmask2b256:
12428 case clang::X86::BI__builtin_ia32_cvtmask2b512:
12429 case clang::X86::BI__builtin_ia32_cvtmask2w128:
12430 case clang::X86::BI__builtin_ia32_cvtmask2w256:
12431 case clang::X86::BI__builtin_ia32_cvtmask2w512:
12432 case clang::X86::BI__builtin_ia32_cvtmask2d128:
12433 case clang::X86::BI__builtin_ia32_cvtmask2d256:
12434 case clang::X86::BI__builtin_ia32_cvtmask2d512:
12435 case clang::X86::BI__builtin_ia32_cvtmask2q128:
12436 case clang::X86::BI__builtin_ia32_cvtmask2q256:
12437 case clang::X86::BI__builtin_ia32_cvtmask2q512: {
12438 assert(E->getNumArgs() == 1);
12439 APSInt Mask;
12440 if (!EvaluateInteger(E->getArg(0), Mask, Info))
12441 return false;
12442
12443 QualType VecTy = E->getType();
12444 const VectorType *VT = VecTy->castAs<VectorType>();
12445 unsigned VectorLen = VT->getNumElements();
12446 QualType ElemTy = VT->getElementType();
12447 unsigned ElemWidth = Info.Ctx.getTypeSize(ElemTy);
12448
12450 for (unsigned I = 0; I != VectorLen; ++I) {
12451 bool BitSet = Mask[I];
12452 APSInt ElemVal(ElemWidth, /*isUnsigned=*/false);
12453 if (BitSet) {
12454 ElemVal.setAllBits();
12455 }
12456 Elems.push_back(APValue(ElemVal));
12457 }
12458 return Success(APValue(Elems.data(), VectorLen), E);
12459 }
12460
12461 case X86::BI__builtin_ia32_extracti32x4_256_mask:
12462 case X86::BI__builtin_ia32_extractf32x4_256_mask:
12463 case X86::BI__builtin_ia32_extracti32x4_mask:
12464 case X86::BI__builtin_ia32_extractf32x4_mask:
12465 case X86::BI__builtin_ia32_extracti32x8_mask:
12466 case X86::BI__builtin_ia32_extractf32x8_mask:
12467 case X86::BI__builtin_ia32_extracti64x2_256_mask:
12468 case X86::BI__builtin_ia32_extractf64x2_256_mask:
12469 case X86::BI__builtin_ia32_extracti64x2_512_mask:
12470 case X86::BI__builtin_ia32_extractf64x2_512_mask:
12471 case X86::BI__builtin_ia32_extracti64x4_mask:
12472 case X86::BI__builtin_ia32_extractf64x4_mask: {
12473 APValue SourceVec, MergeVec;
12474 APSInt Imm, MaskImm;
12475
12476 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12477 !EvaluateInteger(E->getArg(1), Imm, Info) ||
12478 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
12479 !EvaluateInteger(E->getArg(3), MaskImm, Info))
12480 return false;
12481
12482 const auto *RetVT = E->getType()->castAs<VectorType>();
12483 unsigned RetLen = RetVT->getNumElements();
12484
12485 if (!SourceVec.isVector() || !MergeVec.isVector())
12486 return false;
12487 unsigned SrcLen = SourceVec.getVectorLength();
12488 unsigned Lanes = SrcLen / RetLen;
12489 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
12490 unsigned Base = Lane * RetLen;
12491
12492 SmallVector<APValue, 32> ResultElements;
12493 ResultElements.reserve(RetLen);
12494 for (unsigned I = 0; I < RetLen; ++I) {
12495 if (MaskImm[I])
12496 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
12497 else
12498 ResultElements.push_back(MergeVec.getVectorElt(I));
12499 }
12500 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12501 }
12502
12503 case clang::X86::BI__builtin_ia32_pavgb128:
12504 case clang::X86::BI__builtin_ia32_pavgw128:
12505 case clang::X86::BI__builtin_ia32_pavgb256:
12506 case clang::X86::BI__builtin_ia32_pavgw256:
12507 case clang::X86::BI__builtin_ia32_pavgb512:
12508 case clang::X86::BI__builtin_ia32_pavgw512:
12509 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
12510
12511 case clang::X86::BI__builtin_ia32_pmulhrsw128:
12512 case clang::X86::BI__builtin_ia32_pmulhrsw256:
12513 case clang::X86::BI__builtin_ia32_pmulhrsw512:
12514 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12515 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
12516 .extractBits(16, 1);
12517 });
12518
12519 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12520 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12521 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12522 case clang::X86::BI__builtin_ia32_pmaddwd128:
12523 case clang::X86::BI__builtin_ia32_pmaddwd256:
12524 case clang::X86::BI__builtin_ia32_pmaddwd512: {
12525 APValue SourceLHS, SourceRHS;
12526 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12527 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12528 return false;
12529
12530 auto *DestTy = E->getType()->castAs<VectorType>();
12531 QualType DestEltTy = DestTy->getElementType();
12532 unsigned SourceLen = SourceLHS.getVectorLength();
12533 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12534 SmallVector<APValue, 4> ResultElements;
12535 ResultElements.reserve(SourceLen / 2);
12536
12537 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12538 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
12539 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
12540 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
12541 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
12542 unsigned BitWidth = 2 * LoLHS.getBitWidth();
12543
12544 switch (E->getBuiltinCallee()) {
12545 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12546 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12547 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12548 ResultElements.push_back(APValue(
12549 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
12550 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
12551 DestUnsigned)));
12552 break;
12553 case clang::X86::BI__builtin_ia32_pmaddwd128:
12554 case clang::X86::BI__builtin_ia32_pmaddwd256:
12555 case clang::X86::BI__builtin_ia32_pmaddwd512:
12556 ResultElements.push_back(
12557 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
12558 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
12559 DestUnsigned)));
12560 break;
12561 }
12562 }
12563
12564 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12565 }
12566
12567 case clang::X86::BI__builtin_ia32_pmulhuw128:
12568 case clang::X86::BI__builtin_ia32_pmulhuw256:
12569 case clang::X86::BI__builtin_ia32_pmulhuw512:
12570 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
12571
12572 case clang::X86::BI__builtin_ia32_pmulhw128:
12573 case clang::X86::BI__builtin_ia32_pmulhw256:
12574 case clang::X86::BI__builtin_ia32_pmulhw512:
12575 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
12576
12577 case clang::X86::BI__builtin_ia32_psllv2di:
12578 case clang::X86::BI__builtin_ia32_psllv4di:
12579 case clang::X86::BI__builtin_ia32_psllv4si:
12580 case clang::X86::BI__builtin_ia32_psllv8di:
12581 case clang::X86::BI__builtin_ia32_psllv8hi:
12582 case clang::X86::BI__builtin_ia32_psllv8si:
12583 case clang::X86::BI__builtin_ia32_psllv16hi:
12584 case clang::X86::BI__builtin_ia32_psllv16si:
12585 case clang::X86::BI__builtin_ia32_psllv32hi:
12586 case clang::X86::BI__builtin_ia32_psllwi128:
12587 case clang::X86::BI__builtin_ia32_pslldi128:
12588 case clang::X86::BI__builtin_ia32_psllqi128:
12589 case clang::X86::BI__builtin_ia32_psllwi256:
12590 case clang::X86::BI__builtin_ia32_pslldi256:
12591 case clang::X86::BI__builtin_ia32_psllqi256:
12592 case clang::X86::BI__builtin_ia32_psllwi512:
12593 case clang::X86::BI__builtin_ia32_pslldi512:
12594 case clang::X86::BI__builtin_ia32_psllqi512:
12595 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12596 if (RHS.uge(LHS.getBitWidth())) {
12597 return APInt::getZero(LHS.getBitWidth());
12598 }
12599 return LHS.shl(RHS.getZExtValue());
12600 });
12601
12602 case clang::X86::BI__builtin_ia32_psrav4si:
12603 case clang::X86::BI__builtin_ia32_psrav8di:
12604 case clang::X86::BI__builtin_ia32_psrav8hi:
12605 case clang::X86::BI__builtin_ia32_psrav8si:
12606 case clang::X86::BI__builtin_ia32_psrav16hi:
12607 case clang::X86::BI__builtin_ia32_psrav16si:
12608 case clang::X86::BI__builtin_ia32_psrav32hi:
12609 case clang::X86::BI__builtin_ia32_psravq128:
12610 case clang::X86::BI__builtin_ia32_psravq256:
12611 case clang::X86::BI__builtin_ia32_psrawi128:
12612 case clang::X86::BI__builtin_ia32_psradi128:
12613 case clang::X86::BI__builtin_ia32_psraqi128:
12614 case clang::X86::BI__builtin_ia32_psrawi256:
12615 case clang::X86::BI__builtin_ia32_psradi256:
12616 case clang::X86::BI__builtin_ia32_psraqi256:
12617 case clang::X86::BI__builtin_ia32_psrawi512:
12618 case clang::X86::BI__builtin_ia32_psradi512:
12619 case clang::X86::BI__builtin_ia32_psraqi512:
12620 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12621 if (RHS.uge(LHS.getBitWidth())) {
12622 return LHS.ashr(LHS.getBitWidth() - 1);
12623 }
12624 return LHS.ashr(RHS.getZExtValue());
12625 });
12626
12627 case clang::X86::BI__builtin_ia32_psrlv2di:
12628 case clang::X86::BI__builtin_ia32_psrlv4di:
12629 case clang::X86::BI__builtin_ia32_psrlv4si:
12630 case clang::X86::BI__builtin_ia32_psrlv8di:
12631 case clang::X86::BI__builtin_ia32_psrlv8hi:
12632 case clang::X86::BI__builtin_ia32_psrlv8si:
12633 case clang::X86::BI__builtin_ia32_psrlv16hi:
12634 case clang::X86::BI__builtin_ia32_psrlv16si:
12635 case clang::X86::BI__builtin_ia32_psrlv32hi:
12636 case clang::X86::BI__builtin_ia32_psrlwi128:
12637 case clang::X86::BI__builtin_ia32_psrldi128:
12638 case clang::X86::BI__builtin_ia32_psrlqi128:
12639 case clang::X86::BI__builtin_ia32_psrlwi256:
12640 case clang::X86::BI__builtin_ia32_psrldi256:
12641 case clang::X86::BI__builtin_ia32_psrlqi256:
12642 case clang::X86::BI__builtin_ia32_psrlwi512:
12643 case clang::X86::BI__builtin_ia32_psrldi512:
12644 case clang::X86::BI__builtin_ia32_psrlqi512:
12645 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12646 if (RHS.uge(LHS.getBitWidth())) {
12647 return APInt::getZero(LHS.getBitWidth());
12648 }
12649 return LHS.lshr(RHS.getZExtValue());
12650 });
12651 case X86::BI__builtin_ia32_packsswb128:
12652 case X86::BI__builtin_ia32_packsswb256:
12653 case X86::BI__builtin_ia32_packsswb512:
12654 case X86::BI__builtin_ia32_packssdw128:
12655 case X86::BI__builtin_ia32_packssdw256:
12656 case X86::BI__builtin_ia32_packssdw512:
12657 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12658 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
12659 });
12660 case X86::BI__builtin_ia32_packusdw128:
12661 case X86::BI__builtin_ia32_packusdw256:
12662 case X86::BI__builtin_ia32_packusdw512:
12663 case X86::BI__builtin_ia32_packuswb128:
12664 case X86::BI__builtin_ia32_packuswb256:
12665 case X86::BI__builtin_ia32_packuswb512:
12666 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
12667 return APSInt(Src).truncSSatU(Src.getBitWidth() / 2);
12668 });
12669 case clang::X86::BI__builtin_ia32_selectss_128:
12670 return EvalSelectScalar(4);
12671 case clang::X86::BI__builtin_ia32_selectsd_128:
12672 return EvalSelectScalar(2);
12673 case clang::X86::BI__builtin_ia32_selectsh_128:
12674 case clang::X86::BI__builtin_ia32_selectsbf_128:
12675 return EvalSelectScalar(8);
12676 case clang::X86::BI__builtin_ia32_pmuldq128:
12677 case clang::X86::BI__builtin_ia32_pmuldq256:
12678 case clang::X86::BI__builtin_ia32_pmuldq512:
12679 case clang::X86::BI__builtin_ia32_pmuludq128:
12680 case clang::X86::BI__builtin_ia32_pmuludq256:
12681 case clang::X86::BI__builtin_ia32_pmuludq512: {
12682 APValue SourceLHS, SourceRHS;
12683 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12684 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12685 return false;
12686
12687 unsigned SourceLen = SourceLHS.getVectorLength();
12688 SmallVector<APValue, 4> ResultElements;
12689 ResultElements.reserve(SourceLen / 2);
12690
12691 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12692 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12693 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12694
12695 switch (E->getBuiltinCallee()) {
12696 case clang::X86::BI__builtin_ia32_pmuludq128:
12697 case clang::X86::BI__builtin_ia32_pmuludq256:
12698 case clang::X86::BI__builtin_ia32_pmuludq512:
12699 ResultElements.push_back(
12700 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
12701 break;
12702 case clang::X86::BI__builtin_ia32_pmuldq128:
12703 case clang::X86::BI__builtin_ia32_pmuldq256:
12704 case clang::X86::BI__builtin_ia32_pmuldq512:
12705 ResultElements.push_back(
12706 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
12707 break;
12708 }
12709 }
12710
12711 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12712 }
12713
12714 case X86::BI__builtin_ia32_vpmadd52luq128:
12715 case X86::BI__builtin_ia32_vpmadd52luq256:
12716 case X86::BI__builtin_ia32_vpmadd52luq512: {
12717 APValue A, B, C;
12718 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12719 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12720 !EvaluateAsRValue(Info, E->getArg(2), C))
12721 return false;
12722
12723 unsigned ALen = A.getVectorLength();
12724 SmallVector<APValue, 4> ResultElements;
12725 ResultElements.reserve(ALen);
12726
12727 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12728 APInt AElt = A.getVectorElt(EltNum).getInt();
12729 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12730 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12731 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
12732 ResultElements.push_back(APValue(ResElt));
12733 }
12734
12735 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12736 }
12737 case X86::BI__builtin_ia32_vpmadd52huq128:
12738 case X86::BI__builtin_ia32_vpmadd52huq256:
12739 case X86::BI__builtin_ia32_vpmadd52huq512: {
12740 APValue A, B, C;
12741 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12742 !EvaluateAsRValue(Info, E->getArg(1), B) ||
12743 !EvaluateAsRValue(Info, E->getArg(2), C))
12744 return false;
12745
12746 unsigned ALen = A.getVectorLength();
12747 SmallVector<APValue, 4> ResultElements;
12748 ResultElements.reserve(ALen);
12749
12750 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
12751 APInt AElt = A.getVectorElt(EltNum).getInt();
12752 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
12753 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
12754 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
12755 ResultElements.push_back(APValue(ResElt));
12756 }
12757
12758 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12759 }
12760
12761 case clang::X86::BI__builtin_ia32_vprotbi:
12762 case clang::X86::BI__builtin_ia32_vprotdi:
12763 case clang::X86::BI__builtin_ia32_vprotqi:
12764 case clang::X86::BI__builtin_ia32_vprotwi:
12765 case clang::X86::BI__builtin_ia32_prold128:
12766 case clang::X86::BI__builtin_ia32_prold256:
12767 case clang::X86::BI__builtin_ia32_prold512:
12768 case clang::X86::BI__builtin_ia32_prolq128:
12769 case clang::X86::BI__builtin_ia32_prolq256:
12770 case clang::X86::BI__builtin_ia32_prolq512:
12771 return EvaluateBinOpExpr(
12772 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
12773
12774 case clang::X86::BI__builtin_ia32_prord128:
12775 case clang::X86::BI__builtin_ia32_prord256:
12776 case clang::X86::BI__builtin_ia32_prord512:
12777 case clang::X86::BI__builtin_ia32_prorq128:
12778 case clang::X86::BI__builtin_ia32_prorq256:
12779 case clang::X86::BI__builtin_ia32_prorq512:
12780 return EvaluateBinOpExpr(
12781 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
12782
12783 case Builtin::BI__builtin_elementwise_max:
12784 case Builtin::BI__builtin_elementwise_min: {
12785 APValue SourceLHS, SourceRHS;
12786 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12787 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12788 return false;
12789
12790 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12791
12792 if (!DestEltTy->isIntegerType())
12793 return false;
12794
12795 unsigned SourceLen = SourceLHS.getVectorLength();
12796 SmallVector<APValue, 4> ResultElements;
12797 ResultElements.reserve(SourceLen);
12798
12799 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12800 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
12801 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
12802 switch (E->getBuiltinCallee()) {
12803 case Builtin::BI__builtin_elementwise_max:
12804 ResultElements.push_back(
12805 APValue(APSInt(std::max(LHS, RHS),
12806 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12807 break;
12808 case Builtin::BI__builtin_elementwise_min:
12809 ResultElements.push_back(
12810 APValue(APSInt(std::min(LHS, RHS),
12811 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12812 break;
12813 }
12814 }
12815
12816 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12817 }
12818 case X86::BI__builtin_ia32_vpshldd128:
12819 case X86::BI__builtin_ia32_vpshldd256:
12820 case X86::BI__builtin_ia32_vpshldd512:
12821 case X86::BI__builtin_ia32_vpshldq128:
12822 case X86::BI__builtin_ia32_vpshldq256:
12823 case X86::BI__builtin_ia32_vpshldq512:
12824 case X86::BI__builtin_ia32_vpshldw128:
12825 case X86::BI__builtin_ia32_vpshldw256:
12826 case X86::BI__builtin_ia32_vpshldw512: {
12827 APValue SourceHi, SourceLo, SourceAmt;
12828 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
12829 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
12830 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12831 return false;
12832
12833 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12834 unsigned SourceLen = SourceHi.getVectorLength();
12835 SmallVector<APValue, 32> ResultElements;
12836 ResultElements.reserve(SourceLen);
12837
12838 APInt Amt = SourceAmt.getInt();
12839 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12840 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12841 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12842 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
12843 ResultElements.push_back(
12845 }
12846
12847 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12848 }
12849 case X86::BI__builtin_ia32_vpshrdd128:
12850 case X86::BI__builtin_ia32_vpshrdd256:
12851 case X86::BI__builtin_ia32_vpshrdd512:
12852 case X86::BI__builtin_ia32_vpshrdq128:
12853 case X86::BI__builtin_ia32_vpshrdq256:
12854 case X86::BI__builtin_ia32_vpshrdq512:
12855 case X86::BI__builtin_ia32_vpshrdw128:
12856 case X86::BI__builtin_ia32_vpshrdw256:
12857 case X86::BI__builtin_ia32_vpshrdw512: {
12858 // NOTE: Reversed Hi/Lo operands.
12859 APValue SourceHi, SourceLo, SourceAmt;
12860 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
12861 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
12862 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
12863 return false;
12864
12865 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12866 unsigned SourceLen = SourceHi.getVectorLength();
12867 SmallVector<APValue, 32> ResultElements;
12868 ResultElements.reserve(SourceLen);
12869
12870 APInt Amt = SourceAmt.getInt();
12871 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12872 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
12873 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
12874 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
12875 ResultElements.push_back(
12877 }
12878
12879 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12880 }
12881 case X86::BI__builtin_ia32_compressdf128_mask:
12882 case X86::BI__builtin_ia32_compressdf256_mask:
12883 case X86::BI__builtin_ia32_compressdf512_mask:
12884 case X86::BI__builtin_ia32_compressdi128_mask:
12885 case X86::BI__builtin_ia32_compressdi256_mask:
12886 case X86::BI__builtin_ia32_compressdi512_mask:
12887 case X86::BI__builtin_ia32_compresshi128_mask:
12888 case X86::BI__builtin_ia32_compresshi256_mask:
12889 case X86::BI__builtin_ia32_compresshi512_mask:
12890 case X86::BI__builtin_ia32_compressqi128_mask:
12891 case X86::BI__builtin_ia32_compressqi256_mask:
12892 case X86::BI__builtin_ia32_compressqi512_mask:
12893 case X86::BI__builtin_ia32_compresssf128_mask:
12894 case X86::BI__builtin_ia32_compresssf256_mask:
12895 case X86::BI__builtin_ia32_compresssf512_mask:
12896 case X86::BI__builtin_ia32_compresssi128_mask:
12897 case X86::BI__builtin_ia32_compresssi256_mask:
12898 case X86::BI__builtin_ia32_compresssi512_mask: {
12899 APValue Source, Passthru;
12900 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
12901 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
12902 return false;
12903 APSInt Mask;
12904 if (!EvaluateInteger(E->getArg(2), Mask, Info))
12905 return false;
12906
12907 unsigned NumElts = Source.getVectorLength();
12908 SmallVector<APValue, 64> ResultElements;
12909 ResultElements.reserve(NumElts);
12910
12911 for (unsigned I = 0; I != NumElts; ++I) {
12912 if (Mask[I])
12913 ResultElements.push_back(Source.getVectorElt(I));
12914 }
12915 for (unsigned I = ResultElements.size(); I != NumElts; ++I) {
12916 ResultElements.push_back(Passthru.getVectorElt(I));
12917 }
12918
12919 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12920 }
12921 case X86::BI__builtin_ia32_expanddf128_mask:
12922 case X86::BI__builtin_ia32_expanddf256_mask:
12923 case X86::BI__builtin_ia32_expanddf512_mask:
12924 case X86::BI__builtin_ia32_expanddi128_mask:
12925 case X86::BI__builtin_ia32_expanddi256_mask:
12926 case X86::BI__builtin_ia32_expanddi512_mask:
12927 case X86::BI__builtin_ia32_expandhi128_mask:
12928 case X86::BI__builtin_ia32_expandhi256_mask:
12929 case X86::BI__builtin_ia32_expandhi512_mask:
12930 case X86::BI__builtin_ia32_expandqi128_mask:
12931 case X86::BI__builtin_ia32_expandqi256_mask:
12932 case X86::BI__builtin_ia32_expandqi512_mask:
12933 case X86::BI__builtin_ia32_expandsf128_mask:
12934 case X86::BI__builtin_ia32_expandsf256_mask:
12935 case X86::BI__builtin_ia32_expandsf512_mask:
12936 case X86::BI__builtin_ia32_expandsi128_mask:
12937 case X86::BI__builtin_ia32_expandsi256_mask:
12938 case X86::BI__builtin_ia32_expandsi512_mask: {
12939 APValue Source, Passthru;
12940 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
12941 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
12942 return false;
12943 APSInt Mask;
12944 if (!EvaluateInteger(E->getArg(2), Mask, Info))
12945 return false;
12946
12947 unsigned NumElts = Source.getVectorLength();
12948 SmallVector<APValue, 64> ResultElements;
12949 ResultElements.reserve(NumElts);
12950
12951 unsigned SourceIdx = 0;
12952 for (unsigned I = 0; I != NumElts; ++I) {
12953 if (Mask[I])
12954 ResultElements.push_back(Source.getVectorElt(SourceIdx++));
12955 else
12956 ResultElements.push_back(Passthru.getVectorElt(I));
12957 }
12958 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12959 }
12960 case X86::BI__builtin_ia32_vpconflictsi_128:
12961 case X86::BI__builtin_ia32_vpconflictsi_256:
12962 case X86::BI__builtin_ia32_vpconflictsi_512:
12963 case X86::BI__builtin_ia32_vpconflictdi_128:
12964 case X86::BI__builtin_ia32_vpconflictdi_256:
12965 case X86::BI__builtin_ia32_vpconflictdi_512: {
12966 APValue Source;
12967
12968 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12969 return false;
12970
12971 unsigned SourceLen = Source.getVectorLength();
12972 SmallVector<APValue, 32> ResultElements;
12973 ResultElements.reserve(SourceLen);
12974
12975 const auto *VecT = E->getType()->castAs<VectorType>();
12976 bool DestUnsigned =
12977 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
12978
12979 for (unsigned I = 0; I != SourceLen; ++I) {
12980 const APValue &EltI = Source.getVectorElt(I);
12981
12982 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
12983 for (unsigned J = 0; J != I; ++J) {
12984 const APValue &EltJ = Source.getVectorElt(J);
12985 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
12986 }
12987 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
12988 }
12989 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12990 }
12991 case X86::BI__builtin_ia32_blendpd:
12992 case X86::BI__builtin_ia32_blendpd256:
12993 case X86::BI__builtin_ia32_blendps:
12994 case X86::BI__builtin_ia32_blendps256:
12995 case X86::BI__builtin_ia32_pblendw128:
12996 case X86::BI__builtin_ia32_pblendw256:
12997 case X86::BI__builtin_ia32_pblendd128:
12998 case X86::BI__builtin_ia32_pblendd256: {
12999 APValue SourceF, SourceT, SourceC;
13000 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13001 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13002 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13003 return false;
13004
13005 const APInt &C = SourceC.getInt();
13006 unsigned SourceLen = SourceF.getVectorLength();
13007 SmallVector<APValue, 32> ResultElements;
13008 ResultElements.reserve(SourceLen);
13009 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
13010 const APValue &F = SourceF.getVectorElt(EltNum);
13011 const APValue &T = SourceT.getVectorElt(EltNum);
13012 ResultElements.push_back(C[EltNum % 8] ? T : F);
13013 }
13014
13015 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13016 }
13017
13018 case X86::BI__builtin_ia32_psignb128:
13019 case X86::BI__builtin_ia32_psignb256:
13020 case X86::BI__builtin_ia32_psignw128:
13021 case X86::BI__builtin_ia32_psignw256:
13022 case X86::BI__builtin_ia32_psignd128:
13023 case X86::BI__builtin_ia32_psignd256:
13024 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
13025 if (BElem.isZero())
13026 return APInt::getZero(AElem.getBitWidth());
13027 if (BElem.isNegative())
13028 return -AElem;
13029 return AElem;
13030 });
13031
13032 case X86::BI__builtin_ia32_blendvpd:
13033 case X86::BI__builtin_ia32_blendvpd256:
13034 case X86::BI__builtin_ia32_blendvps:
13035 case X86::BI__builtin_ia32_blendvps256:
13036 case X86::BI__builtin_ia32_pblendvb128:
13037 case X86::BI__builtin_ia32_pblendvb256: {
13038 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
13039 APValue SourceF, SourceT, SourceC;
13040 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13041 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13042 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13043 return false;
13044
13045 unsigned SourceLen = SourceF.getVectorLength();
13046 SmallVector<APValue, 32> ResultElements;
13047 ResultElements.reserve(SourceLen);
13048
13049 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13050 const APValue &F = SourceF.getVectorElt(EltNum);
13051 const APValue &T = SourceT.getVectorElt(EltNum);
13052 const APValue &C = SourceC.getVectorElt(EltNum);
13053 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
13054 ResultElements.push_back(M.isNegative() ? T : F);
13055 }
13056
13057 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13058 }
13059 case X86::BI__builtin_ia32_selectb_128:
13060 case X86::BI__builtin_ia32_selectb_256:
13061 case X86::BI__builtin_ia32_selectb_512:
13062 case X86::BI__builtin_ia32_selectw_128:
13063 case X86::BI__builtin_ia32_selectw_256:
13064 case X86::BI__builtin_ia32_selectw_512:
13065 case X86::BI__builtin_ia32_selectd_128:
13066 case X86::BI__builtin_ia32_selectd_256:
13067 case X86::BI__builtin_ia32_selectd_512:
13068 case X86::BI__builtin_ia32_selectq_128:
13069 case X86::BI__builtin_ia32_selectq_256:
13070 case X86::BI__builtin_ia32_selectq_512:
13071 case X86::BI__builtin_ia32_selectph_128:
13072 case X86::BI__builtin_ia32_selectph_256:
13073 case X86::BI__builtin_ia32_selectph_512:
13074 case X86::BI__builtin_ia32_selectpbf_128:
13075 case X86::BI__builtin_ia32_selectpbf_256:
13076 case X86::BI__builtin_ia32_selectpbf_512:
13077 case X86::BI__builtin_ia32_selectps_128:
13078 case X86::BI__builtin_ia32_selectps_256:
13079 case X86::BI__builtin_ia32_selectps_512:
13080 case X86::BI__builtin_ia32_selectpd_128:
13081 case X86::BI__builtin_ia32_selectpd_256:
13082 case X86::BI__builtin_ia32_selectpd_512: {
13083 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
13084 APValue SourceMask, SourceLHS, SourceRHS;
13085 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
13086 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
13087 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
13088 return false;
13089
13090 APSInt Mask = SourceMask.getInt();
13091 unsigned SourceLen = SourceLHS.getVectorLength();
13092 SmallVector<APValue, 4> ResultElements;
13093 ResultElements.reserve(SourceLen);
13094
13095 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13096 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
13097 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
13098 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
13099 }
13100
13101 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13102 }
13103
13104 case X86::BI__builtin_ia32_cvtsd2ss: {
13105 APValue VecA, VecB;
13106 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13107 !EvaluateAsRValue(Info, E->getArg(1), VecB))
13108 return false;
13109
13110 SmallVector<APValue, 4> Elements;
13111
13112 APValue ResultVal;
13113 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13114 ResultVal))
13115 return false;
13116
13117 Elements.push_back(ResultVal);
13118
13119 unsigned NumEltsA = VecA.getVectorLength();
13120 for (unsigned I = 1; I < NumEltsA; ++I) {
13121 Elements.push_back(VecA.getVectorElt(I));
13122 }
13123
13124 return Success(Elements, E);
13125 }
13126 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: {
13127 APValue VecA, VecB, VecSrc, MaskValue;
13128
13129 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13130 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
13131 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
13132 !EvaluateAsRValue(Info, E->getArg(3), MaskValue))
13133 return false;
13134
13135 unsigned Mask = MaskValue.getInt().getZExtValue();
13136 SmallVector<APValue, 4> Elements;
13137
13138 if (Mask & 1) {
13139 APValue ResultVal;
13140 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13141 ResultVal))
13142 return false;
13143 Elements.push_back(ResultVal);
13144 } else {
13145 Elements.push_back(VecSrc.getVectorElt(0));
13146 }
13147
13148 unsigned NumEltsA = VecA.getVectorLength();
13149 for (unsigned I = 1; I < NumEltsA; ++I) {
13150 Elements.push_back(VecA.getVectorElt(I));
13151 }
13152
13153 return Success(Elements, E);
13154 }
13155 case X86::BI__builtin_ia32_cvtpd2ps:
13156 case X86::BI__builtin_ia32_cvtpd2ps256:
13157 case X86::BI__builtin_ia32_cvtpd2ps_mask:
13158 case X86::BI__builtin_ia32_cvtpd2ps512_mask: {
13159
13160 const auto BuiltinID = E->getBuiltinCallee();
13161 bool IsMasked = (BuiltinID == X86::BI__builtin_ia32_cvtpd2ps_mask ||
13162 BuiltinID == X86::BI__builtin_ia32_cvtpd2ps512_mask);
13163
13164 APValue InputValue;
13165 if (!EvaluateAsRValue(Info, E->getArg(0), InputValue))
13166 return false;
13167
13168 APValue MergeValue;
13169 unsigned Mask = 0xFFFFFFFF;
13170 bool NeedsMerge = false;
13171 if (IsMasked) {
13172 APValue MaskValue;
13173 if (!EvaluateAsRValue(Info, E->getArg(2), MaskValue))
13174 return false;
13175 Mask = MaskValue.getInt().getZExtValue();
13176 auto NumEltsResult = E->getType()->getAs<VectorType>()->getNumElements();
13177 for (unsigned I = 0; I < NumEltsResult; ++I) {
13178 if (!((Mask >> I) & 1)) {
13179 NeedsMerge = true;
13180 break;
13181 }
13182 }
13183 if (NeedsMerge) {
13184 if (!EvaluateAsRValue(Info, E->getArg(1), MergeValue))
13185 return false;
13186 }
13187 }
13188
13189 unsigned NumEltsResult =
13190 E->getType()->getAs<VectorType>()->getNumElements();
13191 unsigned NumEltsInput = InputValue.getVectorLength();
13192 SmallVector<APValue, 8> Elements;
13193 for (unsigned I = 0; I < NumEltsResult; ++I) {
13194 if (IsMasked && !((Mask >> I) & 1)) {
13195 if (!NeedsMerge) {
13196 return false;
13197 }
13198 Elements.push_back(MergeValue.getVectorElt(I));
13199 continue;
13200 }
13201
13202 if (I >= NumEltsInput) {
13203 Elements.push_back(APValue(APFloat::getZero(APFloat::IEEEsingle())));
13204 continue;
13205 }
13206
13207 APValue ResultVal;
13209 Info, E, InputValue.getVectorElt(I).getFloat(), ResultVal))
13210 return false;
13211
13212 Elements.push_back(ResultVal);
13213 }
13214 return Success(Elements, E);
13215 }
13216
13217 case X86::BI__builtin_ia32_shufps:
13218 case X86::BI__builtin_ia32_shufps256:
13219 case X86::BI__builtin_ia32_shufps512: {
13220 APValue R;
13221 if (!evalShuffleGeneric(
13222 Info, E, R,
13223 [](unsigned DstIdx,
13224 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13225 constexpr unsigned LaneBits = 128u;
13226 unsigned NumElemPerLane = LaneBits / 32;
13227 unsigned NumSelectableElems = NumElemPerLane / 2;
13228 unsigned BitsPerElem = 2;
13229 unsigned IndexMask = (1u << BitsPerElem) - 1;
13230 unsigned MaskBits = 8;
13231 unsigned Lane = DstIdx / NumElemPerLane;
13232 unsigned ElemInLane = DstIdx % NumElemPerLane;
13233 unsigned LaneOffset = Lane * NumElemPerLane;
13234 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13235 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13236 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13237 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13238 }))
13239 return false;
13240 return Success(R, E);
13241 }
13242 case X86::BI__builtin_ia32_shufpd:
13243 case X86::BI__builtin_ia32_shufpd256:
13244 case X86::BI__builtin_ia32_shufpd512: {
13245 APValue R;
13246 if (!evalShuffleGeneric(
13247 Info, E, R,
13248 [](unsigned DstIdx,
13249 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13250 constexpr unsigned LaneBits = 128u;
13251 unsigned NumElemPerLane = LaneBits / 64;
13252 unsigned NumSelectableElems = NumElemPerLane / 2;
13253 unsigned BitsPerElem = 1;
13254 unsigned IndexMask = (1u << BitsPerElem) - 1;
13255 unsigned MaskBits = 8;
13256 unsigned Lane = DstIdx / NumElemPerLane;
13257 unsigned ElemInLane = DstIdx % NumElemPerLane;
13258 unsigned LaneOffset = Lane * NumElemPerLane;
13259 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13260 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13261 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13262 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13263 }))
13264 return false;
13265 return Success(R, E);
13266 }
13267 case X86::BI__builtin_ia32_insertps128: {
13268 APValue R;
13269 if (!evalShuffleGeneric(
13270 Info, E, R,
13271 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13272 // Bits [3:0]: zero mask - if bit is set, zero this element
13273 if ((Mask & (1 << DstIdx)) != 0) {
13274 return {0, -1};
13275 }
13276 // Bits [7:6]: select element from source vector Y (0-3)
13277 // Bits [5:4]: select destination position (0-3)
13278 unsigned SrcElem = (Mask >> 6) & 0x3;
13279 unsigned DstElem = (Mask >> 4) & 0x3;
13280 if (DstIdx == DstElem) {
13281 // Insert element from source vector (B) at this position
13282 return {1, static_cast<int>(SrcElem)};
13283 } else {
13284 // Copy from destination vector (A)
13285 return {0, static_cast<int>(DstIdx)};
13286 }
13287 }))
13288 return false;
13289 return Success(R, E);
13290 }
13291 case X86::BI__builtin_ia32_pshufb128:
13292 case X86::BI__builtin_ia32_pshufb256:
13293 case X86::BI__builtin_ia32_pshufb512: {
13294 APValue R;
13295 if (!evalShuffleGeneric(
13296 Info, E, R,
13297 [](unsigned DstIdx,
13298 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13299 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
13300 if (Ctlb & 0x80)
13301 return std::make_pair(0, -1);
13302
13303 unsigned LaneBase = (DstIdx / 16) * 16;
13304 unsigned SrcOffset = Ctlb & 0x0F;
13305 unsigned SrcIdx = LaneBase + SrcOffset;
13306 return std::make_pair(0, static_cast<int>(SrcIdx));
13307 }))
13308 return false;
13309 return Success(R, E);
13310 }
13311
13312 case X86::BI__builtin_ia32_pshuflw:
13313 case X86::BI__builtin_ia32_pshuflw256:
13314 case X86::BI__builtin_ia32_pshuflw512: {
13315 APValue R;
13316 if (!evalShuffleGeneric(
13317 Info, E, R,
13318 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13319 constexpr unsigned LaneBits = 128u;
13320 constexpr unsigned ElemBits = 16u;
13321 constexpr unsigned LaneElts = LaneBits / ElemBits;
13322 constexpr unsigned HalfSize = 4;
13323 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13324 unsigned LaneIdx = DstIdx % LaneElts;
13325 if (LaneIdx < HalfSize) {
13326 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13327 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13328 }
13329 return std::make_pair(0, static_cast<int>(DstIdx));
13330 }))
13331 return false;
13332 return Success(R, E);
13333 }
13334
13335 case X86::BI__builtin_ia32_pshufhw:
13336 case X86::BI__builtin_ia32_pshufhw256:
13337 case X86::BI__builtin_ia32_pshufhw512: {
13338 APValue R;
13339 if (!evalShuffleGeneric(
13340 Info, E, R,
13341 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13342 constexpr unsigned LaneBits = 128u;
13343 constexpr unsigned ElemBits = 16u;
13344 constexpr unsigned LaneElts = LaneBits / ElemBits;
13345 constexpr unsigned HalfSize = 4;
13346 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13347 unsigned LaneIdx = DstIdx % LaneElts;
13348 if (LaneIdx >= HalfSize) {
13349 unsigned Rel = LaneIdx - HalfSize;
13350 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
13351 return std::make_pair(
13352 0, static_cast<int>(LaneBase + HalfSize + Sel));
13353 }
13354 return std::make_pair(0, static_cast<int>(DstIdx));
13355 }))
13356 return false;
13357 return Success(R, E);
13358 }
13359
13360 case X86::BI__builtin_ia32_pshufd:
13361 case X86::BI__builtin_ia32_pshufd256:
13362 case X86::BI__builtin_ia32_pshufd512:
13363 case X86::BI__builtin_ia32_vpermilps:
13364 case X86::BI__builtin_ia32_vpermilps256:
13365 case X86::BI__builtin_ia32_vpermilps512: {
13366 APValue R;
13367 if (!evalShuffleGeneric(
13368 Info, E, R,
13369 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13370 constexpr unsigned LaneBits = 128u;
13371 constexpr unsigned ElemBits = 32u;
13372 constexpr unsigned LaneElts = LaneBits / ElemBits;
13373 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13374 unsigned LaneIdx = DstIdx % LaneElts;
13375 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13376 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13377 }))
13378 return false;
13379 return Success(R, E);
13380 }
13381
13382 case X86::BI__builtin_ia32_vpermilvarpd:
13383 case X86::BI__builtin_ia32_vpermilvarpd256:
13384 case X86::BI__builtin_ia32_vpermilvarpd512: {
13385 APValue R;
13386 if (!evalShuffleGeneric(
13387 Info, E, R,
13388 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13389 unsigned NumElemPerLane = 2;
13390 unsigned Lane = DstIdx / NumElemPerLane;
13391 unsigned Offset = Mask & 0b10 ? 1 : 0;
13392 return std::make_pair(
13393 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13394 }))
13395 return false;
13396 return Success(R, E);
13397 }
13398
13399 case X86::BI__builtin_ia32_vpermilpd:
13400 case X86::BI__builtin_ia32_vpermilpd256:
13401 case X86::BI__builtin_ia32_vpermilpd512: {
13402 APValue R;
13403 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13404 unsigned NumElemPerLane = 2;
13405 unsigned BitsPerElem = 1;
13406 unsigned MaskBits = 8;
13407 unsigned IndexMask = 0x1;
13408 unsigned Lane = DstIdx / NumElemPerLane;
13409 unsigned LaneOffset = Lane * NumElemPerLane;
13410 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13411 unsigned Index = (Control >> BitIndex) & IndexMask;
13412 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
13413 }))
13414 return false;
13415 return Success(R, E);
13416 }
13417
13418 case X86::BI__builtin_ia32_permdf256:
13419 case X86::BI__builtin_ia32_permdi256: {
13420 APValue R;
13421 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13422 // permute4x64 operates on 4 64-bit elements
13423 // For element i (0-3), extract bits [2*i+1:2*i] from Control
13424 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
13425 return std::make_pair(0, static_cast<int>(Index));
13426 }))
13427 return false;
13428 return Success(R, E);
13429 }
13430
13431 case X86::BI__builtin_ia32_vpermilvarps:
13432 case X86::BI__builtin_ia32_vpermilvarps256:
13433 case X86::BI__builtin_ia32_vpermilvarps512: {
13434 APValue R;
13435 if (!evalShuffleGeneric(
13436 Info, E, R,
13437 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13438 unsigned NumElemPerLane = 4;
13439 unsigned Lane = DstIdx / NumElemPerLane;
13440 unsigned Offset = Mask & 0b11;
13441 return std::make_pair(
13442 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13443 }))
13444 return false;
13445 return Success(R, E);
13446 }
13447
13448 case X86::BI__builtin_ia32_vpmultishiftqb128:
13449 case X86::BI__builtin_ia32_vpmultishiftqb256:
13450 case X86::BI__builtin_ia32_vpmultishiftqb512: {
13451 assert(E->getNumArgs() == 2);
13452
13453 APValue A, B;
13454 if (!Evaluate(A, Info, E->getArg(0)) || !Evaluate(B, Info, E->getArg(1)))
13455 return false;
13456
13457 assert(A.getVectorLength() == B.getVectorLength());
13458 unsigned NumBytesInQWord = 8;
13459 unsigned NumBitsInByte = 8;
13460 unsigned NumBytes = A.getVectorLength();
13461 unsigned NumQWords = NumBytes / NumBytesInQWord;
13463 Result.reserve(NumBytes);
13464
13465 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
13466 APInt BQWord(64, 0);
13467 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13468 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13469 uint64_t Byte = B.getVectorElt(Idx).getInt().getZExtValue();
13470 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
13471 }
13472
13473 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13474 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13475 uint64_t Ctrl = A.getVectorElt(Idx).getInt().getZExtValue() & 0x3F;
13476
13477 APInt Byte(8, 0);
13478 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
13479 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
13480 }
13481 Result.push_back(APValue(APSInt(Byte, /*isUnsigned*/ true)));
13482 }
13483 }
13484 return Success(APValue(Result.data(), Result.size()), E);
13485 }
13486
13487 case X86::BI__builtin_ia32_phminposuw128: {
13488 APValue Source;
13489 if (!Evaluate(Source, Info, E->getArg(0)))
13490 return false;
13491 unsigned SourceLen = Source.getVectorLength();
13492 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
13493 QualType ElemQT = VT->getElementType();
13494 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
13495
13496 APInt MinIndex(ElemBitWidth, 0);
13497 APInt MinVal = Source.getVectorElt(0).getInt();
13498 for (unsigned I = 1; I != SourceLen; ++I) {
13499 APInt Val = Source.getVectorElt(I).getInt();
13500 if (MinVal.ugt(Val)) {
13501 MinVal = Val;
13502 MinIndex = I;
13503 }
13504 }
13505
13506 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
13507 ->castAs<VectorType>()
13508 ->getElementType()
13509 ->isUnsignedIntegerOrEnumerationType();
13510
13512 Result.reserve(SourceLen);
13513 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
13514 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
13515 for (unsigned I = 0; I != SourceLen - 2; ++I) {
13516 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
13517 }
13518 return Success(APValue(Result.data(), Result.size()), E);
13519 }
13520
13521 case X86::BI__builtin_ia32_psraq128:
13522 case X86::BI__builtin_ia32_psraq256:
13523 case X86::BI__builtin_ia32_psraq512:
13524 case X86::BI__builtin_ia32_psrad128:
13525 case X86::BI__builtin_ia32_psrad256:
13526 case X86::BI__builtin_ia32_psrad512:
13527 case X86::BI__builtin_ia32_psraw128:
13528 case X86::BI__builtin_ia32_psraw256:
13529 case X86::BI__builtin_ia32_psraw512: {
13530 APValue R;
13531 if (!evalShiftWithCount(
13532 Info, E, R,
13533 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
13534 [](const APInt &Elt, unsigned Width) {
13535 return Elt.ashr(Width - 1);
13536 }))
13537 return false;
13538 return Success(R, E);
13539 }
13540
13541 case X86::BI__builtin_ia32_psllq128:
13542 case X86::BI__builtin_ia32_psllq256:
13543 case X86::BI__builtin_ia32_psllq512:
13544 case X86::BI__builtin_ia32_pslld128:
13545 case X86::BI__builtin_ia32_pslld256:
13546 case X86::BI__builtin_ia32_pslld512:
13547 case X86::BI__builtin_ia32_psllw128:
13548 case X86::BI__builtin_ia32_psllw256:
13549 case X86::BI__builtin_ia32_psllw512: {
13550 APValue R;
13551 if (!evalShiftWithCount(
13552 Info, E, R,
13553 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
13554 [](const APInt &Elt, unsigned Width) {
13555 return APInt::getZero(Width);
13556 }))
13557 return false;
13558 return Success(R, E);
13559 }
13560
13561 case X86::BI__builtin_ia32_psrlq128:
13562 case X86::BI__builtin_ia32_psrlq256:
13563 case X86::BI__builtin_ia32_psrlq512:
13564 case X86::BI__builtin_ia32_psrld128:
13565 case X86::BI__builtin_ia32_psrld256:
13566 case X86::BI__builtin_ia32_psrld512:
13567 case X86::BI__builtin_ia32_psrlw128:
13568 case X86::BI__builtin_ia32_psrlw256:
13569 case X86::BI__builtin_ia32_psrlw512: {
13570 APValue R;
13571 if (!evalShiftWithCount(
13572 Info, E, R,
13573 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
13574 [](const APInt &Elt, unsigned Width) {
13575 return APInt::getZero(Width);
13576 }))
13577 return false;
13578 return Success(R, E);
13579 }
13580
13581 case X86::BI__builtin_ia32_pternlogd128_mask:
13582 case X86::BI__builtin_ia32_pternlogd256_mask:
13583 case X86::BI__builtin_ia32_pternlogd512_mask:
13584 case X86::BI__builtin_ia32_pternlogq128_mask:
13585 case X86::BI__builtin_ia32_pternlogq256_mask:
13586 case X86::BI__builtin_ia32_pternlogq512_mask: {
13587 APValue AValue, BValue, CValue, ImmValue, UValue;
13588 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13589 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13590 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13591 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13592 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13593 return false;
13594
13595 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13596 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13597 APInt Imm = ImmValue.getInt();
13598 APInt U = UValue.getInt();
13599 unsigned ResultLen = AValue.getVectorLength();
13600 SmallVector<APValue, 16> ResultElements;
13601 ResultElements.reserve(ResultLen);
13602
13603 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13604 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13605 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13606 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13607
13608 if (U[EltNum]) {
13609 unsigned BitWidth = ALane.getBitWidth();
13610 APInt ResLane(BitWidth, 0);
13611
13612 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13613 unsigned ABit = ALane[Bit];
13614 unsigned BBit = BLane[Bit];
13615 unsigned CBit = CLane[Bit];
13616
13617 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13618 ResLane.setBitVal(Bit, Imm[Idx]);
13619 }
13620 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13621 } else {
13622 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
13623 }
13624 }
13625 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13626 }
13627 case X86::BI__builtin_ia32_pternlogd128_maskz:
13628 case X86::BI__builtin_ia32_pternlogd256_maskz:
13629 case X86::BI__builtin_ia32_pternlogd512_maskz:
13630 case X86::BI__builtin_ia32_pternlogq128_maskz:
13631 case X86::BI__builtin_ia32_pternlogq256_maskz:
13632 case X86::BI__builtin_ia32_pternlogq512_maskz: {
13633 APValue AValue, BValue, CValue, ImmValue, UValue;
13634 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
13635 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
13636 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
13637 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
13638 !EvaluateAsRValue(Info, E->getArg(4), UValue))
13639 return false;
13640
13641 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13642 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13643 APInt Imm = ImmValue.getInt();
13644 APInt U = UValue.getInt();
13645 unsigned ResultLen = AValue.getVectorLength();
13646 SmallVector<APValue, 16> ResultElements;
13647 ResultElements.reserve(ResultLen);
13648
13649 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
13650 APInt ALane = AValue.getVectorElt(EltNum).getInt();
13651 APInt BLane = BValue.getVectorElt(EltNum).getInt();
13652 APInt CLane = CValue.getVectorElt(EltNum).getInt();
13653
13654 unsigned BitWidth = ALane.getBitWidth();
13655 APInt ResLane(BitWidth, 0);
13656
13657 if (U[EltNum]) {
13658 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
13659 unsigned ABit = ALane[Bit];
13660 unsigned BBit = BLane[Bit];
13661 unsigned CBit = CLane[Bit];
13662
13663 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
13664 ResLane.setBitVal(Bit, Imm[Idx]);
13665 }
13666 }
13667 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
13668 }
13669 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13670 }
13671
13672 case Builtin::BI__builtin_elementwise_clzg:
13673 case Builtin::BI__builtin_elementwise_ctzg: {
13674 APValue SourceLHS;
13675 std::optional<APValue> Fallback;
13676 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
13677 return false;
13678 if (E->getNumArgs() > 1) {
13679 APValue FallbackTmp;
13680 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
13681 return false;
13682 Fallback = FallbackTmp;
13683 }
13684
13685 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13686 unsigned SourceLen = SourceLHS.getVectorLength();
13687 SmallVector<APValue, 4> ResultElements;
13688 ResultElements.reserve(SourceLen);
13689
13690 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13691 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13692 if (!LHS) {
13693 // Without a fallback, a zero element is undefined
13694 if (!Fallback) {
13695 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
13696 << /*IsTrailing=*/(E->getBuiltinCallee() ==
13697 Builtin::BI__builtin_elementwise_ctzg);
13698 return false;
13699 }
13700 ResultElements.push_back(Fallback->getVectorElt(EltNum));
13701 continue;
13702 }
13703 switch (E->getBuiltinCallee()) {
13704 case Builtin::BI__builtin_elementwise_clzg:
13705 ResultElements.push_back(APValue(
13706 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
13707 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13708 break;
13709 case Builtin::BI__builtin_elementwise_ctzg:
13710 ResultElements.push_back(APValue(
13711 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
13712 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13713 break;
13714 }
13715 }
13716
13717 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13718 }
13719
13720 case Builtin::BI__builtin_elementwise_fma: {
13721 APValue SourceX, SourceY, SourceZ;
13722 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
13723 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
13724 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
13725 return false;
13726
13727 unsigned SourceLen = SourceX.getVectorLength();
13728 SmallVector<APValue> ResultElements;
13729 ResultElements.reserve(SourceLen);
13730 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13731 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13732 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
13733 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
13734 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
13735 APFloat Result(X);
13736 (void)Result.fusedMultiplyAdd(Y, Z, RM);
13737 ResultElements.push_back(APValue(Result));
13738 }
13739 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13740 }
13741
13742 case clang::X86::BI__builtin_ia32_phaddw128:
13743 case clang::X86::BI__builtin_ia32_phaddw256:
13744 case clang::X86::BI__builtin_ia32_phaddd128:
13745 case clang::X86::BI__builtin_ia32_phaddd256:
13746 case clang::X86::BI__builtin_ia32_phaddsw128:
13747 case clang::X86::BI__builtin_ia32_phaddsw256:
13748
13749 case clang::X86::BI__builtin_ia32_phsubw128:
13750 case clang::X86::BI__builtin_ia32_phsubw256:
13751 case clang::X86::BI__builtin_ia32_phsubd128:
13752 case clang::X86::BI__builtin_ia32_phsubd256:
13753 case clang::X86::BI__builtin_ia32_phsubsw128:
13754 case clang::X86::BI__builtin_ia32_phsubsw256: {
13755 APValue SourceLHS, SourceRHS;
13756 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13757 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13758 return false;
13759 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13760 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13761
13762 unsigned NumElts = SourceLHS.getVectorLength();
13763 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
13764 unsigned EltsPerLane = 128 / EltBits;
13765 SmallVector<APValue, 4> ResultElements;
13766 ResultElements.reserve(NumElts);
13767
13768 for (unsigned LaneStart = 0; LaneStart != NumElts;
13769 LaneStart += EltsPerLane) {
13770 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13771 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
13772 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
13773 switch (E->getBuiltinCallee()) {
13774 case clang::X86::BI__builtin_ia32_phaddw128:
13775 case clang::X86::BI__builtin_ia32_phaddw256:
13776 case clang::X86::BI__builtin_ia32_phaddd128:
13777 case clang::X86::BI__builtin_ia32_phaddd256: {
13778 APSInt Res(LHSA + LHSB, DestUnsigned);
13779 ResultElements.push_back(APValue(Res));
13780 break;
13781 }
13782 case clang::X86::BI__builtin_ia32_phaddsw128:
13783 case clang::X86::BI__builtin_ia32_phaddsw256: {
13784 APSInt Res(LHSA.sadd_sat(LHSB));
13785 ResultElements.push_back(APValue(Res));
13786 break;
13787 }
13788 case clang::X86::BI__builtin_ia32_phsubw128:
13789 case clang::X86::BI__builtin_ia32_phsubw256:
13790 case clang::X86::BI__builtin_ia32_phsubd128:
13791 case clang::X86::BI__builtin_ia32_phsubd256: {
13792 APSInt Res(LHSA - LHSB, DestUnsigned);
13793 ResultElements.push_back(APValue(Res));
13794 break;
13795 }
13796 case clang::X86::BI__builtin_ia32_phsubsw128:
13797 case clang::X86::BI__builtin_ia32_phsubsw256: {
13798 APSInt Res(LHSA.ssub_sat(LHSB));
13799 ResultElements.push_back(APValue(Res));
13800 break;
13801 }
13802 }
13803 }
13804 for (unsigned I = 0; I != EltsPerLane; I += 2) {
13805 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
13806 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
13807 switch (E->getBuiltinCallee()) {
13808 case clang::X86::BI__builtin_ia32_phaddw128:
13809 case clang::X86::BI__builtin_ia32_phaddw256:
13810 case clang::X86::BI__builtin_ia32_phaddd128:
13811 case clang::X86::BI__builtin_ia32_phaddd256: {
13812 APSInt Res(RHSA + RHSB, DestUnsigned);
13813 ResultElements.push_back(APValue(Res));
13814 break;
13815 }
13816 case clang::X86::BI__builtin_ia32_phaddsw128:
13817 case clang::X86::BI__builtin_ia32_phaddsw256: {
13818 APSInt Res(RHSA.sadd_sat(RHSB));
13819 ResultElements.push_back(APValue(Res));
13820 break;
13821 }
13822 case clang::X86::BI__builtin_ia32_phsubw128:
13823 case clang::X86::BI__builtin_ia32_phsubw256:
13824 case clang::X86::BI__builtin_ia32_phsubd128:
13825 case clang::X86::BI__builtin_ia32_phsubd256: {
13826 APSInt Res(RHSA - RHSB, DestUnsigned);
13827 ResultElements.push_back(APValue(Res));
13828 break;
13829 }
13830 case clang::X86::BI__builtin_ia32_phsubsw128:
13831 case clang::X86::BI__builtin_ia32_phsubsw256: {
13832 APSInt Res(RHSA.ssub_sat(RHSB));
13833 ResultElements.push_back(APValue(Res));
13834 break;
13835 }
13836 }
13837 }
13838 }
13839 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13840 }
13841 case clang::X86::BI__builtin_ia32_haddpd:
13842 case clang::X86::BI__builtin_ia32_haddps:
13843 case clang::X86::BI__builtin_ia32_haddps256:
13844 case clang::X86::BI__builtin_ia32_haddpd256:
13845 case clang::X86::BI__builtin_ia32_hsubpd:
13846 case clang::X86::BI__builtin_ia32_hsubps:
13847 case clang::X86::BI__builtin_ia32_hsubps256:
13848 case clang::X86::BI__builtin_ia32_hsubpd256: {
13849 APValue SourceLHS, SourceRHS;
13850 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13851 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13852 return false;
13853 unsigned NumElts = SourceLHS.getVectorLength();
13854 SmallVector<APValue, 4> ResultElements;
13855 ResultElements.reserve(NumElts);
13856 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13857 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13858 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
13859 unsigned NumLanes = NumElts * EltBits / 128;
13860 unsigned NumElemsPerLane = NumElts / NumLanes;
13861 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
13862
13863 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
13864 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13865 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
13866 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
13867 switch (E->getBuiltinCallee()) {
13868 case clang::X86::BI__builtin_ia32_haddpd:
13869 case clang::X86::BI__builtin_ia32_haddps:
13870 case clang::X86::BI__builtin_ia32_haddps256:
13871 case clang::X86::BI__builtin_ia32_haddpd256:
13872 LHSA.add(LHSB, RM);
13873 break;
13874 case clang::X86::BI__builtin_ia32_hsubpd:
13875 case clang::X86::BI__builtin_ia32_hsubps:
13876 case clang::X86::BI__builtin_ia32_hsubps256:
13877 case clang::X86::BI__builtin_ia32_hsubpd256:
13878 LHSA.subtract(LHSB, RM);
13879 break;
13880 }
13881 ResultElements.push_back(APValue(LHSA));
13882 }
13883 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
13884 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
13885 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
13886 switch (E->getBuiltinCallee()) {
13887 case clang::X86::BI__builtin_ia32_haddpd:
13888 case clang::X86::BI__builtin_ia32_haddps:
13889 case clang::X86::BI__builtin_ia32_haddps256:
13890 case clang::X86::BI__builtin_ia32_haddpd256:
13891 RHSA.add(RHSB, RM);
13892 break;
13893 case clang::X86::BI__builtin_ia32_hsubpd:
13894 case clang::X86::BI__builtin_ia32_hsubps:
13895 case clang::X86::BI__builtin_ia32_hsubps256:
13896 case clang::X86::BI__builtin_ia32_hsubpd256:
13897 RHSA.subtract(RHSB, RM);
13898 break;
13899 }
13900 ResultElements.push_back(APValue(RHSA));
13901 }
13902 }
13903 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13904 }
13905 case clang::X86::BI__builtin_ia32_addsubpd:
13906 case clang::X86::BI__builtin_ia32_addsubps:
13907 case clang::X86::BI__builtin_ia32_addsubpd256:
13908 case clang::X86::BI__builtin_ia32_addsubps256: {
13909 // Addsub: alternates between subtraction and addition
13910 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
13911 APValue SourceLHS, SourceRHS;
13912 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13913 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13914 return false;
13915 unsigned NumElems = SourceLHS.getVectorLength();
13916 SmallVector<APValue, 8> ResultElements;
13917 ResultElements.reserve(NumElems);
13918 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
13919
13920 for (unsigned I = 0; I != NumElems; ++I) {
13921 APFloat LHS = SourceLHS.getVectorElt(I).getFloat();
13922 APFloat RHS = SourceRHS.getVectorElt(I).getFloat();
13923 if (I % 2 == 0) {
13924 // Even indices: subtract
13925 LHS.subtract(RHS, RM);
13926 } else {
13927 // Odd indices: add
13928 LHS.add(RHS, RM);
13929 }
13930 ResultElements.push_back(APValue(LHS));
13931 }
13932 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13933 }
13934 case clang::X86::BI__builtin_ia32_pclmulqdq128:
13935 case clang::X86::BI__builtin_ia32_pclmulqdq256:
13936 case clang::X86::BI__builtin_ia32_pclmulqdq512: {
13937 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
13938 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
13939 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
13940 APValue SourceLHS, SourceRHS;
13941 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13942 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13943 return false;
13944
13945 APSInt Imm8;
13946 if (!EvaluateInteger(E->getArg(2), Imm8, Info))
13947 return false;
13948
13949 // Extract bits 0 and 4 from imm8
13950 bool SelectUpperA = (Imm8 & 0x01) != 0;
13951 bool SelectUpperB = (Imm8 & 0x10) != 0;
13952
13953 unsigned NumElems = SourceLHS.getVectorLength();
13954 SmallVector<APValue, 8> ResultElements;
13955 ResultElements.reserve(NumElems);
13956 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13957 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13958
13959 // Process each 128-bit lane
13960 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
13961 // Get the two 64-bit halves of the first operand
13962 APSInt A0 = SourceLHS.getVectorElt(Lane + 0).getInt();
13963 APSInt A1 = SourceLHS.getVectorElt(Lane + 1).getInt();
13964 // Get the two 64-bit halves of the second operand
13965 APSInt B0 = SourceRHS.getVectorElt(Lane + 0).getInt();
13966 APSInt B1 = SourceRHS.getVectorElt(Lane + 1).getInt();
13967
13968 // Select the appropriate 64-bit values based on imm8
13969 APInt A = SelectUpperA ? A1 : A0;
13970 APInt B = SelectUpperB ? B1 : B0;
13971
13972 // Extend both operands to 128 bits for carry-less multiplication
13973 APInt A128 = A.zext(128);
13974 APInt B128 = B.zext(128);
13975
13976 // Use APIntOps::clmul for carry-less multiplication
13977 APInt Result = llvm::APIntOps::clmul(A128, B128);
13978
13979 // Split the 128-bit result into two 64-bit halves
13980 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
13981 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
13982
13983 ResultElements.push_back(APValue(ResultLow));
13984 ResultElements.push_back(APValue(ResultHigh));
13985 }
13986
13987 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13988 }
13989 case Builtin::BI__builtin_elementwise_fshl:
13990 case Builtin::BI__builtin_elementwise_fshr: {
13991 APValue SourceHi, SourceLo, SourceShift;
13992 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
13993 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
13994 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
13995 return false;
13996
13997 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13998 if (!DestEltTy->isIntegerType())
13999 return false;
14000
14001 unsigned SourceLen = SourceHi.getVectorLength();
14002 SmallVector<APValue> ResultElements;
14003 ResultElements.reserve(SourceLen);
14004 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14005 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
14006 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
14007 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
14008 switch (E->getBuiltinCallee()) {
14009 case Builtin::BI__builtin_elementwise_fshl:
14010 ResultElements.push_back(APValue(
14011 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
14012 break;
14013 case Builtin::BI__builtin_elementwise_fshr:
14014 ResultElements.push_back(APValue(
14015 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
14016 break;
14017 }
14018 }
14019
14020 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14021 }
14022
14023 case X86::BI__builtin_ia32_shuf_f32x4_256:
14024 case X86::BI__builtin_ia32_shuf_i32x4_256:
14025 case X86::BI__builtin_ia32_shuf_f64x2_256:
14026 case X86::BI__builtin_ia32_shuf_i64x2_256:
14027 case X86::BI__builtin_ia32_shuf_f32x4:
14028 case X86::BI__builtin_ia32_shuf_i32x4:
14029 case X86::BI__builtin_ia32_shuf_f64x2:
14030 case X86::BI__builtin_ia32_shuf_i64x2: {
14031 APValue SourceA, SourceB;
14032 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
14033 !EvaluateAsRValue(Info, E->getArg(1), SourceB))
14034 return false;
14035
14036 APSInt Imm;
14037 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14038 return false;
14039
14040 // Destination and sources A, B all have the same type.
14041 unsigned NumElems = SourceA.getVectorLength();
14042 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14043 QualType ElemQT = VT->getElementType();
14044 unsigned ElemBits = Info.Ctx.getTypeSize(ElemQT);
14045 unsigned LaneBits = 128u;
14046 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
14047 unsigned NumElemsPerLane = LaneBits / ElemBits;
14048
14049 unsigned DstLen = SourceA.getVectorLength();
14050 SmallVector<APValue, 16> ResultElements;
14051 ResultElements.reserve(DstLen);
14052
14053 APValue R;
14054 if (!evalShuffleGeneric(
14055 Info, E, R,
14056 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask)
14057 -> std::pair<unsigned, int> {
14058 // DstIdx determines source. ShuffleMask selects lane in source.
14059 unsigned BitsPerElem = NumLanes / 2;
14060 unsigned IndexMask = (1u << BitsPerElem) - 1;
14061 unsigned Lane = DstIdx / NumElemsPerLane;
14062 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
14063 unsigned BitIdx = BitsPerElem * Lane;
14064 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
14065 unsigned ElemInLane = DstIdx % NumElemsPerLane;
14066 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
14067 return {SrcIdx, IdxToPick};
14068 }))
14069 return false;
14070 return Success(R, E);
14071 }
14072
14073 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14074 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14075 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
14076 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
14077 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
14078 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi: {
14079
14080 APValue X, A;
14081 APSInt Imm;
14082 if (!EvaluateAsRValue(Info, E->getArg(0), X) ||
14083 !EvaluateAsRValue(Info, E->getArg(1), A) ||
14084 !EvaluateInteger(E->getArg(2), Imm, Info))
14085 return false;
14086
14087 assert(X.isVector() && A.isVector());
14088 assert(X.getVectorLength() == A.getVectorLength());
14089
14090 bool IsInverse = false;
14091 switch (E->getBuiltinCallee()) {
14092 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14093 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14094 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi: {
14095 IsInverse = true;
14096 }
14097 }
14098
14099 unsigned NumBitsInByte = 8;
14100 unsigned NumBytesInQWord = 8;
14101 unsigned NumBitsInQWord = 64;
14102 unsigned NumBytes = A.getVectorLength();
14103 unsigned NumQWords = NumBytes / NumBytesInQWord;
14105 Result.reserve(NumBytes);
14106
14107 // computing A*X + Imm
14108 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
14109 // Extract the QWords from X, A
14110 APInt XQWord(NumBitsInQWord, 0);
14111 APInt AQWord(NumBitsInQWord, 0);
14112 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14113 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
14114 APInt XByte = X.getVectorElt(Idx).getInt();
14115 APInt AByte = A.getVectorElt(Idx).getInt();
14116 XQWord.insertBits(XByte, ByteIdx * NumBitsInByte);
14117 AQWord.insertBits(AByte, ByteIdx * NumBitsInByte);
14118 }
14119
14120 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14121 uint8_t XByte =
14122 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
14123 Result.push_back(APValue(APSInt(
14124 APInt(8, GFNIAffine(XByte, AQWord, Imm, IsInverse)), false)));
14125 }
14126 }
14127
14128 return Success(APValue(Result.data(), Result.size()), E);
14129 }
14130
14131 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
14132 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
14133 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi: {
14134 APValue A, B;
14135 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
14136 !EvaluateAsRValue(Info, E->getArg(1), B))
14137 return false;
14138
14139 assert(A.isVector() && B.isVector());
14140 assert(A.getVectorLength() == B.getVectorLength());
14141
14142 unsigned NumBytes = A.getVectorLength();
14144 Result.reserve(NumBytes);
14145
14146 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
14147 uint8_t AByte = A.getVectorElt(ByteIdx).getInt().getZExtValue();
14148 uint8_t BByte = B.getVectorElt(ByteIdx).getInt().getZExtValue();
14149 Result.push_back(APValue(
14150 APSInt(APInt(8, GFNIMul(AByte, BByte)), /*IsUnsigned=*/false)));
14151 }
14152
14153 return Success(APValue(Result.data(), Result.size()), E);
14154 }
14155
14156 case X86::BI__builtin_ia32_insertf32x4_256:
14157 case X86::BI__builtin_ia32_inserti32x4_256:
14158 case X86::BI__builtin_ia32_insertf64x2_256:
14159 case X86::BI__builtin_ia32_inserti64x2_256:
14160 case X86::BI__builtin_ia32_insertf32x4:
14161 case X86::BI__builtin_ia32_inserti32x4:
14162 case X86::BI__builtin_ia32_insertf64x2_512:
14163 case X86::BI__builtin_ia32_inserti64x2_512:
14164 case X86::BI__builtin_ia32_insertf32x8:
14165 case X86::BI__builtin_ia32_inserti32x8:
14166 case X86::BI__builtin_ia32_insertf64x4:
14167 case X86::BI__builtin_ia32_inserti64x4:
14168 case X86::BI__builtin_ia32_vinsertf128_ps256:
14169 case X86::BI__builtin_ia32_vinsertf128_pd256:
14170 case X86::BI__builtin_ia32_vinsertf128_si256:
14171 case X86::BI__builtin_ia32_insert128i256: {
14172 APValue SourceDst, SourceSub;
14173 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
14174 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
14175 return false;
14176
14177 APSInt Imm;
14178 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14179 return false;
14180
14181 assert(SourceDst.isVector() && SourceSub.isVector());
14182 unsigned DstLen = SourceDst.getVectorLength();
14183 unsigned SubLen = SourceSub.getVectorLength();
14184 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
14185 unsigned NumLanes = DstLen / SubLen;
14186 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
14187
14188 SmallVector<APValue, 16> ResultElements;
14189 ResultElements.reserve(DstLen);
14190
14191 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
14192 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
14193 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
14194 else
14195 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
14196 }
14197
14198 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14199 }
14200
14201 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
14202 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
14203 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
14204 case clang::X86::BI__builtin_ia32_vec_set_v4si:
14205 case clang::X86::BI__builtin_ia32_vec_set_v2di:
14206 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
14207 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
14208 case clang::X86::BI__builtin_ia32_vec_set_v8si:
14209 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
14210 APValue VecVal;
14211 APSInt Scalar, IndexAPS;
14212 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
14213 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
14214 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
14215 return false;
14216
14217 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
14218 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
14219 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
14220 Scalar.setIsUnsigned(ElemUnsigned);
14221 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
14222 APValue ElemAV(ElemAPS);
14223
14224 unsigned NumElems = VecVal.getVectorLength();
14225 unsigned Index =
14226 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
14227
14229 Elems.reserve(NumElems);
14230 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
14231 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
14232
14233 return Success(APValue(Elems.data(), NumElems), E);
14234 }
14235
14236 case X86::BI__builtin_ia32_pslldqi128_byteshift:
14237 case X86::BI__builtin_ia32_pslldqi256_byteshift:
14238 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
14239 APValue R;
14240 if (!evalShuffleGeneric(
14241 Info, E, R,
14242 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14243 unsigned LaneBase = (DstIdx / 16) * 16;
14244 unsigned LaneIdx = DstIdx % 16;
14245 if (LaneIdx < Shift)
14246 return std::make_pair(0, -1);
14247
14248 return std::make_pair(
14249 0, static_cast<int>(LaneBase + LaneIdx - Shift));
14250 }))
14251 return false;
14252 return Success(R, E);
14253 }
14254
14255 case X86::BI__builtin_ia32_psrldqi128_byteshift:
14256 case X86::BI__builtin_ia32_psrldqi256_byteshift:
14257 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
14258 APValue R;
14259 if (!evalShuffleGeneric(
14260 Info, E, R,
14261 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14262 unsigned LaneBase = (DstIdx / 16) * 16;
14263 unsigned LaneIdx = DstIdx % 16;
14264 if (LaneIdx + Shift < 16)
14265 return std::make_pair(
14266 0, static_cast<int>(LaneBase + LaneIdx + Shift));
14267
14268 return std::make_pair(0, -1);
14269 }))
14270 return false;
14271 return Success(R, E);
14272 }
14273
14274 case X86::BI__builtin_ia32_palignr128:
14275 case X86::BI__builtin_ia32_palignr256:
14276 case X86::BI__builtin_ia32_palignr512: {
14277 APValue R;
14278 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
14279 // Default to -1 → zero-fill this destination element
14280 unsigned VecIdx = 1;
14281 int ElemIdx = -1;
14282
14283 int Lane = DstIdx / 16;
14284 int Offset = DstIdx % 16;
14285
14286 // Elements come from VecB first, then VecA after the shift boundary
14287 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
14288 if (ShiftedIdx < 16) { // from VecB
14289 ElemIdx = ShiftedIdx + (Lane * 16);
14290 } else if (ShiftedIdx < 32) { // from VecA
14291 VecIdx = 0;
14292 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
14293 }
14294
14295 return std::pair<unsigned, int>{VecIdx, ElemIdx};
14296 }))
14297 return false;
14298 return Success(R, E);
14299 }
14300 case X86::BI__builtin_ia32_alignd128:
14301 case X86::BI__builtin_ia32_alignd256:
14302 case X86::BI__builtin_ia32_alignd512:
14303 case X86::BI__builtin_ia32_alignq128:
14304 case X86::BI__builtin_ia32_alignq256:
14305 case X86::BI__builtin_ia32_alignq512: {
14306 APValue R;
14307 unsigned NumElems = E->getType()->castAs<VectorType>()->getNumElements();
14308 if (!evalShuffleGeneric(Info, E, R,
14309 [NumElems](unsigned DstIdx, unsigned Shift) {
14310 unsigned Imm = Shift & 0xFF;
14311 unsigned EffectiveShift = Imm & (NumElems - 1);
14312 unsigned SourcePos = DstIdx + EffectiveShift;
14313 unsigned VecIdx = SourcePos < NumElems ? 1 : 0;
14314 unsigned ElemIdx = SourcePos & (NumElems - 1);
14315
14316 return std::pair<unsigned, int>{
14317 VecIdx, static_cast<int>(ElemIdx)};
14318 }))
14319 return false;
14320 return Success(R, E);
14321 }
14322 case X86::BI__builtin_ia32_permvarsi256:
14323 case X86::BI__builtin_ia32_permvarsf256:
14324 case X86::BI__builtin_ia32_permvardf512:
14325 case X86::BI__builtin_ia32_permvardi512:
14326 case X86::BI__builtin_ia32_permvarhi128: {
14327 APValue R;
14328 if (!evalShuffleGeneric(Info, E, R,
14329 [](unsigned DstIdx, unsigned ShuffleMask) {
14330 int Offset = ShuffleMask & 0x7;
14331 return std::pair<unsigned, int>{0, Offset};
14332 }))
14333 return false;
14334 return Success(R, E);
14335 }
14336 case X86::BI__builtin_ia32_permvarqi128:
14337 case X86::BI__builtin_ia32_permvarhi256:
14338 case X86::BI__builtin_ia32_permvarsi512:
14339 case X86::BI__builtin_ia32_permvarsf512: {
14340 APValue R;
14341 if (!evalShuffleGeneric(Info, E, R,
14342 [](unsigned DstIdx, unsigned ShuffleMask) {
14343 int Offset = ShuffleMask & 0xF;
14344 return std::pair<unsigned, int>{0, Offset};
14345 }))
14346 return false;
14347 return Success(R, E);
14348 }
14349 case X86::BI__builtin_ia32_permvardi256:
14350 case X86::BI__builtin_ia32_permvardf256: {
14351 APValue R;
14352 if (!evalShuffleGeneric(Info, E, R,
14353 [](unsigned DstIdx, unsigned ShuffleMask) {
14354 int Offset = ShuffleMask & 0x3;
14355 return std::pair<unsigned, int>{0, Offset};
14356 }))
14357 return false;
14358 return Success(R, E);
14359 }
14360 case X86::BI__builtin_ia32_permvarqi256:
14361 case X86::BI__builtin_ia32_permvarhi512: {
14362 APValue R;
14363 if (!evalShuffleGeneric(Info, E, R,
14364 [](unsigned DstIdx, unsigned ShuffleMask) {
14365 int Offset = ShuffleMask & 0x1F;
14366 return std::pair<unsigned, int>{0, Offset};
14367 }))
14368 return false;
14369 return Success(R, E);
14370 }
14371 case X86::BI__builtin_ia32_permvarqi512: {
14372 APValue R;
14373 if (!evalShuffleGeneric(Info, E, R,
14374 [](unsigned DstIdx, unsigned ShuffleMask) {
14375 int Offset = ShuffleMask & 0x3F;
14376 return std::pair<unsigned, int>{0, Offset};
14377 }))
14378 return false;
14379 return Success(R, E);
14380 }
14381 case X86::BI__builtin_ia32_vpermi2varq128:
14382 case X86::BI__builtin_ia32_vpermi2varpd128: {
14383 APValue R;
14384 if (!evalShuffleGeneric(Info, E, R,
14385 [](unsigned DstIdx, unsigned ShuffleMask) {
14386 int Offset = ShuffleMask & 0x1;
14387 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
14388 return std::pair<unsigned, int>{SrcIdx, Offset};
14389 }))
14390 return false;
14391 return Success(R, E);
14392 }
14393 case X86::BI__builtin_ia32_vpermi2vard128:
14394 case X86::BI__builtin_ia32_vpermi2varps128:
14395 case X86::BI__builtin_ia32_vpermi2varq256:
14396 case X86::BI__builtin_ia32_vpermi2varpd256: {
14397 APValue R;
14398 if (!evalShuffleGeneric(Info, E, R,
14399 [](unsigned DstIdx, unsigned ShuffleMask) {
14400 int Offset = ShuffleMask & 0x3;
14401 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
14402 return std::pair<unsigned, int>{SrcIdx, Offset};
14403 }))
14404 return false;
14405 return Success(R, E);
14406 }
14407 case X86::BI__builtin_ia32_vpermi2varhi128:
14408 case X86::BI__builtin_ia32_vpermi2vard256:
14409 case X86::BI__builtin_ia32_vpermi2varps256:
14410 case X86::BI__builtin_ia32_vpermi2varq512:
14411 case X86::BI__builtin_ia32_vpermi2varpd512: {
14412 APValue R;
14413 if (!evalShuffleGeneric(Info, E, R,
14414 [](unsigned DstIdx, unsigned ShuffleMask) {
14415 int Offset = ShuffleMask & 0x7;
14416 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
14417 return std::pair<unsigned, int>{SrcIdx, Offset};
14418 }))
14419 return false;
14420 return Success(R, E);
14421 }
14422 case X86::BI__builtin_ia32_vpermi2varqi128:
14423 case X86::BI__builtin_ia32_vpermi2varhi256:
14424 case X86::BI__builtin_ia32_vpermi2vard512:
14425 case X86::BI__builtin_ia32_vpermi2varps512: {
14426 APValue R;
14427 if (!evalShuffleGeneric(Info, E, R,
14428 [](unsigned DstIdx, unsigned ShuffleMask) {
14429 int Offset = ShuffleMask & 0xF;
14430 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
14431 return std::pair<unsigned, int>{SrcIdx, Offset};
14432 }))
14433 return false;
14434 return Success(R, E);
14435 }
14436 case X86::BI__builtin_ia32_vpermi2varqi256:
14437 case X86::BI__builtin_ia32_vpermi2varhi512: {
14438 APValue R;
14439 if (!evalShuffleGeneric(Info, E, R,
14440 [](unsigned DstIdx, unsigned ShuffleMask) {
14441 int Offset = ShuffleMask & 0x1F;
14442 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
14443 return std::pair<unsigned, int>{SrcIdx, Offset};
14444 }))
14445 return false;
14446 return Success(R, E);
14447 }
14448 case X86::BI__builtin_ia32_vpermi2varqi512: {
14449 APValue R;
14450 if (!evalShuffleGeneric(Info, E, R,
14451 [](unsigned DstIdx, unsigned ShuffleMask) {
14452 int Offset = ShuffleMask & 0x3F;
14453 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
14454 return std::pair<unsigned, int>{SrcIdx, Offset};
14455 }))
14456 return false;
14457 return Success(R, E);
14458 }
14459
14460 case clang::X86::BI__builtin_ia32_minps:
14461 case clang::X86::BI__builtin_ia32_minpd:
14462 case clang::X86::BI__builtin_ia32_minps256:
14463 case clang::X86::BI__builtin_ia32_minpd256:
14464 case clang::X86::BI__builtin_ia32_minps512:
14465 case clang::X86::BI__builtin_ia32_minpd512:
14466 case clang::X86::BI__builtin_ia32_minph128:
14467 case clang::X86::BI__builtin_ia32_minph256:
14468 case clang::X86::BI__builtin_ia32_minph512:
14469 return EvaluateFpBinOpExpr(
14470 [](const APFloat &A, const APFloat &B,
14471 std::optional<APSInt>) -> std::optional<APFloat> {
14472 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
14473 B.isInfinity() || B.isDenormal())
14474 return std::nullopt;
14475 if (A.isZero() && B.isZero())
14476 return B;
14477 return llvm::minimum(A, B);
14478 });
14479
14480 case clang::X86::BI__builtin_ia32_minss:
14481 case clang::X86::BI__builtin_ia32_minsd:
14482 return EvaluateFpBinOpExpr(
14483 [](const APFloat &A, const APFloat &B,
14484 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14485 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/true);
14486 },
14487 /*IsScalar=*/true);
14488
14489 case clang::X86::BI__builtin_ia32_minsd_round_mask:
14490 case clang::X86::BI__builtin_ia32_minss_round_mask:
14491 case clang::X86::BI__builtin_ia32_minsh_round_mask:
14492 case clang::X86::BI__builtin_ia32_maxsd_round_mask:
14493 case clang::X86::BI__builtin_ia32_maxss_round_mask:
14494 case clang::X86::BI__builtin_ia32_maxsh_round_mask: {
14495 bool IsMin =
14496 E->getBuiltinCallee() ==
14497 clang::X86::BI__builtin_ia32_minsd_round_mask ||
14498 E->getBuiltinCallee() ==
14499 clang::X86::BI__builtin_ia32_minss_round_mask ||
14500 E->getBuiltinCallee() == clang::X86::BI__builtin_ia32_minsh_round_mask;
14501 return EvaluateScalarFpRoundMaskBinOp(
14502 [IsMin](const APFloat &A, const APFloat &B,
14503 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14504 return EvalScalarMinMaxFp(A, B, RoundingMode, IsMin);
14505 });
14506 }
14507
14508 case clang::X86::BI__builtin_ia32_maxps:
14509 case clang::X86::BI__builtin_ia32_maxpd:
14510 case clang::X86::BI__builtin_ia32_maxps256:
14511 case clang::X86::BI__builtin_ia32_maxpd256:
14512 case clang::X86::BI__builtin_ia32_maxps512:
14513 case clang::X86::BI__builtin_ia32_maxpd512:
14514 case clang::X86::BI__builtin_ia32_maxph128:
14515 case clang::X86::BI__builtin_ia32_maxph256:
14516 case clang::X86::BI__builtin_ia32_maxph512:
14517 return EvaluateFpBinOpExpr(
14518 [](const APFloat &A, const APFloat &B,
14519 std::optional<APSInt>) -> std::optional<APFloat> {
14520 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
14521 B.isInfinity() || B.isDenormal())
14522 return std::nullopt;
14523 if (A.isZero() && B.isZero())
14524 return B;
14525 return llvm::maximum(A, B);
14526 });
14527
14528 case clang::X86::BI__builtin_ia32_maxss:
14529 case clang::X86::BI__builtin_ia32_maxsd:
14530 return EvaluateFpBinOpExpr(
14531 [](const APFloat &A, const APFloat &B,
14532 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14533 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/false);
14534 },
14535 /*IsScalar=*/true);
14536
14537 case clang::X86::BI__builtin_ia32_vcvtps2ph:
14538 case clang::X86::BI__builtin_ia32_vcvtps2ph256: {
14539 APValue SrcVec;
14540 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec))
14541 return false;
14542
14543 APSInt Imm;
14544 if (!EvaluateInteger(E->getArg(1), Imm, Info))
14545 return false;
14546
14547 const auto *SrcVTy = E->getArg(0)->getType()->castAs<VectorType>();
14548 unsigned SrcNumElems = SrcVTy->getNumElements();
14549 const auto *DstVTy = E->getType()->castAs<VectorType>();
14550 unsigned DstNumElems = DstVTy->getNumElements();
14551 QualType DstElemTy = DstVTy->getElementType();
14552
14553 const llvm::fltSemantics &HalfSem =
14554 Info.Ctx.getFloatTypeSemantics(Info.Ctx.HalfTy);
14555
14556 int ImmVal = Imm.getZExtValue();
14557 bool UseMXCSR = (ImmVal & 4) != 0;
14558 bool IsFPConstrained =
14559 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained();
14560
14561 llvm::RoundingMode RM;
14562 if (!UseMXCSR) {
14563 switch (ImmVal & 3) {
14564 case 0:
14565 RM = llvm::RoundingMode::NearestTiesToEven;
14566 break;
14567 case 1:
14568 RM = llvm::RoundingMode::TowardNegative;
14569 break;
14570 case 2:
14571 RM = llvm::RoundingMode::TowardPositive;
14572 break;
14573 case 3:
14574 RM = llvm::RoundingMode::TowardZero;
14575 break;
14576 default:
14577 llvm_unreachable("Invalid immediate rounding mode");
14578 }
14579 } else {
14580 RM = llvm::RoundingMode::NearestTiesToEven;
14581 }
14582
14583 SmallVector<APValue, 8> ResultElements;
14584 ResultElements.reserve(DstNumElems);
14585
14586 for (unsigned I = 0; I < SrcNumElems; ++I) {
14587 APFloat SrcVal = SrcVec.getVectorElt(I).getFloat();
14588
14589 bool LostInfo;
14590 APFloat::opStatus St = SrcVal.convert(HalfSem, RM, &LostInfo);
14591
14592 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
14593 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
14594 return false;
14595 }
14596
14597 APSInt DstInt(SrcVal.bitcastToAPInt(),
14599 ResultElements.push_back(APValue(DstInt));
14600 }
14601
14602 if (DstNumElems > SrcNumElems) {
14603 APSInt Zero = Info.Ctx.MakeIntValue(0, DstElemTy);
14604 for (unsigned I = SrcNumElems; I < DstNumElems; ++I) {
14605 ResultElements.push_back(APValue(Zero));
14606 }
14607 }
14608
14609 return Success(ResultElements, E);
14610 }
14611 case X86::BI__builtin_ia32_vperm2f128_pd256:
14612 case X86::BI__builtin_ia32_vperm2f128_ps256:
14613 case X86::BI__builtin_ia32_vperm2f128_si256:
14614 case X86::BI__builtin_ia32_permti256: {
14615 unsigned NumElements =
14616 E->getArg(0)->getType()->getAs<VectorType>()->getNumElements();
14617 unsigned PreservedBitsCnt = NumElements >> 2;
14618 APValue R;
14619 if (!evalShuffleGeneric(
14620 Info, E, R,
14621 [PreservedBitsCnt](unsigned DstIdx, unsigned ShuffleMask) {
14622 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
14623 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
14624
14625 if (ControlBits & 0b1000)
14626 return std::make_pair(0u, -1);
14627
14628 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
14629 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
14630 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
14631 (DstIdx & PreservedBitsMask);
14632 return std::make_pair(SrcVecIdx, SrcIdx);
14633 }))
14634 return false;
14635 return Success(R, E);
14636 }
14637 }
14638}
14639
14640bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
14641 APValue Source;
14642 QualType SourceVecType = E->getSrcExpr()->getType();
14643 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
14644 return false;
14645
14646 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
14647 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
14648
14649 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14650
14651 auto SourceLen = Source.getVectorLength();
14652 SmallVector<APValue, 4> ResultElements;
14653 ResultElements.reserve(SourceLen);
14654 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14655 APValue Elt;
14656 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
14657 Source.getVectorElt(EltNum), Elt))
14658 return false;
14659 ResultElements.push_back(std::move(Elt));
14660 }
14661
14662 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14663}
14664
14665static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
14666 QualType ElemType, APValue const &VecVal1,
14667 APValue const &VecVal2, unsigned EltNum,
14668 APValue &Result) {
14669 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
14670 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
14671
14672 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
14673 int64_t index = IndexVal.getExtValue();
14674 // The spec says that -1 should be treated as undef for optimizations,
14675 // but in constexpr we'd have to produce an APValue::Indeterminate,
14676 // which is prohibited from being a top-level constant value. Emit a
14677 // diagnostic instead.
14678 if (index == -1) {
14679 Info.FFDiag(
14680 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
14681 << EltNum;
14682 return false;
14683 }
14684
14685 if (index < 0 ||
14686 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
14687 llvm_unreachable("Out of bounds shuffle index");
14688
14689 if (index >= TotalElementsInInputVector1)
14690 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
14691 else
14692 Result = VecVal1.getVectorElt(index);
14693 return true;
14694}
14695
14696bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
14697 // FIXME: Unary shuffle with mask not currently supported.
14698 if (E->getNumSubExprs() == 2)
14699 return Error(E);
14700 APValue VecVal1;
14701 const Expr *Vec1 = E->getExpr(0);
14702 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
14703 return false;
14704 APValue VecVal2;
14705 const Expr *Vec2 = E->getExpr(1);
14706 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
14707 return false;
14708
14709 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
14710 QualType DestElTy = DestVecTy->getElementType();
14711
14712 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
14713
14714 SmallVector<APValue, 4> ResultElements;
14715 ResultElements.reserve(TotalElementsInOutputVector);
14716 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
14717 APValue Elt;
14718 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
14719 return false;
14720 ResultElements.push_back(std::move(Elt));
14721 }
14722
14723 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14724}
14725
14726//===----------------------------------------------------------------------===//
14727// Matrix Evaluation
14728//===----------------------------------------------------------------------===//
14729
14730namespace {
14731class MatrixExprEvaluator : public ExprEvaluatorBase<MatrixExprEvaluator> {
14732 APValue &Result;
14733
14734public:
14735 MatrixExprEvaluator(EvalInfo &Info, APValue &Result)
14736 : ExprEvaluatorBaseTy(Info), Result(Result) {}
14737
14738 bool Success(ArrayRef<APValue> M, const Expr *E) {
14739 auto *CMTy = E->getType()->castAs<ConstantMatrixType>();
14740 assert(M.size() == CMTy->getNumElementsFlattened());
14741 // FIXME: remove this APValue copy.
14742 Result = APValue(M.data(), CMTy->getNumRows(), CMTy->getNumColumns());
14743 return true;
14744 }
14745 bool Success(const APValue &M, const Expr *E) {
14746 assert(M.isMatrix() && "expected matrix");
14747 Result = M;
14748 return true;
14749 }
14750
14751 bool VisitCastExpr(const CastExpr *E);
14752 bool VisitInitListExpr(const InitListExpr *E);
14753};
14754} // end anonymous namespace
14755
14756static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info) {
14757 assert(E->isPRValue() && E->getType()->isConstantMatrixType() &&
14758 "not a matrix prvalue");
14759 return MatrixExprEvaluator(Info, Result).Visit(E);
14760}
14761
14762bool MatrixExprEvaluator::VisitCastExpr(const CastExpr *E) {
14763 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
14764 unsigned NumRows = MT->getNumRows();
14765 unsigned NumCols = MT->getNumColumns();
14766 unsigned NElts = NumRows * NumCols;
14767 QualType EltTy = MT->getElementType();
14768 const Expr *SE = E->getSubExpr();
14769
14770 switch (E->getCastKind()) {
14771 case CK_HLSLAggregateSplatCast: {
14772 APValue Val;
14773 QualType ValTy;
14774
14775 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
14776 return false;
14777
14778 APValue CastedVal;
14779 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14780 if (!handleScalarCast(Info, FPO, E, ValTy, EltTy, Val, CastedVal))
14781 return false;
14782
14783 SmallVector<APValue, 16> SplatEls(NElts, CastedVal);
14784 return Success(SplatEls, E);
14785 }
14786 case CK_HLSLElementwiseCast: {
14787 SmallVector<APValue> SrcVals;
14788 SmallVector<QualType> SrcTypes;
14789
14790 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
14791 return false;
14792
14793 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14794 SmallVector<QualType, 16> DestTypes(NElts, EltTy);
14795 SmallVector<APValue, 16> ResultEls(NElts);
14796 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
14797 ResultEls))
14798 return false;
14799 return Success(ResultEls, E);
14800 }
14801 default:
14802 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14803 }
14804}
14805
14806bool MatrixExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14807 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
14808 QualType EltTy = MT->getElementType();
14809
14810 assert(E->getNumInits() == MT->getNumElementsFlattened() &&
14811 "Expected number of elements in initializer list to match the number "
14812 "of matrix elements");
14813
14814 SmallVector<APValue, 16> Elements;
14815 Elements.reserve(MT->getNumElementsFlattened());
14816
14817 // The following loop assumes the elements of the matrix InitListExpr are in
14818 // row-major order, which matches the row-major ordering assumption of the
14819 // matrix APValue.
14820 for (unsigned I = 0, N = MT->getNumElementsFlattened(); I < N; ++I) {
14821 if (EltTy->isIntegerType()) {
14822 llvm::APSInt IntVal;
14823 if (!EvaluateInteger(E->getInit(I), IntVal, Info))
14824 return false;
14825 Elements.push_back(APValue(IntVal));
14826 } else {
14827 llvm::APFloat FloatVal(0.0);
14828 if (!EvaluateFloat(E->getInit(I), FloatVal, Info))
14829 return false;
14830 Elements.push_back(APValue(FloatVal));
14831 }
14832 }
14833
14834 return Success(Elements, E);
14835}
14836
14837//===----------------------------------------------------------------------===//
14838// Array Evaluation
14839//===----------------------------------------------------------------------===//
14840
14841namespace {
14842 class ArrayExprEvaluator
14843 : public ExprEvaluatorBase<ArrayExprEvaluator> {
14844 const LValue &This;
14845 APValue &Result;
14846 public:
14847
14848 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
14849 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14850
14851 bool Success(const APValue &V, const Expr *E) {
14852 assert(V.isArray() && "expected array");
14853 Result = V;
14854 return true;
14855 }
14856
14857 bool ZeroInitialization(const Expr *E) {
14858 const ConstantArrayType *CAT =
14859 Info.Ctx.getAsConstantArrayType(E->getType());
14860 if (!CAT) {
14861 if (E->getType()->isIncompleteArrayType()) {
14862 // We can be asked to zero-initialize a flexible array member; this
14863 // is represented as an ImplicitValueInitExpr of incomplete array
14864 // type. In this case, the array has zero elements.
14865 Result = APValue(APValue::UninitArray(), 0, 0);
14866 return true;
14867 }
14868 // FIXME: We could handle VLAs here.
14869 return Error(E);
14870 }
14871
14872 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
14873 if (!Result.hasArrayFiller())
14874 return true;
14875
14876 // Zero-initialize all elements.
14877 LValue Subobject = This;
14878 Subobject.addArray(Info, E, CAT);
14879 ImplicitValueInitExpr VIE(CAT->getElementType());
14880 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
14881 }
14882
14883 bool VisitCallExpr(const CallExpr *E) {
14884 return handleCallExpr(E, Result, &This);
14885 }
14886 bool VisitCastExpr(const CastExpr *E);
14887 bool VisitInitListExpr(const InitListExpr *E,
14888 QualType AllocType = QualType());
14889 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
14890 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
14891 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
14892 const LValue &Subobject,
14893 APValue *Value, QualType Type);
14894 bool VisitStringLiteral(const StringLiteral *E,
14895 QualType AllocType = QualType()) {
14896 expandStringLiteral(Info, E, Result, AllocType);
14897 return true;
14898 }
14899 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
14900 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
14901 ArrayRef<Expr *> Args,
14902 const Expr *ArrayFiller,
14903 QualType AllocType = QualType());
14904 };
14905} // end anonymous namespace
14906
14907static bool EvaluateArray(const Expr *E, const LValue &This,
14908 APValue &Result, EvalInfo &Info) {
14909 assert(!E->isValueDependent());
14910 assert(E->isPRValue() && E->getType()->isArrayType() &&
14911 "not an array prvalue");
14912 return ArrayExprEvaluator(Info, This, Result).Visit(E);
14913}
14914
14915static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
14916 APValue &Result, const InitListExpr *ILE,
14917 QualType AllocType) {
14918 assert(!ILE->isValueDependent());
14919 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
14920 "not an array prvalue");
14921 return ArrayExprEvaluator(Info, This, Result)
14922 .VisitInitListExpr(ILE, AllocType);
14923}
14924
14925static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
14926 APValue &Result,
14927 const CXXConstructExpr *CCE,
14928 QualType AllocType) {
14929 assert(!CCE->isValueDependent());
14930 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
14931 "not an array prvalue");
14932 return ArrayExprEvaluator(Info, This, Result)
14933 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
14934}
14935
14936// Return true iff the given array filler may depend on the element index.
14937static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
14938 // For now, just allow non-class value-initialization and initialization
14939 // lists comprised of them.
14940 if (isa<ImplicitValueInitExpr>(FillerExpr))
14941 return false;
14942 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
14943 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
14944 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
14945 return true;
14946 }
14947
14948 if (ILE->hasArrayFiller() &&
14949 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
14950 return true;
14951
14952 return false;
14953 }
14954 return true;
14955}
14956
14957bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
14958 const Expr *SE = E->getSubExpr();
14959
14960 switch (E->getCastKind()) {
14961 default:
14962 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14963 case CK_HLSLAggregateSplatCast: {
14964 APValue Val;
14965 QualType ValTy;
14966
14967 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
14968 return false;
14969
14970 unsigned NEls = elementwiseSize(Info, E->getType());
14971
14972 SmallVector<APValue> SplatEls(NEls, Val);
14973 SmallVector<QualType> SplatType(NEls, ValTy);
14974
14975 // cast the elements
14976 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14977 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
14978 SplatType))
14979 return false;
14980
14981 return true;
14982 }
14983 case CK_HLSLElementwiseCast: {
14984 SmallVector<APValue> SrcEls;
14985 SmallVector<QualType> SrcTypes;
14986
14987 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
14988 return false;
14989
14990 // cast the elements
14991 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
14992 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
14993 SrcTypes))
14994 return false;
14995 return true;
14996 }
14997 }
14998}
14999
15000bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
15001 QualType AllocType) {
15002 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15003 AllocType.isNull() ? E->getType() : AllocType);
15004 if (!CAT)
15005 return Error(E);
15006
15007 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
15008 // an appropriately-typed string literal enclosed in braces.
15009 if (E->isStringLiteralInit()) {
15010 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
15011 // FIXME: Support ObjCEncodeExpr here once we support it in
15012 // ArrayExprEvaluator generally.
15013 if (!SL)
15014 return Error(E);
15015 return VisitStringLiteral(SL, AllocType);
15016 }
15017 // Any other transparent list init will need proper handling of the
15018 // AllocType; we can't just recurse to the inner initializer.
15019 assert(!E->isTransparent() &&
15020 "transparent array list initialization is not string literal init?");
15021
15022 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
15023 AllocType);
15024}
15025
15026bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
15027 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
15028 QualType AllocType) {
15029 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15030 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
15031
15032 bool Success = true;
15033
15034 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
15035 "zero-initialized array shouldn't have any initialized elts");
15036 APValue Filler;
15037 if (Result.isArray() && Result.hasArrayFiller())
15038 Filler = Result.getArrayFiller();
15039
15040 unsigned NumEltsToInit = Args.size();
15041 unsigned NumElts = CAT->getZExtSize();
15042
15043 // If the initializer might depend on the array index, run it for each
15044 // array element.
15045 if (NumEltsToInit != NumElts &&
15046 MaybeElementDependentArrayFiller(ArrayFiller)) {
15047 NumEltsToInit = NumElts;
15048 } else {
15049 for (auto *Init : Args) {
15050 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
15051 NumEltsToInit += EmbedS->getDataElementCount() - 1;
15052 }
15053 if (NumEltsToInit > NumElts)
15054 NumEltsToInit = NumElts;
15055 }
15056
15057 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
15058 << NumEltsToInit << ".\n");
15059
15060 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15061
15062 // If the array was previously zero-initialized, preserve the
15063 // zero-initialized values.
15064 if (Filler.hasValue()) {
15065 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
15066 Result.getArrayInitializedElt(I) = Filler;
15067 if (Result.hasArrayFiller())
15068 Result.getArrayFiller() = Filler;
15069 }
15070
15071 LValue Subobject = This;
15072 Subobject.addArray(Info, ExprToVisit, CAT);
15073 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
15074 if (Init->isValueDependent())
15075 return EvaluateDependentExpr(Init, Info);
15076
15077 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
15078 Subobject, Init) ||
15079 !HandleLValueArrayAdjustment(Info, Init, Subobject,
15080 CAT->getElementType(), 1)) {
15081 if (!Info.noteFailure())
15082 return false;
15083 Success = false;
15084 }
15085 return true;
15086 };
15087 unsigned ArrayIndex = 0;
15088 QualType DestTy = CAT->getElementType();
15089 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
15090 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
15091 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
15092 if (ArrayIndex >= NumEltsToInit)
15093 break;
15094 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
15095 StringLiteral *SL = EmbedS->getDataStringLiteral();
15096 for (unsigned I = EmbedS->getStartingElementPos(),
15097 N = EmbedS->getDataElementCount();
15098 I != EmbedS->getStartingElementPos() + N; ++I) {
15099 Value = SL->getCodeUnit(I);
15100 if (DestTy->isIntegerType()) {
15101 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
15102 } else {
15103 assert(DestTy->isFloatingType() && "unexpected type");
15104 const FPOptions FPO =
15105 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15106 APFloat FValue(0.0);
15107 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
15108 DestTy, FValue))
15109 return false;
15110 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
15111 }
15112 ArrayIndex++;
15113 }
15114 } else {
15115 if (!Eval(Init, ArrayIndex))
15116 return false;
15117 ++ArrayIndex;
15118 }
15119 }
15120
15121 if (!Result.hasArrayFiller())
15122 return Success;
15123
15124 // If we get here, we have a trivial filler, which we can just evaluate
15125 // once and splat over the rest of the array elements.
15126 assert(ArrayFiller && "no array filler for incomplete init list");
15127 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
15128 ArrayFiller) &&
15129 Success;
15130}
15131
15132bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
15133 LValue CommonLV;
15134 if (E->getCommonExpr() &&
15135 !Evaluate(Info.CurrentCall->createTemporary(
15136 E->getCommonExpr(),
15137 getStorageType(Info.Ctx, E->getCommonExpr()),
15138 ScopeKind::FullExpression, CommonLV),
15139 Info, E->getCommonExpr()->getSourceExpr()))
15140 return false;
15141
15143
15144 uint64_t Elements = CAT->getZExtSize();
15145 Result = APValue(APValue::UninitArray(), Elements, Elements);
15146
15147 LValue Subobject = This;
15148 Subobject.addArray(Info, E, CAT);
15149
15150 bool Success = true;
15151 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
15152 // C++ [class.temporary]/5
15153 // There are four contexts in which temporaries are destroyed at a different
15154 // point than the end of the full-expression. [...] The second context is
15155 // when a copy constructor is called to copy an element of an array while
15156 // the entire array is copied [...]. In either case, if the constructor has
15157 // one or more default arguments, the destruction of every temporary created
15158 // in a default argument is sequenced before the construction of the next
15159 // array element, if any.
15160 FullExpressionRAII Scope(Info);
15161
15162 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
15163 Info, Subobject, E->getSubExpr()) ||
15164 !HandleLValueArrayAdjustment(Info, E, Subobject,
15165 CAT->getElementType(), 1)) {
15166 if (!Info.noteFailure())
15167 return false;
15168 Success = false;
15169 }
15170
15171 // Make sure we run the destructors too.
15172 Scope.destroy();
15173 }
15174
15175 return Success;
15176}
15177
15178bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
15179 return VisitCXXConstructExpr(E, This, &Result, E->getType());
15180}
15181
15182bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
15183 const LValue &Subobject,
15184 APValue *Value,
15185 QualType Type) {
15186 bool HadZeroInit = Value->hasValue();
15187
15188 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
15189 unsigned FinalSize = CAT->getZExtSize();
15190
15191 // Preserve the array filler if we had prior zero-initialization.
15192 APValue Filler =
15193 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
15194 : APValue();
15195
15196 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
15197 if (FinalSize == 0)
15198 return true;
15199
15200 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
15201 Info, E->getExprLoc(), E->getConstructor(),
15203 LValue ArrayElt = Subobject;
15204 ArrayElt.addArray(Info, E, CAT);
15205 // We do the whole initialization in two passes, first for just one element,
15206 // then for the whole array. It's possible we may find out we can't do const
15207 // init in the first pass, in which case we avoid allocating a potentially
15208 // large array. We don't do more passes because expanding array requires
15209 // copying the data, which is wasteful.
15210 for (const unsigned N : {1u, FinalSize}) {
15211 unsigned OldElts = Value->getArrayInitializedElts();
15212 if (OldElts == N)
15213 break;
15214
15215 // Expand the array to appropriate size.
15216 APValue NewValue(APValue::UninitArray(), N, FinalSize);
15217 for (unsigned I = 0; I < OldElts; ++I)
15218 NewValue.getArrayInitializedElt(I).swap(
15219 Value->getArrayInitializedElt(I));
15220 Value->swap(NewValue);
15221
15222 if (HadZeroInit)
15223 for (unsigned I = OldElts; I < N; ++I)
15224 Value->getArrayInitializedElt(I) = Filler;
15225
15226 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
15227 // If we have a trivial constructor, only evaluate it once and copy
15228 // the result into all the array elements.
15229 APValue &FirstResult = Value->getArrayInitializedElt(0);
15230 for (unsigned I = OldElts; I < FinalSize; ++I)
15231 Value->getArrayInitializedElt(I) = FirstResult;
15232 } else {
15233 for (unsigned I = OldElts; I < N; ++I) {
15234 if (!VisitCXXConstructExpr(E, ArrayElt,
15235 &Value->getArrayInitializedElt(I),
15236 CAT->getElementType()) ||
15237 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
15238 CAT->getElementType(), 1))
15239 return false;
15240 // When checking for const initilization any diagnostic is considered
15241 // an error.
15242 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
15243 !Info.keepEvaluatingAfterFailure())
15244 return false;
15245 }
15246 }
15247 }
15248
15249 return true;
15250 }
15251
15252 if (!Type->isRecordType())
15253 return Error(E);
15254
15255 return RecordExprEvaluator(Info, Subobject, *Value)
15256 .VisitCXXConstructExpr(E, Type);
15257}
15258
15259bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
15260 const CXXParenListInitExpr *E) {
15261 assert(E->getType()->isConstantArrayType() &&
15262 "Expression result is not a constant array type");
15263
15264 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
15265 E->getArrayFiller());
15266}
15267
15268//===----------------------------------------------------------------------===//
15269// Integer Evaluation
15270//
15271// As a GNU extension, we support casting pointers to sufficiently-wide integer
15272// types and back in constant folding. Integer values are thus represented
15273// either as an integer-valued APValue, or as an lvalue-valued APValue.
15274//===----------------------------------------------------------------------===//
15275
15276namespace {
15277class IntExprEvaluator
15278 : public ExprEvaluatorBase<IntExprEvaluator> {
15279 APValue &Result;
15280public:
15281 IntExprEvaluator(EvalInfo &info, APValue &result)
15282 : ExprEvaluatorBaseTy(info), Result(result) {}
15283
15284 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
15285 assert(E->getType()->isIntegralOrEnumerationType() &&
15286 "Invalid evaluation result.");
15287 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
15288 "Invalid evaluation result.");
15289 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15290 "Invalid evaluation result.");
15291 Result = APValue(SI);
15292 return true;
15293 }
15294 bool Success(const llvm::APSInt &SI, const Expr *E) {
15295 return Success(SI, E, Result);
15296 }
15297
15298 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
15299 assert(E->getType()->isIntegralOrEnumerationType() &&
15300 "Invalid evaluation result.");
15301 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15302 "Invalid evaluation result.");
15303 Result = APValue(APSInt(I));
15304 Result.getInt().setIsUnsigned(
15306 return true;
15307 }
15308 bool Success(const llvm::APInt &I, const Expr *E) {
15309 return Success(I, E, Result);
15310 }
15311
15312 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
15313 assert(E->getType()->isIntegralOrEnumerationType() &&
15314 "Invalid evaluation result.");
15315 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
15316 return true;
15317 }
15318 bool Success(uint64_t Value, const Expr *E) {
15319 return Success(Value, E, Result);
15320 }
15321
15322 bool Success(CharUnits Size, const Expr *E) {
15323 return Success(Size.getQuantity(), E);
15324 }
15325
15326 bool Success(const APValue &V, const Expr *E) {
15327 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
15328 // pointer allow further evaluation of the value.
15329 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
15330 V.allowConstexprUnknown()) {
15331 Result = V;
15332 return true;
15333 }
15334 return Success(V.getInt(), E);
15335 }
15336
15337 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
15338
15339 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
15340 const CallExpr *);
15341
15342 //===--------------------------------------------------------------------===//
15343 // Visitor Methods
15344 //===--------------------------------------------------------------------===//
15345
15346 bool VisitIntegerLiteral(const IntegerLiteral *E) {
15347 return Success(E->getValue(), E);
15348 }
15349 bool VisitCharacterLiteral(const CharacterLiteral *E) {
15350 return Success(E->getValue(), E);
15351 }
15352
15353 bool CheckReferencedDecl(const Expr *E, const Decl *D);
15354 bool VisitDeclRefExpr(const DeclRefExpr *E) {
15355 if (CheckReferencedDecl(E, E->getDecl()))
15356 return true;
15357
15358 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
15359 }
15360 bool VisitMemberExpr(const MemberExpr *E) {
15361 if (CheckReferencedDecl(E, E->getMemberDecl())) {
15362 VisitIgnoredBaseExpression(E->getBase());
15363 return true;
15364 }
15365
15366 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
15367 }
15368
15369 bool VisitCallExpr(const CallExpr *E);
15370 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
15371 bool VisitBinaryOperator(const BinaryOperator *E);
15372 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
15373 bool VisitUnaryOperator(const UnaryOperator *E);
15374
15375 bool VisitCastExpr(const CastExpr* E);
15376 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
15377
15378 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
15379 return Success(E->getValue(), E);
15380 }
15381
15382 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
15383 return Success(E->getValue(), E);
15384 }
15385
15386 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
15387 if (Info.ArrayInitIndex == uint64_t(-1)) {
15388 // We were asked to evaluate this subexpression independent of the
15389 // enclosing ArrayInitLoopExpr. We can't do that.
15390 Info.FFDiag(E);
15391 return false;
15392 }
15393 return Success(Info.ArrayInitIndex, E);
15394 }
15395
15396 // Note, GNU defines __null as an integer, not a pointer.
15397 bool VisitGNUNullExpr(const GNUNullExpr *E) {
15398 return ZeroInitialization(E);
15399 }
15400
15401 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
15402 if (E->isStoredAsBoolean())
15403 return Success(E->getBoolValue(), E);
15404 if (E->getAPValue().isAbsent())
15405 return false;
15406 assert(E->getAPValue().isInt() && "APValue type not supported");
15407 return Success(E->getAPValue().getInt(), E);
15408 }
15409
15410 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
15411 return Success(E->getValue(), E);
15412 }
15413
15414 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
15415 return Success(E->getValue(), E);
15416 }
15417
15418 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
15419 // This should not be evaluated during constant expr evaluation, as it
15420 // should always be in an unevaluated context (the args list of a 'gang' or
15421 // 'tile' clause).
15422 return Error(E);
15423 }
15424
15425 bool VisitUnaryReal(const UnaryOperator *E);
15426 bool VisitUnaryImag(const UnaryOperator *E);
15427
15428 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
15429 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
15430 bool VisitSourceLocExpr(const SourceLocExpr *E);
15431 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
15432 bool VisitRequiresExpr(const RequiresExpr *E);
15433 // FIXME: Missing: array subscript of vector, member of vector
15434};
15435
15436class FixedPointExprEvaluator
15437 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
15438 APValue &Result;
15439
15440 public:
15441 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
15442 : ExprEvaluatorBaseTy(info), Result(result) {}
15443
15444 bool Success(const llvm::APInt &I, const Expr *E) {
15445 return Success(
15446 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15447 }
15448
15449 bool Success(uint64_t Value, const Expr *E) {
15450 return Success(
15451 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15452 }
15453
15454 bool Success(const APValue &V, const Expr *E) {
15455 return Success(V.getFixedPoint(), E);
15456 }
15457
15458 bool Success(const APFixedPoint &V, const Expr *E) {
15459 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
15460 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15461 "Invalid evaluation result.");
15462 Result = APValue(V);
15463 return true;
15464 }
15465
15466 bool ZeroInitialization(const Expr *E) {
15467 return Success(0, E);
15468 }
15469
15470 //===--------------------------------------------------------------------===//
15471 // Visitor Methods
15472 //===--------------------------------------------------------------------===//
15473
15474 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
15475 return Success(E->getValue(), E);
15476 }
15477
15478 bool VisitCastExpr(const CastExpr *E);
15479 bool VisitUnaryOperator(const UnaryOperator *E);
15480 bool VisitBinaryOperator(const BinaryOperator *E);
15481};
15482} // end anonymous namespace
15483
15484/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
15485/// produce either the integer value or a pointer.
15486///
15487/// GCC has a heinous extension which folds casts between pointer types and
15488/// pointer-sized integral types. We support this by allowing the evaluation of
15489/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
15490/// Some simple arithmetic on such values is supported (they are treated much
15491/// like char*).
15492static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
15493 EvalInfo &Info) {
15494 assert(!E->isValueDependent());
15495 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
15496 return IntExprEvaluator(Info, Result).Visit(E);
15497}
15498
15499static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
15500 assert(!E->isValueDependent());
15501 APValue Val;
15502 if (!EvaluateIntegerOrLValue(E, Val, Info))
15503 return false;
15504 if (!Val.isInt()) {
15505 // FIXME: It would be better to produce the diagnostic for casting
15506 // a pointer to an integer.
15507 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15508 return false;
15509 }
15510 Result = Val.getInt();
15511 return true;
15512}
15513
15514bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
15516 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
15517 return Success(Evaluated, E);
15518}
15519
15520static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
15521 EvalInfo &Info) {
15522 assert(!E->isValueDependent());
15523 if (E->getType()->isFixedPointType()) {
15524 APValue Val;
15525 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
15526 return false;
15527 if (!Val.isFixedPoint())
15528 return false;
15529
15530 Result = Val.getFixedPoint();
15531 return true;
15532 }
15533 return false;
15534}
15535
15536static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
15537 EvalInfo &Info) {
15538 assert(!E->isValueDependent());
15539 if (E->getType()->isIntegerType()) {
15540 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
15541 APSInt Val;
15542 if (!EvaluateInteger(E, Val, Info))
15543 return false;
15544 Result = APFixedPoint(Val, FXSema);
15545 return true;
15546 } else if (E->getType()->isFixedPointType()) {
15547 return EvaluateFixedPoint(E, Result, Info);
15548 }
15549 return false;
15550}
15551
15552/// Check whether the given declaration can be directly converted to an integral
15553/// rvalue. If not, no diagnostic is produced; there are other things we can
15554/// try.
15555bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
15556 // Enums are integer constant exprs.
15557 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
15558 // Check for signedness/width mismatches between E type and ECD value.
15559 bool SameSign = (ECD->getInitVal().isSigned()
15561 bool SameWidth = (ECD->getInitVal().getBitWidth()
15562 == Info.Ctx.getIntWidth(E->getType()));
15563 if (SameSign && SameWidth)
15564 return Success(ECD->getInitVal(), E);
15565 else {
15566 // Get rid of mismatch (otherwise Success assertions will fail)
15567 // by computing a new value matching the type of E.
15568 llvm::APSInt Val = ECD->getInitVal();
15569 if (!SameSign)
15570 Val.setIsSigned(!ECD->getInitVal().isSigned());
15571 if (!SameWidth)
15572 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
15573 return Success(Val, E);
15574 }
15575 }
15576 return false;
15577}
15578
15579/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15580/// as GCC.
15582 const LangOptions &LangOpts) {
15583 assert(!T->isDependentType() && "unexpected dependent type");
15584
15585 QualType CanTy = T.getCanonicalType();
15586
15587 switch (CanTy->getTypeClass()) {
15588#define TYPE(ID, BASE)
15589#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
15590#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
15591#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
15592#include "clang/AST/TypeNodes.inc"
15593 case Type::Auto:
15594 case Type::DeducedTemplateSpecialization:
15595 llvm_unreachable("unexpected non-canonical or dependent type");
15596
15597 case Type::Builtin:
15598 switch (cast<BuiltinType>(CanTy)->getKind()) {
15599#define BUILTIN_TYPE(ID, SINGLETON_ID)
15600#define SIGNED_TYPE(ID, SINGLETON_ID) \
15601 case BuiltinType::ID: return GCCTypeClass::Integer;
15602#define FLOATING_TYPE(ID, SINGLETON_ID) \
15603 case BuiltinType::ID: return GCCTypeClass::RealFloat;
15604#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
15605 case BuiltinType::ID: break;
15606#include "clang/AST/BuiltinTypes.def"
15607 case BuiltinType::Void:
15608 return GCCTypeClass::Void;
15609
15610 case BuiltinType::Bool:
15611 return GCCTypeClass::Bool;
15612
15613 case BuiltinType::Char_U:
15614 case BuiltinType::UChar:
15615 case BuiltinType::WChar_U:
15616 case BuiltinType::Char8:
15617 case BuiltinType::Char16:
15618 case BuiltinType::Char32:
15619 case BuiltinType::UShort:
15620 case BuiltinType::UInt:
15621 case BuiltinType::ULong:
15622 case BuiltinType::ULongLong:
15623 case BuiltinType::UInt128:
15624 return GCCTypeClass::Integer;
15625
15626 case BuiltinType::UShortAccum:
15627 case BuiltinType::UAccum:
15628 case BuiltinType::ULongAccum:
15629 case BuiltinType::UShortFract:
15630 case BuiltinType::UFract:
15631 case BuiltinType::ULongFract:
15632 case BuiltinType::SatUShortAccum:
15633 case BuiltinType::SatUAccum:
15634 case BuiltinType::SatULongAccum:
15635 case BuiltinType::SatUShortFract:
15636 case BuiltinType::SatUFract:
15637 case BuiltinType::SatULongFract:
15638 return GCCTypeClass::None;
15639
15640 case BuiltinType::NullPtr:
15641
15642 case BuiltinType::ObjCId:
15643 case BuiltinType::ObjCClass:
15644 case BuiltinType::ObjCSel:
15645#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15646 case BuiltinType::Id:
15647#include "clang/Basic/OpenCLImageTypes.def"
15648#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
15649 case BuiltinType::Id:
15650#include "clang/Basic/OpenCLExtensionTypes.def"
15651 case BuiltinType::OCLSampler:
15652 case BuiltinType::OCLEvent:
15653 case BuiltinType::OCLClkEvent:
15654 case BuiltinType::OCLQueue:
15655 case BuiltinType::OCLReserveID:
15656#define SVE_TYPE(Name, Id, SingletonId) \
15657 case BuiltinType::Id:
15658#include "clang/Basic/AArch64ACLETypes.def"
15659#define PPC_VECTOR_TYPE(Name, Id, Size) \
15660 case BuiltinType::Id:
15661#include "clang/Basic/PPCTypes.def"
15662#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15663#include "clang/Basic/RISCVVTypes.def"
15664#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15665#include "clang/Basic/WebAssemblyReferenceTypes.def"
15666#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
15667#include "clang/Basic/AMDGPUTypes.def"
15668#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
15669#include "clang/Basic/HLSLIntangibleTypes.def"
15670 return GCCTypeClass::None;
15671
15672 case BuiltinType::Dependent:
15673 llvm_unreachable("unexpected dependent type");
15674 };
15675 llvm_unreachable("unexpected placeholder type");
15676
15677 case Type::Enum:
15678 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
15679
15680 case Type::Pointer:
15681 case Type::ConstantArray:
15682 case Type::VariableArray:
15683 case Type::IncompleteArray:
15684 case Type::FunctionNoProto:
15685 case Type::FunctionProto:
15686 case Type::ArrayParameter:
15687 return GCCTypeClass::Pointer;
15688
15689 case Type::MemberPointer:
15690 return CanTy->isMemberDataPointerType()
15693
15694 case Type::Complex:
15695 return GCCTypeClass::Complex;
15696
15697 case Type::Record:
15698 return CanTy->isUnionType() ? GCCTypeClass::Union
15700
15701 case Type::Atomic:
15702 // GCC classifies _Atomic T the same as T.
15704 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
15705
15706 case Type::Vector:
15707 case Type::ExtVector:
15708 return GCCTypeClass::Vector;
15709
15710 case Type::BlockPointer:
15711 case Type::ConstantMatrix:
15712 case Type::ObjCObject:
15713 case Type::ObjCInterface:
15714 case Type::ObjCObjectPointer:
15715 case Type::Pipe:
15716 case Type::HLSLAttributedResource:
15717 case Type::HLSLInlineSpirv:
15718 case Type::OverflowBehavior:
15719 // Classify all other types that don't fit into the regular
15720 // classification the same way.
15721 return GCCTypeClass::None;
15722
15723 case Type::BitInt:
15724 return GCCTypeClass::BitInt;
15725
15726 case Type::LValueReference:
15727 case Type::RValueReference:
15728 llvm_unreachable("invalid type for expression");
15729 }
15730
15731 llvm_unreachable("unexpected type class");
15732}
15733
15734/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
15735/// as GCC.
15736static GCCTypeClass
15738 // If no argument was supplied, default to None. This isn't
15739 // ideal, however it is what gcc does.
15740 if (E->getNumArgs() == 0)
15741 return GCCTypeClass::None;
15742
15743 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
15744 // being an ICE, but still folds it to a constant using the type of the first
15745 // argument.
15746 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
15747}
15748
15749/// EvaluateBuiltinConstantPForLValue - Determine the result of
15750/// __builtin_constant_p when applied to the given pointer.
15751///
15752/// A pointer is only "constant" if it is null (or a pointer cast to integer)
15753/// or it points to the first character of a string literal.
15756 if (Base.isNull()) {
15757 // A null base is acceptable.
15758 return true;
15759 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
15760 if (!isa<StringLiteral>(E))
15761 return false;
15762 return LV.getLValueOffset().isZero();
15763 } else if (Base.is<TypeInfoLValue>()) {
15764 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
15765 // evaluate to true.
15766 return true;
15767 } else {
15768 // Any other base is not constant enough for GCC.
15769 return false;
15770 }
15771}
15772
15773/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
15774/// GCC as we can manage.
15775static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
15776 // This evaluation is not permitted to have side-effects, so evaluate it in
15777 // a speculative evaluation context.
15778 SpeculativeEvaluationRAII SpeculativeEval(Info);
15779
15780 // Constant-folding is always enabled for the operand of __builtin_constant_p
15781 // (even when the enclosing evaluation context otherwise requires a strict
15782 // language-specific constant expression).
15783 FoldConstant Fold(Info, true);
15784
15785 QualType ArgType = Arg->getType();
15786
15787 // __builtin_constant_p always has one operand. The rules which gcc follows
15788 // are not precisely documented, but are as follows:
15789 //
15790 // - If the operand is of integral, floating, complex or enumeration type,
15791 // and can be folded to a known value of that type, it returns 1.
15792 // - If the operand can be folded to a pointer to the first character
15793 // of a string literal (or such a pointer cast to an integral type)
15794 // or to a null pointer or an integer cast to a pointer, it returns 1.
15795 //
15796 // Otherwise, it returns 0.
15797 //
15798 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
15799 // its support for this did not work prior to GCC 9 and is not yet well
15800 // understood.
15801 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
15802 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
15803 ArgType->isNullPtrType()) {
15804 APValue V;
15805 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
15806 Fold.keepDiagnostics();
15807 return false;
15808 }
15809
15810 // For a pointer (possibly cast to integer), there are special rules.
15811 if (V.getKind() == APValue::LValue)
15813
15814 // Otherwise, any constant value is good enough.
15815 return V.hasValue();
15816 }
15817
15818 // Anything else isn't considered to be sufficiently constant.
15819 return false;
15820}
15821
15822/// Retrieves the "underlying object type" of the given expression,
15823/// as used by __builtin_object_size.
15825 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
15826 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
15827 return VD->getType();
15828 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
15830 return E->getType();
15831 } else if (B.is<TypeInfoLValue>()) {
15832 return B.getTypeInfoType();
15833 } else if (B.is<DynamicAllocLValue>()) {
15834 return B.getDynamicAllocType();
15835 }
15836
15837 return QualType();
15838}
15839
15840/// A more selective version of E->IgnoreParenCasts for
15841/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
15842/// to change the type of E.
15843/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
15844///
15845/// Always returns an RValue with a pointer representation.
15846static const Expr *ignorePointerCastsAndParens(const Expr *E) {
15847 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
15848
15849 const Expr *NoParens = E->IgnoreParens();
15850 const auto *Cast = dyn_cast<CastExpr>(NoParens);
15851 if (Cast == nullptr)
15852 return NoParens;
15853
15854 // We only conservatively allow a few kinds of casts, because this code is
15855 // inherently a simple solution that seeks to support the common case.
15856 auto CastKind = Cast->getCastKind();
15857 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
15858 CastKind != CK_AddressSpaceConversion)
15859 return NoParens;
15860
15861 const auto *SubExpr = Cast->getSubExpr();
15862 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
15863 return NoParens;
15864 return ignorePointerCastsAndParens(SubExpr);
15865}
15866
15867/// Checks to see if the given LValue's Designator is at the end of the LValue's
15868/// record layout. e.g.
15869/// struct { struct { int a, b; } fst, snd; } obj;
15870/// obj.fst // no
15871/// obj.snd // yes
15872/// obj.fst.a // no
15873/// obj.fst.b // no
15874/// obj.snd.a // no
15875/// obj.snd.b // yes
15876///
15877/// Please note: this function is specialized for how __builtin_object_size
15878/// views "objects".
15879///
15880/// If this encounters an invalid RecordDecl or otherwise cannot determine the
15881/// correct result, it will always return true.
15882static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
15883 assert(!LVal.Designator.Invalid);
15884
15885 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
15886 const RecordDecl *Parent = FD->getParent();
15887 if (Parent->isInvalidDecl() || Parent->isUnion())
15888 return true;
15889 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
15890 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
15891 };
15892
15893 auto &Base = LVal.getLValueBase();
15894 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
15895 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
15896 if (!IsLastOrInvalidFieldDecl(FD))
15897 return false;
15898 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
15899 for (auto *FD : IFD->chain()) {
15900 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
15901 return false;
15902 }
15903 }
15904 }
15905
15906 unsigned I = 0;
15907 QualType BaseType = getType(Base);
15908 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
15909 // If we don't know the array bound, conservatively assume we're looking at
15910 // the final array element.
15911 ++I;
15912 if (BaseType->isIncompleteArrayType())
15913 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
15914 else
15915 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
15916 }
15917
15918 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
15919 const auto &Entry = LVal.Designator.Entries[I];
15920 if (BaseType->isArrayType()) {
15921 // Because __builtin_object_size treats arrays as objects, we can ignore
15922 // the index iff this is the last array in the Designator.
15923 if (I + 1 == E)
15924 return true;
15925 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
15926 uint64_t Index = Entry.getAsArrayIndex();
15927 if (Index + 1 != CAT->getZExtSize())
15928 return false;
15929 BaseType = CAT->getElementType();
15930 } else if (BaseType->isAnyComplexType()) {
15931 const auto *CT = BaseType->castAs<ComplexType>();
15932 uint64_t Index = Entry.getAsArrayIndex();
15933 if (Index != 1)
15934 return false;
15935 BaseType = CT->getElementType();
15936 } else if (auto *FD = getAsField(Entry)) {
15937 if (!IsLastOrInvalidFieldDecl(FD))
15938 return false;
15939 BaseType = FD->getType();
15940 } else {
15941 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
15942 return false;
15943 }
15944 }
15945 return true;
15946}
15947
15948/// Tests to see if the LValue has a user-specified designator (that isn't
15949/// necessarily valid). Note that this always returns 'true' if the LValue has
15950/// an unsized array as its first designator entry, because there's currently no
15951/// way to tell if the user typed *foo or foo[0].
15952static bool refersToCompleteObject(const LValue &LVal) {
15953 if (LVal.Designator.Invalid)
15954 return false;
15955
15956 if (!LVal.Designator.Entries.empty())
15957 return LVal.Designator.isMostDerivedAnUnsizedArray();
15958
15959 if (!LVal.InvalidBase)
15960 return true;
15961
15962 // If `E` is a MemberExpr, then the first part of the designator is hiding in
15963 // the LValueBase.
15964 const auto *E = LVal.Base.dyn_cast<const Expr *>();
15965 return !E || !isa<MemberExpr>(E);
15966}
15967
15968/// Attempts to detect a user writing into a piece of memory that's impossible
15969/// to figure out the size of by just using types.
15970static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
15971 const SubobjectDesignator &Designator = LVal.Designator;
15972 // Notes:
15973 // - Users can only write off of the end when we have an invalid base. Invalid
15974 // bases imply we don't know where the memory came from.
15975 // - We used to be a bit more aggressive here; we'd only be conservative if
15976 // the array at the end was flexible, or if it had 0 or 1 elements. This
15977 // broke some common standard library extensions (PR30346), but was
15978 // otherwise seemingly fine. It may be useful to reintroduce this behavior
15979 // with some sort of list. OTOH, it seems that GCC is always
15980 // conservative with the last element in structs (if it's an array), so our
15981 // current behavior is more compatible than an explicit list approach would
15982 // be.
15983 auto isFlexibleArrayMember = [&] {
15985 FAMKind StrictFlexArraysLevel =
15986 Ctx.getLangOpts().getStrictFlexArraysLevel();
15987
15988 if (Designator.isMostDerivedAnUnsizedArray())
15989 return true;
15990
15991 if (StrictFlexArraysLevel == FAMKind::Default)
15992 return true;
15993
15994 if (Designator.getMostDerivedArraySize() == 0 &&
15995 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
15996 return true;
15997
15998 if (Designator.getMostDerivedArraySize() == 1 &&
15999 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
16000 return true;
16001
16002 return false;
16003 };
16004
16005 return LVal.InvalidBase &&
16006 Designator.Entries.size() == Designator.MostDerivedPathLength &&
16007 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
16008 isDesignatorAtObjectEnd(Ctx, LVal);
16009}
16010
16011/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
16012/// Fails if the conversion would cause loss of precision.
16013static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
16014 CharUnits &Result) {
16015 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
16016 if (Int.ugt(CharUnitsMax))
16017 return false;
16018 Result = CharUnits::fromQuantity(Int.getZExtValue());
16019 return true;
16020}
16021
16022/// If we're evaluating the object size of an instance of a struct that
16023/// contains a flexible array member, add the size of the initializer.
16024static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
16025 const LValue &LV, CharUnits &Size) {
16026 if (!T.isNull() && T->isStructureType() &&
16027 T->castAsRecordDecl()->hasFlexibleArrayMember())
16028 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
16029 if (const auto *VD = dyn_cast<VarDecl>(V))
16030 if (VD->hasInit())
16031 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
16032}
16033
16034/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
16035/// determine how many bytes exist from the beginning of the object to either
16036/// the end of the current subobject, or the end of the object itself, depending
16037/// on what the LValue looks like + the value of Type.
16038///
16039/// If this returns false, the value of Result is undefined.
16040static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
16041 unsigned Type, const LValue &LVal,
16042 CharUnits &EndOffset) {
16043 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
16044
16045 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
16046 if (Ty.isNull())
16047 return false;
16048
16049 Ty = Ty.getNonReferenceType();
16050
16051 if (Ty->isIncompleteType() || Ty->isFunctionType())
16052 return false;
16053
16054 return HandleSizeof(Info, ExprLoc, Ty, Result);
16055 };
16056
16057 // We want to evaluate the size of the entire object. This is a valid fallback
16058 // for when Type=1 and the designator is invalid, because we're asked for an
16059 // upper-bound.
16060 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
16061 // Type=3 wants a lower bound, so we can't fall back to this.
16062 if (Type == 3 && !DetermineForCompleteObject)
16063 return false;
16064
16065 llvm::APInt APEndOffset;
16066 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16067 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16068 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16069
16070 if (LVal.InvalidBase)
16071 return false;
16072
16073 QualType BaseTy = getObjectType(LVal.getLValueBase());
16074 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
16075 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
16076 return Ret;
16077 }
16078
16079 // We want to evaluate the size of a subobject.
16080 const SubobjectDesignator &Designator = LVal.Designator;
16081
16082 // The following is a moderately common idiom in C:
16083 //
16084 // struct Foo { int a; char c[1]; };
16085 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
16086 // strcpy(&F->c[0], Bar);
16087 //
16088 // In order to not break too much legacy code, we need to support it.
16089 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
16090 // If we can resolve this to an alloc_size call, we can hand that back,
16091 // because we know for certain how many bytes there are to write to.
16092 llvm::APInt APEndOffset;
16093 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16094 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16095 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16096
16097 // If we cannot determine the size of the initial allocation, then we can't
16098 // given an accurate upper-bound. However, we are still able to give
16099 // conservative lower-bounds for Type=3.
16100 if (Type == 1)
16101 return false;
16102 }
16103
16104 CharUnits BytesPerElem;
16105 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
16106 return false;
16107
16108 // According to the GCC documentation, we want the size of the subobject
16109 // denoted by the pointer. But that's not quite right -- what we actually
16110 // want is the size of the immediately-enclosing array, if there is one.
16111 int64_t ElemsRemaining;
16112 if (Designator.MostDerivedIsArrayElement &&
16113 Designator.Entries.size() == Designator.MostDerivedPathLength) {
16114 uint64_t ArraySize = Designator.getMostDerivedArraySize();
16115 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
16116 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
16117 } else {
16118 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
16119 }
16120
16121 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
16122 return true;
16123}
16124
16125/// Tries to evaluate the __builtin_object_size for @p E. If successful,
16126/// returns true and stores the result in @p Size.
16127///
16128/// If @p WasError is non-null, this will report whether the failure to evaluate
16129/// is to be treated as an Error in IntExprEvaluator.
16130static std::optional<uint64_t>
16131tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info) {
16132 // Determine the denoted object.
16133 LValue LVal;
16134 {
16135 // The operand of __builtin_object_size is never evaluated for side-effects.
16136 // If there are any, but we can determine the pointed-to object anyway, then
16137 // ignore the side-effects.
16138 SpeculativeEvaluationRAII SpeculativeEval(Info);
16139 IgnoreSideEffectsRAII Fold(Info);
16140
16141 if (E->isGLValue()) {
16142 // It's possible for us to be given GLValues if we're called via
16143 // Expr::tryEvaluateObjectSize.
16144 APValue RVal;
16145 if (!EvaluateAsRValue(Info, E, RVal))
16146 return std::nullopt;
16147 LVal.setFrom(Info.Ctx, RVal);
16148 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
16149 /*InvalidBaseOK=*/true))
16150 return std::nullopt;
16151 }
16152
16153 // If we point to before the start of the object, there are no accessible
16154 // bytes.
16155 if (LVal.getLValueOffset().isNegative())
16156 return 0;
16157
16158 CharUnits EndOffset;
16159 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
16160 return std::nullopt;
16161
16162 // If we've fallen outside of the end offset, just pretend there's nothing to
16163 // write to/read from.
16164 if (EndOffset <= LVal.getLValueOffset())
16165 return 0;
16166 return (EndOffset - LVal.getLValueOffset()).getQuantity();
16167}
16168
16169bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
16170 if (!IsConstantEvaluatedBuiltinCall(E))
16171 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16172 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
16173}
16174
16175static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
16176 APValue &Val, APSInt &Alignment) {
16177 QualType SrcTy = E->getArg(0)->getType();
16178 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
16179 return false;
16180 // Even though we are evaluating integer expressions we could get a pointer
16181 // argument for the __builtin_is_aligned() case.
16182 if (SrcTy->isPointerType()) {
16183 LValue Ptr;
16184 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
16185 return false;
16186 Ptr.moveInto(Val);
16187 } else if (!SrcTy->isIntegralOrEnumerationType()) {
16188 Info.FFDiag(E->getArg(0));
16189 return false;
16190 } else {
16191 APSInt SrcInt;
16192 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
16193 return false;
16194 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
16195 "Bit widths must be the same");
16196 Val = APValue(SrcInt);
16197 }
16198 assert(Val.hasValue());
16199 return true;
16200}
16201
16202bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
16203 unsigned BuiltinOp) {
16204 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
16205 Fn) {
16206 APValue SourceLHS, SourceRHS;
16207 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
16208 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
16209 return false;
16210
16211 unsigned SourceLen = SourceLHS.getVectorLength();
16212 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
16213 QualType ElemQT = VT->getElementType();
16214 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
16215
16216 APInt AWide(LaneWidth * SourceLen, 0);
16217 APInt BWide(LaneWidth * SourceLen, 0);
16218
16219 for (unsigned I = 0; I != SourceLen; ++I) {
16220 APInt ALane;
16221 APInt BLane;
16222 if (ElemQT->isIntegerType()) { // Get value.
16223 ALane = SourceLHS.getVectorElt(I).getInt();
16224 BLane = SourceRHS.getVectorElt(I).getInt();
16225 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
16226 ALane =
16227 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16228 BLane =
16229 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16230 } else { // Must be integer or floating type.
16231 return false;
16232 }
16233 AWide.insertBits(ALane, I * LaneWidth);
16234 BWide.insertBits(BLane, I * LaneWidth);
16235 }
16236 return Success(Fn(AWide, BWide), E);
16237 };
16238
16239 auto HandleMaskBinOp =
16240 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
16241 -> bool {
16242 APValue LHS, RHS;
16243 if (!Evaluate(LHS, Info, E->getArg(0)) ||
16244 !Evaluate(RHS, Info, E->getArg(1)))
16245 return false;
16246
16247 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
16248
16249 return Success(APValue(ResultInt), E);
16250 };
16251
16252 auto HandleCRC32 = [&](unsigned DataBytes) -> bool {
16253 APSInt CRC, Data;
16254 if (!EvaluateInteger(E->getArg(0), CRC, Info) ||
16255 !EvaluateInteger(E->getArg(1), Data, Info))
16256 return false;
16257
16258 uint64_t CRCVal = CRC.getZExtValue();
16259 uint64_t DataVal = Data.getZExtValue();
16260
16261 // CRC32C polynomial (iSCSI polynomial, bit-reversed)
16262 static const uint32_t CRC32C_POLY = 0x82F63B78;
16263
16264 // Process each byte
16265 uint32_t Result = static_cast<uint32_t>(CRCVal);
16266 for (unsigned I = 0; I != DataBytes; ++I) {
16267 uint8_t Byte = static_cast<uint8_t>((DataVal >> (I * 8)) & 0xFF);
16268 Result ^= Byte;
16269 for (int J = 0; J != 8; ++J) {
16270 Result = (Result >> 1) ^ ((Result & 1) ? CRC32C_POLY : 0);
16271 }
16272 }
16273
16274 return Success(Result, E);
16275 };
16276
16277 switch (BuiltinOp) {
16278 default:
16279 return false;
16280
16281 case X86::BI__builtin_ia32_crc32qi:
16282 return HandleCRC32(1);
16283 case X86::BI__builtin_ia32_crc32hi:
16284 return HandleCRC32(2);
16285 case X86::BI__builtin_ia32_crc32si:
16286 return HandleCRC32(4);
16287 case X86::BI__builtin_ia32_crc32di:
16288 return HandleCRC32(8);
16289
16290 case Builtin::BI__builtin_dynamic_object_size:
16291 case Builtin::BI__builtin_object_size: {
16292 // The type was checked when we built the expression.
16293 unsigned Type =
16294 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16295 assert(Type <= 3 && "unexpected type");
16296
16297 if (std::optional<uint64_t> Size =
16299 return Success(*Size, E);
16300
16301 if (E->getArg(0)->HasSideEffects(Info.Ctx))
16302 return Success((Type & 2) ? 0 : -1, E);
16303
16304 // Expression had no side effects, but we couldn't statically determine the
16305 // size of the referenced object.
16306 switch (Info.EvalMode) {
16307 case EvaluationMode::ConstantExpression:
16308 case EvaluationMode::ConstantFold:
16309 case EvaluationMode::IgnoreSideEffects:
16310 // Leave it to IR generation.
16311 return Error(E);
16312 case EvaluationMode::ConstantExpressionUnevaluated:
16313 // Reduce it to a constant now.
16314 return Success((Type & 2) ? 0 : -1, E);
16315 }
16316
16317 llvm_unreachable("unexpected EvalMode");
16318 }
16319
16320 case Builtin::BI__builtin_os_log_format_buffer_size: {
16321 analyze_os_log::OSLogBufferLayout Layout;
16322 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
16323 return Success(Layout.size().getQuantity(), E);
16324 }
16325
16326 case Builtin::BI__builtin_is_aligned: {
16327 APValue Src;
16328 APSInt Alignment;
16329 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16330 return false;
16331 if (Src.isLValue()) {
16332 // If we evaluated a pointer, check the minimum known alignment.
16333 LValue Ptr;
16334 Ptr.setFrom(Info.Ctx, Src);
16335 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
16336 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
16337 // We can return true if the known alignment at the computed offset is
16338 // greater than the requested alignment.
16339 assert(PtrAlign.isPowerOfTwo());
16340 assert(Alignment.isPowerOf2());
16341 if (PtrAlign.getQuantity() >= Alignment)
16342 return Success(1, E);
16343 // If the alignment is not known to be sufficient, some cases could still
16344 // be aligned at run time. However, if the requested alignment is less or
16345 // equal to the base alignment and the offset is not aligned, we know that
16346 // the run-time value can never be aligned.
16347 if (BaseAlignment.getQuantity() >= Alignment &&
16348 PtrAlign.getQuantity() < Alignment)
16349 return Success(0, E);
16350 // Otherwise we can't infer whether the value is sufficiently aligned.
16351 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
16352 // in cases where we can't fully evaluate the pointer.
16353 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
16354 << Alignment;
16355 return false;
16356 }
16357 assert(Src.isInt());
16358 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
16359 }
16360 case Builtin::BI__builtin_align_up: {
16361 APValue Src;
16362 APSInt Alignment;
16363 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16364 return false;
16365 if (!Src.isInt())
16366 return Error(E);
16367 APSInt AlignedVal =
16368 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
16369 Src.getInt().isUnsigned());
16370 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16371 return Success(AlignedVal, E);
16372 }
16373 case Builtin::BI__builtin_align_down: {
16374 APValue Src;
16375 APSInt Alignment;
16376 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16377 return false;
16378 if (!Src.isInt())
16379 return Error(E);
16380 APSInt AlignedVal =
16381 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
16382 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16383 return Success(AlignedVal, E);
16384 }
16385
16386 case Builtin::BI__builtin_bitreverseg:
16387 case Builtin::BI__builtin_bitreverse8:
16388 case Builtin::BI__builtin_bitreverse16:
16389 case Builtin::BI__builtin_bitreverse32:
16390 case Builtin::BI__builtin_bitreverse64:
16391 case Builtin::BI__builtin_elementwise_bitreverse: {
16392 APSInt Val;
16393 if (!EvaluateInteger(E->getArg(0), Val, Info))
16394 return false;
16395
16396 return Success(Val.reverseBits(), E);
16397 }
16398 case Builtin::BI__builtin_bswapg:
16399 case Builtin::BI__builtin_bswap16:
16400 case Builtin::BI__builtin_bswap32:
16401 case Builtin::BI__builtin_bswap64: {
16402 APSInt Val;
16403 if (!EvaluateInteger(E->getArg(0), Val, Info))
16404 return false;
16405 if (Val.getBitWidth() == 8 || Val.getBitWidth() == 1)
16406 return Success(Val, E);
16407
16408 return Success(Val.byteSwap(), E);
16409 }
16410
16411 case Builtin::BI__builtin_classify_type:
16412 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
16413
16414 case Builtin::BI__builtin_clrsb:
16415 case Builtin::BI__builtin_clrsbl:
16416 case Builtin::BI__builtin_clrsbll: {
16417 APSInt Val;
16418 if (!EvaluateInteger(E->getArg(0), Val, Info))
16419 return false;
16420
16421 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
16422 }
16423
16424 case Builtin::BI__builtin_clz:
16425 case Builtin::BI__builtin_clzl:
16426 case Builtin::BI__builtin_clzll:
16427 case Builtin::BI__builtin_clzs:
16428 case Builtin::BI__builtin_clzg:
16429 case Builtin::BI__builtin_elementwise_clzg:
16430 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
16431 case Builtin::BI__lzcnt:
16432 case Builtin::BI__lzcnt64: {
16433 APSInt Val;
16434 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16435 APValue Vec;
16436 if (!EvaluateVector(E->getArg(0), Vec, Info))
16437 return false;
16438 Val = ConvertBoolVectorToInt(Vec);
16439 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16440 return false;
16441 }
16442
16443 std::optional<APSInt> Fallback;
16444 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
16445 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
16446 E->getNumArgs() > 1) {
16447 APSInt FallbackTemp;
16448 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16449 return false;
16450 Fallback = FallbackTemp;
16451 }
16452
16453 if (!Val) {
16454 if (Fallback)
16455 return Success(*Fallback, E);
16456
16457 // When the argument is 0, the result of GCC builtins is undefined,
16458 // whereas for Microsoft intrinsics, the result is the bit-width of the
16459 // argument.
16460 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
16461 BuiltinOp != Builtin::BI__lzcnt &&
16462 BuiltinOp != Builtin::BI__lzcnt64;
16463
16464 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
16465 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16466 << /*IsTrailing=*/false;
16467 }
16468
16469 if (ZeroIsUndefined)
16470 return Error(E);
16471 }
16472
16473 return Success(Val.countl_zero(), E);
16474 }
16475
16476 case Builtin::BI__builtin_constant_p: {
16477 const Expr *Arg = E->getArg(0);
16478 if (EvaluateBuiltinConstantP(Info, Arg))
16479 return Success(true, E);
16480 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
16481 // Outside a constant context, eagerly evaluate to false in the presence
16482 // of side-effects in order to avoid -Wunsequenced false-positives in
16483 // a branch on __builtin_constant_p(expr).
16484 return Success(false, E);
16485 }
16486 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16487 return false;
16488 }
16489
16490 case Builtin::BI__noop:
16491 // __noop always evaluates successfully and returns 0.
16492 return Success(0, E);
16493
16494 case Builtin::BI__builtin_is_constant_evaluated: {
16495 const auto *Callee = Info.CurrentCall->getCallee();
16496 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
16497 (Info.CallStackDepth == 1 ||
16498 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
16499 Callee->getIdentifier() &&
16500 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
16501 // FIXME: Find a better way to avoid duplicated diagnostics.
16502 if (Info.EvalStatus.Diag)
16503 Info.report((Info.CallStackDepth == 1)
16504 ? E->getExprLoc()
16505 : Info.CurrentCall->getCallRange().getBegin(),
16506 diag::warn_is_constant_evaluated_always_true_constexpr)
16507 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
16508 : "std::is_constant_evaluated");
16509 }
16510
16511 return Success(Info.InConstantContext, E);
16512 }
16513
16514 case Builtin::BI__builtin_is_within_lifetime:
16515 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
16516 return Success(*result, E);
16517 return false;
16518
16519 case Builtin::BI__builtin_ctz:
16520 case Builtin::BI__builtin_ctzl:
16521 case Builtin::BI__builtin_ctzll:
16522 case Builtin::BI__builtin_ctzs:
16523 case Builtin::BI__builtin_ctzg:
16524 case Builtin::BI__builtin_elementwise_ctzg: {
16525 APSInt Val;
16526 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16527 APValue Vec;
16528 if (!EvaluateVector(E->getArg(0), Vec, Info))
16529 return false;
16530 Val = ConvertBoolVectorToInt(Vec);
16531 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16532 return false;
16533 }
16534
16535 std::optional<APSInt> Fallback;
16536 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
16537 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
16538 E->getNumArgs() > 1) {
16539 APSInt FallbackTemp;
16540 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16541 return false;
16542 Fallback = FallbackTemp;
16543 }
16544
16545 if (!Val) {
16546 if (Fallback)
16547 return Success(*Fallback, E);
16548
16549 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
16550 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16551 << /*IsTrailing=*/true;
16552 }
16553 return Error(E);
16554 }
16555
16556 return Success(Val.countr_zero(), E);
16557 }
16558
16559 case Builtin::BI__builtin_eh_return_data_regno: {
16560 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16561 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
16562 return Success(Operand, E);
16563 }
16564
16565 case Builtin::BI__builtin_elementwise_abs: {
16566 APSInt Val;
16567 if (!EvaluateInteger(E->getArg(0), Val, Info))
16568 return false;
16569
16570 return Success(Val.abs(), E);
16571 }
16572
16573 case Builtin::BI__builtin_expect:
16574 case Builtin::BI__builtin_expect_with_probability:
16575 return Visit(E->getArg(0));
16576
16577 case Builtin::BI__builtin_ptrauth_string_discriminator: {
16578 const auto *Literal =
16580 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
16581 return Success(Result, E);
16582 }
16583
16584 case Builtin::BI__builtin_infer_alloc_token: {
16585 // If we fail to infer a type, this fails to be a constant expression; this
16586 // can be checked with __builtin_constant_p(...).
16587 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
16588 if (AllocType.isNull())
16589 return Error(
16590 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
16591 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
16592 if (!ATMD)
16593 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
16594 auto Mode =
16595 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
16596 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
16597 auto MaxTokensOpt = Info.getLangOpts().AllocTokenMax;
16598 uint64_t MaxTokens =
16599 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
16600 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
16601 if (!MaybeToken)
16602 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
16603 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
16604 }
16605
16606 case Builtin::BI__builtin_ffs:
16607 case Builtin::BI__builtin_ffsl:
16608 case Builtin::BI__builtin_ffsll: {
16609 APSInt Val;
16610 if (!EvaluateInteger(E->getArg(0), Val, Info))
16611 return false;
16612
16613 unsigned N = Val.countr_zero();
16614 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
16615 }
16616
16617 case Builtin::BI__builtin_fpclassify: {
16618 APFloat Val(0.0);
16619 if (!EvaluateFloat(E->getArg(5), Val, Info))
16620 return false;
16621 unsigned Arg;
16622 switch (Val.getCategory()) {
16623 case APFloat::fcNaN: Arg = 0; break;
16624 case APFloat::fcInfinity: Arg = 1; break;
16625 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
16626 case APFloat::fcZero: Arg = 4; break;
16627 }
16628 return Visit(E->getArg(Arg));
16629 }
16630
16631 case Builtin::BI__builtin_isinf_sign: {
16632 APFloat Val(0.0);
16633 return EvaluateFloat(E->getArg(0), Val, Info) &&
16634 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
16635 }
16636
16637 case Builtin::BI__builtin_isinf: {
16638 APFloat Val(0.0);
16639 return EvaluateFloat(E->getArg(0), Val, Info) &&
16640 Success(Val.isInfinity() ? 1 : 0, E);
16641 }
16642
16643 case Builtin::BI__builtin_isfinite: {
16644 APFloat Val(0.0);
16645 return EvaluateFloat(E->getArg(0), Val, Info) &&
16646 Success(Val.isFinite() ? 1 : 0, E);
16647 }
16648
16649 case Builtin::BI__builtin_isnan: {
16650 APFloat Val(0.0);
16651 return EvaluateFloat(E->getArg(0), Val, Info) &&
16652 Success(Val.isNaN() ? 1 : 0, E);
16653 }
16654
16655 case Builtin::BI__builtin_isnormal: {
16656 APFloat Val(0.0);
16657 return EvaluateFloat(E->getArg(0), Val, Info) &&
16658 Success(Val.isNormal() ? 1 : 0, E);
16659 }
16660
16661 case Builtin::BI__builtin_issubnormal: {
16662 APFloat Val(0.0);
16663 return EvaluateFloat(E->getArg(0), Val, Info) &&
16664 Success(Val.isDenormal() ? 1 : 0, E);
16665 }
16666
16667 case Builtin::BI__builtin_iszero: {
16668 APFloat Val(0.0);
16669 return EvaluateFloat(E->getArg(0), Val, Info) &&
16670 Success(Val.isZero() ? 1 : 0, E);
16671 }
16672
16673 case Builtin::BI__builtin_signbit:
16674 case Builtin::BI__builtin_signbitf:
16675 case Builtin::BI__builtin_signbitl: {
16676 APFloat Val(0.0);
16677 return EvaluateFloat(E->getArg(0), Val, Info) &&
16678 Success(Val.isNegative() ? 1 : 0, E);
16679 }
16680
16681 case Builtin::BI__builtin_isgreater:
16682 case Builtin::BI__builtin_isgreaterequal:
16683 case Builtin::BI__builtin_isless:
16684 case Builtin::BI__builtin_islessequal:
16685 case Builtin::BI__builtin_islessgreater:
16686 case Builtin::BI__builtin_isunordered: {
16687 APFloat LHS(0.0);
16688 APFloat RHS(0.0);
16689 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
16690 !EvaluateFloat(E->getArg(1), RHS, Info))
16691 return false;
16692
16693 return Success(
16694 [&] {
16695 switch (BuiltinOp) {
16696 case Builtin::BI__builtin_isgreater:
16697 return LHS > RHS;
16698 case Builtin::BI__builtin_isgreaterequal:
16699 return LHS >= RHS;
16700 case Builtin::BI__builtin_isless:
16701 return LHS < RHS;
16702 case Builtin::BI__builtin_islessequal:
16703 return LHS <= RHS;
16704 case Builtin::BI__builtin_islessgreater: {
16705 APFloat::cmpResult cmp = LHS.compare(RHS);
16706 return cmp == APFloat::cmpResult::cmpLessThan ||
16707 cmp == APFloat::cmpResult::cmpGreaterThan;
16708 }
16709 case Builtin::BI__builtin_isunordered:
16710 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
16711 default:
16712 llvm_unreachable("Unexpected builtin ID: Should be a floating "
16713 "point comparison function");
16714 }
16715 }()
16716 ? 1
16717 : 0,
16718 E);
16719 }
16720
16721 case Builtin::BI__builtin_issignaling: {
16722 APFloat Val(0.0);
16723 return EvaluateFloat(E->getArg(0), Val, Info) &&
16724 Success(Val.isSignaling() ? 1 : 0, E);
16725 }
16726
16727 case Builtin::BI__builtin_isfpclass: {
16728 APSInt MaskVal;
16729 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
16730 return false;
16731 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
16732 APFloat Val(0.0);
16733 return EvaluateFloat(E->getArg(0), Val, Info) &&
16734 Success((Val.classify() & Test) ? 1 : 0, E);
16735 }
16736
16737 case Builtin::BI__builtin_parity:
16738 case Builtin::BI__builtin_parityl:
16739 case Builtin::BI__builtin_parityll: {
16740 APSInt Val;
16741 if (!EvaluateInteger(E->getArg(0), Val, Info))
16742 return false;
16743
16744 return Success(Val.popcount() % 2, E);
16745 }
16746
16747 case Builtin::BI__builtin_abs:
16748 case Builtin::BI__builtin_labs:
16749 case Builtin::BI__builtin_llabs: {
16750 APSInt Val;
16751 if (!EvaluateInteger(E->getArg(0), Val, Info))
16752 return false;
16753 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
16754 /*IsUnsigned=*/false))
16755 return false;
16756 if (Val.isNegative())
16757 Val.negate();
16758 return Success(Val, E);
16759 }
16760
16761 case Builtin::BI__builtin_popcount:
16762 case Builtin::BI__builtin_popcountl:
16763 case Builtin::BI__builtin_popcountll:
16764 case Builtin::BI__builtin_popcountg:
16765 case Builtin::BI__builtin_elementwise_popcount:
16766 case Builtin::BI__popcnt16: // Microsoft variants of popcount
16767 case Builtin::BI__popcnt:
16768 case Builtin::BI__popcnt64: {
16769 APSInt Val;
16770 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16771 APValue Vec;
16772 if (!EvaluateVector(E->getArg(0), Vec, Info))
16773 return false;
16774 Val = ConvertBoolVectorToInt(Vec);
16775 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16776 return false;
16777 }
16778
16779 return Success(Val.popcount(), E);
16780 }
16781
16782 case Builtin::BI__builtin_rotateleft8:
16783 case Builtin::BI__builtin_rotateleft16:
16784 case Builtin::BI__builtin_rotateleft32:
16785 case Builtin::BI__builtin_rotateleft64:
16786 case Builtin::BI__builtin_rotateright8:
16787 case Builtin::BI__builtin_rotateright16:
16788 case Builtin::BI__builtin_rotateright32:
16789 case Builtin::BI__builtin_rotateright64:
16790 case Builtin::BI__builtin_stdc_rotate_left:
16791 case Builtin::BI__builtin_stdc_rotate_right:
16792 case Builtin::BI_rotl8: // Microsoft variants of rotate left
16793 case Builtin::BI_rotl16:
16794 case Builtin::BI_rotl:
16795 case Builtin::BI_lrotl:
16796 case Builtin::BI_rotl64:
16797 case Builtin::BI_rotr8: // Microsoft variants of rotate right
16798 case Builtin::BI_rotr16:
16799 case Builtin::BI_rotr:
16800 case Builtin::BI_lrotr:
16801 case Builtin::BI_rotr64: {
16802 APSInt Value, Amount;
16803 if (!EvaluateInteger(E->getArg(0), Value, Info) ||
16804 !EvaluateInteger(E->getArg(1), Amount, Info))
16805 return false;
16806
16807 Amount = NormalizeRotateAmount(Value, Amount);
16808
16809 switch (BuiltinOp) {
16810 case Builtin::BI__builtin_rotateright8:
16811 case Builtin::BI__builtin_rotateright16:
16812 case Builtin::BI__builtin_rotateright32:
16813 case Builtin::BI__builtin_rotateright64:
16814 case Builtin::BI__builtin_stdc_rotate_right:
16815 case Builtin::BI_rotr8:
16816 case Builtin::BI_rotr16:
16817 case Builtin::BI_rotr:
16818 case Builtin::BI_lrotr:
16819 case Builtin::BI_rotr64:
16820 return Success(
16821 APSInt(Value.rotr(Amount.getZExtValue()), Value.isUnsigned()), E);
16822 default:
16823 return Success(
16824 APSInt(Value.rotl(Amount.getZExtValue()), Value.isUnsigned()), E);
16825 }
16826 }
16827
16828 case Builtin::BI__builtin_elementwise_add_sat: {
16829 APSInt LHS, RHS;
16830 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16831 !EvaluateInteger(E->getArg(1), RHS, Info))
16832 return false;
16833
16834 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
16835 return Success(APSInt(Result, !LHS.isSigned()), E);
16836 }
16837 case Builtin::BI__builtin_elementwise_sub_sat: {
16838 APSInt LHS, RHS;
16839 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16840 !EvaluateInteger(E->getArg(1), RHS, Info))
16841 return false;
16842
16843 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
16844 return Success(APSInt(Result, !LHS.isSigned()), E);
16845 }
16846 case Builtin::BI__builtin_elementwise_max: {
16847 APSInt LHS, RHS;
16848 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16849 !EvaluateInteger(E->getArg(1), RHS, Info))
16850 return false;
16851
16852 APInt Result = std::max(LHS, RHS);
16853 return Success(APSInt(Result, !LHS.isSigned()), E);
16854 }
16855 case Builtin::BI__builtin_elementwise_min: {
16856 APSInt LHS, RHS;
16857 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
16858 !EvaluateInteger(E->getArg(1), RHS, Info))
16859 return false;
16860
16861 APInt Result = std::min(LHS, RHS);
16862 return Success(APSInt(Result, !LHS.isSigned()), E);
16863 }
16864 case Builtin::BI__builtin_elementwise_fshl:
16865 case Builtin::BI__builtin_elementwise_fshr: {
16866 APSInt Hi, Lo, Shift;
16867 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
16868 !EvaluateInteger(E->getArg(1), Lo, Info) ||
16869 !EvaluateInteger(E->getArg(2), Shift, Info))
16870 return false;
16871
16872 switch (BuiltinOp) {
16873 case Builtin::BI__builtin_elementwise_fshl: {
16874 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
16875 return Success(Result, E);
16876 }
16877 case Builtin::BI__builtin_elementwise_fshr: {
16878 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
16879 return Success(Result, E);
16880 }
16881 }
16882 llvm_unreachable("Fully covered switch above");
16883 }
16884 case Builtin::BIstrlen:
16885 case Builtin::BIwcslen:
16886 // A call to strlen is not a constant expression.
16887 if (Info.getLangOpts().CPlusPlus11)
16888 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
16889 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
16890 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
16891 else
16892 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
16893 [[fallthrough]];
16894 case Builtin::BI__builtin_strlen:
16895 case Builtin::BI__builtin_wcslen: {
16896 // As an extension, we support __builtin_strlen() as a constant expression,
16897 // and support folding strlen() to a constant.
16898 if (std::optional<uint64_t> StrLen =
16899 EvaluateBuiltinStrLen(E->getArg(0), Info))
16900 return Success(*StrLen, E);
16901 return false;
16902 }
16903
16904 case Builtin::BIstrcmp:
16905 case Builtin::BIwcscmp:
16906 case Builtin::BIstrncmp:
16907 case Builtin::BIwcsncmp:
16908 case Builtin::BImemcmp:
16909 case Builtin::BIbcmp:
16910 case Builtin::BIwmemcmp:
16911 // A call to strlen is not a constant expression.
16912 if (Info.getLangOpts().CPlusPlus11)
16913 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
16914 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
16915 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
16916 else
16917 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
16918 [[fallthrough]];
16919 case Builtin::BI__builtin_strcmp:
16920 case Builtin::BI__builtin_wcscmp:
16921 case Builtin::BI__builtin_strncmp:
16922 case Builtin::BI__builtin_wcsncmp:
16923 case Builtin::BI__builtin_memcmp:
16924 case Builtin::BI__builtin_bcmp:
16925 case Builtin::BI__builtin_wmemcmp: {
16926 LValue String1, String2;
16927 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
16928 !EvaluatePointer(E->getArg(1), String2, Info))
16929 return false;
16930
16931 uint64_t MaxLength = uint64_t(-1);
16932 if (BuiltinOp != Builtin::BIstrcmp &&
16933 BuiltinOp != Builtin::BIwcscmp &&
16934 BuiltinOp != Builtin::BI__builtin_strcmp &&
16935 BuiltinOp != Builtin::BI__builtin_wcscmp) {
16936 APSInt N;
16937 if (!EvaluateInteger(E->getArg(2), N, Info))
16938 return false;
16939 MaxLength = N.getZExtValue();
16940 }
16941
16942 // Empty substrings compare equal by definition.
16943 if (MaxLength == 0u)
16944 return Success(0, E);
16945
16946 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
16947 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
16948 String1.Designator.Invalid || String2.Designator.Invalid)
16949 return false;
16950
16951 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
16952 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
16953
16954 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
16955 BuiltinOp == Builtin::BIbcmp ||
16956 BuiltinOp == Builtin::BI__builtin_memcmp ||
16957 BuiltinOp == Builtin::BI__builtin_bcmp;
16958
16959 assert(IsRawByte ||
16960 (Info.Ctx.hasSameUnqualifiedType(
16961 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
16962 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
16963
16964 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
16965 // 'char8_t', but no other types.
16966 if (IsRawByte &&
16967 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
16968 // FIXME: Consider using our bit_cast implementation to support this.
16969 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
16970 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
16971 << CharTy2;
16972 return false;
16973 }
16974
16975 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
16976 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
16977 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
16978 Char1.isInt() && Char2.isInt();
16979 };
16980 const auto &AdvanceElems = [&] {
16981 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
16982 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
16983 };
16984
16985 bool StopAtNull =
16986 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
16987 BuiltinOp != Builtin::BIwmemcmp &&
16988 BuiltinOp != Builtin::BI__builtin_memcmp &&
16989 BuiltinOp != Builtin::BI__builtin_bcmp &&
16990 BuiltinOp != Builtin::BI__builtin_wmemcmp);
16991 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
16992 BuiltinOp == Builtin::BIwcsncmp ||
16993 BuiltinOp == Builtin::BIwmemcmp ||
16994 BuiltinOp == Builtin::BI__builtin_wcscmp ||
16995 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
16996 BuiltinOp == Builtin::BI__builtin_wmemcmp;
16997
16998 for (; MaxLength; --MaxLength) {
16999 APValue Char1, Char2;
17000 if (!ReadCurElems(Char1, Char2))
17001 return false;
17002 if (Char1.getInt().ne(Char2.getInt())) {
17003 if (IsWide) // wmemcmp compares with wchar_t signedness.
17004 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
17005 // memcmp always compares unsigned chars.
17006 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
17007 }
17008 if (StopAtNull && !Char1.getInt())
17009 return Success(0, E);
17010 assert(!(StopAtNull && !Char2.getInt()));
17011 if (!AdvanceElems())
17012 return false;
17013 }
17014 // We hit the strncmp / memcmp limit.
17015 return Success(0, E);
17016 }
17017
17018 case Builtin::BI__atomic_always_lock_free:
17019 case Builtin::BI__atomic_is_lock_free:
17020 case Builtin::BI__c11_atomic_is_lock_free: {
17021 APSInt SizeVal;
17022 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
17023 return false;
17024
17025 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
17026 // of two less than or equal to the maximum inline atomic width, we know it
17027 // is lock-free. If the size isn't a power of two, or greater than the
17028 // maximum alignment where we promote atomics, we know it is not lock-free
17029 // (at least not in the sense of atomic_is_lock_free). Otherwise,
17030 // the answer can only be determined at runtime; for example, 16-byte
17031 // atomics have lock-free implementations on some, but not all,
17032 // x86-64 processors.
17033
17034 // Check power-of-two.
17035 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
17036 if (Size.isPowerOfTwo()) {
17037 // Check against inlining width.
17038 unsigned InlineWidthBits =
17039 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
17040 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
17041 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
17042 Size == CharUnits::One())
17043 return Success(1, E);
17044
17045 // If the pointer argument can be evaluated to a compile-time constant
17046 // integer (or nullptr), check if that value is appropriately aligned.
17047 const Expr *PtrArg = E->getArg(1);
17048 Expr::EvalResult ExprResult;
17049 APSInt IntResult;
17050 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
17051 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
17052 Info.Ctx) &&
17053 IntResult.isAligned(Size.getAsAlign()))
17054 return Success(1, E);
17055
17056 // Otherwise, check if the type's alignment against Size.
17057 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
17058 // Drop the potential implicit-cast to 'const volatile void*', getting
17059 // the underlying type.
17060 if (ICE->getCastKind() == CK_BitCast)
17061 PtrArg = ICE->getSubExpr();
17062 }
17063
17064 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
17065 QualType PointeeType = PtrTy->getPointeeType();
17066 if (!PointeeType->isIncompleteType() &&
17067 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
17068 // OK, we will inline operations on this object.
17069 return Success(1, E);
17070 }
17071 }
17072 }
17073 }
17074
17075 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
17076 Success(0, E) : Error(E);
17077 }
17078 case Builtin::BI__builtin_addcb:
17079 case Builtin::BI__builtin_addcs:
17080 case Builtin::BI__builtin_addc:
17081 case Builtin::BI__builtin_addcl:
17082 case Builtin::BI__builtin_addcll:
17083 case Builtin::BI__builtin_subcb:
17084 case Builtin::BI__builtin_subcs:
17085 case Builtin::BI__builtin_subc:
17086 case Builtin::BI__builtin_subcl:
17087 case Builtin::BI__builtin_subcll: {
17088 LValue CarryOutLValue;
17089 APSInt LHS, RHS, CarryIn, CarryOut, Result;
17090 QualType ResultType = E->getArg(0)->getType();
17091 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17092 !EvaluateInteger(E->getArg(1), RHS, Info) ||
17093 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
17094 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
17095 return false;
17096 // Copy the number of bits and sign.
17097 Result = LHS;
17098 CarryOut = LHS;
17099
17100 bool FirstOverflowed = false;
17101 bool SecondOverflowed = false;
17102 switch (BuiltinOp) {
17103 default:
17104 llvm_unreachable("Invalid value for BuiltinOp");
17105 case Builtin::BI__builtin_addcb:
17106 case Builtin::BI__builtin_addcs:
17107 case Builtin::BI__builtin_addc:
17108 case Builtin::BI__builtin_addcl:
17109 case Builtin::BI__builtin_addcll:
17110 Result =
17111 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
17112 break;
17113 case Builtin::BI__builtin_subcb:
17114 case Builtin::BI__builtin_subcs:
17115 case Builtin::BI__builtin_subc:
17116 case Builtin::BI__builtin_subcl:
17117 case Builtin::BI__builtin_subcll:
17118 Result =
17119 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
17120 break;
17121 }
17122
17123 // It is possible for both overflows to happen but CGBuiltin uses an OR so
17124 // this is consistent.
17125 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
17126 APValue APV{CarryOut};
17127 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
17128 return false;
17129 return Success(Result, E);
17130 }
17131 case Builtin::BI__builtin_add_overflow:
17132 case Builtin::BI__builtin_sub_overflow:
17133 case Builtin::BI__builtin_mul_overflow:
17134 case Builtin::BI__builtin_sadd_overflow:
17135 case Builtin::BI__builtin_uadd_overflow:
17136 case Builtin::BI__builtin_uaddl_overflow:
17137 case Builtin::BI__builtin_uaddll_overflow:
17138 case Builtin::BI__builtin_usub_overflow:
17139 case Builtin::BI__builtin_usubl_overflow:
17140 case Builtin::BI__builtin_usubll_overflow:
17141 case Builtin::BI__builtin_umul_overflow:
17142 case Builtin::BI__builtin_umull_overflow:
17143 case Builtin::BI__builtin_umulll_overflow:
17144 case Builtin::BI__builtin_saddl_overflow:
17145 case Builtin::BI__builtin_saddll_overflow:
17146 case Builtin::BI__builtin_ssub_overflow:
17147 case Builtin::BI__builtin_ssubl_overflow:
17148 case Builtin::BI__builtin_ssubll_overflow:
17149 case Builtin::BI__builtin_smul_overflow:
17150 case Builtin::BI__builtin_smull_overflow:
17151 case Builtin::BI__builtin_smulll_overflow: {
17152 LValue ResultLValue;
17153 APSInt LHS, RHS;
17154
17155 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
17156 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17157 !EvaluateInteger(E->getArg(1), RHS, Info) ||
17158 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
17159 return false;
17160
17161 APSInt Result;
17162 bool DidOverflow = false;
17163
17164 // If the types don't have to match, enlarge all 3 to the largest of them.
17165 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
17166 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
17167 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
17168 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
17170 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
17172 uint64_t LHSSize = LHS.getBitWidth();
17173 uint64_t RHSSize = RHS.getBitWidth();
17174 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
17175 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
17176
17177 // Add an additional bit if the signedness isn't uniformly agreed to. We
17178 // could do this ONLY if there is a signed and an unsigned that both have
17179 // MaxBits, but the code to check that is pretty nasty. The issue will be
17180 // caught in the shrink-to-result later anyway.
17181 if (IsSigned && !AllSigned)
17182 ++MaxBits;
17183
17184 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
17185 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
17186 Result = APSInt(MaxBits, !IsSigned);
17187 }
17188
17189 // Find largest int.
17190 switch (BuiltinOp) {
17191 default:
17192 llvm_unreachable("Invalid value for BuiltinOp");
17193 case Builtin::BI__builtin_add_overflow:
17194 case Builtin::BI__builtin_sadd_overflow:
17195 case Builtin::BI__builtin_saddl_overflow:
17196 case Builtin::BI__builtin_saddll_overflow:
17197 case Builtin::BI__builtin_uadd_overflow:
17198 case Builtin::BI__builtin_uaddl_overflow:
17199 case Builtin::BI__builtin_uaddll_overflow:
17200 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
17201 : LHS.uadd_ov(RHS, DidOverflow);
17202 break;
17203 case Builtin::BI__builtin_sub_overflow:
17204 case Builtin::BI__builtin_ssub_overflow:
17205 case Builtin::BI__builtin_ssubl_overflow:
17206 case Builtin::BI__builtin_ssubll_overflow:
17207 case Builtin::BI__builtin_usub_overflow:
17208 case Builtin::BI__builtin_usubl_overflow:
17209 case Builtin::BI__builtin_usubll_overflow:
17210 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
17211 : LHS.usub_ov(RHS, DidOverflow);
17212 break;
17213 case Builtin::BI__builtin_mul_overflow:
17214 case Builtin::BI__builtin_smul_overflow:
17215 case Builtin::BI__builtin_smull_overflow:
17216 case Builtin::BI__builtin_smulll_overflow:
17217 case Builtin::BI__builtin_umul_overflow:
17218 case Builtin::BI__builtin_umull_overflow:
17219 case Builtin::BI__builtin_umulll_overflow:
17220 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
17221 : LHS.umul_ov(RHS, DidOverflow);
17222 break;
17223 }
17224
17225 // In the case where multiple sizes are allowed, truncate and see if
17226 // the values are the same.
17227 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
17228 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
17229 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
17230 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
17231 // since it will give us the behavior of a TruncOrSelf in the case where
17232 // its parameter <= its size. We previously set Result to be at least the
17233 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
17234 // will work exactly like TruncOrSelf.
17235 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
17236 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
17237
17238 if (!APSInt::isSameValue(Temp, Result))
17239 DidOverflow = true;
17240 Result = Temp;
17241 }
17242
17243 APValue APV{Result};
17244 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
17245 return false;
17246 return Success(DidOverflow, E);
17247 }
17248
17249 case Builtin::BI__builtin_reduce_add:
17250 case Builtin::BI__builtin_reduce_mul:
17251 case Builtin::BI__builtin_reduce_and:
17252 case Builtin::BI__builtin_reduce_or:
17253 case Builtin::BI__builtin_reduce_xor:
17254 case Builtin::BI__builtin_reduce_min:
17255 case Builtin::BI__builtin_reduce_max: {
17256 APValue Source;
17257 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
17258 return false;
17259
17260 unsigned SourceLen = Source.getVectorLength();
17261 APSInt Reduced = Source.getVectorElt(0).getInt();
17262 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
17263 switch (BuiltinOp) {
17264 default:
17265 return false;
17266 case Builtin::BI__builtin_reduce_add: {
17268 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
17269 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
17270 return false;
17271 break;
17272 }
17273 case Builtin::BI__builtin_reduce_mul: {
17275 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
17276 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
17277 return false;
17278 break;
17279 }
17280 case Builtin::BI__builtin_reduce_and: {
17281 Reduced &= Source.getVectorElt(EltNum).getInt();
17282 break;
17283 }
17284 case Builtin::BI__builtin_reduce_or: {
17285 Reduced |= Source.getVectorElt(EltNum).getInt();
17286 break;
17287 }
17288 case Builtin::BI__builtin_reduce_xor: {
17289 Reduced ^= Source.getVectorElt(EltNum).getInt();
17290 break;
17291 }
17292 case Builtin::BI__builtin_reduce_min: {
17293 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
17294 break;
17295 }
17296 case Builtin::BI__builtin_reduce_max: {
17297 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
17298 break;
17299 }
17300 }
17301 }
17302
17303 return Success(Reduced, E);
17304 }
17305
17306 case clang::X86::BI__builtin_ia32_addcarryx_u32:
17307 case clang::X86::BI__builtin_ia32_addcarryx_u64:
17308 case clang::X86::BI__builtin_ia32_subborrow_u32:
17309 case clang::X86::BI__builtin_ia32_subborrow_u64: {
17310 LValue ResultLValue;
17311 APSInt CarryIn, LHS, RHS;
17312 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
17313 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
17314 !EvaluateInteger(E->getArg(1), LHS, Info) ||
17315 !EvaluateInteger(E->getArg(2), RHS, Info) ||
17316 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
17317 return false;
17318
17319 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
17320 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
17321
17322 unsigned BitWidth = LHS.getBitWidth();
17323 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
17324 APInt ExResult =
17325 IsAdd
17326 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
17327 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
17328
17329 APInt Result = ExResult.extractBits(BitWidth, 0);
17330 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
17331
17332 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
17333 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
17334 return false;
17335 return Success(CarryOut, E);
17336 }
17337
17338 case clang::X86::BI__builtin_ia32_movmskps:
17339 case clang::X86::BI__builtin_ia32_movmskpd:
17340 case clang::X86::BI__builtin_ia32_pmovmskb128:
17341 case clang::X86::BI__builtin_ia32_pmovmskb256:
17342 case clang::X86::BI__builtin_ia32_movmskps256:
17343 case clang::X86::BI__builtin_ia32_movmskpd256: {
17344 APValue Source;
17345 if (!Evaluate(Source, Info, E->getArg(0)))
17346 return false;
17347 unsigned SourceLen = Source.getVectorLength();
17348 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
17349 QualType ElemQT = VT->getElementType();
17350 unsigned ResultLen = Info.Ctx.getTypeSize(
17351 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
17352 APInt Result(ResultLen, 0);
17353
17354 for (unsigned I = 0; I != SourceLen; ++I) {
17355 APInt Elem;
17356 if (ElemQT->isIntegerType()) {
17357 Elem = Source.getVectorElt(I).getInt();
17358 } else if (ElemQT->isRealFloatingType()) {
17359 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
17360 } else {
17361 return false;
17362 }
17363 Result.setBitVal(I, Elem.isNegative());
17364 }
17365 return Success(Result, E);
17366 }
17367
17368 case clang::X86::BI__builtin_ia32_bextr_u32:
17369 case clang::X86::BI__builtin_ia32_bextr_u64:
17370 case clang::X86::BI__builtin_ia32_bextri_u32:
17371 case clang::X86::BI__builtin_ia32_bextri_u64: {
17372 APSInt Val, Idx;
17373 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17374 !EvaluateInteger(E->getArg(1), Idx, Info))
17375 return false;
17376
17377 unsigned BitWidth = Val.getBitWidth();
17378 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
17379 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
17380 Length = Length > BitWidth ? BitWidth : Length;
17381
17382 // Handle out of bounds cases.
17383 if (Length == 0 || Shift >= BitWidth)
17384 return Success(0, E);
17385
17386 uint64_t Result = Val.getZExtValue() >> Shift;
17387 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
17388 return Success(Result, E);
17389 }
17390
17391 case clang::X86::BI__builtin_ia32_bzhi_si:
17392 case clang::X86::BI__builtin_ia32_bzhi_di: {
17393 APSInt Val, Idx;
17394 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17395 !EvaluateInteger(E->getArg(1), Idx, Info))
17396 return false;
17397
17398 unsigned BitWidth = Val.getBitWidth();
17399 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
17400 if (Index < BitWidth)
17401 Val.clearHighBits(BitWidth - Index);
17402 return Success(Val, E);
17403 }
17404
17405 case clang::X86::BI__builtin_ia32_ktestcqi:
17406 case clang::X86::BI__builtin_ia32_ktestchi:
17407 case clang::X86::BI__builtin_ia32_ktestcsi:
17408 case clang::X86::BI__builtin_ia32_ktestcdi: {
17409 APSInt A, B;
17410 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17411 !EvaluateInteger(E->getArg(1), B, Info))
17412 return false;
17413
17414 return Success((~A & B) == 0, E);
17415 }
17416
17417 case clang::X86::BI__builtin_ia32_ktestzqi:
17418 case clang::X86::BI__builtin_ia32_ktestzhi:
17419 case clang::X86::BI__builtin_ia32_ktestzsi:
17420 case clang::X86::BI__builtin_ia32_ktestzdi: {
17421 APSInt A, B;
17422 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17423 !EvaluateInteger(E->getArg(1), B, Info))
17424 return false;
17425
17426 return Success((A & B) == 0, E);
17427 }
17428
17429 case clang::X86::BI__builtin_ia32_kortestcqi:
17430 case clang::X86::BI__builtin_ia32_kortestchi:
17431 case clang::X86::BI__builtin_ia32_kortestcsi:
17432 case clang::X86::BI__builtin_ia32_kortestcdi: {
17433 APSInt A, B;
17434 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17435 !EvaluateInteger(E->getArg(1), B, Info))
17436 return false;
17437
17438 return Success(~(A | B) == 0, E);
17439 }
17440
17441 case clang::X86::BI__builtin_ia32_kortestzqi:
17442 case clang::X86::BI__builtin_ia32_kortestzhi:
17443 case clang::X86::BI__builtin_ia32_kortestzsi:
17444 case clang::X86::BI__builtin_ia32_kortestzdi: {
17445 APSInt A, B;
17446 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17447 !EvaluateInteger(E->getArg(1), B, Info))
17448 return false;
17449
17450 return Success((A | B) == 0, E);
17451 }
17452
17453 case clang::X86::BI__builtin_ia32_kunpckhi:
17454 case clang::X86::BI__builtin_ia32_kunpckdi:
17455 case clang::X86::BI__builtin_ia32_kunpcksi: {
17456 APSInt A, B;
17457 if (!EvaluateInteger(E->getArg(0), A, Info) ||
17458 !EvaluateInteger(E->getArg(1), B, Info))
17459 return false;
17460
17461 // Generic kunpack: extract lower half of each operand and concatenate
17462 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
17463 unsigned BW = A.getBitWidth();
17464 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
17465 return Success(Result, E);
17466 }
17467
17468 case clang::X86::BI__builtin_ia32_lzcnt_u16:
17469 case clang::X86::BI__builtin_ia32_lzcnt_u32:
17470 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
17471 APSInt Val;
17472 if (!EvaluateInteger(E->getArg(0), Val, Info))
17473 return false;
17474 return Success(Val.countLeadingZeros(), E);
17475 }
17476
17477 case clang::X86::BI__builtin_ia32_tzcnt_u16:
17478 case clang::X86::BI__builtin_ia32_tzcnt_u32:
17479 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
17480 APSInt Val;
17481 if (!EvaluateInteger(E->getArg(0), Val, Info))
17482 return false;
17483 return Success(Val.countTrailingZeros(), E);
17484 }
17485
17486 case clang::X86::BI__builtin_ia32_pdep_si:
17487 case clang::X86::BI__builtin_ia32_pdep_di: {
17488 APSInt Val, Msk;
17489 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17490 !EvaluateInteger(E->getArg(1), Msk, Info))
17491 return false;
17492
17493 unsigned BitWidth = Val.getBitWidth();
17494 APInt Result = APInt::getZero(BitWidth);
17495 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
17496 if (Msk[I])
17497 Result.setBitVal(I, Val[P++]);
17498 return Success(Result, E);
17499 }
17500
17501 case clang::X86::BI__builtin_ia32_pext_si:
17502 case clang::X86::BI__builtin_ia32_pext_di: {
17503 APSInt Val, Msk;
17504 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
17505 !EvaluateInteger(E->getArg(1), Msk, Info))
17506 return false;
17507
17508 unsigned BitWidth = Val.getBitWidth();
17509 APInt Result = APInt::getZero(BitWidth);
17510 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
17511 if (Msk[I])
17512 Result.setBitVal(P++, Val[I]);
17513 return Success(Result, E);
17514 }
17515 case X86::BI__builtin_ia32_ptestz128:
17516 case X86::BI__builtin_ia32_ptestz256:
17517 case X86::BI__builtin_ia32_vtestzps:
17518 case X86::BI__builtin_ia32_vtestzps256:
17519 case X86::BI__builtin_ia32_vtestzpd:
17520 case X86::BI__builtin_ia32_vtestzpd256: {
17521 return EvalTestOp(
17522 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
17523 }
17524 case X86::BI__builtin_ia32_ptestc128:
17525 case X86::BI__builtin_ia32_ptestc256:
17526 case X86::BI__builtin_ia32_vtestcps:
17527 case X86::BI__builtin_ia32_vtestcps256:
17528 case X86::BI__builtin_ia32_vtestcpd:
17529 case X86::BI__builtin_ia32_vtestcpd256: {
17530 return EvalTestOp(
17531 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
17532 }
17533 case X86::BI__builtin_ia32_ptestnzc128:
17534 case X86::BI__builtin_ia32_ptestnzc256:
17535 case X86::BI__builtin_ia32_vtestnzcps:
17536 case X86::BI__builtin_ia32_vtestnzcps256:
17537 case X86::BI__builtin_ia32_vtestnzcpd:
17538 case X86::BI__builtin_ia32_vtestnzcpd256: {
17539 return EvalTestOp([](const APInt &A, const APInt &B) {
17540 return ((A & B) != 0) && ((~A & B) != 0);
17541 });
17542 }
17543 case X86::BI__builtin_ia32_kandqi:
17544 case X86::BI__builtin_ia32_kandhi:
17545 case X86::BI__builtin_ia32_kandsi:
17546 case X86::BI__builtin_ia32_kanddi: {
17547 return HandleMaskBinOp(
17548 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
17549 }
17550
17551 case X86::BI__builtin_ia32_kandnqi:
17552 case X86::BI__builtin_ia32_kandnhi:
17553 case X86::BI__builtin_ia32_kandnsi:
17554 case X86::BI__builtin_ia32_kandndi: {
17555 return HandleMaskBinOp(
17556 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
17557 }
17558
17559 case X86::BI__builtin_ia32_korqi:
17560 case X86::BI__builtin_ia32_korhi:
17561 case X86::BI__builtin_ia32_korsi:
17562 case X86::BI__builtin_ia32_kordi: {
17563 return HandleMaskBinOp(
17564 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
17565 }
17566
17567 case X86::BI__builtin_ia32_kxnorqi:
17568 case X86::BI__builtin_ia32_kxnorhi:
17569 case X86::BI__builtin_ia32_kxnorsi:
17570 case X86::BI__builtin_ia32_kxnordi: {
17571 return HandleMaskBinOp(
17572 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
17573 }
17574
17575 case X86::BI__builtin_ia32_kxorqi:
17576 case X86::BI__builtin_ia32_kxorhi:
17577 case X86::BI__builtin_ia32_kxorsi:
17578 case X86::BI__builtin_ia32_kxordi: {
17579 return HandleMaskBinOp(
17580 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
17581 }
17582
17583 case X86::BI__builtin_ia32_knotqi:
17584 case X86::BI__builtin_ia32_knothi:
17585 case X86::BI__builtin_ia32_knotsi:
17586 case X86::BI__builtin_ia32_knotdi: {
17587 APSInt Val;
17588 if (!EvaluateInteger(E->getArg(0), Val, Info))
17589 return false;
17590 APSInt Result = ~Val;
17591 return Success(APValue(Result), E);
17592 }
17593
17594 case X86::BI__builtin_ia32_kaddqi:
17595 case X86::BI__builtin_ia32_kaddhi:
17596 case X86::BI__builtin_ia32_kaddsi:
17597 case X86::BI__builtin_ia32_kadddi: {
17598 return HandleMaskBinOp(
17599 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
17600 }
17601
17602 case X86::BI__builtin_ia32_kmovb:
17603 case X86::BI__builtin_ia32_kmovw:
17604 case X86::BI__builtin_ia32_kmovd:
17605 case X86::BI__builtin_ia32_kmovq: {
17606 APSInt Val;
17607 if (!EvaluateInteger(E->getArg(0), Val, Info))
17608 return false;
17609 return Success(Val, E);
17610 }
17611
17612 case X86::BI__builtin_ia32_kshiftliqi:
17613 case X86::BI__builtin_ia32_kshiftlihi:
17614 case X86::BI__builtin_ia32_kshiftlisi:
17615 case X86::BI__builtin_ia32_kshiftlidi: {
17616 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
17617 unsigned Amt = RHS.getZExtValue() & 0xFF;
17618 if (Amt >= LHS.getBitWidth())
17619 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
17620 return APSInt(LHS.shl(Amt), LHS.isUnsigned());
17621 });
17622 }
17623
17624 case X86::BI__builtin_ia32_kshiftriqi:
17625 case X86::BI__builtin_ia32_kshiftrihi:
17626 case X86::BI__builtin_ia32_kshiftrisi:
17627 case X86::BI__builtin_ia32_kshiftridi: {
17628 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
17629 unsigned Amt = RHS.getZExtValue() & 0xFF;
17630 if (Amt >= LHS.getBitWidth())
17631 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
17632 return APSInt(LHS.lshr(Amt), LHS.isUnsigned());
17633 });
17634 }
17635
17636 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
17637 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
17638 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
17639 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
17640 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
17641 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
17642 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
17643 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
17644 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
17645 APValue Vec;
17646 APSInt IdxAPS;
17647 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
17648 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
17649 return false;
17650 unsigned N = Vec.getVectorLength();
17651 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
17652 return Success(Vec.getVectorElt(Idx).getInt(), E);
17653 }
17654
17655 case clang::X86::BI__builtin_ia32_cvtb2mask128:
17656 case clang::X86::BI__builtin_ia32_cvtb2mask256:
17657 case clang::X86::BI__builtin_ia32_cvtb2mask512:
17658 case clang::X86::BI__builtin_ia32_cvtw2mask128:
17659 case clang::X86::BI__builtin_ia32_cvtw2mask256:
17660 case clang::X86::BI__builtin_ia32_cvtw2mask512:
17661 case clang::X86::BI__builtin_ia32_cvtd2mask128:
17662 case clang::X86::BI__builtin_ia32_cvtd2mask256:
17663 case clang::X86::BI__builtin_ia32_cvtd2mask512:
17664 case clang::X86::BI__builtin_ia32_cvtq2mask128:
17665 case clang::X86::BI__builtin_ia32_cvtq2mask256:
17666 case clang::X86::BI__builtin_ia32_cvtq2mask512: {
17667 assert(E->getNumArgs() == 1);
17668 APValue Vec;
17669 if (!EvaluateVector(E->getArg(0), Vec, Info))
17670 return false;
17671
17672 unsigned VectorLen = Vec.getVectorLength();
17673 unsigned RetWidth = Info.Ctx.getIntWidth(E->getType());
17674 llvm::APInt Bits(RetWidth, 0);
17675
17676 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
17677 const APSInt &A = Vec.getVectorElt(ElemNum).getInt();
17678 unsigned MSB = A[A.getBitWidth() - 1];
17679 Bits.setBitVal(ElemNum, MSB);
17680 }
17681
17682 APSInt RetMask(Bits, /*isUnsigned=*/true);
17683 return Success(APValue(RetMask), E);
17684 }
17685
17686 case clang::X86::BI__builtin_ia32_cmpb128_mask:
17687 case clang::X86::BI__builtin_ia32_cmpw128_mask:
17688 case clang::X86::BI__builtin_ia32_cmpd128_mask:
17689 case clang::X86::BI__builtin_ia32_cmpq128_mask:
17690 case clang::X86::BI__builtin_ia32_cmpb256_mask:
17691 case clang::X86::BI__builtin_ia32_cmpw256_mask:
17692 case clang::X86::BI__builtin_ia32_cmpd256_mask:
17693 case clang::X86::BI__builtin_ia32_cmpq256_mask:
17694 case clang::X86::BI__builtin_ia32_cmpb512_mask:
17695 case clang::X86::BI__builtin_ia32_cmpw512_mask:
17696 case clang::X86::BI__builtin_ia32_cmpd512_mask:
17697 case clang::X86::BI__builtin_ia32_cmpq512_mask:
17698 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
17699 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
17700 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
17701 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
17702 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
17703 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
17704 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
17705 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
17706 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
17707 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
17708 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
17709 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
17710 assert(E->getNumArgs() == 4);
17711
17712 bool IsUnsigned =
17713 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
17714 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpw512_mask);
17715
17716 APValue LHS, RHS;
17717 APSInt Mask, Opcode;
17718 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
17719 !EvaluateVector(E->getArg(1), RHS, Info) ||
17720 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
17721 !EvaluateInteger(E->getArg(3), Mask, Info))
17722 return false;
17723
17724 assert(LHS.getVectorLength() == RHS.getVectorLength());
17725
17726 unsigned VectorLen = LHS.getVectorLength();
17727 unsigned RetWidth = Mask.getBitWidth();
17728
17729 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
17730
17731 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
17732 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
17733 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
17734 bool Result = false;
17735
17736 switch (Opcode.getExtValue() & 0x7) {
17737 case 0: // _MM_CMPINT_EQ
17738 Result = (A == B);
17739 break;
17740 case 1: // _MM_CMPINT_LT
17741 Result = IsUnsigned ? A.ult(B) : A.slt(B);
17742 break;
17743 case 2: // _MM_CMPINT_LE
17744 Result = IsUnsigned ? A.ule(B) : A.sle(B);
17745 break;
17746 case 3: // _MM_CMPINT_FALSE
17747 Result = false;
17748 break;
17749 case 4: // _MM_CMPINT_NE
17750 Result = (A != B);
17751 break;
17752 case 5: // _MM_CMPINT_NLT (>=)
17753 Result = IsUnsigned ? A.uge(B) : A.sge(B);
17754 break;
17755 case 6: // _MM_CMPINT_NLE (>)
17756 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
17757 break;
17758 case 7: // _MM_CMPINT_TRUE
17759 Result = true;
17760 break;
17761 }
17762
17763 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
17764 }
17765
17766 return Success(APValue(RetMask), E);
17767 }
17768 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
17769 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
17770 case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
17771 assert(E->getNumArgs() == 3);
17772
17773 APValue Source, ShuffleMask;
17774 APSInt ZeroMask;
17775 if (!EvaluateVector(E->getArg(0), Source, Info) ||
17776 !EvaluateVector(E->getArg(1), ShuffleMask, Info) ||
17777 !EvaluateInteger(E->getArg(2), ZeroMask, Info))
17778 return false;
17779
17780 assert(Source.getVectorLength() == ShuffleMask.getVectorLength());
17781 assert(ZeroMask.getBitWidth() == Source.getVectorLength());
17782
17783 unsigned NumBytesInQWord = 8;
17784 unsigned NumBitsInByte = 8;
17785 unsigned NumBytes = Source.getVectorLength();
17786 unsigned NumQWords = NumBytes / NumBytesInQWord;
17787 unsigned RetWidth = ZeroMask.getBitWidth();
17788 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
17789
17790 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
17791 APInt SourceQWord(64, 0);
17792 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
17793 uint64_t Byte = Source.getVectorElt(QWordId * NumBytesInQWord + ByteIdx)
17794 .getInt()
17795 .getZExtValue();
17796 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
17797 }
17798
17799 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
17800 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
17801 unsigned M =
17802 ShuffleMask.getVectorElt(SelIdx).getInt().getZExtValue() & 0x3F;
17803 if (ZeroMask[SelIdx]) {
17804 RetMask.setBitVal(SelIdx, SourceQWord[M]);
17805 }
17806 }
17807 }
17808 return Success(APValue(RetMask), E);
17809 }
17810 }
17811}
17812
17813/// Determine whether this is a pointer past the end of the complete
17814/// object referred to by the lvalue.
17816 const LValue &LV) {
17817 // A null pointer can be viewed as being "past the end" but we don't
17818 // choose to look at it that way here.
17819 if (!LV.getLValueBase())
17820 return false;
17821
17822 // If the designator is valid and refers to a subobject, we're not pointing
17823 // past the end.
17824 if (!LV.getLValueDesignator().Invalid &&
17825 !LV.getLValueDesignator().isOnePastTheEnd())
17826 return false;
17827
17828 // A pointer to an incomplete type might be past-the-end if the type's size is
17829 // zero. We cannot tell because the type is incomplete.
17830 QualType Ty = getType(LV.getLValueBase());
17831 if (Ty->isIncompleteType())
17832 return true;
17833
17834 // Can't be past the end of an invalid object.
17835 if (LV.getLValueDesignator().Invalid)
17836 return false;
17837
17838 // We're a past-the-end pointer if we point to the byte after the object,
17839 // no matter what our type or path is.
17840 auto Size = Ctx.getTypeSizeInChars(Ty);
17841 return LV.getLValueOffset() == Size;
17842}
17843
17844namespace {
17845
17846/// Data recursive integer evaluator of certain binary operators.
17847///
17848/// We use a data recursive algorithm for binary operators so that we are able
17849/// to handle extreme cases of chained binary operators without causing stack
17850/// overflow.
17851class DataRecursiveIntBinOpEvaluator {
17852 struct EvalResult {
17853 APValue Val;
17854 bool Failed = false;
17855
17856 EvalResult() = default;
17857
17858 void swap(EvalResult &RHS) {
17859 Val.swap(RHS.Val);
17860 Failed = RHS.Failed;
17861 RHS.Failed = false;
17862 }
17863 };
17864
17865 struct Job {
17866 const Expr *E;
17867 EvalResult LHSResult; // meaningful only for binary operator expression.
17868 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
17869
17870 Job() = default;
17871 Job(Job &&) = default;
17872
17873 void startSpeculativeEval(EvalInfo &Info) {
17874 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
17875 }
17876
17877 private:
17878 SpeculativeEvaluationRAII SpecEvalRAII;
17879 };
17880
17881 SmallVector<Job, 16> Queue;
17882
17883 IntExprEvaluator &IntEval;
17884 EvalInfo &Info;
17885 APValue &FinalResult;
17886
17887public:
17888 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
17889 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
17890
17891 /// True if \param E is a binary operator that we are going to handle
17892 /// data recursively.
17893 /// We handle binary operators that are comma, logical, or that have operands
17894 /// with integral or enumeration type.
17895 static bool shouldEnqueue(const BinaryOperator *E) {
17896 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
17900 }
17901
17902 bool Traverse(const BinaryOperator *E) {
17903 enqueue(E);
17904 EvalResult PrevResult;
17905 while (!Queue.empty())
17906 process(PrevResult);
17907
17908 if (PrevResult.Failed) return false;
17909
17910 FinalResult.swap(PrevResult.Val);
17911 return true;
17912 }
17913
17914private:
17915 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
17916 return IntEval.Success(Value, E, Result);
17917 }
17918 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
17919 return IntEval.Success(Value, E, Result);
17920 }
17921 bool Error(const Expr *E) {
17922 return IntEval.Error(E);
17923 }
17924 bool Error(const Expr *E, diag::kind D) {
17925 return IntEval.Error(E, D);
17926 }
17927
17928 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
17929 return Info.CCEDiag(E, D);
17930 }
17931
17932 // Returns true if visiting the RHS is necessary, false otherwise.
17933 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
17934 bool &SuppressRHSDiags);
17935
17936 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
17937 const BinaryOperator *E, APValue &Result);
17938
17939 void EvaluateExpr(const Expr *E, EvalResult &Result) {
17940 Result.Failed = !Evaluate(Result.Val, Info, E);
17941 if (Result.Failed)
17942 Result.Val = APValue();
17943 }
17944
17945 void process(EvalResult &Result);
17946
17947 void enqueue(const Expr *E) {
17948 E = E->IgnoreParens();
17949 Queue.resize(Queue.size()+1);
17950 Queue.back().E = E;
17951 Queue.back().Kind = Job::AnyExprKind;
17952 }
17953};
17954
17955}
17956
17957bool DataRecursiveIntBinOpEvaluator::
17958 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
17959 bool &SuppressRHSDiags) {
17960 if (E->getOpcode() == BO_Comma) {
17961 // Ignore LHS but note if we could not evaluate it.
17962 if (LHSResult.Failed)
17963 return Info.noteSideEffect();
17964 return true;
17965 }
17966
17967 if (E->isLogicalOp()) {
17968 bool LHSAsBool;
17969 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
17970 // We were able to evaluate the LHS, see if we can get away with not
17971 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
17972 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
17973 Success(LHSAsBool, E, LHSResult.Val);
17974 return false; // Ignore RHS
17975 }
17976 } else {
17977 LHSResult.Failed = true;
17978
17979 // Since we weren't able to evaluate the left hand side, it
17980 // might have had side effects.
17981 if (!Info.noteSideEffect())
17982 return false;
17983
17984 // We can't evaluate the LHS; however, sometimes the result
17985 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
17986 // Don't ignore RHS and suppress diagnostics from this arm.
17987 SuppressRHSDiags = true;
17988 }
17989
17990 return true;
17991 }
17992
17993 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
17995
17996 if (LHSResult.Failed && !Info.noteFailure())
17997 return false; // Ignore RHS;
17998
17999 return true;
18000}
18001
18002static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
18003 bool IsSub) {
18004 // Compute the new offset in the appropriate width, wrapping at 64 bits.
18005 // FIXME: When compiling for a 32-bit target, we should use 32-bit
18006 // offsets.
18007 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
18008 CharUnits &Offset = LVal.getLValueOffset();
18009 uint64_t Offset64 = Offset.getQuantity();
18010 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
18011 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
18012 : Offset64 + Index64);
18013}
18014
18015bool DataRecursiveIntBinOpEvaluator::
18016 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18017 const BinaryOperator *E, APValue &Result) {
18018 if (E->getOpcode() == BO_Comma) {
18019 if (RHSResult.Failed)
18020 return false;
18021 Result = RHSResult.Val;
18022 return true;
18023 }
18024
18025 if (E->isLogicalOp()) {
18026 bool lhsResult, rhsResult;
18027 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
18028 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
18029
18030 if (LHSIsOK) {
18031 if (RHSIsOK) {
18032 if (E->getOpcode() == BO_LOr)
18033 return Success(lhsResult || rhsResult, E, Result);
18034 else
18035 return Success(lhsResult && rhsResult, E, Result);
18036 }
18037 } else {
18038 if (RHSIsOK) {
18039 // We can't evaluate the LHS; however, sometimes the result
18040 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18041 if (rhsResult == (E->getOpcode() == BO_LOr))
18042 return Success(rhsResult, E, Result);
18043 }
18044 }
18045
18046 return false;
18047 }
18048
18049 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18051
18052 if (LHSResult.Failed || RHSResult.Failed)
18053 return false;
18054
18055 const APValue &LHSVal = LHSResult.Val;
18056 const APValue &RHSVal = RHSResult.Val;
18057
18058 // Handle cases like (unsigned long)&a + 4.
18059 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
18060 Result = LHSVal;
18061 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
18062 return true;
18063 }
18064
18065 // Handle cases like 4 + (unsigned long)&a
18066 if (E->getOpcode() == BO_Add &&
18067 RHSVal.isLValue() && LHSVal.isInt()) {
18068 Result = RHSVal;
18069 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
18070 return true;
18071 }
18072
18073 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
18074 // Handle (intptr_t)&&A - (intptr_t)&&B.
18075 if (!LHSVal.getLValueOffset().isZero() ||
18076 !RHSVal.getLValueOffset().isZero())
18077 return false;
18078 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
18079 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
18080 if (!LHSExpr || !RHSExpr)
18081 return false;
18082 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
18083 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
18084 if (!LHSAddrExpr || !RHSAddrExpr)
18085 return false;
18086 // Make sure both labels come from the same function.
18087 if (LHSAddrExpr->getLabel()->getDeclContext() !=
18088 RHSAddrExpr->getLabel()->getDeclContext())
18089 return false;
18090 Result = APValue(LHSAddrExpr, RHSAddrExpr);
18091 return true;
18092 }
18093
18094 // All the remaining cases expect both operands to be an integer
18095 if (!LHSVal.isInt() || !RHSVal.isInt())
18096 return Error(E);
18097
18098 // Set up the width and signedness manually, in case it can't be deduced
18099 // from the operation we're performing.
18100 // FIXME: Don't do this in the cases where we can deduce it.
18101 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
18103 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
18104 RHSVal.getInt(), Value))
18105 return false;
18106 return Success(Value, E, Result);
18107}
18108
18109void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
18110 Job &job = Queue.back();
18111
18112 switch (job.Kind) {
18113 case Job::AnyExprKind: {
18114 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
18115 if (shouldEnqueue(Bop)) {
18116 job.Kind = Job::BinOpKind;
18117 enqueue(Bop->getLHS());
18118 return;
18119 }
18120 }
18121
18122 EvaluateExpr(job.E, Result);
18123 Queue.pop_back();
18124 return;
18125 }
18126
18127 case Job::BinOpKind: {
18128 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
18129 bool SuppressRHSDiags = false;
18130 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
18131 Queue.pop_back();
18132 return;
18133 }
18134 if (SuppressRHSDiags)
18135 job.startSpeculativeEval(Info);
18136 job.LHSResult.swap(Result);
18137 job.Kind = Job::BinOpVisitedLHSKind;
18138 enqueue(Bop->getRHS());
18139 return;
18140 }
18141
18142 case Job::BinOpVisitedLHSKind: {
18143 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
18144 EvalResult RHS;
18145 RHS.swap(Result);
18146 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
18147 Queue.pop_back();
18148 return;
18149 }
18150 }
18151
18152 llvm_unreachable("Invalid Job::Kind!");
18153}
18154
18155namespace {
18156enum class CmpResult {
18157 Unequal,
18158 Less,
18159 Equal,
18160 Greater,
18161 Unordered,
18162};
18163}
18164
18165template <class SuccessCB, class AfterCB>
18166static bool
18168 SuccessCB &&Success, AfterCB &&DoAfter) {
18169 assert(!E->isValueDependent());
18170 assert(E->isComparisonOp() && "expected comparison operator");
18171 assert((E->getOpcode() == BO_Cmp ||
18173 "unsupported binary expression evaluation");
18174 auto Error = [&](const Expr *E) {
18175 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
18176 return false;
18177 };
18178
18179 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
18180 bool IsEquality = E->isEqualityOp();
18181
18182 QualType LHSTy = E->getLHS()->getType();
18183 QualType RHSTy = E->getRHS()->getType();
18184
18185 if (LHSTy->isIntegralOrEnumerationType() &&
18186 RHSTy->isIntegralOrEnumerationType()) {
18187 APSInt LHS, RHS;
18188 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
18189 if (!LHSOK && !Info.noteFailure())
18190 return false;
18191 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
18192 return false;
18193 if (LHS < RHS)
18194 return Success(CmpResult::Less, E);
18195 if (LHS > RHS)
18196 return Success(CmpResult::Greater, E);
18197 return Success(CmpResult::Equal, E);
18198 }
18199
18200 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
18201 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
18202 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
18203
18204 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
18205 if (!LHSOK && !Info.noteFailure())
18206 return false;
18207 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
18208 return false;
18209 if (LHSFX < RHSFX)
18210 return Success(CmpResult::Less, E);
18211 if (LHSFX > RHSFX)
18212 return Success(CmpResult::Greater, E);
18213 return Success(CmpResult::Equal, E);
18214 }
18215
18216 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
18217 ComplexValue LHS, RHS;
18218 bool LHSOK;
18219 if (E->isAssignmentOp()) {
18220 LValue LV;
18221 EvaluateLValue(E->getLHS(), LV, Info);
18222 LHSOK = false;
18223 } else if (LHSTy->isRealFloatingType()) {
18224 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
18225 if (LHSOK) {
18226 LHS.makeComplexFloat();
18227 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
18228 }
18229 } else {
18230 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
18231 }
18232 if (!LHSOK && !Info.noteFailure())
18233 return false;
18234
18235 if (E->getRHS()->getType()->isRealFloatingType()) {
18236 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
18237 return false;
18238 RHS.makeComplexFloat();
18239 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
18240 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
18241 return false;
18242
18243 if (LHS.isComplexFloat()) {
18244 APFloat::cmpResult CR_r =
18245 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
18246 APFloat::cmpResult CR_i =
18247 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
18248 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
18249 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
18250 } else {
18251 assert(IsEquality && "invalid complex comparison");
18252 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
18253 LHS.getComplexIntImag() == RHS.getComplexIntImag();
18254 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
18255 }
18256 }
18257
18258 if (LHSTy->isRealFloatingType() &&
18259 RHSTy->isRealFloatingType()) {
18260 APFloat RHS(0.0), LHS(0.0);
18261
18262 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
18263 if (!LHSOK && !Info.noteFailure())
18264 return false;
18265
18266 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
18267 return false;
18268
18269 assert(E->isComparisonOp() && "Invalid binary operator!");
18270 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
18271 if (!Info.InConstantContext &&
18272 APFloatCmpResult == APFloat::cmpUnordered &&
18273 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
18274 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
18275 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
18276 return false;
18277 }
18278 auto GetCmpRes = [&]() {
18279 switch (APFloatCmpResult) {
18280 case APFloat::cmpEqual:
18281 return CmpResult::Equal;
18282 case APFloat::cmpLessThan:
18283 return CmpResult::Less;
18284 case APFloat::cmpGreaterThan:
18285 return CmpResult::Greater;
18286 case APFloat::cmpUnordered:
18287 return CmpResult::Unordered;
18288 }
18289 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
18290 };
18291 return Success(GetCmpRes(), E);
18292 }
18293
18294 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
18295 LValue LHSValue, RHSValue;
18296
18297 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
18298 if (!LHSOK && !Info.noteFailure())
18299 return false;
18300
18301 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18302 return false;
18303
18304 // Reject differing bases from the normal codepath; we special-case
18305 // comparisons to null.
18306 if (!HasSameBase(LHSValue, RHSValue)) {
18307 // Bail out early if we're checking potential constant expression.
18308 // Otherwise, prefer to diagnose other issues.
18309 if (Info.checkingPotentialConstantExpression() &&
18310 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
18311 return false;
18312 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
18313 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
18314 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
18315 Info.FFDiag(E, DiagID)
18316 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
18317 return false;
18318 };
18319 // Inequalities and subtractions between unrelated pointers have
18320 // unspecified or undefined behavior.
18321 if (!IsEquality)
18322 return DiagComparison(
18323 diag::note_constexpr_pointer_comparison_unspecified);
18324 // A constant address may compare equal to the address of a symbol.
18325 // The one exception is that address of an object cannot compare equal
18326 // to a null pointer constant.
18327 // TODO: Should we restrict this to actual null pointers, and exclude the
18328 // case of zero cast to pointer type?
18329 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
18330 (!RHSValue.Base && !RHSValue.Offset.isZero()))
18331 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
18332 !RHSValue.Base);
18333 // C++2c [intro.object]/10:
18334 // Two objects [...] may have the same address if [...] they are both
18335 // potentially non-unique objects.
18336 // C++2c [intro.object]/9:
18337 // An object is potentially non-unique if it is a string literal object,
18338 // the backing array of an initializer list, or a subobject thereof.
18339 //
18340 // This makes the comparison result unspecified, so it's not a constant
18341 // expression.
18342 //
18343 // TODO: Do we need to handle the initializer list case here?
18344 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
18345 return DiagComparison(diag::note_constexpr_literal_comparison);
18346 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
18347 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
18348 !IsOpaqueConstantCall(LHSValue));
18349 // We can't tell whether weak symbols will end up pointing to the same
18350 // object.
18351 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
18352 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
18353 !IsWeakLValue(LHSValue));
18354 // We can't compare the address of the start of one object with the
18355 // past-the-end address of another object, per C++ DR1652.
18356 if (LHSValue.Base && LHSValue.Offset.isZero() &&
18357 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
18358 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
18359 true);
18360 if (RHSValue.Base && RHSValue.Offset.isZero() &&
18361 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
18362 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
18363 false);
18364 // We can't tell whether an object is at the same address as another
18365 // zero sized object.
18366 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
18367 (LHSValue.Base && isZeroSized(RHSValue)))
18368 return DiagComparison(
18369 diag::note_constexpr_pointer_comparison_zero_sized);
18370 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
18371 return DiagComparison(
18372 diag::note_constexpr_pointer_comparison_unspecified);
18373 // FIXME: Verify both variables are live.
18374 return Success(CmpResult::Unequal, E);
18375 }
18376
18377 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
18378 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
18379
18380 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
18381 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
18382
18383 // C++11 [expr.rel]p2:
18384 // - If two pointers point to non-static data members of the same object,
18385 // or to subobjects or array elements fo such members, recursively, the
18386 // pointer to the later declared member compares greater provided the
18387 // two members have the same access control and provided their class is
18388 // not a union.
18389 // [...]
18390 // - Otherwise pointer comparisons are unspecified.
18391 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
18392 bool WasArrayIndex;
18393 unsigned Mismatch = FindDesignatorMismatch(
18394 LHSValue.Base.isNull() ? QualType()
18395 : getType(LHSValue.Base).getNonReferenceType(),
18396 LHSDesignator, RHSDesignator, WasArrayIndex);
18397 // At the point where the designators diverge, the comparison has a
18398 // specified value if:
18399 // - we are comparing array indices
18400 // - we are comparing fields of a union, or fields with the same access
18401 // Otherwise, the result is unspecified and thus the comparison is not a
18402 // constant expression.
18403 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
18404 Mismatch < RHSDesignator.Entries.size()) {
18405 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
18406 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
18407 if (!LF && !RF)
18408 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
18409 else if (!LF)
18410 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18411 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
18412 << RF->getParent() << RF;
18413 else if (!RF)
18414 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
18415 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
18416 << LF->getParent() << LF;
18417 else if (!LF->getParent()->isUnion() &&
18418 LF->getAccess() != RF->getAccess())
18419 Info.CCEDiag(E,
18420 diag::note_constexpr_pointer_comparison_differing_access)
18421 << LF << LF->getAccess() << RF << RF->getAccess()
18422 << LF->getParent();
18423 }
18424 }
18425
18426 // The comparison here must be unsigned, and performed with the same
18427 // width as the pointer.
18428 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
18429 uint64_t CompareLHS = LHSOffset.getQuantity();
18430 uint64_t CompareRHS = RHSOffset.getQuantity();
18431 assert(PtrSize <= 64 && "Unexpected pointer width");
18432 uint64_t Mask = ~0ULL >> (64 - PtrSize);
18433 CompareLHS &= Mask;
18434 CompareRHS &= Mask;
18435
18436 // If there is a base and this is a relational operator, we can only
18437 // compare pointers within the object in question; otherwise, the result
18438 // depends on where the object is located in memory.
18439 if (!LHSValue.Base.isNull() && IsRelational) {
18440 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
18441 if (BaseTy->isIncompleteType())
18442 return Error(E);
18443 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
18444 uint64_t OffsetLimit = Size.getQuantity();
18445 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
18446 return Error(E);
18447 }
18448
18449 if (CompareLHS < CompareRHS)
18450 return Success(CmpResult::Less, E);
18451 if (CompareLHS > CompareRHS)
18452 return Success(CmpResult::Greater, E);
18453 return Success(CmpResult::Equal, E);
18454 }
18455
18456 if (LHSTy->isMemberPointerType()) {
18457 assert(IsEquality && "unexpected member pointer operation");
18458 assert(RHSTy->isMemberPointerType() && "invalid comparison");
18459
18460 MemberPtr LHSValue, RHSValue;
18461
18462 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
18463 if (!LHSOK && !Info.noteFailure())
18464 return false;
18465
18466 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18467 return false;
18468
18469 // If either operand is a pointer to a weak function, the comparison is not
18470 // constant.
18471 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
18472 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18473 << LHSValue.getDecl();
18474 return false;
18475 }
18476 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
18477 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
18478 << RHSValue.getDecl();
18479 return false;
18480 }
18481
18482 // C++11 [expr.eq]p2:
18483 // If both operands are null, they compare equal. Otherwise if only one is
18484 // null, they compare unequal.
18485 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
18486 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
18487 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18488 }
18489
18490 // Otherwise if either is a pointer to a virtual member function, the
18491 // result is unspecified.
18492 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
18493 if (MD->isVirtual())
18494 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18495 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
18496 if (MD->isVirtual())
18497 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
18498
18499 // Otherwise they compare equal if and only if they would refer to the
18500 // same member of the same most derived object or the same subobject if
18501 // they were dereferenced with a hypothetical object of the associated
18502 // class type.
18503 bool Equal = LHSValue == RHSValue;
18504 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
18505 }
18506
18507 if (LHSTy->isNullPtrType()) {
18508 assert(E->isComparisonOp() && "unexpected nullptr operation");
18509 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
18510 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
18511 // are compared, the result is true of the operator is <=, >= or ==, and
18512 // false otherwise.
18513 LValue Res;
18514 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
18515 !EvaluatePointer(E->getRHS(), Res, Info))
18516 return false;
18517 return Success(CmpResult::Equal, E);
18518 }
18519
18520 return DoAfter();
18521}
18522
18523bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
18524 if (!CheckLiteralType(Info, E))
18525 return false;
18526
18527 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18529 switch (CR) {
18530 case CmpResult::Unequal:
18531 llvm_unreachable("should never produce Unequal for three-way comparison");
18532 case CmpResult::Less:
18533 CCR = ComparisonCategoryResult::Less;
18534 break;
18535 case CmpResult::Equal:
18536 CCR = ComparisonCategoryResult::Equal;
18537 break;
18538 case CmpResult::Greater:
18539 CCR = ComparisonCategoryResult::Greater;
18540 break;
18541 case CmpResult::Unordered:
18542 CCR = ComparisonCategoryResult::Unordered;
18543 break;
18544 }
18545 // Evaluation succeeded. Lookup the information for the comparison category
18546 // type and fetch the VarDecl for the result.
18547 const ComparisonCategoryInfo &CmpInfo =
18548 Info.Ctx.CompCategories.getInfoForType(E->getType());
18549 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
18550 // Check and evaluate the result as a constant expression.
18551 LValue LV;
18552 LV.set(VD);
18553 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
18554 return false;
18555 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
18556 ConstantExprKind::Normal);
18557 };
18558 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18559 return ExprEvaluatorBaseTy::VisitBinCmp(E);
18560 });
18561}
18562
18563bool RecordExprEvaluator::VisitCXXParenListInitExpr(
18564 const CXXParenListInitExpr *E) {
18565 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
18566}
18567
18568bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
18569 // We don't support assignment in C. C++ assignments don't get here because
18570 // assignment is an lvalue in C++.
18571 if (E->isAssignmentOp()) {
18572 Error(E);
18573 if (!Info.noteFailure())
18574 return false;
18575 }
18576
18577 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
18578 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
18579
18580 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
18582 "DataRecursiveIntBinOpEvaluator should have handled integral types");
18583
18584 if (E->isComparisonOp()) {
18585 // Evaluate builtin binary comparisons by evaluating them as three-way
18586 // comparisons and then translating the result.
18587 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
18588 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
18589 "should only produce Unequal for equality comparisons");
18590 bool IsEqual = CR == CmpResult::Equal,
18591 IsLess = CR == CmpResult::Less,
18592 IsGreater = CR == CmpResult::Greater;
18593 auto Op = E->getOpcode();
18594 switch (Op) {
18595 default:
18596 llvm_unreachable("unsupported binary operator");
18597 case BO_EQ:
18598 case BO_NE:
18599 return Success(IsEqual == (Op == BO_EQ), E);
18600 case BO_LT:
18601 return Success(IsLess, E);
18602 case BO_GT:
18603 return Success(IsGreater, E);
18604 case BO_LE:
18605 return Success(IsEqual || IsLess, E);
18606 case BO_GE:
18607 return Success(IsEqual || IsGreater, E);
18608 }
18609 };
18610 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
18611 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18612 });
18613 }
18614
18615 QualType LHSTy = E->getLHS()->getType();
18616 QualType RHSTy = E->getRHS()->getType();
18617
18618 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
18619 E->getOpcode() == BO_Sub) {
18620 LValue LHSValue, RHSValue;
18621
18622 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
18623 if (!LHSOK && !Info.noteFailure())
18624 return false;
18625
18626 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
18627 return false;
18628
18629 // Reject differing bases from the normal codepath; we special-case
18630 // comparisons to null.
18631 if (!HasSameBase(LHSValue, RHSValue)) {
18632 if (Info.checkingPotentialConstantExpression() &&
18633 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
18634 return false;
18635
18636 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
18637 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
18638
18639 auto DiagArith = [&](unsigned DiagID) {
18640 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
18641 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
18642 Info.FFDiag(E, DiagID) << LHS << RHS;
18643 if (LHSExpr && LHSExpr == RHSExpr)
18644 Info.Note(LHSExpr->getExprLoc(),
18645 diag::note_constexpr_repeated_literal_eval)
18646 << LHSExpr->getSourceRange();
18647 return false;
18648 };
18649
18650 if (!LHSExpr || !RHSExpr)
18651 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
18652
18653 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
18654 return DiagArith(diag::note_constexpr_literal_arith);
18655
18656 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
18657 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
18658 if (!LHSAddrExpr || !RHSAddrExpr)
18659 return Error(E);
18660 // Make sure both labels come from the same function.
18661 if (LHSAddrExpr->getLabel()->getDeclContext() !=
18662 RHSAddrExpr->getLabel()->getDeclContext())
18663 return Error(E);
18664 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
18665 }
18666 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
18667 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
18668
18669 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
18670 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
18671
18672 // C++11 [expr.add]p6:
18673 // Unless both pointers point to elements of the same array object, or
18674 // one past the last element of the array object, the behavior is
18675 // undefined.
18676 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
18677 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
18678 RHSDesignator))
18679 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
18680
18681 QualType Type = E->getLHS()->getType();
18682 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
18683
18684 CharUnits ElementSize;
18685 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
18686 return false;
18687
18688 // As an extension, a type may have zero size (empty struct or union in
18689 // C, array of zero length). Pointer subtraction in such cases has
18690 // undefined behavior, so is not constant.
18691 if (ElementSize.isZero()) {
18692 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
18693 << ElementType;
18694 return false;
18695 }
18696
18697 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
18698 // and produce incorrect results when it overflows. Such behavior
18699 // appears to be non-conforming, but is common, so perhaps we should
18700 // assume the standard intended for such cases to be undefined behavior
18701 // and check for them.
18702
18703 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
18704 // overflow in the final conversion to ptrdiff_t.
18705 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
18706 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
18707 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
18708 false);
18709 APSInt TrueResult = (LHS - RHS) / ElemSize;
18710 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
18711
18712 if (Result.extend(65) != TrueResult &&
18713 !HandleOverflow(Info, E, TrueResult, E->getType()))
18714 return false;
18715 return Success(Result, E);
18716 }
18717
18718 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
18719}
18720
18721/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
18722/// a result as the expression's type.
18723bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
18724 const UnaryExprOrTypeTraitExpr *E) {
18725 switch(E->getKind()) {
18726 case UETT_PreferredAlignOf:
18727 case UETT_AlignOf: {
18728 if (E->isArgumentType())
18729 return Success(
18730 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
18731 else
18732 return Success(
18733 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
18734 }
18735
18736 case UETT_PtrAuthTypeDiscriminator: {
18737 if (E->getArgumentType()->isDependentType())
18738 return false;
18739 return Success(
18740 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
18741 }
18742 case UETT_VecStep: {
18743 QualType Ty = E->getTypeOfArgument();
18744
18745 if (Ty->isVectorType()) {
18746 unsigned n = Ty->castAs<VectorType>()->getNumElements();
18747
18748 // The vec_step built-in functions that take a 3-component
18749 // vector return 4. (OpenCL 1.1 spec 6.11.12)
18750 if (n == 3)
18751 n = 4;
18752
18753 return Success(n, E);
18754 } else
18755 return Success(1, E);
18756 }
18757
18758 case UETT_DataSizeOf:
18759 case UETT_SizeOf: {
18760 QualType SrcTy = E->getTypeOfArgument();
18761 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
18762 // the result is the size of the referenced type."
18763 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
18764 SrcTy = Ref->getPointeeType();
18765
18766 CharUnits Sizeof;
18767 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
18768 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
18769 : SizeOfType::SizeOf)) {
18770 return false;
18771 }
18772 return Success(Sizeof, E);
18773 }
18774 case UETT_OpenMPRequiredSimdAlign:
18775 assert(E->isArgumentType());
18776 return Success(
18777 Info.Ctx.toCharUnitsFromBits(
18778 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
18779 .getQuantity(),
18780 E);
18781 case UETT_VectorElements: {
18782 QualType Ty = E->getTypeOfArgument();
18783 // If the vector has a fixed size, we can determine the number of elements
18784 // at compile time.
18785 if (const auto *VT = Ty->getAs<VectorType>())
18786 return Success(VT->getNumElements(), E);
18787
18788 assert(Ty->isSizelessVectorType());
18789 if (Info.InConstantContext)
18790 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
18791 << E->getSourceRange();
18792
18793 return false;
18794 }
18795 case UETT_CountOf: {
18796 QualType Ty = E->getTypeOfArgument();
18797 assert(Ty->isArrayType());
18798
18799 // We don't need to worry about array element qualifiers, so getting the
18800 // unsafe array type is fine.
18801 if (const auto *CAT =
18802 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
18803 return Success(CAT->getSize(), E);
18804 }
18805
18806 assert(!Ty->isConstantSizeType());
18807
18808 // If it's a variable-length array type, we need to check whether it is a
18809 // multidimensional array. If so, we need to check the size expression of
18810 // the VLA to see if it's a constant size. If so, we can return that value.
18811 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
18812 assert(VAT);
18813 if (VAT->getElementType()->isArrayType()) {
18814 // Variable array size expression could be missing (e.g. int a[*][10]) In
18815 // that case, it can't be a constant expression.
18816 if (!VAT->getSizeExpr()) {
18817 Info.FFDiag(E->getBeginLoc());
18818 return false;
18819 }
18820
18821 std::optional<APSInt> Res =
18822 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
18823 if (Res) {
18824 // The resulting value always has type size_t, so we need to make the
18825 // returned APInt have the correct sign and bit-width.
18826 APInt Val{
18827 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
18828 Res->getZExtValue()};
18829 return Success(Val, E);
18830 }
18831 }
18832
18833 // Definitely a variable-length type, which is not an ICE.
18834 // FIXME: Better diagnostic.
18835 Info.FFDiag(E->getBeginLoc());
18836 return false;
18837 }
18838 }
18839
18840 llvm_unreachable("unknown expr/type trait");
18841}
18842
18843bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
18844 Info.Ctx.recordOffsetOfEvaluation(OOE);
18845 CharUnits Result;
18846 unsigned n = OOE->getNumComponents();
18847 if (n == 0)
18848 return Error(OOE);
18849 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
18850 for (unsigned i = 0; i != n; ++i) {
18851 OffsetOfNode ON = OOE->getComponent(i);
18852 switch (ON.getKind()) {
18853 case OffsetOfNode::Array: {
18854 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
18855 APSInt IdxResult;
18856 if (!EvaluateInteger(Idx, IdxResult, Info))
18857 return false;
18858 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
18859 if (!AT)
18860 return Error(OOE);
18861 CurrentType = AT->getElementType();
18862 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
18863 Result += IdxResult.getSExtValue() * ElementSize;
18864 break;
18865 }
18866
18867 case OffsetOfNode::Field: {
18868 FieldDecl *MemberDecl = ON.getField();
18869 const auto *RD = CurrentType->getAsRecordDecl();
18870 if (!RD)
18871 return Error(OOE);
18872 if (RD->isInvalidDecl()) return false;
18873 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
18874 unsigned i = MemberDecl->getFieldIndex();
18875 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
18876 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
18877 CurrentType = MemberDecl->getType().getNonReferenceType();
18878 break;
18879 }
18880
18882 llvm_unreachable("dependent __builtin_offsetof");
18883
18884 case OffsetOfNode::Base: {
18885 CXXBaseSpecifier *BaseSpec = ON.getBase();
18886 if (BaseSpec->isVirtual())
18887 return Error(OOE);
18888
18889 // Find the layout of the class whose base we are looking into.
18890 const auto *RD = CurrentType->getAsCXXRecordDecl();
18891 if (!RD)
18892 return Error(OOE);
18893 if (RD->isInvalidDecl()) return false;
18894 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
18895
18896 // Find the base class itself.
18897 CurrentType = BaseSpec->getType();
18898 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
18899 if (!BaseRD)
18900 return Error(OOE);
18901
18902 // Add the offset to the base.
18903 Result += RL.getBaseClassOffset(BaseRD);
18904 break;
18905 }
18906 }
18907 }
18908 return Success(Result, OOE);
18909}
18910
18911bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
18912 switch (E->getOpcode()) {
18913 default:
18914 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
18915 // See C99 6.6p3.
18916 return Error(E);
18917 case UO_Extension:
18918 // FIXME: Should extension allow i-c-e extension expressions in its scope?
18919 // If so, we could clear the diagnostic ID.
18920 return Visit(E->getSubExpr());
18921 case UO_Plus:
18922 // The result is just the value.
18923 return Visit(E->getSubExpr());
18924 case UO_Minus: {
18925 if (!Visit(E->getSubExpr()))
18926 return false;
18927 if (!Result.isInt()) return Error(E);
18928 const APSInt &Value = Result.getInt();
18929 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
18930 !E->getType().isWrapType()) {
18931 if (Info.checkingForUndefinedBehavior())
18932 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
18933 diag::warn_integer_constant_overflow)
18934 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
18935 /*UpperCase=*/true, /*InsertSeparators=*/true)
18936 << E->getType() << E->getSourceRange();
18937
18938 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
18939 E->getType()))
18940 return false;
18941 }
18942 return Success(-Value, E);
18943 }
18944 case UO_Not: {
18945 if (!Visit(E->getSubExpr()))
18946 return false;
18947 if (!Result.isInt()) return Error(E);
18948 return Success(~Result.getInt(), E);
18949 }
18950 case UO_LNot: {
18951 bool bres;
18952 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
18953 return false;
18954 return Success(!bres, E);
18955 }
18956 }
18957}
18958
18959/// HandleCast - This is used to evaluate implicit or explicit casts where the
18960/// result type is integer.
18961bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
18962 const Expr *SubExpr = E->getSubExpr();
18963 QualType DestType = E->getType();
18964 QualType SrcType = SubExpr->getType();
18965
18966 switch (E->getCastKind()) {
18967 case CK_BaseToDerived:
18968 case CK_DerivedToBase:
18969 case CK_UncheckedDerivedToBase:
18970 case CK_Dynamic:
18971 case CK_ToUnion:
18972 case CK_ArrayToPointerDecay:
18973 case CK_FunctionToPointerDecay:
18974 case CK_NullToPointer:
18975 case CK_NullToMemberPointer:
18976 case CK_BaseToDerivedMemberPointer:
18977 case CK_DerivedToBaseMemberPointer:
18978 case CK_ReinterpretMemberPointer:
18979 case CK_ConstructorConversion:
18980 case CK_IntegralToPointer:
18981 case CK_ToVoid:
18982 case CK_VectorSplat:
18983 case CK_IntegralToFloating:
18984 case CK_FloatingCast:
18985 case CK_CPointerToObjCPointerCast:
18986 case CK_BlockPointerToObjCPointerCast:
18987 case CK_AnyPointerToBlockPointerCast:
18988 case CK_ObjCObjectLValueCast:
18989 case CK_FloatingRealToComplex:
18990 case CK_FloatingComplexToReal:
18991 case CK_FloatingComplexCast:
18992 case CK_FloatingComplexToIntegralComplex:
18993 case CK_IntegralRealToComplex:
18994 case CK_IntegralComplexCast:
18995 case CK_IntegralComplexToFloatingComplex:
18996 case CK_BuiltinFnToFnPtr:
18997 case CK_ZeroToOCLOpaqueType:
18998 case CK_NonAtomicToAtomic:
18999 case CK_AddressSpaceConversion:
19000 case CK_IntToOCLSampler:
19001 case CK_FloatingToFixedPoint:
19002 case CK_FixedPointToFloating:
19003 case CK_FixedPointCast:
19004 case CK_IntegralToFixedPoint:
19005 case CK_MatrixCast:
19006 case CK_HLSLAggregateSplatCast:
19007 llvm_unreachable("invalid cast kind for integral value");
19008
19009 case CK_BitCast:
19010 case CK_Dependent:
19011 case CK_LValueBitCast:
19012 case CK_ARCProduceObject:
19013 case CK_ARCConsumeObject:
19014 case CK_ARCReclaimReturnedObject:
19015 case CK_ARCExtendBlockObject:
19016 case CK_CopyAndAutoreleaseBlockObject:
19017 return Error(E);
19018
19019 case CK_UserDefinedConversion:
19020 case CK_LValueToRValue:
19021 case CK_AtomicToNonAtomic:
19022 case CK_NoOp:
19023 case CK_LValueToRValueBitCast:
19024 case CK_HLSLArrayRValue:
19025 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19026
19027 case CK_MemberPointerToBoolean:
19028 case CK_PointerToBoolean:
19029 case CK_IntegralToBoolean:
19030 case CK_FloatingToBoolean:
19031 case CK_BooleanToSignedIntegral:
19032 case CK_FloatingComplexToBoolean:
19033 case CK_IntegralComplexToBoolean: {
19034 bool BoolResult;
19035 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
19036 return false;
19037 uint64_t IntResult = BoolResult;
19038 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
19039 IntResult = (uint64_t)-1;
19040 return Success(IntResult, E);
19041 }
19042
19043 case CK_FixedPointToIntegral: {
19044 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
19045 if (!EvaluateFixedPoint(SubExpr, Src, Info))
19046 return false;
19047 bool Overflowed;
19048 llvm::APSInt Result = Src.convertToInt(
19049 Info.Ctx.getIntWidth(DestType),
19050 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
19051 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
19052 return false;
19053 return Success(Result, E);
19054 }
19055
19056 case CK_FixedPointToBoolean: {
19057 // Unsigned padding does not affect this.
19058 APValue Val;
19059 if (!Evaluate(Val, Info, SubExpr))
19060 return false;
19061 return Success(Val.getFixedPoint().getBoolValue(), E);
19062 }
19063
19064 case CK_IntegralCast: {
19065 if (!Visit(SubExpr))
19066 return false;
19067
19068 if (!Result.isInt()) {
19069 // Allow casts of address-of-label differences if they are no-ops
19070 // or narrowing, if the result is at least 32 bits wide.
19071 // (The narrowing case isn't actually guaranteed to
19072 // be constant-evaluatable except in some narrow cases which are hard
19073 // to detect here. We let it through on the assumption the user knows
19074 // what they are doing.)
19075 if (Result.isAddrLabelDiff()) {
19076 unsigned DestBits = Info.Ctx.getTypeSize(DestType);
19077 return DestBits >= 32 && DestBits <= Info.Ctx.getTypeSize(SrcType);
19078 }
19079 // Only allow casts of lvalues if they are lossless.
19080 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
19081 }
19082
19083 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
19084 const auto *ED = DestType->getAsEnumDecl();
19085 // Check that the value is within the range of the enumeration values.
19086 //
19087 // This corressponds to [expr.static.cast]p10 which says:
19088 // A value of integral or enumeration type can be explicitly converted
19089 // to a complete enumeration type ... If the enumeration type does not
19090 // have a fixed underlying type, the value is unchanged if the original
19091 // value is within the range of the enumeration values ([dcl.enum]), and
19092 // otherwise, the behavior is undefined.
19093 //
19094 // This was resolved as part of DR2338 which has CD5 status.
19095 if (!ED->isFixed()) {
19096 llvm::APInt Min;
19097 llvm::APInt Max;
19098
19099 ED->getValueRange(Max, Min);
19100 --Max;
19101
19102 if (ED->getNumNegativeBits() &&
19103 (Max.slt(Result.getInt().getSExtValue()) ||
19104 Min.sgt(Result.getInt().getSExtValue())))
19105 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
19106 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
19107 << Max.getSExtValue() << ED;
19108 else if (!ED->getNumNegativeBits() &&
19109 Max.ult(Result.getInt().getZExtValue()))
19110 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
19111 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
19112 << Max.getZExtValue() << ED;
19113 }
19114 }
19115
19116 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
19117 Result.getInt()), E);
19118 }
19119
19120 case CK_PointerToIntegral: {
19121 CCEDiag(E, diag::note_constexpr_invalid_cast)
19122 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
19123 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
19124
19125 LValue LV;
19126 if (!EvaluatePointer(SubExpr, LV, Info))
19127 return false;
19128
19129 if (LV.getLValueBase()) {
19130 // Only allow based lvalue casts if they are lossless.
19131 // FIXME: Allow a larger integer size than the pointer size, and allow
19132 // narrowing back down to pointer width in subsequent integral casts.
19133 // FIXME: Check integer type's active bits, not its type size.
19134 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
19135 return Error(E);
19136
19137 LV.Designator.setInvalid();
19138 LV.moveInto(Result);
19139 return true;
19140 }
19141
19142 APSInt AsInt;
19143 APValue V;
19144 LV.moveInto(V);
19145 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
19146 llvm_unreachable("Can't cast this!");
19147
19148 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
19149 }
19150
19151 case CK_IntegralComplexToReal: {
19152 ComplexValue C;
19153 if (!EvaluateComplex(SubExpr, C, Info))
19154 return false;
19155 return Success(C.getComplexIntReal(), E);
19156 }
19157
19158 case CK_FloatingToIntegral: {
19159 APFloat F(0.0);
19160 if (!EvaluateFloat(SubExpr, F, Info))
19161 return false;
19162
19163 APSInt Value;
19164 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
19165 return false;
19166 return Success(Value, E);
19167 }
19168 case CK_HLSLVectorTruncation: {
19169 APValue Val;
19170 if (!EvaluateVector(SubExpr, Val, Info))
19171 return Error(E);
19172 return Success(Val.getVectorElt(0), E);
19173 }
19174 case CK_HLSLMatrixTruncation: {
19175 APValue Val;
19176 if (!EvaluateMatrix(SubExpr, Val, Info))
19177 return Error(E);
19178 return Success(Val.getMatrixElt(0, 0), E);
19179 }
19180 case CK_HLSLElementwiseCast: {
19181 SmallVector<APValue> SrcVals;
19182 SmallVector<QualType> SrcTypes;
19183
19184 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
19185 return false;
19186
19187 // cast our single element
19188 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
19189 APValue ResultVal;
19190 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
19191 ResultVal))
19192 return false;
19193 return Success(ResultVal, E);
19194 }
19195 }
19196
19197 llvm_unreachable("unknown cast resulting in integral value");
19198}
19199
19200bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
19201 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19202 ComplexValue LV;
19203 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
19204 return false;
19205 if (!LV.isComplexInt())
19206 return Error(E);
19207 return Success(LV.getComplexIntReal(), E);
19208 }
19209
19210 return Visit(E->getSubExpr());
19211}
19212
19213bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
19214 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
19215 ComplexValue LV;
19216 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
19217 return false;
19218 if (!LV.isComplexInt())
19219 return Error(E);
19220 return Success(LV.getComplexIntImag(), E);
19221 }
19222
19223 VisitIgnoredValue(E->getSubExpr());
19224 return Success(0, E);
19225}
19226
19227bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
19228 return Success(E->getPackLength(), E);
19229}
19230
19231bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
19232 return Success(E->getValue(), E);
19233}
19234
19235bool IntExprEvaluator::VisitConceptSpecializationExpr(
19236 const ConceptSpecializationExpr *E) {
19237 return Success(E->isSatisfied(), E);
19238}
19239
19240bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
19241 return Success(E->isSatisfied(), E);
19242}
19243
19244bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19245 switch (E->getOpcode()) {
19246 default:
19247 // Invalid unary operators
19248 return Error(E);
19249 case UO_Plus:
19250 // The result is just the value.
19251 return Visit(E->getSubExpr());
19252 case UO_Minus: {
19253 if (!Visit(E->getSubExpr())) return false;
19254 if (!Result.isFixedPoint())
19255 return Error(E);
19256 bool Overflowed;
19257 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
19258 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
19259 return false;
19260 return Success(Negated, E);
19261 }
19262 case UO_LNot: {
19263 bool bres;
19264 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
19265 return false;
19266 return Success(!bres, E);
19267 }
19268 }
19269}
19270
19271bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
19272 const Expr *SubExpr = E->getSubExpr();
19273 QualType DestType = E->getType();
19274 assert(DestType->isFixedPointType() &&
19275 "Expected destination type to be a fixed point type");
19276 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
19277
19278 switch (E->getCastKind()) {
19279 case CK_FixedPointCast: {
19280 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
19281 if (!EvaluateFixedPoint(SubExpr, Src, Info))
19282 return false;
19283 bool Overflowed;
19284 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
19285 if (Overflowed) {
19286 if (Info.checkingForUndefinedBehavior())
19287 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19288 diag::warn_fixedpoint_constant_overflow)
19289 << Result.toString() << E->getType();
19290 if (!HandleOverflow(Info, E, Result, E->getType()))
19291 return false;
19292 }
19293 return Success(Result, E);
19294 }
19295 case CK_IntegralToFixedPoint: {
19296 APSInt Src;
19297 if (!EvaluateInteger(SubExpr, Src, Info))
19298 return false;
19299
19300 bool Overflowed;
19301 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
19302 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
19303
19304 if (Overflowed) {
19305 if (Info.checkingForUndefinedBehavior())
19306 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19307 diag::warn_fixedpoint_constant_overflow)
19308 << IntResult.toString() << E->getType();
19309 if (!HandleOverflow(Info, E, IntResult, E->getType()))
19310 return false;
19311 }
19312
19313 return Success(IntResult, E);
19314 }
19315 case CK_FloatingToFixedPoint: {
19316 APFloat Src(0.0);
19317 if (!EvaluateFloat(SubExpr, Src, Info))
19318 return false;
19319
19320 bool Overflowed;
19321 APFixedPoint Result = APFixedPoint::getFromFloatValue(
19322 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
19323
19324 if (Overflowed) {
19325 if (Info.checkingForUndefinedBehavior())
19326 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19327 diag::warn_fixedpoint_constant_overflow)
19328 << Result.toString() << E->getType();
19329 if (!HandleOverflow(Info, E, Result, E->getType()))
19330 return false;
19331 }
19332
19333 return Success(Result, E);
19334 }
19335 case CK_NoOp:
19336 case CK_LValueToRValue:
19337 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19338 default:
19339 return Error(E);
19340 }
19341}
19342
19343bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19344 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
19345 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19346
19347 const Expr *LHS = E->getLHS();
19348 const Expr *RHS = E->getRHS();
19349 FixedPointSemantics ResultFXSema =
19350 Info.Ctx.getFixedPointSemantics(E->getType());
19351
19352 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
19353 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
19354 return false;
19355 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
19356 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
19357 return false;
19358
19359 bool OpOverflow = false, ConversionOverflow = false;
19360 APFixedPoint Result(LHSFX.getSemantics());
19361 switch (E->getOpcode()) {
19362 case BO_Add: {
19363 Result = LHSFX.add(RHSFX, &OpOverflow)
19364 .convert(ResultFXSema, &ConversionOverflow);
19365 break;
19366 }
19367 case BO_Sub: {
19368 Result = LHSFX.sub(RHSFX, &OpOverflow)
19369 .convert(ResultFXSema, &ConversionOverflow);
19370 break;
19371 }
19372 case BO_Mul: {
19373 Result = LHSFX.mul(RHSFX, &OpOverflow)
19374 .convert(ResultFXSema, &ConversionOverflow);
19375 break;
19376 }
19377 case BO_Div: {
19378 if (RHSFX.getValue() == 0) {
19379 Info.FFDiag(E, diag::note_expr_divide_by_zero);
19380 return false;
19381 }
19382 Result = LHSFX.div(RHSFX, &OpOverflow)
19383 .convert(ResultFXSema, &ConversionOverflow);
19384 break;
19385 }
19386 case BO_Shl:
19387 case BO_Shr: {
19388 FixedPointSemantics LHSSema = LHSFX.getSemantics();
19389 llvm::APSInt RHSVal = RHSFX.getValue();
19390
19391 unsigned ShiftBW =
19392 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
19393 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
19394 // Embedded-C 4.1.6.2.2:
19395 // The right operand must be nonnegative and less than the total number
19396 // of (nonpadding) bits of the fixed-point operand ...
19397 if (RHSVal.isNegative())
19398 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
19399 else if (Amt != RHSVal)
19400 Info.CCEDiag(E, diag::note_constexpr_large_shift)
19401 << RHSVal << E->getType() << ShiftBW;
19402
19403 if (E->getOpcode() == BO_Shl)
19404 Result = LHSFX.shl(Amt, &OpOverflow);
19405 else
19406 Result = LHSFX.shr(Amt, &OpOverflow);
19407 break;
19408 }
19409 default:
19410 return false;
19411 }
19412 if (OpOverflow || ConversionOverflow) {
19413 if (Info.checkingForUndefinedBehavior())
19414 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19415 diag::warn_fixedpoint_constant_overflow)
19416 << Result.toString() << E->getType();
19417 if (!HandleOverflow(Info, E, Result, E->getType()))
19418 return false;
19419 }
19420 return Success(Result, E);
19421}
19422
19423//===----------------------------------------------------------------------===//
19424// Float Evaluation
19425//===----------------------------------------------------------------------===//
19426
19427namespace {
19428class FloatExprEvaluator
19429 : public ExprEvaluatorBase<FloatExprEvaluator> {
19430 APFloat &Result;
19431public:
19432 FloatExprEvaluator(EvalInfo &info, APFloat &result)
19433 : ExprEvaluatorBaseTy(info), Result(result) {}
19434
19435 bool Success(const APValue &V, const Expr *e) {
19436 Result = V.getFloat();
19437 return true;
19438 }
19439
19440 bool ZeroInitialization(const Expr *E) {
19441 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
19442 return true;
19443 }
19444
19445 bool VisitCallExpr(const CallExpr *E);
19446
19447 bool VisitUnaryOperator(const UnaryOperator *E);
19448 bool VisitBinaryOperator(const BinaryOperator *E);
19449 bool VisitFloatingLiteral(const FloatingLiteral *E);
19450 bool VisitCastExpr(const CastExpr *E);
19451
19452 bool VisitUnaryReal(const UnaryOperator *E);
19453 bool VisitUnaryImag(const UnaryOperator *E);
19454
19455 // FIXME: Missing: array subscript of vector, member of vector
19456};
19457} // end anonymous namespace
19458
19459static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
19460 assert(!E->isValueDependent());
19461 assert(E->isPRValue() && E->getType()->isRealFloatingType());
19462 return FloatExprEvaluator(Info, Result).Visit(E);
19463}
19464
19465static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
19466 QualType ResultTy,
19467 const Expr *Arg,
19468 bool SNaN,
19469 llvm::APFloat &Result) {
19470 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
19471 if (!S) return false;
19472
19473 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
19474
19475 llvm::APInt fill;
19476
19477 // Treat empty strings as if they were zero.
19478 if (S->getString().empty())
19479 fill = llvm::APInt(32, 0);
19480 else if (S->getString().getAsInteger(0, fill))
19481 return false;
19482
19483 if (Context.getTargetInfo().isNan2008()) {
19484 if (SNaN)
19485 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19486 else
19487 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19488 } else {
19489 // Prior to IEEE 754-2008, architectures were allowed to choose whether
19490 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
19491 // a different encoding to what became a standard in 2008, and for pre-
19492 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
19493 // sNaN. This is now known as "legacy NaN" encoding.
19494 if (SNaN)
19495 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
19496 else
19497 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
19498 }
19499
19500 return true;
19501}
19502
19503bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
19504 if (!IsConstantEvaluatedBuiltinCall(E))
19505 return ExprEvaluatorBaseTy::VisitCallExpr(E);
19506
19507 switch (E->getBuiltinCallee()) {
19508 default:
19509 return false;
19510
19511 case Builtin::BI__builtin_huge_val:
19512 case Builtin::BI__builtin_huge_valf:
19513 case Builtin::BI__builtin_huge_vall:
19514 case Builtin::BI__builtin_huge_valf16:
19515 case Builtin::BI__builtin_huge_valf128:
19516 case Builtin::BI__builtin_inf:
19517 case Builtin::BI__builtin_inff:
19518 case Builtin::BI__builtin_infl:
19519 case Builtin::BI__builtin_inff16:
19520 case Builtin::BI__builtin_inff128: {
19521 const llvm::fltSemantics &Sem =
19522 Info.Ctx.getFloatTypeSemantics(E->getType());
19523 Result = llvm::APFloat::getInf(Sem);
19524 return true;
19525 }
19526
19527 case Builtin::BI__builtin_nans:
19528 case Builtin::BI__builtin_nansf:
19529 case Builtin::BI__builtin_nansl:
19530 case Builtin::BI__builtin_nansf16:
19531 case Builtin::BI__builtin_nansf128:
19532 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19533 true, Result))
19534 return Error(E);
19535 return true;
19536
19537 case Builtin::BI__builtin_nan:
19538 case Builtin::BI__builtin_nanf:
19539 case Builtin::BI__builtin_nanl:
19540 case Builtin::BI__builtin_nanf16:
19541 case Builtin::BI__builtin_nanf128:
19542 // If this is __builtin_nan() turn this into a nan, otherwise we
19543 // can't constant fold it.
19544 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
19545 false, Result))
19546 return Error(E);
19547 return true;
19548
19549 case Builtin::BI__builtin_elementwise_abs:
19550 case Builtin::BI__builtin_fabs:
19551 case Builtin::BI__builtin_fabsf:
19552 case Builtin::BI__builtin_fabsl:
19553 case Builtin::BI__builtin_fabsf128:
19554 // The C standard says "fabs raises no floating-point exceptions,
19555 // even if x is a signaling NaN. The returned value is independent of
19556 // the current rounding direction mode." Therefore constant folding can
19557 // proceed without regard to the floating point settings.
19558 // Reference, WG14 N2478 F.10.4.3
19559 if (!EvaluateFloat(E->getArg(0), Result, Info))
19560 return false;
19561
19562 if (Result.isNegative())
19563 Result.changeSign();
19564 return true;
19565
19566 case Builtin::BI__arithmetic_fence:
19567 return EvaluateFloat(E->getArg(0), Result, Info);
19568
19569 // FIXME: Builtin::BI__builtin_powi
19570 // FIXME: Builtin::BI__builtin_powif
19571 // FIXME: Builtin::BI__builtin_powil
19572
19573 case Builtin::BI__builtin_copysign:
19574 case Builtin::BI__builtin_copysignf:
19575 case Builtin::BI__builtin_copysignl:
19576 case Builtin::BI__builtin_copysignf128: {
19577 APFloat RHS(0.);
19578 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19579 !EvaluateFloat(E->getArg(1), RHS, Info))
19580 return false;
19581 Result.copySign(RHS);
19582 return true;
19583 }
19584
19585 case Builtin::BI__builtin_fmax:
19586 case Builtin::BI__builtin_fmaxf:
19587 case Builtin::BI__builtin_fmaxl:
19588 case Builtin::BI__builtin_fmaxf16:
19589 case Builtin::BI__builtin_fmaxf128: {
19590 APFloat RHS(0.);
19591 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19592 !EvaluateFloat(E->getArg(1), RHS, Info))
19593 return false;
19594 Result = maxnum(Result, RHS);
19595 return true;
19596 }
19597
19598 case Builtin::BI__builtin_fmin:
19599 case Builtin::BI__builtin_fminf:
19600 case Builtin::BI__builtin_fminl:
19601 case Builtin::BI__builtin_fminf16:
19602 case Builtin::BI__builtin_fminf128: {
19603 APFloat RHS(0.);
19604 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19605 !EvaluateFloat(E->getArg(1), RHS, Info))
19606 return false;
19607 Result = minnum(Result, RHS);
19608 return true;
19609 }
19610
19611 case Builtin::BI__builtin_fmaximum_num:
19612 case Builtin::BI__builtin_fmaximum_numf:
19613 case Builtin::BI__builtin_fmaximum_numl:
19614 case Builtin::BI__builtin_fmaximum_numf16:
19615 case Builtin::BI__builtin_fmaximum_numf128: {
19616 APFloat RHS(0.);
19617 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19618 !EvaluateFloat(E->getArg(1), RHS, Info))
19619 return false;
19620 Result = maximumnum(Result, RHS);
19621 return true;
19622 }
19623
19624 case Builtin::BI__builtin_fminimum_num:
19625 case Builtin::BI__builtin_fminimum_numf:
19626 case Builtin::BI__builtin_fminimum_numl:
19627 case Builtin::BI__builtin_fminimum_numf16:
19628 case Builtin::BI__builtin_fminimum_numf128: {
19629 APFloat RHS(0.);
19630 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19631 !EvaluateFloat(E->getArg(1), RHS, Info))
19632 return false;
19633 Result = minimumnum(Result, RHS);
19634 return true;
19635 }
19636
19637 case Builtin::BI__builtin_elementwise_fma: {
19638 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
19639 !E->getArg(2)->isPRValue()) {
19640 return false;
19641 }
19642 APFloat SourceY(0.), SourceZ(0.);
19643 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
19644 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
19645 !EvaluateFloat(E->getArg(2), SourceZ, Info))
19646 return false;
19647 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
19648 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
19649 return true;
19650 }
19651
19652 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
19653 APValue Vec;
19654 APSInt IdxAPS;
19655 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
19656 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
19657 return false;
19658 unsigned N = Vec.getVectorLength();
19659 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
19660 return Success(Vec.getVectorElt(Idx), E);
19661 }
19662 }
19663}
19664
19665bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
19666 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19667 ComplexValue CV;
19668 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
19669 return false;
19670 Result = CV.FloatReal;
19671 return true;
19672 }
19673
19674 return Visit(E->getSubExpr());
19675}
19676
19677bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
19678 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19679 ComplexValue CV;
19680 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
19681 return false;
19682 Result = CV.FloatImag;
19683 return true;
19684 }
19685
19686 VisitIgnoredValue(E->getSubExpr());
19687 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
19688 Result = llvm::APFloat::getZero(Sem);
19689 return true;
19690}
19691
19692bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19693 switch (E->getOpcode()) {
19694 default: return Error(E);
19695 case UO_Plus:
19696 return EvaluateFloat(E->getSubExpr(), Result, Info);
19697 case UO_Minus:
19698 // In C standard, WG14 N2478 F.3 p4
19699 // "the unary - raises no floating point exceptions,
19700 // even if the operand is signalling."
19701 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
19702 return false;
19703 Result.changeSign();
19704 return true;
19705 }
19706}
19707
19708bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19709 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
19710 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19711
19712 APFloat RHS(0.0);
19713 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
19714 if (!LHSOK && !Info.noteFailure())
19715 return false;
19716 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
19717 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
19718}
19719
19720bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
19721 Result = E->getValue();
19722 return true;
19723}
19724
19725bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
19726 const Expr* SubExpr = E->getSubExpr();
19727
19728 switch (E->getCastKind()) {
19729 default:
19730 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19731
19732 case CK_HLSLAggregateSplatCast:
19733 llvm_unreachable("invalid cast kind for floating value");
19734
19735 case CK_IntegralToFloating: {
19736 APSInt IntResult;
19737 const FPOptions FPO = E->getFPFeaturesInEffect(
19738 Info.Ctx.getLangOpts());
19739 return EvaluateInteger(SubExpr, IntResult, Info) &&
19740 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
19741 IntResult, E->getType(), Result);
19742 }
19743
19744 case CK_FixedPointToFloating: {
19745 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
19746 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
19747 return false;
19748 Result =
19749 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
19750 return true;
19751 }
19752
19753 case CK_FloatingCast: {
19754 if (!Visit(SubExpr))
19755 return false;
19756 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
19757 Result);
19758 }
19759
19760 case CK_FloatingComplexToReal: {
19761 ComplexValue V;
19762 if (!EvaluateComplex(SubExpr, V, Info))
19763 return false;
19764 Result = V.getComplexFloatReal();
19765 return true;
19766 }
19767 case CK_HLSLVectorTruncation: {
19768 APValue Val;
19769 if (!EvaluateVector(SubExpr, Val, Info))
19770 return Error(E);
19771 return Success(Val.getVectorElt(0), E);
19772 }
19773 case CK_HLSLMatrixTruncation: {
19774 APValue Val;
19775 if (!EvaluateMatrix(SubExpr, Val, Info))
19776 return Error(E);
19777 return Success(Val.getMatrixElt(0, 0), E);
19778 }
19779 case CK_HLSLElementwiseCast: {
19780 SmallVector<APValue> SrcVals;
19781 SmallVector<QualType> SrcTypes;
19782
19783 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
19784 SrcTypes))
19785 return false;
19786 APValue Val;
19787
19788 // cast our single element
19789 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
19790 APValue ResultVal;
19791 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
19792 ResultVal))
19793 return false;
19794 return Success(ResultVal, E);
19795 }
19796 }
19797}
19798
19799//===----------------------------------------------------------------------===//
19800// Complex Evaluation (for float and integer)
19801//===----------------------------------------------------------------------===//
19802
19803namespace {
19804class ComplexExprEvaluator
19805 : public ExprEvaluatorBase<ComplexExprEvaluator> {
19806 ComplexValue &Result;
19807
19808public:
19809 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
19810 : ExprEvaluatorBaseTy(info), Result(Result) {}
19811
19812 bool Success(const APValue &V, const Expr *e) {
19813 Result.setFrom(V);
19814 return true;
19815 }
19816
19817 bool ZeroInitialization(const Expr *E);
19818
19819 //===--------------------------------------------------------------------===//
19820 // Visitor Methods
19821 //===--------------------------------------------------------------------===//
19822
19823 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
19824 bool VisitCastExpr(const CastExpr *E);
19825 bool VisitBinaryOperator(const BinaryOperator *E);
19826 bool VisitUnaryOperator(const UnaryOperator *E);
19827 bool VisitInitListExpr(const InitListExpr *E);
19828 bool VisitCallExpr(const CallExpr *E);
19829};
19830} // end anonymous namespace
19831
19832static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
19833 EvalInfo &Info) {
19834 assert(!E->isValueDependent());
19835 assert(E->isPRValue() && E->getType()->isAnyComplexType());
19836 return ComplexExprEvaluator(Info, Result).Visit(E);
19837}
19838
19839bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
19840 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
19841 if (ElemTy->isRealFloatingType()) {
19842 Result.makeComplexFloat();
19843 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
19844 Result.FloatReal = Zero;
19845 Result.FloatImag = Zero;
19846 } else {
19847 Result.makeComplexInt();
19848 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
19849 Result.IntReal = Zero;
19850 Result.IntImag = Zero;
19851 }
19852 return true;
19853}
19854
19855bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
19856 const Expr* SubExpr = E->getSubExpr();
19857
19858 if (SubExpr->getType()->isRealFloatingType()) {
19859 Result.makeComplexFloat();
19860 APFloat &Imag = Result.FloatImag;
19861 if (!EvaluateFloat(SubExpr, Imag, Info))
19862 return false;
19863
19864 Result.FloatReal = APFloat(Imag.getSemantics());
19865 return true;
19866 } else {
19867 assert(SubExpr->getType()->isIntegerType() &&
19868 "Unexpected imaginary literal.");
19869
19870 Result.makeComplexInt();
19871 APSInt &Imag = Result.IntImag;
19872 if (!EvaluateInteger(SubExpr, Imag, Info))
19873 return false;
19874
19875 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
19876 return true;
19877 }
19878}
19879
19880bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
19881
19882 switch (E->getCastKind()) {
19883 case CK_BitCast:
19884 case CK_BaseToDerived:
19885 case CK_DerivedToBase:
19886 case CK_UncheckedDerivedToBase:
19887 case CK_Dynamic:
19888 case CK_ToUnion:
19889 case CK_ArrayToPointerDecay:
19890 case CK_FunctionToPointerDecay:
19891 case CK_NullToPointer:
19892 case CK_NullToMemberPointer:
19893 case CK_BaseToDerivedMemberPointer:
19894 case CK_DerivedToBaseMemberPointer:
19895 case CK_MemberPointerToBoolean:
19896 case CK_ReinterpretMemberPointer:
19897 case CK_ConstructorConversion:
19898 case CK_IntegralToPointer:
19899 case CK_PointerToIntegral:
19900 case CK_PointerToBoolean:
19901 case CK_ToVoid:
19902 case CK_VectorSplat:
19903 case CK_IntegralCast:
19904 case CK_BooleanToSignedIntegral:
19905 case CK_IntegralToBoolean:
19906 case CK_IntegralToFloating:
19907 case CK_FloatingToIntegral:
19908 case CK_FloatingToBoolean:
19909 case CK_FloatingCast:
19910 case CK_CPointerToObjCPointerCast:
19911 case CK_BlockPointerToObjCPointerCast:
19912 case CK_AnyPointerToBlockPointerCast:
19913 case CK_ObjCObjectLValueCast:
19914 case CK_FloatingComplexToReal:
19915 case CK_FloatingComplexToBoolean:
19916 case CK_IntegralComplexToReal:
19917 case CK_IntegralComplexToBoolean:
19918 case CK_ARCProduceObject:
19919 case CK_ARCConsumeObject:
19920 case CK_ARCReclaimReturnedObject:
19921 case CK_ARCExtendBlockObject:
19922 case CK_CopyAndAutoreleaseBlockObject:
19923 case CK_BuiltinFnToFnPtr:
19924 case CK_ZeroToOCLOpaqueType:
19925 case CK_NonAtomicToAtomic:
19926 case CK_AddressSpaceConversion:
19927 case CK_IntToOCLSampler:
19928 case CK_FloatingToFixedPoint:
19929 case CK_FixedPointToFloating:
19930 case CK_FixedPointCast:
19931 case CK_FixedPointToBoolean:
19932 case CK_FixedPointToIntegral:
19933 case CK_IntegralToFixedPoint:
19934 case CK_MatrixCast:
19935 case CK_HLSLVectorTruncation:
19936 case CK_HLSLMatrixTruncation:
19937 case CK_HLSLElementwiseCast:
19938 case CK_HLSLAggregateSplatCast:
19939 llvm_unreachable("invalid cast kind for complex value");
19940
19941 case CK_LValueToRValue:
19942 case CK_AtomicToNonAtomic:
19943 case CK_NoOp:
19944 case CK_LValueToRValueBitCast:
19945 case CK_HLSLArrayRValue:
19946 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19947
19948 case CK_Dependent:
19949 case CK_LValueBitCast:
19950 case CK_UserDefinedConversion:
19951 return Error(E);
19952
19953 case CK_FloatingRealToComplex: {
19954 APFloat &Real = Result.FloatReal;
19955 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
19956 return false;
19957
19958 Result.makeComplexFloat();
19959 Result.FloatImag = APFloat(Real.getSemantics());
19960 return true;
19961 }
19962
19963 case CK_FloatingComplexCast: {
19964 if (!Visit(E->getSubExpr()))
19965 return false;
19966
19967 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
19968 QualType From
19969 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
19970
19971 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
19972 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
19973 }
19974
19975 case CK_FloatingComplexToIntegralComplex: {
19976 if (!Visit(E->getSubExpr()))
19977 return false;
19978
19979 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
19980 QualType From
19981 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
19982 Result.makeComplexInt();
19983 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
19984 To, Result.IntReal) &&
19985 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
19986 To, Result.IntImag);
19987 }
19988
19989 case CK_IntegralRealToComplex: {
19990 APSInt &Real = Result.IntReal;
19991 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
19992 return false;
19993
19994 Result.makeComplexInt();
19995 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
19996 return true;
19997 }
19998
19999 case CK_IntegralComplexCast: {
20000 if (!Visit(E->getSubExpr()))
20001 return false;
20002
20003 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20004 QualType From
20005 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20006
20007 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
20008 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
20009 return true;
20010 }
20011
20012 case CK_IntegralComplexToFloatingComplex: {
20013 if (!Visit(E->getSubExpr()))
20014 return false;
20015
20016 const FPOptions FPO = E->getFPFeaturesInEffect(
20017 Info.Ctx.getLangOpts());
20018 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20019 QualType From
20020 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20021 Result.makeComplexFloat();
20022 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
20023 To, Result.FloatReal) &&
20024 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
20025 To, Result.FloatImag);
20026 }
20027 }
20028
20029 llvm_unreachable("unknown cast resulting in complex value");
20030}
20031
20032uint8_t GFNIMultiplicativeInverse(uint8_t Byte) {
20033 // Lookup Table for Multiplicative Inverse in GF(2^8)
20034 const uint8_t GFInv[256] = {
20035 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0,
20036 0xb0, 0xe1, 0xe5, 0xc7, 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f,
20037 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2, 0x3a, 0x6e, 0x5a, 0xf1,
20038 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,
20039 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f,
20040 0x77, 0xbb, 0x59, 0x19, 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69,
20041 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09, 0xed, 0x5c, 0x05, 0xca,
20042 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,
20043 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf,
20044 0x33, 0x93, 0x21, 0x3b, 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c,
20045 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82, 0x83, 0x7e, 0x7f, 0x80,
20046 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,
20047 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88,
20048 0xf9, 0xdc, 0x89, 0x9a, 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48,
20049 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62, 0x0c, 0xe0, 0x1f, 0xef,
20050 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,
20051 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04,
20052 0x1b, 0xfc, 0xac, 0xe6, 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea,
20053 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b, 0xb1, 0x0d, 0xd6, 0xeb,
20054 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,
20055 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0,
20056 0xcd, 0x1a, 0x41, 0x1c};
20057
20058 return GFInv[Byte];
20059}
20060
20061uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm,
20062 bool Inverse) {
20063 unsigned NumBitsInByte = 8;
20064 // Computing the affine transformation
20065 uint8_t RetByte = 0;
20066 for (uint32_t BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
20067 uint8_t AByte =
20068 AQword.lshr((7 - static_cast<int32_t>(BitIdx)) * NumBitsInByte)
20069 .getLoBits(8)
20070 .getZExtValue();
20071 uint8_t Product;
20072 if (Inverse) {
20073 Product = AByte & GFNIMultiplicativeInverse(XByte);
20074 } else {
20075 Product = AByte & XByte;
20076 }
20077 uint8_t Parity = 0;
20078
20079 // Dot product in GF(2) uses XOR instead of addition
20080 for (unsigned PBitIdx = 0; PBitIdx != NumBitsInByte; ++PBitIdx) {
20081 Parity = Parity ^ ((Product >> PBitIdx) & 0x1);
20082 }
20083
20084 uint8_t Temp = Imm[BitIdx] ? 1 : 0;
20085 RetByte |= (Temp ^ Parity) << BitIdx;
20086 }
20087 return RetByte;
20088}
20089
20090uint8_t GFNIMul(uint8_t AByte, uint8_t BByte) {
20091 // Multiplying two polynomials of degree 7
20092 // Polynomial of degree 7
20093 // x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
20094 uint16_t TWord = 0;
20095 unsigned NumBitsInByte = 8;
20096 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
20097 if ((BByte >> BitIdx) & 0x1) {
20098 TWord = TWord ^ (AByte << BitIdx);
20099 }
20100 }
20101
20102 // When multiplying two polynomials of degree 7
20103 // results in a polynomial of degree 14
20104 // so the result has to be reduced to 7
20105 // Reduction polynomial is x^8 + x^4 + x^3 + x + 1 i.e. 0x11B
20106 for (int32_t BitIdx = 14; BitIdx > 7; --BitIdx) {
20107 if ((TWord >> BitIdx) & 0x1) {
20108 TWord = TWord ^ (0x11B << (BitIdx - 8));
20109 }
20110 }
20111 return (TWord & 0xFF);
20112}
20113
20114void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
20115 APFloat &ResR, APFloat &ResI) {
20116 // This is an implementation of complex multiplication according to the
20117 // constraints laid out in C11 Annex G. The implementation uses the
20118 // following naming scheme:
20119 // (a + ib) * (c + id)
20120
20121 APFloat AC = A * C;
20122 APFloat BD = B * D;
20123 APFloat AD = A * D;
20124 APFloat BC = B * C;
20125 ResR = AC - BD;
20126 ResI = AD + BC;
20127 if (ResR.isNaN() && ResI.isNaN()) {
20128 bool Recalc = false;
20129 if (A.isInfinity() || B.isInfinity()) {
20130 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
20131 A);
20132 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
20133 B);
20134 if (C.isNaN())
20135 C = APFloat::copySign(APFloat(C.getSemantics()), C);
20136 if (D.isNaN())
20137 D = APFloat::copySign(APFloat(D.getSemantics()), D);
20138 Recalc = true;
20139 }
20140 if (C.isInfinity() || D.isInfinity()) {
20141 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
20142 C);
20143 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
20144 D);
20145 if (A.isNaN())
20146 A = APFloat::copySign(APFloat(A.getSemantics()), A);
20147 if (B.isNaN())
20148 B = APFloat::copySign(APFloat(B.getSemantics()), B);
20149 Recalc = true;
20150 }
20151 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
20152 BC.isInfinity())) {
20153 if (A.isNaN())
20154 A = APFloat::copySign(APFloat(A.getSemantics()), A);
20155 if (B.isNaN())
20156 B = APFloat::copySign(APFloat(B.getSemantics()), B);
20157 if (C.isNaN())
20158 C = APFloat::copySign(APFloat(C.getSemantics()), C);
20159 if (D.isNaN())
20160 D = APFloat::copySign(APFloat(D.getSemantics()), D);
20161 Recalc = true;
20162 }
20163 if (Recalc) {
20164 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
20165 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
20166 }
20167 }
20168}
20169
20170void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
20171 APFloat &ResR, APFloat &ResI) {
20172 // This is an implementation of complex division according to the
20173 // constraints laid out in C11 Annex G. The implementation uses the
20174 // following naming scheme:
20175 // (a + ib) / (c + id)
20176
20177 int DenomLogB = 0;
20178 APFloat MaxCD = maxnum(abs(C), abs(D));
20179 if (MaxCD.isFinite()) {
20180 DenomLogB = ilogb(MaxCD);
20181 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
20182 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
20183 }
20184 APFloat Denom = C * C + D * D;
20185 ResR =
20186 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
20187 ResI =
20188 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
20189 if (ResR.isNaN() && ResI.isNaN()) {
20190 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
20191 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
20192 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
20193 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
20194 D.isFinite()) {
20195 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
20196 A);
20197 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
20198 B);
20199 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
20200 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
20201 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
20202 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
20203 C);
20204 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
20205 D);
20206 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
20207 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
20208 }
20209 }
20210}
20211
20213 // Normalize shift amount to [0, BitWidth) range to match runtime behavior
20214 APSInt NormAmt = Amount;
20215 unsigned BitWidth = Value.getBitWidth();
20216 unsigned AmtBitWidth = NormAmt.getBitWidth();
20217 if (BitWidth == 1) {
20218 // Rotating a 1-bit value is always a no-op
20219 NormAmt = APSInt(APInt(AmtBitWidth, 0), NormAmt.isUnsigned());
20220 } else if (BitWidth == 2) {
20221 // For 2-bit values: rotation amount is 0 or 1 based on
20222 // whether the amount is even or odd. We can't use srem here because
20223 // the divisor (2) would be misinterpreted as -2 in 2-bit signed arithmetic.
20224 NormAmt =
20225 APSInt(APInt(AmtBitWidth, NormAmt[0] ? 1 : 0), NormAmt.isUnsigned());
20226 } else {
20227 APInt Divisor;
20228 if (AmtBitWidth > BitWidth) {
20229 Divisor = llvm::APInt(AmtBitWidth, BitWidth);
20230 } else {
20231 Divisor = llvm::APInt(BitWidth, BitWidth);
20232 if (AmtBitWidth < BitWidth) {
20233 NormAmt = NormAmt.extend(BitWidth);
20234 }
20235 }
20236
20237 // Normalize to [0, BitWidth)
20238 if (NormAmt.isSigned()) {
20239 NormAmt = APSInt(NormAmt.srem(Divisor), /*isUnsigned=*/false);
20240 if (NormAmt.isNegative()) {
20241 APSInt SignedDivisor(Divisor, /*isUnsigned=*/false);
20242 NormAmt += SignedDivisor;
20243 }
20244 } else {
20245 NormAmt = APSInt(NormAmt.urem(Divisor), /*isUnsigned=*/true);
20246 }
20247 }
20248
20249 return NormAmt;
20250}
20251
20252bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20253 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20254 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20255
20256 // Track whether the LHS or RHS is real at the type system level. When this is
20257 // the case we can simplify our evaluation strategy.
20258 bool LHSReal = false, RHSReal = false;
20259
20260 bool LHSOK;
20261 if (E->getLHS()->getType()->isRealFloatingType()) {
20262 LHSReal = true;
20263 APFloat &Real = Result.FloatReal;
20264 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
20265 if (LHSOK) {
20266 Result.makeComplexFloat();
20267 Result.FloatImag = APFloat(Real.getSemantics());
20268 }
20269 } else {
20270 LHSOK = Visit(E->getLHS());
20271 }
20272 if (!LHSOK && !Info.noteFailure())
20273 return false;
20274
20275 ComplexValue RHS;
20276 if (E->getRHS()->getType()->isRealFloatingType()) {
20277 RHSReal = true;
20278 APFloat &Real = RHS.FloatReal;
20279 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
20280 return false;
20281 RHS.makeComplexFloat();
20282 RHS.FloatImag = APFloat(Real.getSemantics());
20283 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
20284 return false;
20285
20286 assert(!(LHSReal && RHSReal) &&
20287 "Cannot have both operands of a complex operation be real.");
20288 switch (E->getOpcode()) {
20289 default: return Error(E);
20290 case BO_Add:
20291 if (Result.isComplexFloat()) {
20292 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
20293 APFloat::rmNearestTiesToEven);
20294 if (LHSReal)
20295 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
20296 else if (!RHSReal)
20297 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
20298 APFloat::rmNearestTiesToEven);
20299 } else {
20300 Result.getComplexIntReal() += RHS.getComplexIntReal();
20301 Result.getComplexIntImag() += RHS.getComplexIntImag();
20302 }
20303 break;
20304 case BO_Sub:
20305 if (Result.isComplexFloat()) {
20306 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
20307 APFloat::rmNearestTiesToEven);
20308 if (LHSReal) {
20309 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
20310 Result.getComplexFloatImag().changeSign();
20311 } else if (!RHSReal) {
20312 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
20313 APFloat::rmNearestTiesToEven);
20314 }
20315 } else {
20316 Result.getComplexIntReal() -= RHS.getComplexIntReal();
20317 Result.getComplexIntImag() -= RHS.getComplexIntImag();
20318 }
20319 break;
20320 case BO_Mul:
20321 if (Result.isComplexFloat()) {
20322 // This is an implementation of complex multiplication according to the
20323 // constraints laid out in C11 Annex G. The implementation uses the
20324 // following naming scheme:
20325 // (a + ib) * (c + id)
20326 ComplexValue LHS = Result;
20327 APFloat &A = LHS.getComplexFloatReal();
20328 APFloat &B = LHS.getComplexFloatImag();
20329 APFloat &C = RHS.getComplexFloatReal();
20330 APFloat &D = RHS.getComplexFloatImag();
20331 APFloat &ResR = Result.getComplexFloatReal();
20332 APFloat &ResI = Result.getComplexFloatImag();
20333 if (LHSReal) {
20334 assert(!RHSReal && "Cannot have two real operands for a complex op!");
20335 ResR = A;
20336 ResI = A;
20337 // ResR = A * C;
20338 // ResI = A * D;
20339 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
20340 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
20341 return false;
20342 } else if (RHSReal) {
20343 // ResR = C * A;
20344 // ResI = C * B;
20345 ResR = C;
20346 ResI = C;
20347 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
20348 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
20349 return false;
20350 } else {
20351 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
20352 }
20353 } else {
20354 ComplexValue LHS = Result;
20355 Result.getComplexIntReal() =
20356 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
20357 LHS.getComplexIntImag() * RHS.getComplexIntImag());
20358 Result.getComplexIntImag() =
20359 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
20360 LHS.getComplexIntImag() * RHS.getComplexIntReal());
20361 }
20362 break;
20363 case BO_Div:
20364 if (Result.isComplexFloat()) {
20365 // This is an implementation of complex division according to the
20366 // constraints laid out in C11 Annex G. The implementation uses the
20367 // following naming scheme:
20368 // (a + ib) / (c + id)
20369 ComplexValue LHS = Result;
20370 APFloat &A = LHS.getComplexFloatReal();
20371 APFloat &B = LHS.getComplexFloatImag();
20372 APFloat &C = RHS.getComplexFloatReal();
20373 APFloat &D = RHS.getComplexFloatImag();
20374 APFloat &ResR = Result.getComplexFloatReal();
20375 APFloat &ResI = Result.getComplexFloatImag();
20376 if (RHSReal) {
20377 ResR = A;
20378 ResI = B;
20379 // ResR = A / C;
20380 // ResI = B / C;
20381 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
20382 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
20383 return false;
20384 } else {
20385 if (LHSReal) {
20386 // No real optimizations we can do here, stub out with zero.
20387 B = APFloat::getZero(A.getSemantics());
20388 }
20389 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
20390 }
20391 } else {
20392 ComplexValue LHS = Result;
20393 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
20394 RHS.getComplexIntImag() * RHS.getComplexIntImag();
20395 if (Den.isZero())
20396 return Error(E, diag::note_expr_divide_by_zero);
20397
20398 Result.getComplexIntReal() =
20399 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
20400 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
20401 Result.getComplexIntImag() =
20402 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
20403 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
20404 }
20405 break;
20406 }
20407
20408 return true;
20409}
20410
20411bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20412 // Get the operand value into 'Result'.
20413 if (!Visit(E->getSubExpr()))
20414 return false;
20415
20416 switch (E->getOpcode()) {
20417 default:
20418 return Error(E);
20419 case UO_Extension:
20420 return true;
20421 case UO_Plus:
20422 // The result is always just the subexpr.
20423 return true;
20424 case UO_Minus:
20425 if (Result.isComplexFloat()) {
20426 Result.getComplexFloatReal().changeSign();
20427 Result.getComplexFloatImag().changeSign();
20428 }
20429 else {
20430 Result.getComplexIntReal() = -Result.getComplexIntReal();
20431 Result.getComplexIntImag() = -Result.getComplexIntImag();
20432 }
20433 return true;
20434 case UO_Not:
20435 if (Result.isComplexFloat())
20436 Result.getComplexFloatImag().changeSign();
20437 else
20438 Result.getComplexIntImag() = -Result.getComplexIntImag();
20439 return true;
20440 }
20441}
20442
20443bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
20444 if (E->getNumInits() == 2) {
20445 if (E->getType()->isComplexType()) {
20446 Result.makeComplexFloat();
20447 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
20448 return false;
20449 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
20450 return false;
20451 } else {
20452 Result.makeComplexInt();
20453 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
20454 return false;
20455 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
20456 return false;
20457 }
20458 return true;
20459 }
20460 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
20461}
20462
20463bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
20464 if (!IsConstantEvaluatedBuiltinCall(E))
20465 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20466
20467 switch (E->getBuiltinCallee()) {
20468 case Builtin::BI__builtin_complex:
20469 Result.makeComplexFloat();
20470 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
20471 return false;
20472 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
20473 return false;
20474 return true;
20475
20476 default:
20477 return false;
20478 }
20479}
20480
20481//===----------------------------------------------------------------------===//
20482// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
20483// implicit conversion.
20484//===----------------------------------------------------------------------===//
20485
20486namespace {
20487class AtomicExprEvaluator :
20488 public ExprEvaluatorBase<AtomicExprEvaluator> {
20489 const LValue *This;
20490 APValue &Result;
20491public:
20492 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
20493 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
20494
20495 bool Success(const APValue &V, const Expr *E) {
20496 Result = V;
20497 return true;
20498 }
20499
20500 bool ZeroInitialization(const Expr *E) {
20501 ImplicitValueInitExpr VIE(
20502 E->getType()->castAs<AtomicType>()->getValueType());
20503 // For atomic-qualified class (and array) types in C++, initialize the
20504 // _Atomic-wrapped subobject directly, in-place.
20505 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
20506 : Evaluate(Result, Info, &VIE);
20507 }
20508
20509 bool VisitCastExpr(const CastExpr *E) {
20510 switch (E->getCastKind()) {
20511 default:
20512 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20513 case CK_NullToPointer:
20514 VisitIgnoredValue(E->getSubExpr());
20515 return ZeroInitialization(E);
20516 case CK_NonAtomicToAtomic:
20517 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
20518 : Evaluate(Result, Info, E->getSubExpr());
20519 }
20520 }
20521};
20522} // end anonymous namespace
20523
20524static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
20525 EvalInfo &Info) {
20526 assert(!E->isValueDependent());
20527 assert(E->isPRValue() && E->getType()->isAtomicType());
20528 return AtomicExprEvaluator(Info, This, Result).Visit(E);
20529}
20530
20531//===----------------------------------------------------------------------===//
20532// Void expression evaluation, primarily for a cast to void on the LHS of a
20533// comma operator
20534//===----------------------------------------------------------------------===//
20535
20536namespace {
20537class VoidExprEvaluator
20538 : public ExprEvaluatorBase<VoidExprEvaluator> {
20539public:
20540 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
20541
20542 bool Success(const APValue &V, const Expr *e) { return true; }
20543
20544 bool ZeroInitialization(const Expr *E) { return true; }
20545
20546 bool VisitCastExpr(const CastExpr *E) {
20547 switch (E->getCastKind()) {
20548 default:
20549 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20550 case CK_ToVoid:
20551 VisitIgnoredValue(E->getSubExpr());
20552 return true;
20553 }
20554 }
20555
20556 bool VisitCallExpr(const CallExpr *E) {
20557 if (!IsConstantEvaluatedBuiltinCall(E))
20558 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20559
20560 switch (E->getBuiltinCallee()) {
20561 case Builtin::BI__assume:
20562 case Builtin::BI__builtin_assume:
20563 // The argument is not evaluated!
20564 return true;
20565
20566 case Builtin::BI__builtin_operator_delete:
20567 return HandleOperatorDeleteCall(Info, E);
20568
20569 default:
20570 return false;
20571 }
20572 }
20573
20574 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
20575};
20576} // end anonymous namespace
20577
20578bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
20579 // We cannot speculatively evaluate a delete expression.
20580 if (Info.SpeculativeEvaluationDepth)
20581 return false;
20582
20583 FunctionDecl *OperatorDelete = E->getOperatorDelete();
20584 if (!OperatorDelete
20585 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
20586 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
20587 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
20588 return false;
20589 }
20590
20591 const Expr *Arg = E->getArgument();
20592
20593 LValue Pointer;
20594 if (!EvaluatePointer(Arg, Pointer, Info))
20595 return false;
20596 if (Pointer.Designator.Invalid)
20597 return false;
20598
20599 // Deleting a null pointer has no effect.
20600 if (Pointer.isNullPointer()) {
20601 // This is the only case where we need to produce an extension warning:
20602 // the only other way we can succeed is if we find a dynamic allocation,
20603 // and we will have warned when we allocated it in that case.
20604 if (!Info.getLangOpts().CPlusPlus20)
20605 Info.CCEDiag(E, diag::note_constexpr_new);
20606 return true;
20607 }
20608
20609 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
20610 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
20611 if (!Alloc)
20612 return false;
20613 QualType AllocType = Pointer.Base.getDynamicAllocType();
20614
20615 // For the non-array case, the designator must be empty if the static type
20616 // does not have a virtual destructor.
20617 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
20619 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
20620 << Arg->getType()->getPointeeType() << AllocType;
20621 return false;
20622 }
20623
20624 // For a class type with a virtual destructor, the selected operator delete
20625 // is the one looked up when building the destructor.
20626 if (!E->isArrayForm() && !E->isGlobalDelete()) {
20627 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
20628 if (VirtualDelete &&
20629 !VirtualDelete
20630 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
20631 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
20632 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
20633 return false;
20634 }
20635 }
20636
20637 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
20638 (*Alloc)->Value, AllocType))
20639 return false;
20640
20641 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
20642 // The element was already erased. This means the destructor call also
20643 // deleted the object.
20644 // FIXME: This probably results in undefined behavior before we get this
20645 // far, and should be diagnosed elsewhere first.
20646 Info.FFDiag(E, diag::note_constexpr_double_delete);
20647 return false;
20648 }
20649
20650 return true;
20651}
20652
20653static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
20654 assert(!E->isValueDependent());
20655 assert(E->isPRValue() && E->getType()->isVoidType());
20656 return VoidExprEvaluator(Info).Visit(E);
20657}
20658
20659//===----------------------------------------------------------------------===//
20660// Top level Expr::EvaluateAsRValue method.
20661//===----------------------------------------------------------------------===//
20662
20663static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
20664 assert(!E->isValueDependent());
20665 // In C, function designators are not lvalues, but we evaluate them as if they
20666 // are.
20667 QualType T = E->getType();
20668 if (E->isGLValue() || T->isFunctionType()) {
20669 LValue LV;
20670 if (!EvaluateLValue(E, LV, Info))
20671 return false;
20672 LV.moveInto(Result);
20673 } else if (T->isVectorType()) {
20674 if (!EvaluateVector(E, Result, Info))
20675 return false;
20676 } else if (T->isConstantMatrixType()) {
20677 if (!EvaluateMatrix(E, Result, Info))
20678 return false;
20679 } else if (T->isIntegralOrEnumerationType()) {
20680 if (!IntExprEvaluator(Info, Result).Visit(E))
20681 return false;
20682 } else if (T->hasPointerRepresentation()) {
20683 LValue LV;
20684 if (!EvaluatePointer(E, LV, Info))
20685 return false;
20686 LV.moveInto(Result);
20687 } else if (T->isRealFloatingType()) {
20688 llvm::APFloat F(0.0);
20689 if (!EvaluateFloat(E, F, Info))
20690 return false;
20691 Result = APValue(F);
20692 } else if (T->isAnyComplexType()) {
20693 ComplexValue C;
20694 if (!EvaluateComplex(E, C, Info))
20695 return false;
20696 C.moveInto(Result);
20697 } else if (T->isFixedPointType()) {
20698 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
20699 } else if (T->isMemberPointerType()) {
20700 MemberPtr P;
20701 if (!EvaluateMemberPointer(E, P, Info))
20702 return false;
20703 P.moveInto(Result);
20704 return true;
20705 } else if (T->isArrayType()) {
20706 LValue LV;
20707 APValue &Value =
20708 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
20709 if (!EvaluateArray(E, LV, Value, Info))
20710 return false;
20711 Result = Value;
20712 } else if (T->isRecordType()) {
20713 LValue LV;
20714 APValue &Value =
20715 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
20716 if (!EvaluateRecord(E, LV, Value, Info))
20717 return false;
20718 Result = Value;
20719 } else if (T->isVoidType()) {
20720 if (!Info.getLangOpts().CPlusPlus11)
20721 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
20722 << E->getType();
20723 if (!EvaluateVoid(E, Info))
20724 return false;
20725 } else if (T->isAtomicType()) {
20727 if (Unqual->isArrayType() || Unqual->isRecordType()) {
20728 LValue LV;
20729 APValue &Value = Info.CurrentCall->createTemporary(
20730 E, Unqual, ScopeKind::FullExpression, LV);
20731 if (!EvaluateAtomic(E, &LV, Value, Info))
20732 return false;
20733 Result = Value;
20734 } else {
20735 if (!EvaluateAtomic(E, nullptr, Result, Info))
20736 return false;
20737 }
20738 } else if (Info.getLangOpts().CPlusPlus11) {
20739 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
20740 return false;
20741 } else {
20742 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
20743 return false;
20744 }
20745
20746 return true;
20747}
20748
20749/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
20750/// cases, the in-place evaluation is essential, since later initializers for
20751/// an object can indirectly refer to subobjects which were initialized earlier.
20752static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
20753 const Expr *E, bool AllowNonLiteralTypes) {
20754 assert(!E->isValueDependent());
20755
20756 // Normally expressions passed to EvaluateInPlace have a type, but not when
20757 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
20758 // replaced with a CXXConstructExpr. This can happen in LLDB.
20759 if (E->getType().isNull())
20760 return false;
20761
20762 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
20763 return false;
20764
20765 if (E->isPRValue()) {
20766 // Evaluate arrays and record types in-place, so that later initializers can
20767 // refer to earlier-initialized members of the object.
20768 QualType T = E->getType();
20769 if (T->isArrayType())
20770 return EvaluateArray(E, This, Result, Info);
20771 else if (T->isRecordType())
20772 return EvaluateRecord(E, This, Result, Info);
20773 else if (T->isAtomicType()) {
20775 if (Unqual->isArrayType() || Unqual->isRecordType())
20776 return EvaluateAtomic(E, &This, Result, Info);
20777 }
20778 }
20779
20780 // For any other type, in-place evaluation is unimportant.
20781 return Evaluate(Result, Info, E);
20782}
20783
20784/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
20785/// lvalue-to-rvalue cast if it is an lvalue.
20786static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
20787 assert(!E->isValueDependent());
20788
20789 if (E->getType().isNull())
20790 return false;
20791
20792 if (!CheckLiteralType(Info, E))
20793 return false;
20794
20795 if (Info.EnableNewConstInterp) {
20796 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
20797 return false;
20798 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
20799 ConstantExprKind::Normal);
20800 }
20801
20802 if (!::Evaluate(Result, Info, E))
20803 return false;
20804
20805 // Implicit lvalue-to-rvalue cast.
20806 if (E->isGLValue()) {
20807 LValue LV;
20808 LV.setFrom(Info.Ctx, Result);
20809 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
20810 return false;
20811 }
20812
20813 // Check this core constant expression is a constant expression.
20814 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
20815 ConstantExprKind::Normal) &&
20816 CheckMemoryLeaks(Info);
20817}
20818
20819static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
20820 const ASTContext &Ctx, bool &IsConst) {
20821 // Fast-path evaluations of integer literals, since we sometimes see files
20822 // containing vast quantities of these.
20823 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
20824 Result =
20825 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
20826 IsConst = true;
20827 return true;
20828 }
20829
20830 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
20831 Result = APValue(APSInt(APInt(1, L->getValue())));
20832 IsConst = true;
20833 return true;
20834 }
20835
20836 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
20837 Result = APValue(FL->getValue());
20838 IsConst = true;
20839 return true;
20840 }
20841
20842 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
20843 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
20844 IsConst = true;
20845 return true;
20846 }
20847
20848 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
20849 if (CE->hasAPValueResult()) {
20850 APValue APV = CE->getAPValueResult();
20851 if (!APV.isLValue()) {
20852 Result = std::move(APV);
20853 IsConst = true;
20854 return true;
20855 }
20856 }
20857
20858 // The SubExpr is usually just an IntegerLiteral.
20859 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
20860 }
20861
20862 // This case should be rare, but we need to check it before we check on
20863 // the type below.
20864 if (Exp->getType().isNull()) {
20865 IsConst = false;
20866 return true;
20867 }
20868
20869 return false;
20870}
20871
20874 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
20875 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
20876}
20877
20878static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
20879 const ASTContext &Ctx, EvalInfo &Info) {
20880 assert(!E->isValueDependent());
20881 bool IsConst;
20882 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
20883 return IsConst;
20884
20885 return EvaluateAsRValue(Info, E, Result.Val);
20886}
20887
20889 const ASTContext &Ctx,
20890 Expr::SideEffectsKind AllowSideEffects,
20891 EvalInfo &Info) {
20892 assert(!E->isValueDependent());
20894 return false;
20895
20896 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
20897 !ExprResult.Val.isInt() ||
20898 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
20899 return false;
20900
20901 return true;
20902}
20903
20905 const ASTContext &Ctx,
20906 Expr::SideEffectsKind AllowSideEffects,
20907 EvalInfo &Info) {
20908 assert(!E->isValueDependent());
20909 if (!E->getType()->isFixedPointType())
20910 return false;
20911
20912 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
20913 return false;
20914
20915 if (!ExprResult.Val.isFixedPoint() ||
20916 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
20917 return false;
20918
20919 return true;
20920}
20921
20922/// EvaluateAsRValue - Return true if this is a constant which we can fold using
20923/// any crazy technique (that has nothing to do with language standards) that
20924/// we want to. If this function returns true, it returns the folded constant
20925/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
20926/// will be applied to the result.
20928 bool InConstantContext) const {
20929 assert(!isValueDependent() &&
20930 "Expression evaluator can't be called on a dependent expression.");
20931 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
20932 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
20933 Info.InConstantContext = InConstantContext;
20934 return ::EvaluateAsRValue(this, Result, Ctx, Info);
20935}
20936
20938 bool InConstantContext) const {
20939 assert(!isValueDependent() &&
20940 "Expression evaluator can't be called on a dependent expression.");
20941 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
20942 EvalResult Scratch;
20943 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
20944 HandleConversionToBool(Scratch.Val, Result);
20945}
20946
20948 SideEffectsKind AllowSideEffects,
20949 bool InConstantContext) const {
20950 assert(!isValueDependent() &&
20951 "Expression evaluator can't be called on a dependent expression.");
20952 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
20953 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
20954 Info.InConstantContext = InConstantContext;
20955 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
20956}
20957
20959 SideEffectsKind AllowSideEffects,
20960 bool InConstantContext) const {
20961 assert(!isValueDependent() &&
20962 "Expression evaluator can't be called on a dependent expression.");
20963 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
20964 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
20965 Info.InConstantContext = InConstantContext;
20966 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
20967}
20968
20969bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
20970 SideEffectsKind AllowSideEffects,
20971 bool InConstantContext) const {
20972 assert(!isValueDependent() &&
20973 "Expression evaluator can't be called on a dependent expression.");
20974
20975 if (!getType()->isRealFloatingType())
20976 return false;
20977
20978 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
20980 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
20981 !ExprResult.Val.isFloat() ||
20982 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
20983 return false;
20984
20985 Result = ExprResult.Val.getFloat();
20986 return true;
20987}
20988
20990 bool InConstantContext) const {
20991 assert(!isValueDependent() &&
20992 "Expression evaluator can't be called on a dependent expression.");
20993
20994 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
20995 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
20996 Info.InConstantContext = InConstantContext;
20997 LValue LV;
20998 CheckedTemporaries CheckedTemps;
20999
21000 if (Info.EnableNewConstInterp) {
21001 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
21002 ConstantExprKind::Normal))
21003 return false;
21004
21005 LV.setFrom(Ctx, Result.Val);
21007 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
21008 ConstantExprKind::Normal, CheckedTemps);
21009 }
21010
21011 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
21012 Result.HasSideEffects ||
21015 ConstantExprKind::Normal, CheckedTemps))
21016 return false;
21017
21018 LV.moveInto(Result.Val);
21019 return true;
21020}
21021
21023 APValue DestroyedValue, QualType Type,
21024 SourceLocation Loc, Expr::EvalStatus &EStatus,
21025 bool IsConstantDestruction) {
21026 EvalInfo Info(Ctx, EStatus,
21027 IsConstantDestruction ? EvaluationMode::ConstantExpression
21029 Info.setEvaluatingDecl(Base, DestroyedValue,
21030 EvalInfo::EvaluatingDeclKind::Dtor);
21031 Info.InConstantContext = IsConstantDestruction;
21032
21033 LValue LVal;
21034 LVal.set(Base);
21035
21036 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
21037 EStatus.HasSideEffects)
21038 return false;
21039
21040 if (!Info.discardCleanups())
21041 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21042
21043 return true;
21044}
21045
21047 ConstantExprKind Kind) const {
21048 assert(!isValueDependent() &&
21049 "Expression evaluator can't be called on a dependent expression.");
21050 bool IsConst;
21051 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
21052 Result.Val.hasValue())
21053 return true;
21054
21055 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
21057 EvalInfo Info(Ctx, Result, EM);
21058 Info.InConstantContext = true;
21059
21060 if (Info.EnableNewConstInterp) {
21061 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
21062 return false;
21063 return CheckConstantExpression(Info, getExprLoc(),
21064 getStorageType(Ctx, this), Result.Val, Kind);
21065 }
21066
21067 // The type of the object we're initializing is 'const T' for a class NTTP.
21068 QualType T = getType();
21069 if (Kind == ConstantExprKind::ClassTemplateArgument)
21070 T.addConst();
21071
21072 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
21073 // represent the result of the evaluation. CheckConstantExpression ensures
21074 // this doesn't escape.
21075 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
21076 APValue::LValueBase Base(&BaseMTE);
21077 Info.setEvaluatingDecl(Base, Result.Val);
21078
21079 LValue LVal;
21080 LVal.set(Base);
21081 // C++23 [intro.execution]/p5
21082 // A full-expression is [...] a constant-expression
21083 // So we need to make sure temporary objects are destroyed after having
21084 // evaluating the expression (per C++23 [class.temporary]/p4).
21085 FullExpressionRAII Scope(Info);
21086 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
21087 Result.HasSideEffects || !Scope.destroy())
21088 return false;
21089
21090 if (!Info.discardCleanups())
21091 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21092
21093 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
21094 Result.Val, Kind))
21095 return false;
21096 if (!CheckMemoryLeaks(Info))
21097 return false;
21098
21099 // If this is a class template argument, it's required to have constant
21100 // destruction too.
21101 if (Kind == ConstantExprKind::ClassTemplateArgument &&
21103 true) ||
21104 Result.HasSideEffects)) {
21105 // FIXME: Prefix a note to indicate that the problem is lack of constant
21106 // destruction.
21107 return false;
21108 }
21109
21110 return true;
21111}
21112
21114 const VarDecl *VD,
21116 bool IsConstantInitialization) const {
21117 assert(!isValueDependent() &&
21118 "Expression evaluator can't be called on a dependent expression.");
21119 assert(VD && "Need a valid VarDecl");
21120
21121 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
21122 std::string Name;
21123 llvm::raw_string_ostream OS(Name);
21124 VD->printQualifiedName(OS);
21125 return Name;
21126 });
21127
21128 Expr::EvalStatus EStatus;
21129 EStatus.Diag = &Notes;
21130
21131 EvalInfo Info(Ctx, EStatus,
21132 (IsConstantInitialization &&
21133 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
21136 Info.setEvaluatingDecl(VD, Value);
21137 Info.InConstantContext = IsConstantInitialization;
21138
21139 SourceLocation DeclLoc = VD->getLocation();
21140 QualType DeclTy = VD->getType();
21141
21142 if (Info.EnableNewConstInterp) {
21143 auto &InterpCtx = Ctx.getInterpContext();
21144 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, Value))
21145 return false;
21146
21147 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
21148 ConstantExprKind::Normal);
21149 } else {
21150 LValue LVal;
21151 LVal.set(VD);
21152
21153 {
21154 // C++23 [intro.execution]/p5
21155 // A full-expression is ... an init-declarator ([dcl.decl]) or a
21156 // mem-initializer.
21157 // So we need to make sure temporary objects are destroyed after having
21158 // evaluated the expression (per C++23 [class.temporary]/p4).
21159 //
21160 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
21161 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
21162 // outermost FullExpr, such as ExprWithCleanups.
21163 FullExpressionRAII Scope(Info);
21164 if (!EvaluateInPlace(Value, Info, LVal, this,
21165 /*AllowNonLiteralTypes=*/true) ||
21166 EStatus.HasSideEffects)
21167 return false;
21168 }
21169
21170 // At this point, any lifetime-extended temporaries are completely
21171 // initialized.
21172 Info.performLifetimeExtension();
21173
21174 if (!Info.discardCleanups())
21175 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21176 }
21177
21178 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
21179 ConstantExprKind::Normal) &&
21180 CheckMemoryLeaks(Info);
21181}
21182
21185 Expr::EvalStatus EStatus;
21186 EStatus.Diag = &Notes;
21187
21188 // Only treat the destruction as constant destruction if we formally have
21189 // constant initialization (or are usable in a constant expression).
21190 bool IsConstantDestruction = hasConstantInitialization();
21191
21192 // Make a copy of the value for the destructor to mutate, if we know it.
21193 // Otherwise, treat the value as default-initialized; if the destructor works
21194 // anyway, then the destruction is constant (and must be essentially empty).
21195 APValue DestroyedValue;
21196 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
21197 DestroyedValue = *getEvaluatedValue();
21198 else if (!handleDefaultInitValue(getType(), DestroyedValue))
21199 return false;
21200
21201 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
21202 getType(), getLocation(), EStatus,
21203 IsConstantDestruction) ||
21204 EStatus.HasSideEffects)
21205 return false;
21206
21207 ensureEvaluatedStmt()->HasConstantDestruction = true;
21208 return true;
21209}
21210
21211/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
21212/// constant folded, but discard the result.
21214 assert(!isValueDependent() &&
21215 "Expression evaluator can't be called on a dependent expression.");
21216
21218 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
21220}
21221
21222APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
21223 assert(!isValueDependent() &&
21224 "Expression evaluator can't be called on a dependent expression.");
21225
21226 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
21227 EvalResult EVResult;
21228 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21229 Info.InConstantContext = true;
21230
21231 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
21232 (void)Result;
21233 assert(Result && "Could not evaluate expression");
21234 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
21235
21236 return EVResult.Val.getInt();
21237}
21238
21241 assert(!isValueDependent() &&
21242 "Expression evaluator can't be called on a dependent expression.");
21243
21244 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
21245 EvalResult EVResult;
21246 EVResult.Diag = Diag;
21247 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21248 Info.InConstantContext = true;
21249 Info.CheckingForUndefinedBehavior = true;
21250
21251 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
21252 (void)Result;
21253 assert(Result && "Could not evaluate expression");
21254 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
21255
21256 return EVResult.Val.getInt();
21257}
21258
21260 assert(!isValueDependent() &&
21261 "Expression evaluator can't be called on a dependent expression.");
21262
21263 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
21264 bool IsConst;
21265 EvalResult EVResult;
21266 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
21267 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21268 Info.CheckingForUndefinedBehavior = true;
21269 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
21270 }
21271}
21272
21274 assert(Val.isLValue());
21275 return IsGlobalLValue(Val.getLValueBase());
21276}
21277
21278/// isIntegerConstantExpr - this recursive routine will test if an expression is
21279/// an integer constant expression.
21280
21281/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
21282/// comma, etc
21283
21284// CheckICE - This function does the fundamental ICE checking: the returned
21285// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
21286//
21287// Note that to reduce code duplication, this helper does no evaluation
21288// itself; the caller checks whether the expression is evaluatable, and
21289// in the rare cases where CheckICE actually cares about the evaluated
21290// value, it calls into Evaluate.
21291
21292namespace {
21293
21294enum ICEKind {
21295 /// This expression is an ICE.
21296 IK_ICE,
21297 /// This expression is not an ICE, but if it isn't evaluated, it's
21298 /// a legal subexpression for an ICE. This return value is used to handle
21299 /// the comma operator in C99 mode, and non-constant subexpressions.
21300 IK_ICEIfUnevaluated,
21301 /// This expression is not an ICE, and is not a legal subexpression for one.
21302 IK_NotICE
21303};
21304
21305struct ICEDiag {
21306 ICEKind Kind;
21307 SourceLocation Loc;
21308
21309 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
21310};
21311
21312}
21313
21314static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
21315
21316static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
21317
21318static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
21319 Expr::EvalResult EVResult;
21320 Expr::EvalStatus Status;
21321 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21322
21323 Info.InConstantContext = true;
21324 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
21325 !EVResult.Val.isInt())
21326 return ICEDiag(IK_NotICE, E->getBeginLoc());
21327
21328 return NoDiag();
21329}
21330
21331static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
21332 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
21334 return ICEDiag(IK_NotICE, E->getBeginLoc());
21335
21336 switch (E->getStmtClass()) {
21337#define ABSTRACT_STMT(Node)
21338#define STMT(Node, Base) case Expr::Node##Class:
21339#define EXPR(Node, Base)
21340#include "clang/AST/StmtNodes.inc"
21341 case Expr::PredefinedExprClass:
21342 case Expr::FloatingLiteralClass:
21343 case Expr::ImaginaryLiteralClass:
21344 case Expr::StringLiteralClass:
21345 case Expr::ArraySubscriptExprClass:
21346 case Expr::MatrixSingleSubscriptExprClass:
21347 case Expr::MatrixSubscriptExprClass:
21348 case Expr::ArraySectionExprClass:
21349 case Expr::OMPArrayShapingExprClass:
21350 case Expr::OMPIteratorExprClass:
21351 case Expr::CompoundAssignOperatorClass:
21352 case Expr::CompoundLiteralExprClass:
21353 case Expr::ExtVectorElementExprClass:
21354 case Expr::MatrixElementExprClass:
21355 case Expr::DesignatedInitExprClass:
21356 case Expr::ArrayInitLoopExprClass:
21357 case Expr::ArrayInitIndexExprClass:
21358 case Expr::NoInitExprClass:
21359 case Expr::DesignatedInitUpdateExprClass:
21360 case Expr::ImplicitValueInitExprClass:
21361 case Expr::ParenListExprClass:
21362 case Expr::VAArgExprClass:
21363 case Expr::AddrLabelExprClass:
21364 case Expr::StmtExprClass:
21365 case Expr::CXXMemberCallExprClass:
21366 case Expr::CUDAKernelCallExprClass:
21367 case Expr::CXXAddrspaceCastExprClass:
21368 case Expr::CXXDynamicCastExprClass:
21369 case Expr::CXXTypeidExprClass:
21370 case Expr::CXXUuidofExprClass:
21371 case Expr::MSPropertyRefExprClass:
21372 case Expr::MSPropertySubscriptExprClass:
21373 case Expr::CXXNullPtrLiteralExprClass:
21374 case Expr::UserDefinedLiteralClass:
21375 case Expr::CXXThisExprClass:
21376 case Expr::CXXThrowExprClass:
21377 case Expr::CXXNewExprClass:
21378 case Expr::CXXDeleteExprClass:
21379 case Expr::CXXPseudoDestructorExprClass:
21380 case Expr::UnresolvedLookupExprClass:
21381 case Expr::RecoveryExprClass:
21382 case Expr::DependentScopeDeclRefExprClass:
21383 case Expr::CXXConstructExprClass:
21384 case Expr::CXXInheritedCtorInitExprClass:
21385 case Expr::CXXStdInitializerListExprClass:
21386 case Expr::CXXBindTemporaryExprClass:
21387 case Expr::ExprWithCleanupsClass:
21388 case Expr::CXXTemporaryObjectExprClass:
21389 case Expr::CXXUnresolvedConstructExprClass:
21390 case Expr::CXXDependentScopeMemberExprClass:
21391 case Expr::UnresolvedMemberExprClass:
21392 case Expr::ObjCStringLiteralClass:
21393 case Expr::ObjCBoxedExprClass:
21394 case Expr::ObjCArrayLiteralClass:
21395 case Expr::ObjCDictionaryLiteralClass:
21396 case Expr::ObjCEncodeExprClass:
21397 case Expr::ObjCMessageExprClass:
21398 case Expr::ObjCSelectorExprClass:
21399 case Expr::ObjCProtocolExprClass:
21400 case Expr::ObjCIvarRefExprClass:
21401 case Expr::ObjCPropertyRefExprClass:
21402 case Expr::ObjCSubscriptRefExprClass:
21403 case Expr::ObjCIsaExprClass:
21404 case Expr::ObjCAvailabilityCheckExprClass:
21405 case Expr::ShuffleVectorExprClass:
21406 case Expr::ConvertVectorExprClass:
21407 case Expr::BlockExprClass:
21408 case Expr::NoStmtClass:
21409 case Expr::OpaqueValueExprClass:
21410 case Expr::PackExpansionExprClass:
21411 case Expr::SubstNonTypeTemplateParmPackExprClass:
21412 case Expr::FunctionParmPackExprClass:
21413 case Expr::AsTypeExprClass:
21414 case Expr::ObjCIndirectCopyRestoreExprClass:
21415 case Expr::MaterializeTemporaryExprClass:
21416 case Expr::PseudoObjectExprClass:
21417 case Expr::AtomicExprClass:
21418 case Expr::LambdaExprClass:
21419 case Expr::CXXFoldExprClass:
21420 case Expr::CoawaitExprClass:
21421 case Expr::DependentCoawaitExprClass:
21422 case Expr::CoyieldExprClass:
21423 case Expr::SYCLUniqueStableNameExprClass:
21424 case Expr::CXXParenListInitExprClass:
21425 case Expr::HLSLOutArgExprClass:
21426 return ICEDiag(IK_NotICE, E->getBeginLoc());
21427
21428 case Expr::MemberExprClass: {
21429 if (Ctx.getLangOpts().C23) {
21430 const Expr *ME = E->IgnoreParenImpCasts();
21431 while (const auto *M = dyn_cast<MemberExpr>(ME)) {
21432 if (M->isArrow())
21433 return ICEDiag(IK_NotICE, E->getBeginLoc());
21434 ME = M->getBase()->IgnoreParenImpCasts();
21435 }
21436 const auto *DRE = dyn_cast<DeclRefExpr>(ME);
21437 if (DRE) {
21438 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
21439 VD && VD->isConstexpr())
21440 return CheckEvalInICE(E, Ctx);
21441 }
21442 }
21443 return ICEDiag(IK_NotICE, E->getBeginLoc());
21444 }
21445
21446 case Expr::InitListExprClass: {
21447 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
21448 // form "T x = { a };" is equivalent to "T x = a;".
21449 // Unless we're initializing a reference, T is a scalar as it is known to be
21450 // of integral or enumeration type.
21451 if (E->isPRValue())
21452 if (cast<InitListExpr>(E)->getNumInits() == 1)
21453 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
21454 return ICEDiag(IK_NotICE, E->getBeginLoc());
21455 }
21456
21457 case Expr::SizeOfPackExprClass:
21458 case Expr::GNUNullExprClass:
21459 case Expr::SourceLocExprClass:
21460 case Expr::EmbedExprClass:
21461 case Expr::OpenACCAsteriskSizeExprClass:
21462 return NoDiag();
21463
21464 case Expr::PackIndexingExprClass:
21465 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
21466
21467 case Expr::SubstNonTypeTemplateParmExprClass:
21468 return
21469 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
21470
21471 case Expr::ConstantExprClass:
21472 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
21473
21474 case Expr::ParenExprClass:
21475 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
21476 case Expr::GenericSelectionExprClass:
21477 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
21478 case Expr::IntegerLiteralClass:
21479 case Expr::FixedPointLiteralClass:
21480 case Expr::CharacterLiteralClass:
21481 case Expr::ObjCBoolLiteralExprClass:
21482 case Expr::CXXBoolLiteralExprClass:
21483 case Expr::CXXScalarValueInitExprClass:
21484 case Expr::TypeTraitExprClass:
21485 case Expr::ConceptSpecializationExprClass:
21486 case Expr::RequiresExprClass:
21487 case Expr::ArrayTypeTraitExprClass:
21488 case Expr::ExpressionTraitExprClass:
21489 case Expr::CXXNoexceptExprClass:
21490 case Expr::CXXReflectExprClass:
21491 return NoDiag();
21492 case Expr::CallExprClass:
21493 case Expr::CXXOperatorCallExprClass: {
21494 // C99 6.6/3 allows function calls within unevaluated subexpressions of
21495 // constant expressions, but they can never be ICEs because an ICE cannot
21496 // contain an operand of (pointer to) function type.
21497 const CallExpr *CE = cast<CallExpr>(E);
21498 if (CE->getBuiltinCallee())
21499 return CheckEvalInICE(E, Ctx);
21500 return ICEDiag(IK_NotICE, E->getBeginLoc());
21501 }
21502 case Expr::CXXRewrittenBinaryOperatorClass:
21503 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
21504 Ctx);
21505 case Expr::DeclRefExprClass: {
21506 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
21507 if (isa<EnumConstantDecl>(D))
21508 return NoDiag();
21509
21510 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
21511 // integer variables in constant expressions:
21512 //
21513 // C++ 7.1.5.1p2
21514 // A variable of non-volatile const-qualified integral or enumeration
21515 // type initialized by an ICE can be used in ICEs.
21516 //
21517 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
21518 // that mode, use of reference variables should not be allowed.
21519 const VarDecl *VD = dyn_cast<VarDecl>(D);
21520 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
21521 !VD->getType()->isReferenceType())
21522 return NoDiag();
21523
21524 return ICEDiag(IK_NotICE, E->getBeginLoc());
21525 }
21526 case Expr::UnaryOperatorClass: {
21527 const UnaryOperator *Exp = cast<UnaryOperator>(E);
21528 switch (Exp->getOpcode()) {
21529 case UO_PostInc:
21530 case UO_PostDec:
21531 case UO_PreInc:
21532 case UO_PreDec:
21533 case UO_AddrOf:
21534 case UO_Deref:
21535 case UO_Coawait:
21536 // C99 6.6/3 allows increment and decrement within unevaluated
21537 // subexpressions of constant expressions, but they can never be ICEs
21538 // because an ICE cannot contain an lvalue operand.
21539 return ICEDiag(IK_NotICE, E->getBeginLoc());
21540 case UO_Extension:
21541 case UO_LNot:
21542 case UO_Plus:
21543 case UO_Minus:
21544 case UO_Not:
21545 case UO_Real:
21546 case UO_Imag:
21547 return CheckICE(Exp->getSubExpr(), Ctx);
21548 }
21549 llvm_unreachable("invalid unary operator class");
21550 }
21551 case Expr::OffsetOfExprClass: {
21552 // Note that per C99, offsetof must be an ICE. And AFAIK, using
21553 // EvaluateAsRValue matches the proposed gcc behavior for cases like
21554 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
21555 // compliance: we should warn earlier for offsetof expressions with
21556 // array subscripts that aren't ICEs, and if the array subscripts
21557 // are ICEs, the value of the offsetof must be an integer constant.
21558 return CheckEvalInICE(E, Ctx);
21559 }
21560 case Expr::UnaryExprOrTypeTraitExprClass: {
21562 if ((Exp->getKind() == UETT_SizeOf) &&
21564 return ICEDiag(IK_NotICE, E->getBeginLoc());
21565 if (Exp->getKind() == UETT_CountOf) {
21566 QualType ArgTy = Exp->getTypeOfArgument();
21567 if (ArgTy->isVariableArrayType()) {
21568 // We need to look whether the array is multidimensional. If it is,
21569 // then we want to check the size expression manually to see whether
21570 // it is an ICE or not.
21571 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
21572 if (VAT->getElementType()->isArrayType())
21573 // Variable array size expression could be missing (e.g. int a[*][10])
21574 // In that case, it can't be a constant expression.
21575 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
21576 : ICEDiag(IK_NotICE, E->getBeginLoc());
21577
21578 // Otherwise, this is a regular VLA, which is definitely not an ICE.
21579 return ICEDiag(IK_NotICE, E->getBeginLoc());
21580 }
21581 }
21582 return NoDiag();
21583 }
21584 case Expr::BinaryOperatorClass: {
21585 const BinaryOperator *Exp = cast<BinaryOperator>(E);
21586 switch (Exp->getOpcode()) {
21587 case BO_PtrMemD:
21588 case BO_PtrMemI:
21589 case BO_Assign:
21590 case BO_MulAssign:
21591 case BO_DivAssign:
21592 case BO_RemAssign:
21593 case BO_AddAssign:
21594 case BO_SubAssign:
21595 case BO_ShlAssign:
21596 case BO_ShrAssign:
21597 case BO_AndAssign:
21598 case BO_XorAssign:
21599 case BO_OrAssign:
21600 // C99 6.6/3 allows assignments within unevaluated subexpressions of
21601 // constant expressions, but they can never be ICEs because an ICE cannot
21602 // contain an lvalue operand.
21603 return ICEDiag(IK_NotICE, E->getBeginLoc());
21604
21605 case BO_Mul:
21606 case BO_Div:
21607 case BO_Rem:
21608 case BO_Add:
21609 case BO_Sub:
21610 case BO_Shl:
21611 case BO_Shr:
21612 case BO_LT:
21613 case BO_GT:
21614 case BO_LE:
21615 case BO_GE:
21616 case BO_EQ:
21617 case BO_NE:
21618 case BO_And:
21619 case BO_Xor:
21620 case BO_Or:
21621 case BO_Comma:
21622 case BO_Cmp: {
21623 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
21624 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
21625 if (Exp->getOpcode() == BO_Div ||
21626 Exp->getOpcode() == BO_Rem) {
21627 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
21628 // we don't evaluate one.
21629 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
21630 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
21631 if (REval == 0)
21632 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21633 if (REval.isSigned() && REval.isAllOnes()) {
21634 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
21635 if (LEval.isMinSignedValue())
21636 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21637 }
21638 }
21639 }
21640 if (Exp->getOpcode() == BO_Comma) {
21641 if (Ctx.getLangOpts().C99) {
21642 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
21643 // if it isn't evaluated.
21644 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
21645 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
21646 } else {
21647 // In both C89 and C++, commas in ICEs are illegal.
21648 return ICEDiag(IK_NotICE, E->getBeginLoc());
21649 }
21650 }
21651 return Worst(LHSResult, RHSResult);
21652 }
21653 case BO_LAnd:
21654 case BO_LOr: {
21655 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
21656 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
21657 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
21658 // Rare case where the RHS has a comma "side-effect"; we need
21659 // to actually check the condition to see whether the side
21660 // with the comma is evaluated.
21661 if ((Exp->getOpcode() == BO_LAnd) !=
21662 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
21663 return RHSResult;
21664 return NoDiag();
21665 }
21666
21667 return Worst(LHSResult, RHSResult);
21668 }
21669 }
21670 llvm_unreachable("invalid binary operator kind");
21671 }
21672 case Expr::ImplicitCastExprClass:
21673 case Expr::CStyleCastExprClass:
21674 case Expr::CXXFunctionalCastExprClass:
21675 case Expr::CXXStaticCastExprClass:
21676 case Expr::CXXReinterpretCastExprClass:
21677 case Expr::CXXConstCastExprClass:
21678 case Expr::ObjCBridgedCastExprClass: {
21679 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
21680 if (isa<ExplicitCastExpr>(E)) {
21681 if (const FloatingLiteral *FL
21682 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
21683 unsigned DestWidth = Ctx.getIntWidth(E->getType());
21684 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
21685 APSInt IgnoredVal(DestWidth, !DestSigned);
21686 bool Ignored;
21687 // If the value does not fit in the destination type, the behavior is
21688 // undefined, so we are not required to treat it as a constant
21689 // expression.
21690 if (FL->getValue().convertToInteger(IgnoredVal,
21691 llvm::APFloat::rmTowardZero,
21692 &Ignored) & APFloat::opInvalidOp)
21693 return ICEDiag(IK_NotICE, E->getBeginLoc());
21694 return NoDiag();
21695 }
21696 }
21697 switch (cast<CastExpr>(E)->getCastKind()) {
21698 case CK_LValueToRValue:
21699 case CK_AtomicToNonAtomic:
21700 case CK_NonAtomicToAtomic:
21701 case CK_NoOp:
21702 case CK_IntegralToBoolean:
21703 case CK_IntegralCast:
21704 return CheckICE(SubExpr, Ctx);
21705 default:
21706 return ICEDiag(IK_NotICE, E->getBeginLoc());
21707 }
21708 }
21709 case Expr::BinaryConditionalOperatorClass: {
21711 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
21712 if (CommonResult.Kind == IK_NotICE) return CommonResult;
21713 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
21714 if (FalseResult.Kind == IK_NotICE) return FalseResult;
21715 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
21716 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
21717 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
21718 return FalseResult;
21719 }
21720 case Expr::ConditionalOperatorClass: {
21722 // If the condition (ignoring parens) is a __builtin_constant_p call,
21723 // then only the true side is actually considered in an integer constant
21724 // expression, and it is fully evaluated. This is an important GNU
21725 // extension. See GCC PR38377 for discussion.
21726 if (const CallExpr *CallCE
21727 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
21728 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
21729 return CheckEvalInICE(E, Ctx);
21730 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
21731 if (CondResult.Kind == IK_NotICE)
21732 return CondResult;
21733
21734 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
21735 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
21736
21737 if (TrueResult.Kind == IK_NotICE)
21738 return TrueResult;
21739 if (FalseResult.Kind == IK_NotICE)
21740 return FalseResult;
21741 if (CondResult.Kind == IK_ICEIfUnevaluated)
21742 return CondResult;
21743 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
21744 return NoDiag();
21745 // Rare case where the diagnostics depend on which side is evaluated
21746 // Note that if we get here, CondResult is 0, and at least one of
21747 // TrueResult and FalseResult is non-zero.
21748 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
21749 return FalseResult;
21750 return TrueResult;
21751 }
21752 case Expr::CXXDefaultArgExprClass:
21753 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
21754 case Expr::CXXDefaultInitExprClass:
21755 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
21756 case Expr::ChooseExprClass: {
21757 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
21758 }
21759 case Expr::BuiltinBitCastExprClass: {
21760 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
21761 return ICEDiag(IK_NotICE, E->getBeginLoc());
21762 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
21763 }
21764 }
21765
21766 llvm_unreachable("Invalid StmtClass!");
21767}
21768
21769/// Evaluate an expression as a C++11 integral constant expression.
21771 const Expr *E,
21772 llvm::APSInt *Value) {
21774 return false;
21775
21776 APValue Result;
21777 if (!E->isCXX11ConstantExpr(Ctx, &Result))
21778 return false;
21779
21780 if (!Result.isInt())
21781 return false;
21782
21783 if (Value) *Value = Result.getInt();
21784 return true;
21785}
21786
21788 assert(!isValueDependent() &&
21789 "Expression evaluator can't be called on a dependent expression.");
21790
21791 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
21792
21793 if (Ctx.getLangOpts().CPlusPlus11)
21794 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
21795
21796 ICEDiag D = CheckICE(this, Ctx);
21797 if (D.Kind != IK_ICE)
21798 return false;
21799 return true;
21800}
21801
21802std::optional<llvm::APSInt>
21804 if (isValueDependent()) {
21805 // Expression evaluator can't succeed on a dependent expression.
21806 return std::nullopt;
21807 }
21808
21809 if (Ctx.getLangOpts().CPlusPlus11) {
21810 APSInt Value;
21812 return Value;
21813 return std::nullopt;
21814 }
21815
21816 if (!isIntegerConstantExpr(Ctx))
21817 return std::nullopt;
21818
21819 // The only possible side-effects here are due to UB discovered in the
21820 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
21821 // required to treat the expression as an ICE, so we produce the folded
21822 // value.
21824 Expr::EvalStatus Status;
21825 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
21826 Info.InConstantContext = true;
21827
21828 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
21829 llvm_unreachable("ICE cannot be evaluated!");
21830
21831 return ExprResult.Val.getInt();
21832}
21833
21835 assert(!isValueDependent() &&
21836 "Expression evaluator can't be called on a dependent expression.");
21837
21838 return CheckICE(this, Ctx).Kind == IK_ICE;
21839}
21840
21842 assert(!isValueDependent() &&
21843 "Expression evaluator can't be called on a dependent expression.");
21844
21845 // We support this checking in C++98 mode in order to diagnose compatibility
21846 // issues.
21847 assert(Ctx.getLangOpts().CPlusPlus);
21848
21849 bool IsConst;
21850 APValue Scratch;
21851 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
21852 if (Result)
21853 *Result = std::move(Scratch);
21854 return true;
21855 }
21856
21857 // Build evaluation settings.
21858 Expr::EvalStatus Status;
21860 Status.Diag = &Diags;
21861 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
21862
21863 bool IsConstExpr =
21864 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
21865 // FIXME: We don't produce a diagnostic for this, but the callers that
21866 // call us on arbitrary full-expressions should generally not care.
21867 Info.discardCleanups() && !Status.HasSideEffects;
21868
21869 return IsConstExpr && Diags.empty();
21870}
21871
21873 const FunctionDecl *Callee,
21875 const Expr *This) const {
21876 assert(!isValueDependent() &&
21877 "Expression evaluator can't be called on a dependent expression.");
21878
21879 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
21880 std::string Name;
21881 llvm::raw_string_ostream OS(Name);
21882 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
21883 /*Qualified=*/true);
21884 return Name;
21885 });
21886
21887 Expr::EvalStatus Status;
21888 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
21889 Info.InConstantContext = true;
21890
21891 LValue ThisVal;
21892 const LValue *ThisPtr = nullptr;
21893 if (This) {
21894#ifndef NDEBUG
21895 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
21896 assert(MD && "Don't provide `this` for non-methods.");
21897 assert(MD->isImplicitObjectMemberFunction() &&
21898 "Don't provide `this` for methods without an implicit object.");
21899#endif
21900 if (!This->isValueDependent() &&
21901 EvaluateObjectArgument(Info, This, ThisVal) &&
21902 !Info.EvalStatus.HasSideEffects)
21903 ThisPtr = &ThisVal;
21904
21905 // Ignore any side-effects from a failed evaluation. This is safe because
21906 // they can't interfere with any other argument evaluation.
21907 Info.EvalStatus.HasSideEffects = false;
21908 }
21909
21910 CallRef Call = Info.CurrentCall->createCall(Callee);
21911 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
21912 I != E; ++I) {
21913 unsigned Idx = I - Args.begin();
21914 if (Idx >= Callee->getNumParams())
21915 break;
21916 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
21917 if ((*I)->isValueDependent() ||
21918 !EvaluateCallArg(PVD, *I, Call, Info) ||
21919 Info.EvalStatus.HasSideEffects) {
21920 // If evaluation fails, throw away the argument entirely.
21921 if (APValue *Slot = Info.getParamSlot(Call, PVD))
21922 *Slot = APValue();
21923 }
21924
21925 // Ignore any side-effects from a failed evaluation. This is safe because
21926 // they can't interfere with any other argument evaluation.
21927 Info.EvalStatus.HasSideEffects = false;
21928 }
21929
21930 // Parameter cleanups happen in the caller and are not part of this
21931 // evaluation.
21932 Info.discardCleanups();
21933 Info.EvalStatus.HasSideEffects = false;
21934
21935 // Build fake call to Callee.
21936 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
21937 Call);
21938 // FIXME: Missing ExprWithCleanups in enable_if conditions?
21939 FullExpressionRAII Scope(Info);
21940 return Evaluate(Value, Info, this) && Scope.destroy() &&
21941 !Info.EvalStatus.HasSideEffects;
21942}
21943
21946 PartialDiagnosticAt> &Diags) {
21947 // FIXME: It would be useful to check constexpr function templates, but at the
21948 // moment the constant expression evaluator cannot cope with the non-rigorous
21949 // ASTs which we build for dependent expressions.
21950 if (FD->isDependentContext())
21951 return true;
21952
21953 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
21954 std::string Name;
21955 llvm::raw_string_ostream OS(Name);
21957 /*Qualified=*/true);
21958 return Name;
21959 });
21960
21961 Expr::EvalStatus Status;
21962 Status.Diag = &Diags;
21963
21964 EvalInfo Info(FD->getASTContext(), Status,
21966 Info.InConstantContext = true;
21967 Info.CheckingPotentialConstantExpression = true;
21968
21969 // The constexpr VM attempts to compile all methods to bytecode here.
21970 if (Info.EnableNewConstInterp) {
21971 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
21972 return Diags.empty();
21973 }
21974
21975 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
21976 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
21977
21978 // Fabricate an arbitrary expression on the stack and pretend that it
21979 // is a temporary being used as the 'this' pointer.
21980 LValue This;
21981 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
21982 : Info.Ctx.IntTy);
21983 This.set({&VIE, Info.CurrentCall->Index});
21984
21986
21987 APValue Scratch;
21988 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
21989 // Evaluate the call as a constant initializer, to allow the construction
21990 // of objects of non-literal types.
21991 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
21992 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
21993 } else {
21994 SourceLocation Loc = FD->getLocation();
21996 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
21997 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
21998 /*ResultSlot=*/nullptr);
21999 }
22000
22001 return Diags.empty();
22002}
22003
22005 const FunctionDecl *FD,
22007 PartialDiagnosticAt> &Diags) {
22008 assert(!E->isValueDependent() &&
22009 "Expression evaluator can't be called on a dependent expression.");
22010
22011 Expr::EvalStatus Status;
22012 Status.Diag = &Diags;
22013
22014 EvalInfo Info(FD->getASTContext(), Status,
22016 Info.InConstantContext = true;
22017 Info.CheckingPotentialConstantExpression = true;
22018
22019 if (Info.EnableNewConstInterp) {
22020 Info.Ctx.getInterpContext().isPotentialConstantExprUnevaluated(Info, E, FD);
22021 return Diags.empty();
22022 }
22023
22024 // Fabricate a call stack frame to give the arguments a plausible cover story.
22025 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
22026 /*CallExpr=*/nullptr, CallRef());
22027
22028 APValue ResultScratch;
22029 Evaluate(ResultScratch, Info, E);
22030 return Diags.empty();
22031}
22032
22033std::optional<uint64_t> Expr::tryEvaluateObjectSize(const ASTContext &Ctx,
22034 unsigned Type) const {
22035 if (!getType()->isPointerType())
22036 return std::nullopt;
22037
22038 Expr::EvalStatus Status;
22039 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22040 if (Info.EnableNewConstInterp)
22041 return Info.Ctx.getInterpContext().tryEvaluateObjectSize(Info, this, Type);
22042 return tryEvaluateBuiltinObjectSize(this, Type, Info);
22043}
22044
22045static std::optional<uint64_t>
22046EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
22047 std::string *StringResult) {
22048 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
22049 return std::nullopt;
22050
22051 LValue String;
22052
22053 if (!EvaluatePointer(E, String, Info))
22054 return std::nullopt;
22055
22056 QualType CharTy = E->getType()->getPointeeType();
22057
22058 // Fast path: if it's a string literal, search the string value.
22059 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
22060 String.getLValueBase().dyn_cast<const Expr *>())) {
22061 StringRef Str = S->getBytes();
22062 int64_t Off = String.Offset.getQuantity();
22063 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
22064 S->getCharByteWidth() == 1 &&
22065 // FIXME: Add fast-path for wchar_t too.
22066 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
22067 Str = Str.substr(Off);
22068
22069 StringRef::size_type Pos = Str.find(0);
22070 if (Pos != StringRef::npos)
22071 Str = Str.substr(0, Pos);
22072
22073 if (StringResult)
22074 *StringResult = Str;
22075 return Str.size();
22076 }
22077
22078 // Fall through to slow path.
22079 }
22080
22081 // Slow path: scan the bytes of the string looking for the terminating 0.
22082 for (uint64_t Strlen = 0; /**/; ++Strlen) {
22083 APValue Char;
22084 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
22085 !Char.isInt())
22086 return std::nullopt;
22087 if (!Char.getInt())
22088 return Strlen;
22089 else if (StringResult)
22090 StringResult->push_back(Char.getInt().getExtValue());
22091 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
22092 return std::nullopt;
22093 }
22094}
22095
22096std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
22097 Expr::EvalStatus Status;
22098 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22099 std::string StringResult;
22100
22101 if (Info.EnableNewConstInterp) {
22102 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
22103 return std::nullopt;
22104 return StringResult;
22105 }
22106
22107 if (EvaluateBuiltinStrLen(this, Info, &StringResult))
22108 return StringResult;
22109 return std::nullopt;
22110}
22111
22112template <typename T>
22113static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result,
22114 const Expr *SizeExpression,
22115 const Expr *PtrExpression,
22116 ASTContext &Ctx,
22117 Expr::EvalResult &Status) {
22118 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22119 Info.InConstantContext = true;
22120
22121 if (Info.EnableNewConstInterp)
22122 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
22123 PtrExpression, Result);
22124
22125 LValue String;
22126 FullExpressionRAII Scope(Info);
22127 APSInt SizeValue;
22128 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
22129 return false;
22130
22131 uint64_t Size = SizeValue.getZExtValue();
22132
22133 // FIXME: better protect against invalid or excessive sizes
22134 if constexpr (std::is_same_v<APValue, T>)
22135 Result = APValue(APValue::UninitArray{}, Size, Size);
22136 else {
22137 if (Size < Result.max_size())
22138 Result.reserve(Size);
22139 }
22140 if (!::EvaluatePointer(PtrExpression, String, Info))
22141 return false;
22142
22143 QualType CharTy = PtrExpression->getType()->getPointeeType();
22144 for (uint64_t I = 0; I < Size; ++I) {
22145 APValue Char;
22146 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
22147 Char))
22148 return false;
22149
22150 if constexpr (std::is_same_v<APValue, T>) {
22151 Result.getArrayInitializedElt(I) = std::move(Char);
22152 } else {
22153 APSInt C = Char.getInt();
22154
22155 assert(C.getBitWidth() <= 8 &&
22156 "string element not representable in char");
22157
22158 Result.push_back(static_cast<char>(C.getExtValue()));
22159 }
22160
22161 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
22162 return false;
22163 }
22164
22165 return Scope.destroy() && CheckMemoryLeaks(Info);
22166}
22167
22169 const Expr *SizeExpression,
22170 const Expr *PtrExpression, ASTContext &Ctx,
22171 EvalResult &Status) const {
22172 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
22173 PtrExpression, Ctx, Status);
22174}
22175
22177 const Expr *SizeExpression,
22178 const Expr *PtrExpression, ASTContext &Ctx,
22179 EvalResult &Status) const {
22180 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
22181 PtrExpression, Ctx, Status);
22182}
22183
22184std::optional<uint64_t> Expr::tryEvaluateStrLen(const ASTContext &Ctx) const {
22185 Expr::EvalStatus Status;
22186 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22187
22188 if (Info.EnableNewConstInterp)
22189 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this);
22190 return EvaluateBuiltinStrLen(this, Info);
22191}
22192
22193namespace {
22194struct IsWithinLifetimeHandler {
22195 EvalInfo &Info;
22196 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
22197 using result_type = std::optional<bool>;
22198 std::optional<bool> failed() { return std::nullopt; }
22199 template <typename T>
22200 std::optional<bool> found(T &Subobj, QualType SubobjType) {
22201 return true;
22202 }
22203};
22204
22205std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
22206 const CallExpr *E) {
22207 EvalInfo &Info = IEE.Info;
22208 // Sometimes this is called during some sorts of constant folding / early
22209 // evaluation. These are meant for non-constant expressions and are not
22210 // necessary since this consteval builtin will never be evaluated at runtime.
22211 // Just fail to evaluate when not in a constant context.
22212 if (!Info.InConstantContext)
22213 return std::nullopt;
22214 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
22215 const Expr *Arg = E->getArg(0);
22216 if (Arg->isValueDependent())
22217 return std::nullopt;
22218 LValue Val;
22219 if (!EvaluatePointer(Arg, Val, Info))
22220 return std::nullopt;
22221
22222 if (Val.allowConstexprUnknown())
22223 return true;
22224
22225 auto Error = [&](int Diag) {
22226 bool CalledFromStd = false;
22227 const auto *Callee = Info.CurrentCall->getCallee();
22228 if (Callee && Callee->isInStdNamespace()) {
22229 const IdentifierInfo *Identifier = Callee->getIdentifier();
22230 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
22231 }
22232 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
22233 : E->getExprLoc(),
22234 diag::err_invalid_is_within_lifetime)
22235 << (CalledFromStd ? "std::is_within_lifetime"
22236 : "__builtin_is_within_lifetime")
22237 << Diag;
22238 return std::nullopt;
22239 };
22240 // C++2c [meta.const.eval]p4:
22241 // During the evaluation of an expression E as a core constant expression, a
22242 // call to this function is ill-formed unless p points to an object that is
22243 // usable in constant expressions or whose complete object's lifetime began
22244 // within E.
22245
22246 // Make sure it points to an object
22247 // nullptr does not point to an object
22248 if (Val.isNullPointer() || Val.getLValueBase().isNull())
22249 return Error(0);
22250 QualType T = Val.getLValueBase().getType();
22251 assert(!T->isFunctionType() &&
22252 "Pointers to functions should have been typed as function pointers "
22253 "which would have been rejected earlier");
22254 assert(T->isObjectType());
22255 // Hypothetical array element is not an object
22256 if (Val.getLValueDesignator().isOnePastTheEnd())
22257 return Error(1);
22258 assert(Val.getLValueDesignator().isValidSubobject() &&
22259 "Unchecked case for valid subobject");
22260 // All other ill-formed values should have failed EvaluatePointer, so the
22261 // object should be a pointer to an object that is usable in a constant
22262 // expression or whose complete lifetime began within the expression
22263 CompleteObject CO =
22264 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
22265 // The lifetime hasn't begun yet if we are still evaluating the
22266 // initializer ([basic.life]p(1.2))
22267 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
22268 return Error(2);
22269
22270 if (!CO)
22271 return false;
22272 IsWithinLifetimeHandler handler{Info};
22273 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
22274}
22275} // namespace
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
static uint32_t getBitWidth(const Expr *E)
llvm::APSInt APSInt
Definition Compiler.cpp:24
static Decl::Kind getKind(const Decl *D)
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC's builtin.
static bool isRead(AccessKinds AK)
static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, Expr::EvalResult &Status)
static bool isValidIndeterminateAccess(AccessKinds AK)
Is this kind of access valid on an indeterminate object value?
static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy)
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, EvalInfo &Info)
static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, Expr::SideEffectsKind SEK)
static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK, const LValue &LVal, QualType LValType)
Find the complete object to which an LValue refers.
static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, LValue &Result)
Attempts to evaluate the given LValueBase as the result of a call to a function with the alloc_size a...
static const CXXMethodDecl * HandleVirtualDispatch(EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, llvm::SmallVectorImpl< QualType > &CovariantAdjustmentPath)
Perform virtual dispatch.
static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD)
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind, const FieldDecl *SubobjectDecl, CheckedTemporaries &CheckedTemps)
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, bool Imag)
Update an lvalue to refer to a component of a complex number.
static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result, llvm::function_ref< APInt(const APSInt &)> PackFn)
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, CharUnits &Size, SizeOfType SOT=SizeOfType::SizeOf)
Get the size of the given type in char units.
static bool HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result)
Evaluate a constructor call.
static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E, QualType DestTy, SmallVectorImpl< APValue > &SrcVals, SmallVectorImpl< QualType > &SrcTypes)
static bool ShouldPropagateBreakContinue(EvalInfo &Info, const Stmt *LoopOrSwitch, ArrayRef< BlockScopeRAII * > Scopes, EvalStmtResult &ESR)
Helper to implement named break/continue.
static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, const Stmt *Body, const SwitchCase *Case=nullptr)
Evaluate the body of a loop, and translate the result as appropriate.
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, const CXXConstructorDecl *CD, bool IsValueInitialization)
CheckTrivialDefaultConstructor - Check whether a constructor is a trivial default constructor.
static bool EvaluateVector(const Expr *E, APValue &Result, EvalInfo &Info)
static const ValueDecl * GetLValueBaseDecl(const LValue &LVal)
SizeOfType
static bool TryEvaluateBuiltinNaN(const ASTContext &Context, QualType ResultTy, const Expr *Arg, bool SNaN, llvm::APFloat &Result)
static const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize. This ignores some c...
static bool isAnyAccess(AccessKinds AK)
static bool EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, SuccessCB &&Success, AfterCB &&DoAfter)
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result)
Perform zero-initialization on an object of non-union class type. C++11 [dcl.init]p5: To zero-initial...
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info)
std::optional< APFloat > EvalScalarMinMaxFp(const APFloat &A, const APFloat &B, std::optional< APSInt > RoundingMode, bool IsMin)
static bool CheckMemoryLeaks(EvalInfo &Info)
Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless "the allocated storage is dea...
static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static ICEDiag CheckEvalInICE(const Expr *E, const ASTContext &Ctx)
static llvm::APInt ConvertBoolVectorToInt(const APValue &Val)
static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value, QualType BaseTy, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &Types, unsigned Size)
static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal, QualType &SrcTy)
static bool isBaseClassPublic(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Determine whether Base, which is known to be a direct base class of Derived, is a public base class.
static bool hasVirtualDestructor(QualType T)
static bool HandleOverflow(EvalInfo &Info, const Expr *E, const T &SrcValue, QualType DestType)
static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value)
static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, LValue &LVal, const IndirectFieldDecl *IFD)
Update LVal to refer to the given indirect field.
static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E, APFloat OrigVal, APValue &Result)
static ICEDiag Worst(ICEDiag A, ICEDiag B)
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, const VarDecl *VD, CallStackFrame *Frame, unsigned Version, APValue *&Result)
Try to evaluate the initializer for a variable declaration.
static bool handleDefaultInitValue(QualType T, APValue &Result)
Get the value to use for a default-initialized object of type T.
static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, uint64_t Size, uint64_t Idx)
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base)
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const LValue &LVal, ConstantExprKind Kind, CheckedTemporaries &CheckedTemps)
Check that this reference or pointer core constant expression is a valid value for an address or refe...
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, const APSInt &LHS, const APSInt &RHS, unsigned BitWidth, Operation Op, APSInt &Result)
Perform the given integer operation, which is known to need at most BitWidth bits,...
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info)
Evaluate an expression of record type as a temporary.
static bool EvaluateArray(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, APValue &Value, const FieldDecl *FD)
static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E, QualType ElemType, APValue const &VecVal1, APValue const &VecVal2, unsigned EltNum, APValue &Result)
static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static const ValueDecl * HandleMemberPointerAccess(EvalInfo &Info, QualType LVType, LValue &LV, const Expr *RHS, bool IncludeMember=true)
HandleMemberPointerAccess - Evaluate a member access operation and build an lvalue referring to the r...
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, LValue &Result)
HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on the provided lvalue,...
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info)
static bool IsOpaqueConstantCall(const CallExpr *E)
Should this call expression be treated as forming an opaque constant?
static bool CheckMemberPointerConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Member pointers are constant expressions unless they point to a non-virtual dllimport member function...
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal, APValue &RVal, bool WantObjectRepresentation=false)
Perform an lvalue-to-rvalue conversion on the given glvalue.
static bool handleElementwiseCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &SrcTypes, SmallVectorImpl< QualType > &DestTypes, SmallVectorImpl< APValue > &Results)
static bool refersToCompleteObject(const LValue &LVal)
Tests to see if the LValue has a user-specified designator (that isn't necessarily valid)....
static bool AreElementsOfSameArray(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B)
Determine whether the given subobject designators refer to elements of the same array object.
static bool EvaluateDecompositionDeclInit(EvalInfo &Info, const DecompositionDecl *DD)
static bool IsWeakLValue(const LValue &Value)
static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, APValue &Result, const CXXConstructExpr *CCE, QualType AllocType)
static bool EvaluateRecord(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, APValue &Val)
Perform an assignment of Val to LVal. Takes ownership of Val.
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, const RecordDecl *TruncatedType, unsigned TruncatedElements)
Cast an lvalue referring to a base subobject to a derived class, by truncating the lvalue's path to t...
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E)
Evaluate an expression to see if it had side-effects, and discard its result.
static bool constructAggregate(EvalInfo &Info, const FPOptions FPO, const Expr *E, APValue &Result, QualType ResultType, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &ElTypes)
static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T, const LValue &LV, CharUnits &Size)
If we're evaluating the object size of an instance of a struct that contains a flexible array member,...
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, QualType Type, LValue &Result)
static bool evalShuffleGeneric(EvalInfo &Info, const CallExpr *Call, APValue &Out, llvm::function_ref< std::pair< unsigned, int >(unsigned, unsigned)> GetSourceIndex)
static QualType getSubobjectType(QualType ObjType, QualType SubobjType, bool IsMutable=false)
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate an integer or fixed point expression into an APResult.
static std::optional< uint64_t > tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info)
Tries to evaluate the __builtin_object_size for E. If successful, returns true and stores the result ...
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
static const CXXRecordDecl * getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength)
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, const CXXRecordDecl *DerivedRD, const CXXRecordDecl *BaseRD)
Cast an lvalue referring to a derived class to a known base subobject.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
static bool HandleConversionToBool(const APValue &Val, bool &Result)
static void expandVector(APValue &Vec, unsigned NumElements)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool isModification(AccessKinds AK)
static bool handleCompareOpForVector(const APValue &LHSValue, BinaryOperatorKind Opcode, const APValue &RHSValue, APInt &Result)
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info)
CheckEvaluationResultKind
static bool isZeroSized(const LValue &Value)
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, uint64_t Index)
Extract the value of a character from a string literal.
static bool modifySubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &NewVal)
Update the designated sub-object of an rvalue to the given value.
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value)
Evaluate an expression as a C++11 integral constant expression.
static CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T, UnaryExprOrTypeTrait ExprKind)
static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, APValue &Val, APSInt &Alignment)
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, APSInt Adjustment)
Update a pointer value to model pointer arithmetic.
static bool extractSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &Result, AccessKinds AK=AK_Read)
Extract the designated sub-object of an rvalue.
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, const FieldDecl *FD, const ASTRecordLayout *RL=nullptr)
Update LVal to refer to the given field, which must be a member of the type currently described by LV...
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, bool IsSub)
static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD)
static std::optional< uint64_t > EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info, std::string *StringResult=nullptr)
void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, const Expr *E, APValue &Result, bool CopyObjectRepresentation)
Perform a trivial copy from Param, which is the parameter of a copy or move constructor or assignment...
static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, APFloat::opStatus St)
Check if the given evaluation result is allowed for constant evaluation.
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV)
EvaluateBuiltinConstantPForLValue - Determine the result of __builtin_constant_p when applied to the ...
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg)
EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to GCC as we can manage.
static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, const LValue &This, const CXXMethodDecl *NamedMember)
Check that the pointee of the 'this' pointer in a member function call is either within its lifetime ...
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Check that this core constant expression value is a valid value for a constant expression.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
static std::optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
static bool EvaluateDecl(EvalInfo &Info, const Decl *D, bool EvaluateConditionDecl=false)
static void expandArray(APValue &Array, unsigned Index)
static bool handleLogicalOpForVector(const APInt &LHSValue, BinaryOperatorKind Opcode, const APInt &RHSValue, APInt &Result)
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
Find the position where two subobject designators diverge, or equivalently the length of the common i...
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue.
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Get the base index of the given base class within an APValue representing the given derived class.
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate only a fixed point expression into an APResult.
void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info)
static const FunctionDecl * getVirtualOperatorDelete(QualType T)
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal)
Checks to see if the given LValue's Designator is at the end of the LValue's record layout....
static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT, SourceLocation CallLoc={})
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, const Expr *E, bool AllowNonLiteralTypes=false)
EvaluateInPlace - Evaluate an expression in-place in an APValue. In some cases, the in-place evaluati...
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, APFloat &LHS, BinaryOperatorKind Opcode, const APFloat &RHS)
Perform the given binary floating-point operation, in-place, on LHS.
static std::optional< DynAlloc * > CheckDeleteKind(EvalInfo &Info, const Expr *E, const LValue &Pointer, DynAlloc::Kind DeallocKind)
Check that the given object is a suitable pointer to a heap allocation that still exists and is of th...
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
Evaluate an expression as an lvalue. This can be legitimately called on expressions which are not glv...
static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result, const ASTContext &Ctx, bool &IsConst)
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, APValue &Result, ArrayRef< QualType > Path)
Perform the adjustment from a value returned by a virtual function to a value of the statically expec...
static bool evalShiftWithCount(EvalInfo &Info, const CallExpr *Call, APValue &Out, llvm::function_ref< APInt(const APInt &, uint64_t)> ShiftOp, llvm::function_ref< APInt(const APInt &, unsigned)> OverflowOp)
static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, const SwitchStmt *SS)
Evaluate a switch statement.
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, APValue &Result, QualType AllocType=QualType())
static bool EvaluateArgs(ArrayRef< const Expr * > Args, CallRef Call, EvalInfo &Info, const FunctionDecl *Callee, bool RightToLeft=false, LValue *ObjectArg=nullptr)
Evaluate the arguments to a function call.
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, EvalInfo &Info)
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, const LValue &LVal, llvm::APInt &Result)
Convenience function. LVal's base must be a call to an alloc_size function.
static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E, const APSInt &LHS, BinaryOperatorKind Opcode, APSInt RHS, APSInt &Result)
Perform the given binary integer operation.
static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info, const ValueDecl *D, const Expr *Init, LValue &Result, APValue &Val)
Evaluates the initializer of a reference.
static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, AccessKinds AK, bool Polymorphic)
Check that we can access the notional vptr of an object / determine its dynamic type.
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, QualType SrcType, const APFloat &Value, QualType DestType, APSInt &Result)
static bool getAlignmentArgument(const Expr *E, QualType ForType, EvalInfo &Info, APSInt &Alignment)
Evaluate the value of the alignment argument to __builtin_align_{up,down}, __builtin_is_aligned and _...
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value)
Check that this evaluated value is fully-initialized and can be loaded by an lvalue-to-rvalue convers...
static SubobjectHandler::result_type findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, SubobjectHandler &handler)
Find the designated sub-object of an rvalue.
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, unsigned Type, const LValue &LVal, CharUnits &EndOffset)
Helper for tryEvaluateBuiltinObjectSize – Given an LValue, this will determine how many bytes exist f...
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, CharUnits &Result)
Converts the given APInt to CharUnits, assuming the APInt is unsigned. Fails if the conversion would ...
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, CallRef Call, EvalInfo &Info, bool NonNull=false, APValue **EvaluatedArg=nullptr)
llvm::SmallPtrSet< const MaterializeTemporaryExpr *, 8 > CheckedTemporaries
Materialized temporaries that we've already checked to determine if they're initializsed by a constan...
GCCTypeClass EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts)
EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way as GCC.
static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info)
static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info, const VarDecl *VD)
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, QualType DestType, QualType SrcType, const APSInt &Value)
static std::optional< APValue > handleVectorUnaryOperator(ASTContext &Ctx, QualType ResultTy, UnaryOperatorKind Op, APValue Elt)
static bool lifetimeStartedInEvaluation(EvalInfo &Info, APValue::LValueBase Base, bool MutableSubobject=false)
static bool isOneByteCharacterType(QualType T)
static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result, const CXXMethodDecl *MD, const FieldDecl *FD, bool LValueToRValueConversion)
Get an lvalue to a field of a lambda's closure type.
static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, const Expr *Cond, bool &Result)
Evaluate a condition (either a variable declaration or an expression).
static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result)
EvaluateAsRValue - Try to evaluate this expression, performing an implicit lvalue-to-rvalue cast if i...
static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, QualType T)
Diagnose an attempt to read from any unreadable field within the specified type, which might be a cla...
static ICEDiag CheckICE(const Expr *E, const ASTContext &Ctx)
static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, const FunctionDecl *Declaration, const FunctionDecl *Definition, const Stmt *Body)
CheckConstexprFunction - Check that a function can be called in a constant expression.
static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, APValue DestroyedValue, QualType Type, SourceLocation Loc, Expr::EvalStatus &EStatus, bool IsConstantDestruction)
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, const Stmt *S, const SwitchCase *SC=nullptr)
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, APValue &Result, const InitListExpr *ILE, QualType AllocType)
static bool HasSameBase(const LValue &A, const LValue &B)
static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD)
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool IsGlobalLValue(APValue::LValueBase B)
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E)
Get rounding mode to use in evaluation of the specified expression.
static QualType getObjectType(APValue::LValueBase B)
Retrieves the "underlying object type" of the given expression, as used by __builtin_object_size.
static bool handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, const APTy &RHSValue, APInt &Result)
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
static void negateAsSigned(APSInt &Int)
Negate an APSInt in place, converting it to a signed form if necessary, and preserving its value (by ...
static bool HandleFunctionCall(SourceLocation CallLoc, const FunctionDecl *Callee, const LValue *ObjectArg, const Expr *E, ArrayRef< const Expr * > Args, CallRef Call, const Stmt *Body, EvalInfo &Info, APValue &Result, const LValue *ResultSlot)
Evaluate a function call.
static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal)
Attempts to detect a user writing into a piece of memory that's impossible to figure out the size of ...
static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal, LValueBaseString &AsString)
static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E)
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info)
EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and produce either the intege...
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, LValue &Ptr)
Apply the given dynamic cast operation on the provided lvalue.
static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, LValue &Result)
Perform a call to 'operator new' or to ‘__builtin_operator_new’.
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result)
static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, const LValue &LHS)
Handle a builtin simple-assignment or a call to a trivial assignment operator whose left-hand side mi...
uint8_t GFNIMul(uint8_t AByte, uint8_t BByte)
static bool isFormalAccess(AccessKinds AK)
Is this an access per the C++ definition?
static bool handleCompoundAssignment(EvalInfo &Info, const CompoundAssignOperator *E, const LValue &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, const APValue &RVal)
Perform a compound assignment of LVal <op>= RVal.
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, bool IsIncrement, APValue *Old)
Perform an increment or decrement on LVal.
static ICEDiag NoDiag()
static bool EvaluateVoid(const Expr *E, EvalInfo &Info)
static bool HandleDestruction(EvalInfo &Info, const Expr *E, const LValue &This, QualType ThisType)
Perform a destructor or pseudo-destructor call on the given object, which might in general not be a c...
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T)
static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info, const LValue &LHS, const LValue &RHS)
uint8_t GFNIMultiplicativeInverse(uint8_t Byte)
uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm, bool Inverse)
APSInt NormalizeRotateAmount(const APSInt &Value, const APSInt &Amount)
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
#define X(type, name)
Definition Value.h:97
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic which may not be emitted.
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition ParentMap.cpp:21
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Expr * getExpr()
Get 'expr' part of the associated expression/statement.
static QualType getPointeeType(const MemRegion *R)
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ long long abs(long long __n)
a trap message and trap category.
llvm::APInt getValue() const
QualType getType() const
Definition APValue.cpp:63
unsigned getVersion() const
Definition APValue.cpp:113
QualType getDynamicAllocType() const
Definition APValue.cpp:122
QualType getTypeInfoType() const
Definition APValue.cpp:117
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition APValue.cpp:55
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition APValue.cpp:47
A non-discriminated union of a base, field, or array index.
Definition APValue.h:208
BaseOrMemberType getAsBaseOrMember() const
Definition APValue.h:222
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition APValue.h:216
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool hasArrayFiller() const
Definition APValue.h:634
const LValueBase getLValueBase() const
Definition APValue.cpp:1015
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:626
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition APValue.cpp:482
APSInt & getInt()
Definition APValue.h:508
APValue & getStructField(unsigned i)
Definition APValue.h:667
unsigned getMatrixNumColumns() const
Definition APValue.h:599
const FieldDecl * getUnionField() const
Definition APValue.h:679
bool isVector() const
Definition APValue.h:491
APSInt & getComplexIntImag()
Definition APValue.h:546
bool isAbsent() const
Definition APValue.h:481
bool isComplexInt() const
Definition APValue.h:488
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
Definition APValue.h:205
ValueKind getKind() const
Definition APValue.h:479
unsigned getArrayInitializedElts() const
Definition APValue.h:645
static APValue IndeterminateValue()
Definition APValue.h:450
bool isFloat() const
Definition APValue.h:486
APFixedPoint & getFixedPoint()
Definition APValue.h:530
bool hasValue() const
Definition APValue.h:483
bool hasLValuePath() const
Definition APValue.cpp:1030
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1098
APValue & getUnionValue()
Definition APValue.h:683
CharUnits & getLValueOffset()
Definition APValue.cpp:1025
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:717
bool isComplexFloat() const
Definition APValue.h:489
APValue & getVectorElt(unsigned I)
Definition APValue.h:582
APValue & getArrayFiller()
Definition APValue.h:637
unsigned getVectorLength() const
Definition APValue.h:590
bool isLValue() const
Definition APValue.h:490
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition APValue.cpp:1091
bool isIndeterminate() const
Definition APValue.h:482
unsigned getMatrixNumRows() const
Definition APValue.h:595
bool isInt() const
Definition APValue.h:485
unsigned getArraySize() const
Definition APValue.h:649
bool allowConstexprUnknown() const
Definition APValue.h:329
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:988
bool isFixedPoint() const
Definition APValue.h:487
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:606
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isStruct() const
Definition APValue.h:494
APSInt & getComplexIntReal()
Definition APValue.h:538
APFloat & getComplexFloatImag()
Definition APValue.h:562
APFloat & getComplexFloatReal()
Definition APValue.h:554
APFloat & getFloat()
Definition APValue.h:522
APValue & getStructBase(unsigned i)
Definition APValue.h:662
bool isMatrix() const
Definition APValue.h:492
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
SourceManager & getSourceManager()
Definition ASTContext.h:859
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:952
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
interp::Context & getInterpContext() const
Returns the clang bytecode interpreter context.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:851
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
LabelDecl * getLabel() const
Definition Expr.h:4576
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5986
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5991
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2753
uint64_t getValue() const
Definition ExprCXX.h:3045
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3772
QualType getElementType() const
Definition TypeBase.h:3784
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8230
Attr - This represents one attribute.
Definition Attr.h:46
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4456
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4510
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4494
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4491
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4174
Expr * getLHS() const
Definition Expr.h:4091
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4135
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4141
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4188
SourceLocation getExprLoc() const
Definition Expr.h:4082
Expr * getRHS() const
Definition Expr.h:4093
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4127
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4118
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4177
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4254
Opcode getOpcode() const
Definition Expr.h:4086
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4138
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4808
const BlockDecl * getBlockDecl() const
Definition Expr.h:6683
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
const Expr * getSubExpr() const
Definition ExprCXX.h:1516
bool getValue() const
Definition ExprCXX.h:741
Represents a call to a C++ constructor.
Definition ExprCXX.h:1549
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1618
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1692
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1651
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1689
Represents a C++ constructor within a class.
Definition DeclCXX.h:2611
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3017
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition DeclCXX.h:2697
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1105
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2666
bool isArrayForm() const
Definition ExprCXX.h:2653
bool isGlobalDelete() const
Definition ExprCXX.h:2652
Represents a C++ destructor within a class.
Definition DeclCXX.h:2876
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:1789
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2721
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2728
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2838
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2262
bool isInstance() const
Definition DeclCXX.h:2163
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2753
bool isStatic() const
Definition DeclCXX.cpp:2419
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2732
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2863
QualType getAllocatedType() const
Definition ExprCXX.h:2435
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:2470
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2504
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2495
SourceRange getSourceRange() const
Definition ExprCXX.h:2611
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2460
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2534
bool getValue() const
Definition ExprCXX.h:4333
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5182
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
Definition DeclCXX.h:1233
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1679
base_class_iterator bases_end()
Definition DeclCXX.h:617
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1372
base_class_range bases()
Definition DeclCXX.h:608
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition DeclCXX.cpp:1790
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
base_class_iterator bases_begin()
Definition DeclCXX.h:615
const CXXBaseSpecifier * base_class_const_iterator
Iterator that traverses the base classes of a class.
Definition DeclCXX.h:520
capture_const_range captures() const
Definition DeclCXX.h:1097
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2131
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:305
bool isImplicit() const
Definition ExprCXX.h:1178
bool isTypeOperand() const
Definition ExprCXX.h:885
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:896
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:134
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1115
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3150
SourceLocation getBeginLoc() const
Definition Expr.h:3280
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3592
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1592
Expr * getCallee()
Definition Expr.h:3093
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3137
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3239
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3140
Decl * getCalleeDecl()
Definition Expr.h:3123
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1603
CaseStmt - Represent a case statement.
Definition Stmt.h:1921
Expr * getLHS()
Definition Stmt.h:2004
Expr * getRHS()
Definition Stmt.h:2016
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3679
path_iterator path_begin()
Definition Expr.h:3749
unsigned path_size() const
Definition Expr.h:3748
CastKind getCastKind() const
Definition Expr.h:3723
path_iterator path_end()
Definition Expr.h:3750
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3746
bool path_empty() const
Definition Expr.h:3747
Expr * getSubExpr()
Definition Expr.h:3729
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition Expr.h:3793
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPowerOfTwo() const
isPowerOfTwo - Test whether the quantity is a power of two.
Definition CharUnits.h:135
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:207
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
unsigned getValue() const
Definition Expr.h:1632
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4887
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryResult makeWeakResult(ComparisonCategoryResult Res) const
Converts the specified result kind into the correct result kind for this category.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3325
QualType getElementType() const
Definition TypeBase.h:3335
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4303
QualType getComputationLHSType() const
Definition Expr.h:4337
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3608
bool hasStaticStorage() const
Definition Expr.h:3653
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5684
bool isFileScope() const
Definition Expr.h:3640
const Expr * getInitializer() const
Definition Expr.h:3636
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1741
bool body_empty() const
Definition Stmt.h:1785
Stmt *const * const_body_iterator
Definition Stmt.h:1813
body_iterator body_end()
Definition Stmt.h:1806
body_range body()
Definition Stmt.h:1804
body_iterator body_begin()
Definition Stmt.h:1805
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
ConditionalOperator - The ?
Definition Expr.h:4394
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4426
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4417
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4421
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3810
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3873
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:216
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:256
uint64_t getLimitedSize() const
Return the size zero-extended to uint64_t or UINT64_MAX if the value is larger than UINT64_MAX.
Definition TypeBase.h:3899
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3880
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3906
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3866
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3886
APValue getAPValueResult() const
Definition Expr.cpp:413
bool hasAPValueResult() const
Definition Expr.h:1160
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4437
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4799
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4812
Represents the current source location and context used to determine the value of the source location...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h: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:1273
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1477
ValueDecl * getDecl()
Definition Expr.h:1341
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1632
decl_range decls()
Definition Stmt.h:1680
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:4252
auto flat_bindings() const
Definition DeclCXX.h:4295
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2833
Stmt * getBody()
Definition Stmt.h:2858
Expr * getCond()
Definition Stmt.h:2851
Symbolic representation of a dynamic allocation.
Definition APValue.h:65
static unsigned getMaxIndex()
Definition APValue.h:85
const Expr * getBase() const
Definition Expr.h:6580
ChildElementIter< false > begin()
Definition Expr.h:5235
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3931
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3958
This represents one expression.
Definition Expr.h:112
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:84
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluated - Return true if this expression might be usable in a constant exp...
bool isGLValue() const
Definition Expr.h:287
SideEffectsKind
Definition Expr.h:673
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:677
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition Expr.h:675
bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result=nullptr) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
bool EvaluateCharRangeAsString(std::string &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, EvalResult &Status) const
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3095
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition Expr.cpp:3989
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3090
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3086
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
std::optional< uint64_t > tryEvaluateStrLen(const ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3688
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3253
Expr()=delete
ConstantExprKind
Definition Expr.h:752
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
QualType getType() const
Definition Expr.h:144
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This=nullptr) const
EvaluateWithSubstitution - Evaluate an expression as if from the context of a call to the given funct...
bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, const VarDecl *VD, SmallVectorImpl< PartialDiagnosticAt > &Notes, bool IsConstantInitializer) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
void EvaluateForOverflow(const ASTContext &Ctx) const
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition Expr.cpp:4436
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4549
bool isFPConstrained() const
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3175
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3278
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4753
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3260
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3411
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3422
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1578
llvm::APFloat getValue() const
Definition Expr.h:1669
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2889
Stmt * getInit()
Definition Stmt.h:2904
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2933
Expr * getInc()
Definition Stmt.h:2932
Expr * getCond()
Definition Stmt.h:2931
const Expr * getSubExpr() const
Definition Expr.h:1065
Represents a function declaration or definition.
Definition Decl.h:2015
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2812
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3280
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4206
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4194
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3866
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2392
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4330
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2485
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
Definition Decl.cpp:3427
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2400
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Definition Decl.cpp:3126
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6467
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
IfStmt - This represents an if/then/else.
Definition Stmt.h:2260
Stmt * getThen()
Definition Stmt.h:2349
Stmt * getInit()
Definition Stmt.h:2410
bool isNonNegatedConsteval() const
Definition Stmt.h:2445
Expr * getCond()
Definition Stmt.h:2337
Stmt * getElse()
Definition Stmt.h:2358
bool isConsteval() const
Definition Stmt.h:2440
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
const Expr * getSubExpr() const
Definition Expr.h:1746
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6060
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3482
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3503
Describes an C or C++ initializer list.
Definition Expr.h:5302
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2462
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2448
unsigned getNumInits() const
Definition Expr.h:5332
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5404
const Expr * getInit(unsigned Init) const
Definition Expr.h:5356
ArrayRef< Expr * > inits()
Definition Expr.h:5352
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2107
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2095
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:4921
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4946
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4938
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:4954
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
Expr * getBase() const
Definition Expr.h:3444
bool isArrow() const
Definition Expr.h:3551
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition Decl.cpp:1687
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:68
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2589
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2577
TypeSourceInfo * getTypeSourceInfo() const
Definition Expr.h:2570
unsigned getNumComponents() const
Definition Expr.h:2585
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2482
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2488
@ Array
An index into an array.
Definition Expr.h:2429
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2433
@ Field
A field.
Definition Expr.h:2431
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition Expr.h:2436
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2478
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition Expr.h:2498
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1231
Expr * getSelectedExpr() const
Definition ExprCXX.h:4640
const Expr * getSubExpr() const
Definition Expr.h:2202
Represents a parameter to a function.
Definition Decl.h:1805
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1865
bool isExplicitObjectParameter() const
Definition Decl.h:1893
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3378
StringLiteral * getFunctionName()
Definition Expr.h:2052
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6851
ArrayRef< Expr * > semantics()
Definition Expr.h:6875
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8515
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2914
QualType withConst() const
Definition TypeBase.h:1165
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1162
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8431
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8616
QualType getCanonicalType() const
Definition TypeBase.h:8483
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8525
void removeLocalVolatile()
Definition TypeBase.h:8547
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1170
void removeLocalConst()
Definition TypeBase.h:8539
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8504
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1684
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1551
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8477
bool isWrapType() const
Returns true if it is a OverflowBehaviorType of Wrap kind.
Definition Type.cpp:3004
Represents a struct/union/class.
Definition Decl.h:4342
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
Definition Decl.h:4558
field_iterator field_end() const
Definition Decl.h:4548
field_range fields() const
Definition Decl.h:4545
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4542
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4394
bool field_empty() const
Definition Decl.h:4553
field_iterator field_begin() const
Definition Decl.cpp:5276
bool isSatisfied() const
Whether or not the requires clause is satisfied.
SourceLocation getLocation() const
Definition Expr.h:2158
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:587
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4646
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4698
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4679
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4685
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4516
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2282
bool isIntType() const
Definition Expr.h:5044
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
std::string printToString(const SourceManager &SM) const
CompoundStmt * getSubStmt()
Definition Expr.h:4615
Stmt - This represents one statement.
Definition Stmt.h:86
@ NoStmtClass
Definition Stmt.h:89
StmtClass getStmtClass() const
Definition Stmt.h:1494
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
unsigned getLength() const
Definition Expr.h:1912
StringRef getBytes() const
Allow access to clients that need the byte representation, such as ASTWriterStmt::VisitStringLiteral(...
Definition Expr.h:1878
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1885
StringRef getString() const
Definition Expr.h:1870
unsigned getCharByteWidth() const
Definition Expr.h:1913
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1894
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2510
Expr * getCond()
Definition Stmt.h:2573
Stmt * getBody()
Definition Stmt.h:2585
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2590
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2641
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4900
bool isUnion() const
Definition Decl.h:3943
unsigned size() const
Retrieve the number of template arguments in this template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
@ Type
The template argument is a type.
Symbolic representation of typeid(T) for some type T.
Definition APValue.h:44
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8413
bool getBoolValue() const
Definition ExprCXX.h:2948
const APValue & getAPValue() const
Definition ExprCXX.h:2953
bool isStoredAsBoolean() const
Definition ExprCXX.h:2944
The base class of the type hierarchy.
Definition TypeBase.h:1866
bool isVoidType() const
Definition TypeBase.h:9034
bool isBooleanType() const
Definition TypeBase.h:9171
bool isFunctionReferenceType() const
Definition TypeBase.h:8742
bool isMFloat8Type() const
Definition TypeBase.h:9059
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2254
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:420
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3061
bool isIncompleteArrayType() const
Definition TypeBase.h:8775
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2231
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:726
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9337
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2308
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2138
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8771
bool isNothrowT() const
Definition Type.cpp:3245
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:714
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2470
bool isArrayType() const
Definition TypeBase.h:8767
bool isFunctionPointerType() const
Definition TypeBase.h:8735
bool isConstantMatrixType() const
Definition TypeBase.h:8835
bool isPointerType() const
Definition TypeBase.h:8668
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9078
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9328
bool isReferenceType() const
Definition TypeBase.h:8692
bool isEnumeralType() const
Definition TypeBase.h:8799
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1923
bool isVariableArrayType() const
Definition TypeBase.h:8779
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2654
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:754
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9156
bool isExtVectorBoolType() const
Definition TypeBase.h:8815
bool isMemberDataPointerType() const
Definition TypeBase.h:8760
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9003
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2832
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8803
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9094
bool isMemberPointerType() const
Definition TypeBase.h:8749
bool isAtomicType() const
Definition TypeBase.h:8860
bool isComplexIntegerType() const
Definition Type.cpp:732
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9314
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2558
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2480
bool isFunctionType() const
Definition TypeBase.h:8664
bool isVectorType() const
Definition TypeBase.h:8807
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2358
bool isFloatingType() const
Definition Type.cpp:2342
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2285
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2978
bool isAnyPointerType() const
Definition TypeBase.h:8676
TypeClass getTypeClass() const
Definition TypeBase.h:2433
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
bool isNullPtrType() const
Definition TypeBase.h:9071
bool isRecordType() const
Definition TypeBase.h:8795
bool isUnionType() const
Definition Type.cpp:720
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2616
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9205
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2628
QualType getArgumentType() const
Definition Expr.h:2671
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2707
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2697
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2660
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
SourceLocation getExprLoc() const
Definition Expr.h:2371
Expr * getSubExpr() const
Definition Expr.h:2288
Opcode getOpcode() const
Definition Expr.h:2283
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2329
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2301
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5582
QualType getType() const
Definition Value.cpp:237
bool hasValue() const
Definition Value.h:135
Represents a variable declaration or definition.
Definition Decl.h:926
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1584
bool hasInit() const
Definition Decl.cpp:2410
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition Decl.cpp:2648
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1593
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2587
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2889
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2660
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2378
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:2498
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2569
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1208
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1177
const Expr * getInit() const
Definition Decl.h:1383
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or NULL if the value is not yet kn...
Definition Decl.cpp:2640
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:2387
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1268
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition Decl.cpp:2540
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1373
Expr * getSizeExpr() const
Definition TypeBase.h:4030
Represents a GCC generic vector type.
Definition TypeBase.h:4225
unsigned getNumElements() const
Definition TypeBase.h:4240
QualType getElementType() const
Definition TypeBase.h:4239
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2698
Expr * getCond()
Definition Stmt.h:2750
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2762
Base class for stack frames, shared between VM and walker.
Definition Frame.h:25
Interface for the VM to interact with the AST walker's context.
Definition State.h:81
Defines the clang::TargetInfo interface.
#define CHAR_BIT
Definition limits.h:71
#define UINT_MAX
Definition limits.h:64
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
Definition OSLog.cpp:192
static const FunctionDecl * getCallee(const CXXConstructExpr &D)
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
unsigned kind
All of the diagnostics that can be emitted by the frontend.
std::optional< llvm::AllocTokenMetadata > getAllocTokenMetadata(QualType T, const ASTContext &Ctx)
Get the information required for construction of an allocation token ID.
QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE)
Infer the possible allocated type from an allocation call expression.
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1327
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:55
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:2857
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:3524
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.
llvm::json::Array Array
llvm::json::Object Object
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:1045
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:206
@ AS_public
Definition Specifiers.h: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:44
@ CSK_ArrayToPointer
Definition State.h:48
@ CSK_Derived
Definition State.h:46
@ CSK_Base
Definition State.h:45
@ CSK_Real
Definition State.h:50
@ CSK_ArrayIndex
Definition State.h:49
@ CSK_Imag
Definition State.h:51
@ CSK_VectorElement
Definition State.h:52
@ CSK_Field
Definition State.h:47
@ SD_Static
Static storage duration.
Definition Specifiers.h: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:28
@ AK_TypeId
Definition State.h:36
@ AK_Construct
Definition State.h:37
@ AK_Increment
Definition State.h:32
@ AK_DynamicCast
Definition State.h:35
@ AK_Read
Definition State.h:29
@ AK_Assign
Definition State.h:31
@ AK_IsWithinLifetime
Definition State.h:39
@ AK_MemberCall
Definition State.h:34
@ AK_ReadObjectRepresentation
Definition State.h:30
@ AK_Dereference
Definition State.h:40
@ AK_Destroy
Definition State.h:38
@ AK_Decrement
Definition State.h:33
@ Type
The name was classified as a type.
Definition Sema.h:564
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
EvaluationMode
Definition State.h:55
@ ConstantFold
Fold the expression to a constant.
Definition State.h:69
@ ConstantExpressionUnevaluated
Evaluate as a constant expression.
Definition State.h:65
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:58
@ IgnoreSideEffects
Evaluate in any way we know how.
Definition State.h:73
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:179
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5967
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1761
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
unsigned long uint64_t
long int64_t
unsigned int uint32_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
hash_code hash_value(const clang::dependencies::ModuleID &ID)
#define false
Definition stdbool.h:26
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
std::string ObjCEncodeStorage
Represents an element in a path from a derived class to a base class.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
bool isGlobalLValue() const
Return true if the evaluated lvalue expression is global.
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition Expr.h:612
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:636
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
static ObjectUnderConstruction getTombstoneKey()
DenseMapInfo< APValue::LValueBase > Base
static ObjectUnderConstruction getEmptyKey()
static unsigned getHashValue(const ObjectUnderConstruction &Object)
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
#define ilogb(__x)
Definition tgmath.h:851
#define scalbn(__x, __y)
Definition tgmath.h:1165