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 unsigned getHashValue(const ObjectUnderConstruction &Object) {
737 return hash_value(Object);
738 }
739 static bool isEqual(const ObjectUnderConstruction &LHS,
740 const ObjectUnderConstruction &RHS) {
741 return LHS == RHS;
742 }
743};
744}
745
746namespace {
747 /// A dynamically-allocated heap object.
748 struct DynAlloc {
749 /// The value of this heap-allocated object.
750 APValue Value;
751 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
752 /// or a CallExpr (the latter is for direct calls to operator new inside
753 /// std::allocator<T>::allocate).
754 const Expr *AllocExpr = nullptr;
755
756 enum Kind {
757 New,
758 ArrayNew,
759 StdAllocator
760 };
761
762 /// Get the kind of the allocation. This must match between allocation
763 /// and deallocation.
764 Kind getKind() const {
765 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
766 return NE->isArray() ? ArrayNew : New;
767 assert(isa<CallExpr>(AllocExpr));
768 return StdAllocator;
769 }
770 };
771
772 struct DynAllocOrder {
773 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
774 return L.getIndex() < R.getIndex();
775 }
776 };
777
778 /// EvalInfo - This is a private struct used by the evaluator to capture
779 /// information about a subexpression as it is folded. It retains information
780 /// about the AST context, but also maintains information about the folded
781 /// expression.
782 ///
783 /// If an expression could be evaluated, it is still possible it is not a C
784 /// "integer constant expression" or constant expression. If not, this struct
785 /// captures information about how and why not.
786 ///
787 /// One bit of information passed *into* the request for constant folding
788 /// indicates whether the subexpression is "evaluated" or not according to C
789 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
790 /// evaluate the expression regardless of what the RHS is, but C only allows
791 /// certain things in certain situations.
792 class EvalInfo final : public interp::State {
793 public:
794 /// CurrentCall - The top of the constexpr call stack.
795 CallStackFrame *CurrentCall;
796
797 /// CallStackDepth - The number of calls in the call stack right now.
798 unsigned CallStackDepth;
799
800 /// NextCallIndex - The next call index to assign.
801 unsigned NextCallIndex;
802
803 /// StepsLeft - The remaining number of evaluation steps we're permitted
804 /// to perform. This is essentially a limit for the number of statements
805 /// we will evaluate.
806 unsigned StepsLeft;
807
808 /// Enable the experimental new constant interpreter. If an expression is
809 /// not supported by the interpreter, an error is triggered.
810 bool EnableNewConstInterp;
811
812 /// BottomFrame - The frame in which evaluation started. This must be
813 /// initialized after CurrentCall and CallStackDepth.
814 CallStackFrame BottomFrame;
815
816 /// A stack of values whose lifetimes end at the end of some surrounding
817 /// evaluation frame.
818 llvm::SmallVector<Cleanup, 16> CleanupStack;
819
820 /// EvaluatingDecl - This is the declaration whose initializer is being
821 /// evaluated, if any.
822 APValue::LValueBase EvaluatingDecl;
823
824 enum class EvaluatingDeclKind {
825 None,
826 /// We're evaluating the construction of EvaluatingDecl.
827 Ctor,
828 /// We're evaluating the destruction of EvaluatingDecl.
829 Dtor,
830 };
831 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
832
833 /// EvaluatingDeclValue - This is the value being constructed for the
834 /// declaration whose initializer is being evaluated, if any.
835 APValue *EvaluatingDeclValue;
836
837 /// Stack of loops and 'switch' statements which we're currently
838 /// breaking/continuing; null entries are used to mark unlabeled
839 /// break/continue.
840 SmallVector<const Stmt *> BreakContinueStack;
841
842 /// Set of objects that are currently being constructed.
843 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
844 ObjectsUnderConstruction;
845
846 /// Current heap allocations, along with the location where each was
847 /// allocated. We use std::map here because we need stable addresses
848 /// for the stored APValues.
849 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
850
851 /// The number of heap allocations performed so far in this evaluation.
852 unsigned NumHeapAllocs = 0;
853
854 struct EvaluatingConstructorRAII {
855 EvalInfo &EI;
856 ObjectUnderConstruction Object;
857 bool DidInsert;
858 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
859 bool HasBases)
860 : EI(EI), Object(Object) {
861 DidInsert =
862 EI.ObjectsUnderConstruction
863 .insert({Object, HasBases ? ConstructionPhase::Bases
864 : ConstructionPhase::AfterBases})
865 .second;
866 }
867 void finishedConstructingBases() {
868 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
869 }
870 void finishedConstructingFields() {
871 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
872 }
873 ~EvaluatingConstructorRAII() {
874 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
875 }
876 };
877
878 struct EvaluatingDestructorRAII {
879 EvalInfo &EI;
880 ObjectUnderConstruction Object;
881 bool DidInsert;
882 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
883 : EI(EI), Object(Object) {
884 DidInsert = EI.ObjectsUnderConstruction
885 .insert({Object, ConstructionPhase::Destroying})
886 .second;
887 }
888 void startedDestroyingBases() {
889 EI.ObjectsUnderConstruction[Object] =
890 ConstructionPhase::DestroyingBases;
891 }
892 ~EvaluatingDestructorRAII() {
893 if (DidInsert)
894 EI.ObjectsUnderConstruction.erase(Object);
895 }
896 };
897
898 ConstructionPhase
899 isEvaluatingCtorDtor(APValue::LValueBase Base,
900 ArrayRef<APValue::LValuePathEntry> Path) {
901 return ObjectsUnderConstruction.lookup({Base, Path});
902 }
903
904 /// If we're currently speculatively evaluating, the outermost call stack
905 /// depth at which we can mutate state, otherwise 0.
906 unsigned SpeculativeEvaluationDepth = 0;
907
908 /// The current array initialization index, if we're performing array
909 /// initialization.
910 uint64_t ArrayInitIndex = -1;
911
912 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
913 : State(const_cast<ASTContext &>(C), S), CurrentCall(nullptr),
914 CallStackDepth(0), NextCallIndex(1),
915 StepsLeft(C.getLangOpts().ConstexprStepLimit),
916 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
917 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
918 /*This=*/nullptr,
919 /*CallExpr=*/nullptr, CallRef()),
920 EvaluatingDecl((const ValueDecl *)nullptr),
921 EvaluatingDeclValue(nullptr) {
922 EvalMode = Mode;
923 }
924
925 ~EvalInfo() {
926 discardCleanups();
927 }
928
929 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
930 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
931 EvaluatingDecl = Base;
932 IsEvaluatingDecl = EDK;
933 EvaluatingDeclValue = &Value;
934 }
935
936 bool CheckCallLimit(SourceLocation Loc) {
937 // Don't perform any constexpr calls (other than the call we're checking)
938 // when checking a potential constant expression.
939 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
940 return false;
941 if (NextCallIndex == 0) {
942 // NextCallIndex has wrapped around.
943 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
944 return false;
945 }
946 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
947 return true;
948 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
949 << getLangOpts().ConstexprCallDepth;
950 return false;
951 }
952
953 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
954 uint64_t ElemCount, bool Diag) {
955 // FIXME: GH63562
956 // APValue stores array extents as unsigned,
957 // so anything that is greater that unsigned would overflow when
958 // constructing the array, we catch this here.
959 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
960 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
961 if (Diag)
962 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
963 return false;
964 }
965
966 // FIXME: GH63562
967 // Arrays allocate an APValue per element.
968 // We use the number of constexpr steps as a proxy for the maximum size
969 // of arrays to avoid exhausting the system resources, as initialization
970 // of each element is likely to take some number of steps anyway.
971 uint64_t Limit = getLangOpts().ConstexprStepLimit;
972 if (Limit != 0 && ElemCount > Limit) {
973 if (Diag)
974 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
975 << ElemCount << Limit;
976 return false;
977 }
978 return true;
979 }
980
981 std::pair<CallStackFrame *, unsigned>
982 getCallFrameAndDepth(unsigned CallIndex) {
983 assert(CallIndex && "no call index in getCallFrameAndDepth");
984 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
985 // be null in this loop.
986 unsigned Depth = CallStackDepth;
987 CallStackFrame *Frame = CurrentCall;
988 while (Frame->Index > CallIndex) {
989 Frame = Frame->Caller;
990 --Depth;
991 }
992 if (Frame->Index == CallIndex)
993 return {Frame, Depth};
994 return {nullptr, 0};
995 }
996
997 bool nextStep(const Stmt *S) {
998 if (getLangOpts().ConstexprStepLimit == 0)
999 return true;
1000
1001 if (!StepsLeft) {
1002 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1003 return false;
1004 }
1005 --StepsLeft;
1006 return true;
1007 }
1008
1009 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1010
1011 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1012 std::optional<DynAlloc *> Result;
1013 auto It = HeapAllocs.find(DA);
1014 if (It != HeapAllocs.end())
1015 Result = &It->second;
1016 return Result;
1017 }
1018
1019 /// Get the allocated storage for the given parameter of the given call.
1020 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1021 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1022 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1023 : nullptr;
1024 }
1025
1026 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1027 struct StdAllocatorCaller {
1028 unsigned FrameIndex;
1029 QualType ElemType;
1030 const Expr *Call;
1031 explicit operator bool() const { return FrameIndex != 0; };
1032 };
1033
1034 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1035 for (const CallStackFrame *Call = CurrentCall; Call->Caller != nullptr;
1036 Call = Call->Caller) {
1037 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1038 if (!MD)
1039 continue;
1040 const IdentifierInfo *FnII = MD->getIdentifier();
1041 if (!FnII || !FnII->isStr(FnName))
1042 continue;
1043
1044 const auto *CTSD =
1045 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1046 if (!CTSD)
1047 continue;
1048
1049 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1050 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1051 if (CTSD->isInStdNamespace() && ClassII &&
1052 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1053 TAL[0].getKind() == TemplateArgument::Type)
1054 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1055 }
1056
1057 return {};
1058 }
1059
1060 void performLifetimeExtension() {
1061 // Disable the cleanups for lifetime-extended temporaries.
1062 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1063 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1064 });
1065 }
1066
1067 /// Throw away any remaining cleanups at the end of evaluation. If any
1068 /// cleanups would have had a side-effect, note that as an unmodeled
1069 /// side-effect and return false. Otherwise, return true.
1070 bool discardCleanups() {
1071 for (Cleanup &C : CleanupStack) {
1072 if (C.hasSideEffect() && !noteSideEffect()) {
1073 CleanupStack.clear();
1074 return false;
1075 }
1076 }
1077 CleanupStack.clear();
1078 return true;
1079 }
1080
1081 private:
1082 const interp::Frame *getCurrentFrame() override { return CurrentCall; }
1083
1084 unsigned getCallStackDepth() override { return CallStackDepth; }
1085 bool stepsLeft() const override { return StepsLeft > 0; }
1086
1087 public:
1088 /// Notes that we failed to evaluate an expression that other expressions
1089 /// directly depend on, and determine if we should keep evaluating. This
1090 /// should only be called if we actually intend to keep evaluating.
1091 ///
1092 /// Call noteSideEffect() instead if we may be able to ignore the value that
1093 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1094 ///
1095 /// (Foo(), 1) // use noteSideEffect
1096 /// (Foo() || true) // use noteSideEffect
1097 /// Foo() + 1 // use noteFailure
1098 [[nodiscard]] bool noteFailure() {
1099 // Failure when evaluating some expression often means there is some
1100 // subexpression whose evaluation was skipped. Therefore, (because we
1101 // don't track whether we skipped an expression when unwinding after an
1102 // evaluation failure) every evaluation failure that bubbles up from a
1103 // subexpression implies that a side-effect has potentially happened. We
1104 // skip setting the HasSideEffects flag to true until we decide to
1105 // continue evaluating after that point, which happens here.
1106 bool KeepGoing = keepEvaluatingAfterFailure();
1107 EvalStatus.HasSideEffects |= KeepGoing;
1108 return KeepGoing;
1109 }
1110
1111 class ArrayInitLoopIndex {
1112 EvalInfo &Info;
1113 uint64_t OuterIndex;
1114
1115 public:
1116 ArrayInitLoopIndex(EvalInfo &Info)
1117 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1118 Info.ArrayInitIndex = 0;
1119 }
1120 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1121
1122 operator uint64_t&() { return Info.ArrayInitIndex; }
1123 };
1124 };
1125
1126 /// Object used to treat all foldable expressions as constant expressions.
1127 struct FoldConstant {
1128 EvalInfo &Info;
1129 bool Enabled;
1130 bool HadNoPriorDiags;
1131 EvaluationMode OldMode;
1132
1133 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1134 : Info(Info),
1135 Enabled(Enabled),
1136 HadNoPriorDiags(Info.EvalStatus.Diag &&
1137 Info.EvalStatus.Diag->empty() &&
1138 !Info.EvalStatus.HasSideEffects),
1139 OldMode(Info.EvalMode) {
1140 if (Enabled)
1141 Info.EvalMode = EvaluationMode::ConstantFold;
1142 }
1143 void keepDiagnostics() { Enabled = false; }
1144 ~FoldConstant() {
1145 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1146 !Info.EvalStatus.HasSideEffects) {
1147 Info.EvalStatus.Diag->clear();
1148 Info.EvalStatus.DiagEmitted = false;
1149 }
1150 Info.EvalMode = OldMode;
1151 }
1152 };
1153
1154 /// RAII object used to set the current evaluation mode to ignore
1155 /// side-effects.
1156 struct IgnoreSideEffectsRAII {
1157 EvalInfo &Info;
1158 EvaluationMode OldMode;
1159 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1160 : Info(Info), OldMode(Info.EvalMode) {
1161 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1162 }
1163
1164 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1165 };
1166
1167 /// RAII object used to optionally suppress diagnostics and side-effects from
1168 /// a speculative evaluation.
1169 class SpeculativeEvaluationRAII {
1170 EvalInfo *Info = nullptr;
1171 Expr::EvalStatus OldStatus;
1172 unsigned OldSpeculativeEvaluationDepth = 0;
1173
1174 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1175 Info = Other.Info;
1176 OldStatus = Other.OldStatus;
1177 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1178 Other.Info = nullptr;
1179 }
1180
1181 void maybeRestoreState() {
1182 if (!Info)
1183 return;
1184
1185 Info->EvalStatus = OldStatus;
1186 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1187 }
1188
1189 public:
1190 SpeculativeEvaluationRAII() = default;
1191
1192 SpeculativeEvaluationRAII(
1193 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1194 : Info(&Info), OldStatus(Info.EvalStatus),
1195 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1196 Info.EvalStatus.Diag = NewDiag;
1197 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1198 }
1199
1200 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1201 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1202 moveFromAndCancel(std::move(Other));
1203 }
1204
1205 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1206 maybeRestoreState();
1207 moveFromAndCancel(std::move(Other));
1208 return *this;
1209 }
1210
1211 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1212 };
1213
1214 /// RAII object wrapping a full-expression or block scope, and handling
1215 /// the ending of the lifetime of temporaries created within it.
1216 template<ScopeKind Kind>
1217 class ScopeRAII {
1218 EvalInfo &Info;
1219 unsigned OldStackSize;
1220 public:
1221 ScopeRAII(EvalInfo &Info)
1222 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1223 // Push a new temporary version. This is needed to distinguish between
1224 // temporaries created in different iterations of a loop.
1225 Info.CurrentCall->pushTempVersion();
1226 }
1227 bool destroy(bool RunDestructors = true) {
1228 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1229 OldStackSize = std::numeric_limits<unsigned>::max();
1230 return OK;
1231 }
1232 ~ScopeRAII() {
1233 if (OldStackSize != std::numeric_limits<unsigned>::max())
1234 destroy(false);
1235 // Body moved to a static method to encourage the compiler to inline away
1236 // instances of this class.
1237 Info.CurrentCall->popTempVersion();
1238 }
1239 private:
1240 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1241 unsigned OldStackSize) {
1242 assert(OldStackSize <= Info.CleanupStack.size() &&
1243 "running cleanups out of order?");
1244
1245 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1246 // for a full-expression scope.
1247 bool Success = true;
1248 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1249 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1250 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1251 Success = false;
1252 break;
1253 }
1254 }
1255 }
1256
1257 // Compact any retained cleanups.
1258 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1259 if (Kind != ScopeKind::Block)
1260 NewEnd =
1261 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1262 return C.isDestroyedAtEndOf(Kind);
1263 });
1264 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1265 return Success;
1266 }
1267 };
1268 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1269 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1270 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1271}
1272
1273bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1274 CheckSubobjectKind CSK) {
1275 if (Invalid)
1276 return false;
1277 if (isOnePastTheEnd()) {
1278 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1279 << CSK;
1280 setInvalid();
1281 return false;
1282 }
1283 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1284 // must actually be at least one array element; even a VLA cannot have a
1285 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1286 return true;
1287}
1288
1289void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1290 const Expr *E) {
1291 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1292 // Do not set the designator as invalid: we can represent this situation,
1293 // and correct handling of __builtin_object_size requires us to do so.
1294}
1295
1296void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1297 const Expr *E,
1298 const APSInt &N) {
1299 // If we're complaining, we must be able to statically determine the size of
1300 // the most derived array.
1301 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1302 Info.CCEDiag(E, diag::note_constexpr_array_index)
1303 << N << /*array*/ 0
1304 << static_cast<unsigned>(getMostDerivedArraySize());
1305 else
1306 Info.CCEDiag(E, diag::note_constexpr_array_index)
1307 << N << /*non-array*/ 1;
1308 setInvalid();
1309}
1310
1311CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1312 const FunctionDecl *Callee, const LValue *This,
1313 const Expr *CallExpr, CallRef Call)
1314 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1315 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1316 Index(Info.NextCallIndex++) {
1317 Info.CurrentCall = this;
1318 ++Info.CallStackDepth;
1319}
1320
1321CallStackFrame::~CallStackFrame() {
1322 assert(Info.CurrentCall == this && "calls retired out of order");
1323 --Info.CallStackDepth;
1324 Info.CurrentCall = Caller;
1325}
1326
1327static bool isRead(AccessKinds AK) {
1328 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1329 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1330}
1331
1333 switch (AK) {
1334 case AK_Read:
1336 case AK_MemberCall:
1337 case AK_DynamicCast:
1338 case AK_TypeId:
1340 case AK_Dereference:
1341 return false;
1342 case AK_Assign:
1343 case AK_Increment:
1344 case AK_Decrement:
1345 case AK_Construct:
1346 case AK_Destroy:
1347 return true;
1348 }
1349 llvm_unreachable("unknown access kind");
1350}
1351
1352static bool isAnyAccess(AccessKinds AK) {
1353 return isRead(AK) || isModification(AK);
1354}
1355
1356/// Is this an access per the C++ definition?
1358 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1359 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1360}
1361
1362/// Is this kind of access valid on an indeterminate object value?
1364 switch (AK) {
1365 case AK_Read:
1366 case AK_Increment:
1367 case AK_Decrement:
1368 case AK_Dereference:
1369 // These need the object's value.
1370 return false;
1371
1374 case AK_Assign:
1375 case AK_Construct:
1376 case AK_Destroy:
1377 // Construction and destruction don't need the value.
1378 return true;
1379
1380 case AK_MemberCall:
1381 case AK_DynamicCast:
1382 case AK_TypeId:
1383 // These aren't really meaningful on scalars.
1384 return true;
1385 }
1386 llvm_unreachable("unknown access kind");
1387}
1388
1389namespace {
1390 struct ComplexValue {
1391 private:
1392 bool IsInt;
1393
1394 public:
1395 APSInt IntReal, IntImag;
1396 APFloat FloatReal, FloatImag;
1397
1398 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1399
1400 void makeComplexFloat() { IsInt = false; }
1401 bool isComplexFloat() const { return !IsInt; }
1402 APFloat &getComplexFloatReal() { return FloatReal; }
1403 APFloat &getComplexFloatImag() { return FloatImag; }
1404
1405 void makeComplexInt() { IsInt = true; }
1406 bool isComplexInt() const { return IsInt; }
1407 APSInt &getComplexIntReal() { return IntReal; }
1408 APSInt &getComplexIntImag() { return IntImag; }
1409
1410 void moveInto(APValue &v) const {
1411 if (isComplexFloat())
1412 v = APValue(FloatReal, FloatImag);
1413 else
1414 v = APValue(IntReal, IntImag);
1415 }
1416 void setFrom(const APValue &v) {
1417 assert(v.isComplexFloat() || v.isComplexInt());
1418 if (v.isComplexFloat()) {
1419 makeComplexFloat();
1420 FloatReal = v.getComplexFloatReal();
1421 FloatImag = v.getComplexFloatImag();
1422 } else {
1423 makeComplexInt();
1424 IntReal = v.getComplexIntReal();
1425 IntImag = v.getComplexIntImag();
1426 }
1427 }
1428 };
1429
1430 struct LValue {
1431 APValue::LValueBase Base;
1432 CharUnits Offset;
1433 SubobjectDesignator Designator;
1434 bool IsNullPtr : 1;
1435 bool InvalidBase : 1;
1436 // P2280R4 track if we have an unknown reference or pointer.
1437 bool AllowConstexprUnknown = false;
1438
1439 const APValue::LValueBase getLValueBase() const { return Base; }
1440 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1441 CharUnits &getLValueOffset() { return Offset; }
1442 const CharUnits &getLValueOffset() const { return Offset; }
1443 SubobjectDesignator &getLValueDesignator() { return Designator; }
1444 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1445 bool isNullPointer() const { return IsNullPtr;}
1446
1447 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1448 unsigned getLValueVersion() const { return Base.getVersion(); }
1449
1450 void moveInto(APValue &V) const {
1451 if (Designator.Invalid)
1452 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1453 else {
1454 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1455 V = APValue(Base, Offset, Designator.Entries,
1456 Designator.IsOnePastTheEnd, IsNullPtr);
1457 }
1458 if (AllowConstexprUnknown)
1459 V.setConstexprUnknown();
1460 }
1461 void setFrom(const ASTContext &Ctx, const APValue &V) {
1462 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1463 Base = V.getLValueBase();
1464 Offset = V.getLValueOffset();
1465 InvalidBase = false;
1466 Designator = SubobjectDesignator(Ctx, V);
1467 IsNullPtr = V.isNullPointer();
1468 AllowConstexprUnknown = V.allowConstexprUnknown();
1469 }
1470
1471 void set(APValue::LValueBase B, bool BInvalid = false) {
1472#ifndef NDEBUG
1473 // We only allow a few types of invalid bases. Enforce that here.
1474 if (BInvalid) {
1475 const auto *E = B.get<const Expr *>();
1476 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1477 "Unexpected type of invalid base");
1478 }
1479#endif
1480
1481 Base = B;
1482 Offset = CharUnits::fromQuantity(0);
1483 InvalidBase = BInvalid;
1484 Designator = SubobjectDesignator(getType(B));
1485 IsNullPtr = false;
1486 AllowConstexprUnknown = false;
1487 }
1488
1489 void setNull(ASTContext &Ctx, QualType PointerTy) {
1490 Base = (const ValueDecl *)nullptr;
1491 Offset =
1493 InvalidBase = false;
1494 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1495 IsNullPtr = true;
1496 AllowConstexprUnknown = false;
1497 }
1498
1499 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1500 set(B, true);
1501 }
1502
1503 std::string toString(ASTContext &Ctx, QualType T) const {
1504 APValue Printable;
1505 moveInto(Printable);
1506 return Printable.getAsString(Ctx, T);
1507 }
1508
1509 private:
1510 // Check that this LValue is not based on a null pointer. If it is, produce
1511 // a diagnostic and mark the designator as invalid.
1512 template <typename GenDiagType>
1513 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1514 if (Designator.Invalid)
1515 return false;
1516 if (IsNullPtr) {
1517 GenDiag();
1518 Designator.setInvalid();
1519 return false;
1520 }
1521 return true;
1522 }
1523
1524 public:
1525 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1526 CheckSubobjectKind CSK) {
1527 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1528 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1529 });
1530 }
1531
1532 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1533 AccessKinds AK) {
1534 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1535 if (AK == AccessKinds::AK_Dereference)
1536 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1537 else
1538 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1539 });
1540 }
1541
1542 // Check this LValue refers to an object. If not, set the designator to be
1543 // invalid and emit a diagnostic.
1544 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1545 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1546 Designator.checkSubobject(Info, E, CSK);
1547 }
1548
1549 void addDecl(EvalInfo &Info, const Expr *E,
1550 const Decl *D, bool Virtual = false) {
1551 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1552 Designator.addDeclUnchecked(D, Virtual);
1553 }
1554 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1555 if (!Designator.Entries.empty()) {
1556 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1557 Designator.setInvalid();
1558 return;
1559 }
1560 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1561 assert(!Base || getType(Base).getNonReferenceType()->isPointerType() ||
1562 getType(Base).getNonReferenceType()->isArrayType());
1563 Designator.FirstEntryIsAnUnsizedArray = true;
1564 Designator.addUnsizedArrayUnchecked(ElemTy);
1565 }
1566 }
1567 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1568 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1569 Designator.addArrayUnchecked(CAT);
1570 }
1571 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1572 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1573 Designator.addComplexUnchecked(EltTy, Imag);
1574 }
1575 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1576 uint64_t Size, uint64_t Idx) {
1577 if (checkSubobject(Info, E, CSK_VectorElement))
1578 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1579 }
1580 void clearIsNullPointer() {
1581 IsNullPtr = false;
1582 }
1583 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1584 const APSInt &Index, CharUnits ElementSize) {
1585 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1586 // but we're not required to diagnose it and it's valid in C++.)
1587 if (!Index)
1588 return;
1589
1590 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1591 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1592 // offsets.
1593 uint64_t Offset64 = Offset.getQuantity();
1594 uint64_t ElemSize64 = ElementSize.getQuantity();
1595 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1596 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1597
1598 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1599 Designator.adjustIndex(Info, E, Index, *this);
1600 clearIsNullPointer();
1601 }
1602 void adjustOffset(CharUnits N) {
1603 Offset += N;
1604 if (N.getQuantity())
1605 clearIsNullPointer();
1606 }
1607 };
1608
1609 struct MemberPtr {
1610 MemberPtr() {}
1611 explicit MemberPtr(const ValueDecl *Decl)
1612 : DeclAndIsDerivedMember(Decl, false) {}
1613
1614 /// The member or (direct or indirect) field referred to by this member
1615 /// pointer, or 0 if this is a null member pointer.
1616 const ValueDecl *getDecl() const {
1617 return DeclAndIsDerivedMember.getPointer();
1618 }
1619 /// Is this actually a member of some type derived from the relevant class?
1620 bool isDerivedMember() const {
1621 return DeclAndIsDerivedMember.getInt();
1622 }
1623 /// Get the class which the declaration actually lives in.
1624 const CXXRecordDecl *getContainingRecord() const {
1625 return cast<CXXRecordDecl>(
1626 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1627 }
1628
1629 void moveInto(APValue &V) const {
1630 V = APValue(getDecl(), isDerivedMember(), Path);
1631 }
1632 void setFrom(const APValue &V) {
1633 assert(V.isMemberPointer());
1634 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1635 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1636 Path.clear();
1637 llvm::append_range(Path, V.getMemberPointerPath());
1638 }
1639
1640 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1641 /// whether the member is a member of some class derived from the class type
1642 /// of the member pointer.
1643 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1644 /// Path - The path of base/derived classes from the member declaration's
1645 /// class (exclusive) to the class type of the member pointer (inclusive).
1646 SmallVector<const CXXRecordDecl*, 4> Path;
1647
1648 /// Perform a cast towards the class of the Decl (either up or down the
1649 /// hierarchy).
1650 bool castBack(const CXXRecordDecl *Class) {
1651 assert(!Path.empty());
1652 const CXXRecordDecl *Expected;
1653 if (Path.size() >= 2)
1654 Expected = Path[Path.size() - 2];
1655 else
1656 Expected = getContainingRecord();
1657 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1658 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1659 // if B does not contain the original member and is not a base or
1660 // derived class of the class containing the original member, the result
1661 // of the cast is undefined.
1662 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1663 // (D::*). We consider that to be a language defect.
1664 return false;
1665 }
1666 Path.pop_back();
1667 return true;
1668 }
1669 /// Perform a base-to-derived member pointer cast.
1670 bool castToDerived(const CXXRecordDecl *Derived) {
1671 if (!getDecl())
1672 return true;
1673 if (!isDerivedMember()) {
1674 Path.push_back(Derived);
1675 return true;
1676 }
1677 if (!castBack(Derived))
1678 return false;
1679 if (Path.empty())
1680 DeclAndIsDerivedMember.setInt(false);
1681 return true;
1682 }
1683 /// Perform a derived-to-base member pointer cast.
1684 bool castToBase(const CXXRecordDecl *Base) {
1685 if (!getDecl())
1686 return true;
1687 if (Path.empty())
1688 DeclAndIsDerivedMember.setInt(true);
1689 if (isDerivedMember()) {
1690 Path.push_back(Base);
1691 return true;
1692 }
1693 return castBack(Base);
1694 }
1695 };
1696
1697 /// Compare two member pointers, which are assumed to be of the same type.
1698 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1699 if (!LHS.getDecl() || !RHS.getDecl())
1700 return !LHS.getDecl() && !RHS.getDecl();
1701 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1702 return false;
1703 return LHS.Path == RHS.Path;
1704 }
1705}
1706
1707void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1708 const LValue &LV) {
1709 if (Invalid || !N)
1710 return;
1711 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1712 if (isMostDerivedAnUnsizedArray()) {
1713 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1714 // Can't verify -- trust that the user is doing the right thing (or if
1715 // not, trust that the caller will catch the bad behavior).
1716 // FIXME: Should we reject if this overflows, at least?
1717 Entries.back() =
1718 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1719 return;
1720 }
1721
1722 // [expr.add]p4: For the purposes of these operators, a pointer to a
1723 // nonarray object behaves the same as a pointer to the first element of
1724 // an array of length one with the type of the object as its element type.
1725 bool IsArray =
1726 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1727 uint64_t ArrayIndex =
1728 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1729 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1730
1731 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1732 if (!Info.checkingPotentialConstantExpression() ||
1733 !LV.AllowConstexprUnknown) {
1734 // Calculate the actual index in a wide enough type, so we can include
1735 // it in the note.
1736 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1737 (llvm::APInt &)N += ArrayIndex;
1738 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1739 diagnosePointerArithmetic(Info, E, N);
1740 }
1741 setInvalid();
1742 return;
1743 }
1744
1745 ArrayIndex += TruncatedN;
1746 assert(ArrayIndex <= ArraySize &&
1747 "bounds check succeeded for out-of-bounds index");
1748
1749 if (IsArray)
1750 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1751 else
1752 IsOnePastTheEnd = (ArrayIndex != 0);
1753}
1754
1755static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1756static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1757 const LValue &This, const Expr *E,
1758 bool AllowNonLiteralTypes = false);
1759static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1760 bool InvalidBaseOK = false);
1761static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1762 bool InvalidBaseOK = false);
1763static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1764 EvalInfo &Info);
1765static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1766static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1767static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1768 EvalInfo &Info);
1769static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1770static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1771static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info);
1772static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1773 EvalInfo &Info);
1774static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1775static std::optional<uint64_t>
1776EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
1777 std::string *StringResult = nullptr);
1778
1779/// Evaluate an integer or fixed point expression into an APResult.
1780static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1781 EvalInfo &Info);
1782
1783/// Evaluate only a fixed point expression into an APResult.
1784static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1785 EvalInfo &Info);
1786
1787//===----------------------------------------------------------------------===//
1788// Misc utilities
1789//===----------------------------------------------------------------------===//
1790
1791/// Negate an APSInt in place, converting it to a signed form if necessary, and
1792/// preserving its value (by extending by up to one bit as needed).
1793static void negateAsSigned(APSInt &Int) {
1794 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1795 Int = Int.extend(Int.getBitWidth() + 1);
1796 Int.setIsSigned(true);
1797 }
1798 Int = -Int;
1799}
1800
1801template<typename KeyT>
1802APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1803 ScopeKind Scope, LValue &LV) {
1804 unsigned Version = getTempVersion();
1805 APValue::LValueBase Base(Key, Index, Version);
1806 LV.set(Base);
1807 return createLocal(Base, Key, T, Scope);
1808}
1809
1810/// Allocate storage for a parameter of a function call made in this frame.
1811APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1812 LValue &LV) {
1813 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1814 APValue::LValueBase Base(PVD, Index, Args.Version);
1815 LV.set(Base);
1816 // We always destroy parameters at the end of the call, even if we'd allow
1817 // them to live to the end of the full-expression at runtime, in order to
1818 // give portable results and match other compilers.
1819 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1820}
1821
1822APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1823 QualType T, ScopeKind Scope) {
1824 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1825 unsigned Version = Base.getVersion();
1826 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1827 assert(Result.isAbsent() && "local created multiple times");
1828
1829 // If we're creating a local immediately in the operand of a speculative
1830 // evaluation, don't register a cleanup to be run outside the speculative
1831 // evaluation context, since we won't actually be able to initialize this
1832 // object.
1833 if (Index <= Info.SpeculativeEvaluationDepth) {
1834 if (T.isDestructedType())
1835 Info.noteSideEffect();
1836 } else {
1837 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1838 }
1839 return Result;
1840}
1841
1842APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1843 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1844 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1845 return nullptr;
1846 }
1847
1848 DynamicAllocLValue DA(NumHeapAllocs++);
1850 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1851 std::forward_as_tuple(DA), std::tuple<>());
1852 assert(Result.second && "reused a heap alloc index?");
1853 Result.first->second.AllocExpr = E;
1854 return &Result.first->second.Value;
1855}
1856
1857/// Produce a string describing the given constexpr call.
1858void CallStackFrame::describe(raw_ostream &Out) const {
1859 bool IsMemberCall = false;
1860 bool ExplicitInstanceParam = false;
1861 clang::PrintingPolicy PrintingPolicy = Info.Ctx.getPrintingPolicy();
1862 PrintingPolicy.SuppressLambdaBody = true;
1863
1864 if (const auto *MD = dyn_cast<CXXMethodDecl>(Callee)) {
1865 IsMemberCall = !isa<CXXConstructorDecl>(MD) && !MD->isStatic();
1866 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
1867 }
1868
1869 if (!IsMemberCall)
1870 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1871 /*Qualified=*/false);
1872
1873 if (This && IsMemberCall) {
1874 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1875 const Expr *Object = MCE->getImplicitObjectArgument();
1876 Object->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1877 /*Indentation=*/0);
1878 if (Object->getType()->isPointerType())
1879 Out << "->";
1880 else
1881 Out << ".";
1882 } else if (const auto *OCE =
1883 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1884 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1885 /*Indentation=*/0);
1886 Out << ".";
1887 } else {
1888 APValue Val;
1889 This->moveInto(Val);
1890 Val.printPretty(
1891 Out, Info.Ctx,
1892 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1893 Out << ".";
1894 }
1895 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1896 /*Qualified=*/false);
1897 }
1898
1899 Out << '(';
1900
1901 llvm::ListSeparator Comma;
1902 for (const ParmVarDecl *Param :
1903 Callee->parameters().slice(ExplicitInstanceParam)) {
1904 Out << Comma;
1905 const APValue *V = Info.getParamSlot(Arguments, Param);
1906 if (V)
1907 V->printPretty(Out, Info.Ctx, Param->getType());
1908 else
1909 Out << "<...>";
1910 }
1911
1912 Out << ')';
1913}
1914
1915/// Evaluate an expression to see if it had side-effects, and discard its
1916/// result.
1917/// \return \c true if the caller should keep evaluating.
1918static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1919 assert(!E->isValueDependent());
1920 APValue Scratch;
1921 if (!Evaluate(Scratch, Info, E))
1922 // We don't need the value, but we might have skipped a side effect here.
1923 return Info.noteSideEffect();
1924 return true;
1925}
1926
1927/// Should this call expression be treated as forming an opaque constant?
1928static bool IsOpaqueConstantCall(const CallExpr *E) {
1929 unsigned Builtin = E->getBuiltinCallee();
1930 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1931 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1932 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
1933 Builtin == Builtin::BI__builtin_function_start);
1934}
1935
1936static bool IsOpaqueConstantCall(const LValue &LVal) {
1937 const auto *BaseExpr =
1938 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
1939 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
1940}
1941
1943 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1944 // constant expression of pointer type that evaluates to...
1945
1946 // ... a null pointer value, or a prvalue core constant expression of type
1947 // std::nullptr_t.
1948 if (!B)
1949 return true;
1950
1951 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1952 // ... the address of an object with static storage duration,
1953 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1954 return VD->hasGlobalStorage();
1956 return true;
1957 // ... the address of a function,
1958 // ... the address of a GUID [MS extension],
1959 // ... the address of an unnamed global constant
1961 }
1962
1963 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1964 return true;
1965
1966 const Expr *E = B.get<const Expr*>();
1967 switch (E->getStmtClass()) {
1968 default:
1969 return false;
1970 case Expr::CompoundLiteralExprClass: {
1972 return CLE->isFileScope() && CLE->isLValue();
1973 }
1974 case Expr::MaterializeTemporaryExprClass:
1975 // A materialized temporary might have been lifetime-extended to static
1976 // storage duration.
1977 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1978 // A string literal has static storage duration.
1979 case Expr::StringLiteralClass:
1980 case Expr::PredefinedExprClass:
1981 case Expr::ObjCStringLiteralClass:
1982 case Expr::ObjCEncodeExprClass:
1983 return true;
1984 case Expr::ObjCBoxedExprClass:
1985 case Expr::ObjCArrayLiteralClass:
1986 case Expr::ObjCDictionaryLiteralClass:
1987 return cast<ObjCObjectLiteral>(E)->isExpressibleAsConstantInitializer();
1988 case Expr::CallExprClass:
1990 // For GCC compatibility, &&label has static storage duration.
1991 case Expr::AddrLabelExprClass:
1992 return true;
1993 // A Block literal expression may be used as the initialization value for
1994 // Block variables at global or local static scope.
1995 case Expr::BlockExprClass:
1996 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1997 // The APValue generated from a __builtin_source_location will be emitted as a
1998 // literal.
1999 case Expr::SourceLocExprClass:
2000 return true;
2001 case Expr::ImplicitValueInitExprClass:
2002 // FIXME:
2003 // We can never form an lvalue with an implicit value initialization as its
2004 // base through expression evaluation, so these only appear in one case: the
2005 // implicit variable declaration we invent when checking whether a constexpr
2006 // constructor can produce a constant expression. We must assume that such
2007 // an expression might be a global lvalue.
2008 return true;
2009 }
2010}
2011
2012static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2013 return LVal.Base.dyn_cast<const ValueDecl*>();
2014}
2015
2016// Information about an LValueBase that is some kind of string.
2019 StringRef Bytes;
2021};
2022
2023// Gets the lvalue base of LVal as a string.
2024static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2025 LValueBaseString &AsString) {
2026 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2027 if (!BaseExpr)
2028 return false;
2029
2030 // For ObjCEncodeExpr, we need to compute and store the string.
2031 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2032 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2033 AsString.ObjCEncodeStorage);
2034 AsString.Bytes = AsString.ObjCEncodeStorage;
2035 AsString.CharWidth = 1;
2036 return true;
2037 }
2038
2039 // Otherwise, we have a StringLiteral.
2040 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2041 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2042 Lit = PE->getFunctionName();
2043
2044 if (!Lit)
2045 return false;
2046
2047 AsString.Bytes = Lit->getBytes();
2048 AsString.CharWidth = Lit->getCharByteWidth();
2049 return true;
2050}
2051
2052// Determine whether two string literals potentially overlap. This will be the
2053// case if they agree on the values of all the bytes on the overlapping region
2054// between them.
2055//
2056// The overlapping region is the portion of the two string literals that must
2057// overlap in memory if the pointers actually point to the same address at
2058// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2059// the overlapping region is "cdef\0", which in this case does agree, so the
2060// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2061// "bazbar" + 3, the overlapping region contains all of both strings, so they
2062// are not potentially overlapping, even though they agree from the given
2063// addresses onwards.
2064//
2065// See open core issue CWG2765 which is discussing the desired rule here.
2066static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2067 const LValue &LHS,
2068 const LValue &RHS) {
2069 LValueBaseString LHSString, RHSString;
2070 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2071 !GetLValueBaseAsString(Info, RHS, RHSString))
2072 return false;
2073
2074 // This is the byte offset to the location of the first character of LHS
2075 // within RHS. We don't need to look at the characters of one string that
2076 // would appear before the start of the other string if they were merged.
2077 CharUnits Offset = RHS.Offset - LHS.Offset;
2078 if (Offset.isNegative()) {
2079 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2080 return false;
2081 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2082 } else {
2083 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2084 return false;
2085 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2086 }
2087
2088 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2089 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2090 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2091 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2092
2093 // The null terminator isn't included in the string data, so check for it
2094 // manually. If the longer string doesn't have a null terminator where the
2095 // shorter string ends, they aren't potentially overlapping.
2096 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2097 if (Shorter.size() + NullByte >= Longer.size())
2098 break;
2099 if (Longer[Shorter.size() + NullByte])
2100 return false;
2101 }
2102
2103 // Otherwise, they're potentially overlapping if and only if the overlapping
2104 // region is the same.
2105 return Shorter == Longer.take_front(Shorter.size());
2106}
2107
2108static bool IsWeakLValue(const LValue &Value) {
2110 return Decl && Decl->isWeak();
2111}
2112
2113static bool isZeroSized(const LValue &Value) {
2115 if (isa_and_nonnull<VarDecl>(Decl)) {
2116 QualType Ty = Decl->getType();
2117 if (Ty->isArrayType())
2118 return Ty->isIncompleteType() ||
2119 Decl->getASTContext().getTypeSize(Ty) == 0;
2120 }
2121 return false;
2122}
2123
2124static bool HasSameBase(const LValue &A, const LValue &B) {
2125 if (!A.getLValueBase())
2126 return !B.getLValueBase();
2127 if (!B.getLValueBase())
2128 return false;
2129
2130 if (A.getLValueBase().getOpaqueValue() !=
2131 B.getLValueBase().getOpaqueValue())
2132 return false;
2133
2134 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2135 A.getLValueVersion() == B.getLValueVersion();
2136}
2137
2138static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2139 assert(Base && "no location for a null lvalue");
2140 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2141
2142 // For a parameter, find the corresponding call stack frame (if it still
2143 // exists), and point at the parameter of the function definition we actually
2144 // invoked.
2145 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2146 unsigned Idx = PVD->getFunctionScopeIndex();
2147 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2148 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2149 F->Arguments.Version == Base.getVersion() && F->Callee &&
2150 Idx < F->Callee->getNumParams()) {
2151 VD = F->Callee->getParamDecl(Idx);
2152 break;
2153 }
2154 }
2155 }
2156
2157 if (VD)
2158 Info.Note(VD->getLocation(), diag::note_declared_at);
2159 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2160 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2161 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2162 // FIXME: Produce a note for dangling pointers too.
2163 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2164 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2165 diag::note_constexpr_dynamic_alloc_here);
2166 }
2167
2168 // We have no information to show for a typeid(T) object.
2169}
2170
2175
2176/// Materialized temporaries that we've already checked to determine if they're
2177/// initializsed by a constant expression.
2180
2182 EvalInfo &Info, SourceLocation DiagLoc,
2183 QualType Type, const APValue &Value,
2184 ConstantExprKind Kind,
2185 const FieldDecl *SubobjectDecl,
2186 CheckedTemporaries &CheckedTemps);
2187
2188/// Check that this reference or pointer core constant expression is a valid
2189/// value for an address or reference constant expression. Return true if we
2190/// can fold this expression, whether or not it's a constant expression.
2191static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2192 QualType Type, const LValue &LVal,
2193 ConstantExprKind Kind,
2194 CheckedTemporaries &CheckedTemps) {
2195 bool IsReferenceType = Type->isReferenceType();
2196
2197 APValue::LValueBase Base = LVal.getLValueBase();
2198 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2199
2200 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2201 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2202
2203 // Additional restrictions apply in a template argument. We only enforce the
2204 // C++20 restrictions here; additional syntactic and semantic restrictions
2205 // are applied elsewhere.
2206 if (isTemplateArgument(Kind)) {
2207 int InvalidBaseKind = -1;
2208 StringRef Ident;
2209 if (Base.is<TypeInfoLValue>())
2210 InvalidBaseKind = 0;
2211 else if (isa_and_nonnull<StringLiteral>(BaseE))
2212 InvalidBaseKind = 1;
2213 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2214 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2215 InvalidBaseKind = 2;
2216 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2217 InvalidBaseKind = 3;
2218 Ident = PE->getIdentKindName();
2219 }
2220
2221 if (InvalidBaseKind != -1) {
2222 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2223 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2224 << Ident;
2225 return false;
2226 }
2227 }
2228
2229 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2230 FD && FD->isImmediateFunction()) {
2231 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2232 << !Type->isAnyPointerType();
2233 Info.Note(FD->getLocation(), diag::note_declared_at);
2234 return false;
2235 }
2236
2237 // Check that the object is a global. Note that the fake 'this' object we
2238 // manufacture when checking potential constant expressions is conservatively
2239 // assumed to be global here.
2240 if (!IsGlobalLValue(Base)) {
2241 if (Info.getLangOpts().CPlusPlus11) {
2242 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2243 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2244 << BaseVD;
2245 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2246 if (VarD && VarD->isConstexpr()) {
2247 // Non-static local constexpr variables have unintuitive semantics:
2248 // constexpr int a = 1;
2249 // constexpr const int *p = &a;
2250 // ... is invalid because the address of 'a' is not constant. Suggest
2251 // adding a 'static' in this case.
2252 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2253 << VarD
2254 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2255 } else {
2256 NoteLValueLocation(Info, Base);
2257 }
2258 } else {
2259 Info.FFDiag(Loc);
2260 }
2261 // Don't allow references to temporaries to escape.
2262 return false;
2263 }
2264 assert((Info.checkingPotentialConstantExpression() ||
2265 LVal.getLValueCallIndex() == 0) &&
2266 "have call index for global lvalue");
2267
2268 if (LVal.allowConstexprUnknown()) {
2269 if (BaseVD) {
2270 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2271 NoteLValueLocation(Info, Base);
2272 } else {
2273 Info.FFDiag(Loc);
2274 }
2275 return false;
2276 }
2277
2278 if (Base.is<DynamicAllocLValue>()) {
2279 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2280 << IsReferenceType << !Designator.Entries.empty();
2281 NoteLValueLocation(Info, Base);
2282 return false;
2283 }
2284
2285 if (BaseVD) {
2286 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2287 // Check if this is a thread-local variable.
2288 if (Var->getTLSKind())
2289 // FIXME: Diagnostic!
2290 return false;
2291
2292 // A dllimport variable never acts like a constant, unless we're
2293 // evaluating a value for use only in name mangling, and unless it's a
2294 // static local. For the latter case, we'd still need to evaluate the
2295 // constant expression in case we're inside a (inlined) function.
2296 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>() &&
2297 !Var->isStaticLocal())
2298 return false;
2299
2300 // In CUDA/HIP device compilation, only device side variables have
2301 // constant addresses.
2302 if (Info.getLangOpts().CUDA && Info.getLangOpts().CUDAIsDevice &&
2303 Info.Ctx.CUDAConstantEvalCtx.NoWrongSidedVars) {
2304 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2305 !Var->hasAttr<CUDAConstantAttr>() &&
2306 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2307 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2308 Var->hasAttr<HIPManagedAttr>())
2309 return false;
2310 }
2311 }
2312 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2313 // __declspec(dllimport) must be handled very carefully:
2314 // We must never initialize an expression with the thunk in C++.
2315 // Doing otherwise would allow the same id-expression to yield
2316 // different addresses for the same function in different translation
2317 // units. However, this means that we must dynamically initialize the
2318 // expression with the contents of the import address table at runtime.
2319 //
2320 // The C language has no notion of ODR; furthermore, it has no notion of
2321 // dynamic initialization. This means that we are permitted to
2322 // perform initialization with the address of the thunk.
2323 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2324 FD->hasAttr<DLLImportAttr>())
2325 // FIXME: Diagnostic!
2326 return false;
2327 }
2328 } else if (const auto *MTE =
2329 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2330 if (CheckedTemps.insert(MTE).second) {
2331 QualType TempType = getType(Base);
2332 if (TempType.isDestructedType()) {
2333 Info.FFDiag(MTE->getExprLoc(),
2334 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2335 << TempType;
2336 return false;
2337 }
2338
2339 APValue *V = MTE->getOrCreateValue(false);
2340 assert(V && "evasluation result refers to uninitialised temporary");
2342 Info, MTE->getExprLoc(), TempType, *V, Kind,
2343 /*SubobjectDecl=*/nullptr, CheckedTemps))
2344 return false;
2345 }
2346 }
2347
2348 // Allow address constant expressions to be past-the-end pointers. This is
2349 // an extension: the standard requires them to point to an object.
2350 if (!IsReferenceType)
2351 return true;
2352
2353 // A reference constant expression must refer to an object.
2354 if (!Base) {
2355 // FIXME: diagnostic
2356 Info.CCEDiag(Loc);
2357 return true;
2358 }
2359
2360 // Does this refer one past the end of some object?
2361 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2362 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2363 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2364 NoteLValueLocation(Info, Base);
2365 }
2366
2367 return true;
2368}
2369
2370/// Member pointers are constant expressions unless they point to a
2371/// non-virtual dllimport member function.
2372static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2373 SourceLocation Loc,
2374 QualType Type,
2375 const APValue &Value,
2376 ConstantExprKind Kind) {
2377 const ValueDecl *Member = Value.getMemberPointerDecl();
2378 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2379 if (!FD)
2380 return true;
2381 if (FD->isImmediateFunction()) {
2382 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2383 Info.Note(FD->getLocation(), diag::note_declared_at);
2384 return false;
2385 }
2386 return isForManglingOnly(Kind) || FD->isVirtual() ||
2387 !FD->hasAttr<DLLImportAttr>();
2388}
2389
2390/// Check that this core constant expression is of literal type, and if not,
2391/// produce an appropriate diagnostic.
2392static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2393 const LValue *This = nullptr) {
2394 // The restriction to literal types does not exist in C++23 anymore.
2395 if (Info.getLangOpts().CPlusPlus23)
2396 return true;
2397
2398 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2399 return true;
2400
2401 // C++1y: A constant initializer for an object o [...] may also invoke
2402 // constexpr constructors for o and its subobjects even if those objects
2403 // are of non-literal class types.
2404 //
2405 // C++11 missed this detail for aggregates, so classes like this:
2406 // struct foo_t { union { int i; volatile int j; } u; };
2407 // are not (obviously) initializable like so:
2408 // __attribute__((__require_constant_initialization__))
2409 // static const foo_t x = {{0}};
2410 // because "i" is a subobject with non-literal initialization (due to the
2411 // volatile member of the union). See:
2412 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2413 // Therefore, we use the C++1y behavior.
2414 if (This && Info.EvaluatingDecl == This->getLValueBase())
2415 return true;
2416
2417 // Prvalue constant expressions must be of literal types.
2418 if (Info.getLangOpts().CPlusPlus11)
2419 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2420 << E->getType();
2421 else
2422 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2423 return false;
2424}
2425
2427 EvalInfo &Info, SourceLocation DiagLoc,
2428 QualType Type, const APValue &Value,
2429 ConstantExprKind Kind,
2430 const FieldDecl *SubobjectDecl,
2431 CheckedTemporaries &CheckedTemps) {
2432 if (!Value.hasValue()) {
2433 if (SubobjectDecl) {
2434 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2435 << /*(name)*/ 1 << SubobjectDecl;
2436 Info.Note(SubobjectDecl->getLocation(),
2437 diag::note_constexpr_subobject_declared_here);
2438 } else {
2439 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2440 << /*of type*/ 0 << Type;
2441 }
2442 return false;
2443 }
2444
2445 // We allow _Atomic(T) to be initialized from anything that T can be
2446 // initialized from.
2447 if (const AtomicType *AT = Type->getAs<AtomicType>())
2448 Type = AT->getValueType();
2449
2450 // Core issue 1454: For a literal constant expression of array or class type,
2451 // each subobject of its value shall have been initialized by a constant
2452 // expression.
2453 if (Value.isArray()) {
2455 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2456 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2457 Value.getArrayInitializedElt(I), Kind,
2458 SubobjectDecl, CheckedTemps))
2459 return false;
2460 }
2461 if (!Value.hasArrayFiller())
2462 return true;
2463 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2464 Value.getArrayFiller(), Kind, SubobjectDecl,
2465 CheckedTemps);
2466 }
2467 if (Value.isUnion() && Value.getUnionField()) {
2468 return CheckEvaluationResult(
2469 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2470 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2471 }
2472 if (Value.isStruct()) {
2473 auto *RD = Type->castAsRecordDecl();
2474 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2475 unsigned BaseIndex = 0;
2476 for (const CXXBaseSpecifier &BS : CD->bases()) {
2477 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2478 if (!BaseValue.hasValue()) {
2479 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2480 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2481 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2482 return false;
2483 }
2484 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2485 Kind, /*SubobjectDecl=*/nullptr,
2486 CheckedTemps))
2487 return false;
2488 ++BaseIndex;
2489 }
2490 }
2491 for (const auto *I : RD->fields()) {
2492 if (I->isUnnamedBitField())
2493 continue;
2494
2495 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2496 Value.getStructField(I->getFieldIndex()), Kind,
2497 I, CheckedTemps))
2498 return false;
2499 }
2500 }
2501
2502 if (Value.isLValue() &&
2504 LValue LVal;
2505 LVal.setFrom(Info.Ctx, Value);
2506 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2507 CheckedTemps);
2508 }
2509
2510 if (Value.isMemberPointer() &&
2512 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2513
2514 // Everything else is fine.
2515 return true;
2516}
2517
2518/// Check that this core constant expression value is a valid value for a
2519/// constant expression. If not, report an appropriate diagnostic. Does not
2520/// check that the expression is of literal type.
2521static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2522 QualType Type, const APValue &Value,
2523 ConstantExprKind Kind) {
2524 // Nothing to check for a constant expression of type 'cv void'.
2525 if (Type->isVoidType())
2526 return true;
2527
2528 CheckedTemporaries CheckedTemps;
2530 Info, DiagLoc, Type, Value, Kind,
2531 /*SubobjectDecl=*/nullptr, CheckedTemps);
2532}
2533
2534/// Check that this evaluated value is fully-initialized and can be loaded by
2535/// an lvalue-to-rvalue conversion.
2536static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2537 QualType Type, const APValue &Value) {
2538 CheckedTemporaries CheckedTemps;
2539 return CheckEvaluationResult(
2541 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2542}
2543
2544/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2545/// "the allocated storage is deallocated within the evaluation".
2546static bool CheckMemoryLeaks(EvalInfo &Info) {
2547 if (!Info.HeapAllocs.empty()) {
2548 // We can still fold to a constant despite a compile-time memory leak,
2549 // so long as the heap allocation isn't referenced in the result (we check
2550 // that in CheckConstantExpression).
2551 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2552 diag::note_constexpr_memory_leak)
2553 << unsigned(Info.HeapAllocs.size() - 1);
2554 }
2555 return true;
2556}
2557
2558static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2559 // A null base expression indicates a null pointer. These are always
2560 // evaluatable, and they are false unless the offset is zero.
2561 if (!Value.getLValueBase()) {
2562 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2563 Result = !Value.getLValueOffset().isZero();
2564 return true;
2565 }
2566
2567 // We have a non-null base. These are generally known to be true, but if it's
2568 // a weak declaration it can be null at runtime.
2569 Result = true;
2570 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2571 return !Decl || !Decl->isWeak();
2572}
2573
2574static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2575 // TODO: This function should produce notes if it fails.
2576 switch (Val.getKind()) {
2577 case APValue::None:
2579 return false;
2580 case APValue::Int:
2581 Result = Val.getInt().getBoolValue();
2582 return true;
2584 Result = Val.getFixedPoint().getBoolValue();
2585 return true;
2586 case APValue::Float:
2587 Result = !Val.getFloat().isZero();
2588 return true;
2590 Result = Val.getComplexIntReal().getBoolValue() ||
2591 Val.getComplexIntImag().getBoolValue();
2592 return true;
2594 Result = !Val.getComplexFloatReal().isZero() ||
2595 !Val.getComplexFloatImag().isZero();
2596 return true;
2597 case APValue::LValue:
2598 return EvalPointerValueAsBool(Val, Result);
2600 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2601 return false;
2602 }
2604 return true;
2605 case APValue::Vector:
2606 case APValue::Matrix:
2607 case APValue::Array:
2608 case APValue::Struct:
2609 case APValue::Union:
2611 return false;
2612 }
2613
2614 llvm_unreachable("unknown APValue kind");
2615}
2616
2617static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2618 EvalInfo &Info) {
2619 assert(!E->isValueDependent());
2620 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2621 APValue Val;
2622 if (!Evaluate(Val, Info, E))
2623 return false;
2624 return HandleConversionToBool(Val, Result);
2625}
2626
2627template<typename T>
2628static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2629 const T &SrcValue, QualType DestType) {
2630 Info.CCEDiag(E, diag::note_constexpr_overflow) << SrcValue << DestType;
2631 if (const auto *OBT = DestType->getAs<OverflowBehaviorType>();
2632 OBT && OBT->isTrapKind()) {
2633 return false;
2634 }
2635 return Info.noteUndefinedBehavior();
2636}
2637
2638static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2639 QualType SrcType, const APFloat &Value,
2640 QualType DestType, APSInt &Result) {
2641 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2642 // Determine whether we are converting to unsigned or signed.
2643 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2644
2645 Result = APSInt(DestWidth, !DestSigned);
2646 bool ignored;
2647 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2648 & APFloat::opInvalidOp)
2649 return HandleOverflow(Info, E, Value, DestType);
2650 return true;
2651}
2652
2653/// Get rounding mode to use in evaluation of the specified expression.
2654///
2655/// If rounding mode is unknown at compile time, still try to evaluate the
2656/// expression. If the result is exact, it does not depend on rounding mode.
2657/// So return "tonearest" mode instead of "dynamic".
2658static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2659 llvm::RoundingMode RM =
2660 E->getFPFeaturesInEffect(Info.getLangOpts()).getRoundingMode();
2661 if (RM == llvm::RoundingMode::Dynamic)
2662 RM = llvm::RoundingMode::NearestTiesToEven;
2663 return RM;
2664}
2665
2666/// Check if the given evaluation result is allowed for constant evaluation.
2667static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2668 APFloat::opStatus St) {
2669 // In a constant context, assume that any dynamic rounding mode or FP
2670 // exception state matches the default floating-point environment.
2671 if (Info.InConstantContext)
2672 return true;
2673
2674 FPOptions FPO = E->getFPFeaturesInEffect(Info.getLangOpts());
2675 if ((St & APFloat::opInexact) &&
2676 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2677 // Inexact result means that it depends on rounding mode. If the requested
2678 // mode is dynamic, the evaluation cannot be made in compile time.
2679 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2680 return false;
2681 }
2682
2683 if ((St != APFloat::opOK) &&
2684 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2686 FPO.getAllowFEnvAccess())) {
2687 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2688 return false;
2689 }
2690
2691 if ((St & APFloat::opStatus::opInvalidOp) &&
2693 // There is no usefully definable result.
2694 Info.FFDiag(E);
2695 return false;
2696 }
2697
2698 // FIXME: if:
2699 // - evaluation triggered other FP exception, and
2700 // - exception mode is not "ignore", and
2701 // - the expression being evaluated is not a part of global variable
2702 // initializer,
2703 // the evaluation probably need to be rejected.
2704 return true;
2705}
2706
2707static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2708 QualType SrcType, QualType DestType,
2709 APFloat &Result) {
2710 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2712 "HandleFloatToFloatCast has been checked with only CastExpr, "
2713 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2714 "the new expression or address the root cause of this usage.");
2715 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2716 APFloat::opStatus St;
2717 APFloat Value = Result;
2718 bool ignored;
2719 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2720 return checkFloatingPointResult(Info, E, St);
2721}
2722
2723static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2724 QualType DestType, QualType SrcType,
2725 const APSInt &Value) {
2726 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2727 // Figure out if this is a truncate, extend or noop cast.
2728 // If the input is signed, do a sign extend, noop, or truncate.
2729 APSInt Result = Value.extOrTrunc(DestWidth);
2730 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2731 if (DestType->isBooleanType())
2732 Result = Value.getBoolValue();
2733 return Result;
2734}
2735
2736static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2737 const FPOptions FPO,
2738 QualType SrcType, const APSInt &Value,
2739 QualType DestType, APFloat &Result) {
2740 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2741 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2742 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2743 return checkFloatingPointResult(Info, E, St);
2744}
2745
2746static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2747 APValue &Value, const FieldDecl *FD) {
2748 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2749
2750 if (!Value.isInt()) {
2751 // Trying to store a pointer-cast-to-integer into a bitfield.
2752 // FIXME: In this case, we should provide the diagnostic for casting
2753 // a pointer to an integer.
2754 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2755 Info.FFDiag(E);
2756 return false;
2757 }
2758
2759 APSInt &Int = Value.getInt();
2760 unsigned OldBitWidth = Int.getBitWidth();
2761 unsigned NewBitWidth = FD->getBitWidthValue();
2762 if (NewBitWidth < OldBitWidth)
2763 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2764 return true;
2765}
2766
2767/// Perform the given integer operation, which is known to need at most BitWidth
2768/// bits, and check for overflow in the original type (if that type was not an
2769/// unsigned type).
2770template<typename Operation>
2771static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2772 const APSInt &LHS, const APSInt &RHS,
2773 unsigned BitWidth, Operation Op,
2774 APSInt &Result) {
2775 if (LHS.isUnsigned()) {
2776 Result = Op(LHS, RHS);
2777 return true;
2778 }
2779
2780 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2781 Result = Value.trunc(LHS.getBitWidth());
2782 if (Result.extend(BitWidth) != Value && !E->getType().isWrapType()) {
2783 if (Info.checkingForUndefinedBehavior())
2784 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2785 diag::warn_integer_constant_overflow)
2786 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2787 /*UpperCase=*/true, /*InsertSeparators=*/true)
2788 << E->getType() << E->getSourceRange();
2789 return HandleOverflow(Info, E, Value, E->getType());
2790 }
2791 return true;
2792}
2793
2794/// Perform the given binary integer operation.
2795static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2796 const APSInt &LHS, BinaryOperatorKind Opcode,
2797 APSInt RHS, APSInt &Result) {
2798 bool HandleOverflowResult = true;
2799 switch (Opcode) {
2800 default:
2801 Info.FFDiag(E);
2802 return false;
2803 case BO_Mul:
2804 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2805 std::multiplies<APSInt>(), Result);
2806 case BO_Add:
2807 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2808 std::plus<APSInt>(), Result);
2809 case BO_Sub:
2810 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2811 std::minus<APSInt>(), Result);
2812 case BO_And: Result = LHS & RHS; return true;
2813 case BO_Xor: Result = LHS ^ RHS; return true;
2814 case BO_Or: Result = LHS | RHS; return true;
2815 case BO_Div:
2816 case BO_Rem:
2817 if (RHS == 0) {
2818 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2819 << E->getRHS()->getSourceRange();
2820 return false;
2821 }
2822 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2823 // this operation and gives the two's complement result.
2824 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2825 LHS.isMinSignedValue())
2826 HandleOverflowResult = HandleOverflow(
2827 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2828 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2829 return HandleOverflowResult;
2830 case BO_Shl: {
2831 if (Info.getLangOpts().OpenCL)
2832 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2833 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2834 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2835 RHS.isUnsigned());
2836 else if (RHS.isSigned() && RHS.isNegative()) {
2837 // During constant-folding, a negative shift is an opposite shift. Such
2838 // a shift is not a constant expression.
2839 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2840 if (!Info.noteUndefinedBehavior())
2841 return false;
2842 RHS = -RHS;
2843 goto shift_right;
2844 }
2845 shift_left:
2846 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2847 // the shifted type.
2848 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2849 if (SA != RHS) {
2850 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2851 << RHS << E->getType() << LHS.getBitWidth();
2852 if (!Info.noteUndefinedBehavior())
2853 return false;
2854 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2855 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2856 // operand, and must not overflow the corresponding unsigned type.
2857 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2858 // E1 x 2^E2 module 2^N.
2859 if (LHS.isNegative()) {
2860 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2861 if (!Info.noteUndefinedBehavior())
2862 return false;
2863 } else if (LHS.countl_zero() < SA) {
2864 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2865 if (!Info.noteUndefinedBehavior())
2866 return false;
2867 }
2868 }
2869 Result = LHS << SA;
2870 return true;
2871 }
2872 case BO_Shr: {
2873 if (Info.getLangOpts().OpenCL)
2874 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2875 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2876 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2877 RHS.isUnsigned());
2878 else if (RHS.isSigned() && RHS.isNegative()) {
2879 // During constant-folding, a negative shift is an opposite shift. Such a
2880 // shift is not a constant expression.
2881 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2882 if (!Info.noteUndefinedBehavior())
2883 return false;
2884 RHS = -RHS;
2885 goto shift_left;
2886 }
2887 shift_right:
2888 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2889 // shifted type.
2890 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2891 if (SA != RHS) {
2892 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2893 << RHS << E->getType() << LHS.getBitWidth();
2894 if (!Info.noteUndefinedBehavior())
2895 return false;
2896 }
2897
2898 Result = LHS >> SA;
2899 return true;
2900 }
2901
2902 case BO_LT: Result = LHS < RHS; return true;
2903 case BO_GT: Result = LHS > RHS; return true;
2904 case BO_LE: Result = LHS <= RHS; return true;
2905 case BO_GE: Result = LHS >= RHS; return true;
2906 case BO_EQ: Result = LHS == RHS; return true;
2907 case BO_NE: Result = LHS != RHS; return true;
2908 case BO_Cmp:
2909 llvm_unreachable("BO_Cmp should be handled elsewhere");
2910 }
2911}
2912
2913/// Perform the given binary floating-point operation, in-place, on LHS.
2914static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2915 APFloat &LHS, BinaryOperatorKind Opcode,
2916 const APFloat &RHS) {
2917 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2918 APFloat::opStatus St;
2919 switch (Opcode) {
2920 default:
2921 Info.FFDiag(E);
2922 return false;
2923 case BO_Mul:
2924 St = LHS.multiply(RHS, RM);
2925 break;
2926 case BO_Add:
2927 St = LHS.add(RHS, RM);
2928 break;
2929 case BO_Sub:
2930 St = LHS.subtract(RHS, RM);
2931 break;
2932 case BO_Div:
2933 // [expr.mul]p4:
2934 // If the second operand of / or % is zero the behavior is undefined.
2935 if (RHS.isZero())
2936 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2937 St = LHS.divide(RHS, RM);
2938 break;
2939 }
2940
2941 // [expr.pre]p4:
2942 // If during the evaluation of an expression, the result is not
2943 // mathematically defined [...], the behavior is undefined.
2944 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2945 if (LHS.isNaN()) {
2946 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2947 return Info.noteUndefinedBehavior();
2948 }
2949
2950 return checkFloatingPointResult(Info, E, St);
2951}
2952
2953static bool handleLogicalOpForVector(const APInt &LHSValue,
2954 BinaryOperatorKind Opcode,
2955 const APInt &RHSValue, APInt &Result) {
2956 bool LHS = (LHSValue != 0);
2957 bool RHS = (RHSValue != 0);
2958
2959 if (Opcode == BO_LAnd)
2960 Result = LHS && RHS;
2961 else
2962 Result = LHS || RHS;
2963 return true;
2964}
2965static bool handleLogicalOpForVector(const APFloat &LHSValue,
2966 BinaryOperatorKind Opcode,
2967 const APFloat &RHSValue, APInt &Result) {
2968 bool LHS = !LHSValue.isZero();
2969 bool RHS = !RHSValue.isZero();
2970
2971 if (Opcode == BO_LAnd)
2972 Result = LHS && RHS;
2973 else
2974 Result = LHS || RHS;
2975 return true;
2976}
2977
2978static bool handleLogicalOpForVector(const APValue &LHSValue,
2979 BinaryOperatorKind Opcode,
2980 const APValue &RHSValue, APInt &Result) {
2981 // The result is always an int type, however operands match the first.
2982 if (LHSValue.getKind() == APValue::Int)
2983 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2984 RHSValue.getInt(), Result);
2985 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2986 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2987 RHSValue.getFloat(), Result);
2988}
2989
2990template <typename APTy>
2991static bool
2993 const APTy &RHSValue, APInt &Result) {
2994 switch (Opcode) {
2995 default:
2996 llvm_unreachable("unsupported binary operator");
2997 case BO_EQ:
2998 Result = (LHSValue == RHSValue);
2999 break;
3000 case BO_NE:
3001 Result = (LHSValue != RHSValue);
3002 break;
3003 case BO_LT:
3004 Result = (LHSValue < RHSValue);
3005 break;
3006 case BO_GT:
3007 Result = (LHSValue > RHSValue);
3008 break;
3009 case BO_LE:
3010 Result = (LHSValue <= RHSValue);
3011 break;
3012 case BO_GE:
3013 Result = (LHSValue >= RHSValue);
3014 break;
3015 }
3016
3017 // The boolean operations on these vector types use an instruction that
3018 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3019 // to -1 to make sure that we produce the correct value.
3020 Result.negate();
3021
3022 return true;
3023}
3024
3025static bool handleCompareOpForVector(const APValue &LHSValue,
3026 BinaryOperatorKind Opcode,
3027 const APValue &RHSValue, APInt &Result) {
3028 // The result is always an int type, however operands match the first.
3029 if (LHSValue.getKind() == APValue::Int)
3030 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3031 RHSValue.getInt(), Result);
3032 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3033 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3034 RHSValue.getFloat(), Result);
3035}
3036
3037// Perform binary operations for vector types, in place on the LHS.
3038static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3039 BinaryOperatorKind Opcode,
3040 APValue &LHSValue,
3041 const APValue &RHSValue) {
3042 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3043 "Operation not supported on vector types");
3044
3045 const auto *VT = E->getType()->castAs<VectorType>();
3046 unsigned NumElements = VT->getNumElements();
3047 QualType EltTy = VT->getElementType();
3048
3049 // In the cases (typically C as I've observed) where we aren't evaluating
3050 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3051 // just give up.
3052 if (!LHSValue.isVector()) {
3053 assert(LHSValue.isLValue() &&
3054 "A vector result that isn't a vector OR uncalculated LValue");
3055 Info.FFDiag(E);
3056 return false;
3057 }
3058
3059 assert(LHSValue.getVectorLength() == NumElements &&
3060 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3061
3062 SmallVector<APValue, 4> ResultElements;
3063
3064 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3065 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3066 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3067
3068 if (EltTy->isIntegerType()) {
3069 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3070 EltTy->isUnsignedIntegerType()};
3071 bool Success = true;
3072
3073 if (BinaryOperator::isLogicalOp(Opcode))
3074 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3075 else if (BinaryOperator::isComparisonOp(Opcode))
3076 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3077 else
3078 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3079 RHSElt.getInt(), EltResult);
3080
3081 if (!Success) {
3082 Info.FFDiag(E);
3083 return false;
3084 }
3085 ResultElements.emplace_back(EltResult);
3086
3087 } else if (EltTy->isFloatingType()) {
3088 assert(LHSElt.getKind() == APValue::Float &&
3089 RHSElt.getKind() == APValue::Float &&
3090 "Mismatched LHS/RHS/Result Type");
3091 APFloat LHSFloat = LHSElt.getFloat();
3092
3093 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3094 RHSElt.getFloat())) {
3095 Info.FFDiag(E);
3096 return false;
3097 }
3098
3099 ResultElements.emplace_back(LHSFloat);
3100 }
3101 }
3102
3103 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3104 return true;
3105}
3106
3107/// Cast an lvalue referring to a base subobject to a derived class, by
3108/// truncating the lvalue's path to the given length.
3109static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3110 const RecordDecl *TruncatedType,
3111 unsigned TruncatedElements) {
3112 SubobjectDesignator &D = Result.Designator;
3113
3114 // Check we actually point to a derived class object.
3115 if (TruncatedElements == D.Entries.size())
3116 return true;
3117 assert(TruncatedElements >= D.MostDerivedPathLength &&
3118 "not casting to a derived class");
3119 if (!Result.checkSubobject(Info, E, CSK_Derived))
3120 return false;
3121
3122 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3123 const RecordDecl *RD = TruncatedType;
3124 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3125 if (RD->isInvalidDecl()) return false;
3126 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3127 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3128 if (isVirtualBaseClass(D.Entries[I]))
3129 Result.Offset -= Layout.getVBaseClassOffset(Base);
3130 else
3131 Result.Offset -= Layout.getBaseClassOffset(Base);
3132 RD = Base;
3133 }
3134 D.Entries.resize(TruncatedElements);
3135 return true;
3136}
3137
3138static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3139 const CXXRecordDecl *Derived,
3140 const CXXRecordDecl *Base,
3141 const ASTRecordLayout *RL = nullptr) {
3142 if (!RL) {
3143 if (Derived->isInvalidDecl()) return false;
3144 RL = &Info.Ctx.getASTRecordLayout(Derived);
3145 }
3146
3147 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3148 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3149 return true;
3150}
3151
3152static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3153 const CXXRecordDecl *DerivedDecl,
3154 const CXXBaseSpecifier *Base) {
3155 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3156
3157 if (!Base->isVirtual())
3158 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3159
3160 SubobjectDesignator &D = Obj.Designator;
3161 if (D.Invalid)
3162 return false;
3163
3164 // Extract most-derived object and corresponding type.
3165 // FIXME: After implementing P2280R4 it became possible to get references
3166 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3167 // locations and if we see crashes in those locations in the future
3168 // it may make more sense to move this fix into Lvalue::set.
3169 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3170 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3171 return false;
3172
3173 // Find the virtual base class.
3174 if (DerivedDecl->isInvalidDecl()) return false;
3175 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3176 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3177 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3178 return true;
3179}
3180
3181static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3182 QualType Type, LValue &Result) {
3183 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3184 PathE = E->path_end();
3185 PathI != PathE; ++PathI) {
3187 *PathI))
3188 return false;
3189 Type = (*PathI)->getType();
3190 }
3191 return true;
3192}
3193
3194/// Cast an lvalue referring to a derived class to a known base subobject.
3195static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3196 const CXXRecordDecl *DerivedRD,
3197 const CXXRecordDecl *BaseRD) {
3198 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3199 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3200 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3201 llvm_unreachable("Class must be derived from the passed in base class!");
3202
3203 for (CXXBasePathElement &Elem : Paths.front())
3204 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3205 return false;
3206 return true;
3207}
3208
3209/// Update LVal to refer to the given field, which must be a member of the type
3210/// currently described by LVal.
3211static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3212 const FieldDecl *FD,
3213 const ASTRecordLayout *RL = nullptr) {
3214 if (!RL) {
3215 if (FD->getParent()->isInvalidDecl()) return false;
3216 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3217 }
3218
3219 unsigned I = FD->getFieldIndex();
3220 LVal.addDecl(Info, E, FD);
3221 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3222 return true;
3223}
3224
3225/// Update LVal to refer to the given indirect field.
3226static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3227 LValue &LVal,
3228 const IndirectFieldDecl *IFD) {
3229 for (const auto *C : IFD->chain())
3230 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3231 return false;
3232 return true;
3233}
3234
3239
3240/// Get the size of the given type in char units.
3241static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3243 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3244 // extension.
3245 if (Type->isVoidType() || Type->isFunctionType()) {
3246 Size = CharUnits::One();
3247 return true;
3248 }
3249
3250 if (Type->isDependentType()) {
3251 Info.FFDiag(Loc);
3252 return false;
3253 }
3254
3255 if (!Type->isConstantSizeType()) {
3256 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3257 // FIXME: Better diagnostic.
3258 Info.FFDiag(Loc);
3259 return false;
3260 }
3261
3262 if (SOT == SizeOfType::SizeOf)
3263 Size = Info.Ctx.getTypeSizeInChars(Type);
3264 else
3265 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3266 return true;
3267}
3268
3269/// Update a pointer value to model pointer arithmetic.
3270/// \param Info - Information about the ongoing evaluation.
3271/// \param E - The expression being evaluated, for diagnostic purposes.
3272/// \param LVal - The pointer value to be updated.
3273/// \param EltTy - The pointee type represented by LVal.
3274/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3275static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3276 LValue &LVal, QualType EltTy,
3277 APSInt Adjustment) {
3278 CharUnits SizeOfPointee;
3279 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3280 return false;
3281
3282 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3283 return true;
3284}
3285
3286static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3287 LValue &LVal, QualType EltTy,
3288 int64_t Adjustment) {
3289 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3290 APSInt::get(Adjustment));
3291}
3292
3293/// Update an lvalue to refer to a component of a complex number.
3294/// \param Info - Information about the ongoing evaluation.
3295/// \param LVal - The lvalue to be updated.
3296/// \param EltTy - The complex number's component type.
3297/// \param Imag - False for the real component, true for the imaginary.
3298static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3299 LValue &LVal, QualType EltTy,
3300 bool Imag) {
3301 if (Imag) {
3302 CharUnits SizeOfComponent;
3303 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3304 return false;
3305 LVal.Offset += SizeOfComponent;
3306 }
3307 LVal.addComplex(Info, E, EltTy, Imag);
3308 return true;
3309}
3310
3311static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3312 LValue &LVal, QualType EltTy,
3313 uint64_t Size, uint64_t Idx) {
3314 if (Idx) {
3315 CharUnits SizeOfElement;
3316 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3317 return false;
3318 LVal.Offset += SizeOfElement * Idx;
3319 }
3320 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3321 return true;
3322}
3323
3324/// Try to evaluate the initializer for a variable declaration.
3325///
3326/// \param Info Information about the ongoing evaluation.
3327/// \param E An expression to be used when printing diagnostics.
3328/// \param VD The variable whose initializer should be obtained.
3329/// \param Version The version of the variable within the frame.
3330/// \param Frame The frame in which the variable was created. Must be null
3331/// if this variable is not local to the evaluation.
3332/// \param Result Filled in with a pointer to the value of the variable.
3333static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3334 const VarDecl *VD, CallStackFrame *Frame,
3335 unsigned Version, APValue *&Result) {
3336 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3337 // and pointers.
3338 bool AllowConstexprUnknown =
3339 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3340
3341 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3342
3343 auto CheckUninitReference = [&](bool IsLocalVariable) {
3344 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3345 // C++23 [expr.const]p8
3346 // ... For such an object that is not usable in constant expressions, the
3347 // dynamic type of the object is constexpr-unknown. For such a reference
3348 // that is not usable in constant expressions, the reference is treated
3349 // as binding to an unspecified object of the referenced type whose
3350 // lifetime and that of all subobjects includes the entire constant
3351 // evaluation and whose dynamic type is constexpr-unknown.
3352 //
3353 // Variables that are part of the current evaluation are not
3354 // constexpr-unknown.
3355 if (!AllowConstexprUnknown || IsLocalVariable) {
3356 if (!Info.checkingPotentialConstantExpression())
3357 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3358 return false;
3359 }
3360 Result = nullptr;
3361 }
3362 return true;
3363 };
3364
3365 // If this is a local variable, dig out its value.
3366 if (Frame) {
3367 Result = Frame->getTemporary(VD, Version);
3368 if (Result)
3369 return CheckUninitReference(/*IsLocalVariable=*/true);
3370
3371 if (!isa<ParmVarDecl>(VD)) {
3372 // Assume variables referenced within a lambda's call operator that were
3373 // not declared within the call operator are captures and during checking
3374 // of a potential constant expression, assume they are unknown constant
3375 // expressions.
3376 assert(isLambdaCallOperator(Frame->Callee) &&
3377 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3378 "missing value for local variable");
3379 if (Info.checkingPotentialConstantExpression())
3380 return false;
3381
3382 llvm_unreachable(
3383 "A variable in a frame should either be a local or a parameter");
3384 }
3385 }
3386
3387 // If we're currently evaluating the initializer of this declaration, use that
3388 // in-flight value.
3389 if (Info.EvaluatingDecl == Base) {
3390 Result = Info.EvaluatingDeclValue;
3391 return CheckUninitReference(/*IsLocalVariable=*/false);
3392 }
3393
3394 // P2280R4 struck the restriction that variable of reference type lifetime
3395 // should begin within the evaluation of E
3396 // Used to be C++20 [expr.const]p5.12.2:
3397 // ... its lifetime began within the evaluation of E;
3398 if (isa<ParmVarDecl>(VD)) {
3399 if (AllowConstexprUnknown) {
3400 Result = nullptr;
3401 return true;
3402 }
3403
3404 // Assume parameters of a potential constant expression are usable in
3405 // constant expressions.
3406 if (!Info.checkingPotentialConstantExpression() ||
3407 !Info.CurrentCall->Callee ||
3408 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3409 if (Info.getLangOpts().CPlusPlus11) {
3410 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3411 << VD;
3412 NoteLValueLocation(Info, Base);
3413 } else {
3414 Info.FFDiag(E);
3415 }
3416 }
3417 return false;
3418 }
3419
3420 if (E->isValueDependent())
3421 return false;
3422
3423 // Dig out the initializer, and use the declaration which it's attached to.
3424 // FIXME: We should eventually check whether the variable has a reachable
3425 // initializing declaration.
3426 const Expr *Init = VD->getAnyInitializer(VD);
3427 // P2280R4 struck the restriction that variable of reference type should have
3428 // a preceding initialization.
3429 // Used to be C++20 [expr.const]p5.12:
3430 // ... reference has a preceding initialization and either ...
3431 if (!Init && !AllowConstexprUnknown) {
3432 // Don't diagnose during potential constant expression checking; an
3433 // initializer might be added later.
3434 if (!Info.checkingPotentialConstantExpression()) {
3435 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3436 << VD;
3437 NoteLValueLocation(Info, Base);
3438 }
3439 return false;
3440 }
3441
3442 // P2280R4 struck the initialization requirement for variables of reference
3443 // type so we can no longer assume we have an Init.
3444 // Used to be C++20 [expr.const]p5.12:
3445 // ... reference has a preceding initialization and either ...
3446 if (Init && Init->isValueDependent()) {
3447 // The DeclRefExpr is not value-dependent, but the variable it refers to
3448 // has a value-dependent initializer. This should only happen in
3449 // constant-folding cases, where the variable is not actually of a suitable
3450 // type for use in a constant expression (otherwise the DeclRefExpr would
3451 // have been value-dependent too), so diagnose that.
3452 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3453 if (!Info.checkingPotentialConstantExpression()) {
3454 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3455 ? diag::note_constexpr_ltor_non_constexpr
3456 : diag::note_constexpr_ltor_non_integral, 1)
3457 << VD << VD->getType();
3458 NoteLValueLocation(Info, Base);
3459 }
3460 return false;
3461 }
3462
3463 // Check that we can fold the initializer. In C++, we will have already done
3464 // this in the cases where it matters for conformance.
3465 // P2280R4 struck the initialization requirement for variables of reference
3466 // type so we can no longer assume we have an Init.
3467 // Used to be C++20 [expr.const]p5.12:
3468 // ... reference has a preceding initialization and either ...
3469 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3470 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3471 NoteLValueLocation(Info, Base);
3472 return false;
3473 }
3474
3475 // Check that the variable is actually usable in constant expressions. For a
3476 // const integral variable or a reference, we might have a non-constant
3477 // initializer that we can nonetheless evaluate the initializer for. Such
3478 // variables are not usable in constant expressions. In C++98, the
3479 // initializer also syntactically needs to be an ICE.
3480 //
3481 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3482 // expressions here; doing so would regress diagnostics for things like
3483 // reading from a volatile constexpr variable.
3484 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3485 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3486 !AllowConstexprUnknown) ||
3487 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3488 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3489 if (Init) {
3490 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3491 NoteLValueLocation(Info, Base);
3492 } else {
3493 Info.CCEDiag(E);
3494 }
3495 }
3496
3497 // Never use the initializer of a weak variable, not even for constant
3498 // folding. We can't be sure that this is the definition that will be used.
3499 if (VD->isWeak()) {
3500 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3501 NoteLValueLocation(Info, Base);
3502 return false;
3503 }
3504
3505 Result = const_cast<APValue *>(VD->getEvaluatedValue());
3506
3507 if (!Result && !AllowConstexprUnknown)
3508 return false;
3509
3510 return CheckUninitReference(/*IsLocalVariable=*/false);
3511}
3512
3513/// Get the base index of the given base class within an APValue representing
3514/// the given derived class.
3515static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3516 const CXXRecordDecl *Base) {
3517 Base = Base->getCanonicalDecl();
3518 unsigned Index = 0;
3520 E = Derived->bases_end(); I != E; ++I, ++Index) {
3521 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3522 return Index;
3523 }
3524
3525 llvm_unreachable("base class missing from derived class's bases list");
3526}
3527
3528/// Extract the value of a character from a string literal.
3529static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3530 uint64_t Index) {
3531 assert(!isa<SourceLocExpr>(Lit) &&
3532 "SourceLocExpr should have already been converted to a StringLiteral");
3533
3534 // FIXME: Support MakeStringConstant
3535 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3536 std::string Str;
3537 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3538 assert(Index <= Str.size() && "Index too large");
3539 return APSInt::getUnsigned(Str.c_str()[Index]);
3540 }
3541
3542 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3543 Lit = PE->getFunctionName();
3544 const StringLiteral *S = cast<StringLiteral>(Lit);
3545 const ConstantArrayType *CAT =
3546 Info.Ctx.getAsConstantArrayType(S->getType());
3547 assert(CAT && "string literal isn't an array");
3548 QualType CharType = CAT->getElementType();
3549 assert(CharType->isIntegerType() && "unexpected character type");
3550 APSInt Value(Info.Ctx.getTypeSize(CharType),
3551 CharType->isUnsignedIntegerType());
3552 if (Index < S->getLength())
3553 Value = S->getCodeUnit(Index);
3554 return Value;
3555}
3556
3557// Expand a string literal into an array of characters.
3558//
3559// FIXME: This is inefficient; we should probably introduce something similar
3560// to the LLVM ConstantDataArray to make this cheaper.
3561static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3562 APValue &Result,
3563 QualType AllocType = QualType()) {
3564 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3565 AllocType.isNull() ? S->getType() : AllocType);
3566 assert(CAT && "string literal isn't an array");
3567 QualType CharType = CAT->getElementType();
3568 assert(CharType->isIntegerType() && "unexpected character type");
3569
3570 unsigned Elts = CAT->getZExtSize();
3572 std::min(S->getLength(), Elts), Elts);
3573 APSInt Value(Info.Ctx.getTypeSize(CharType),
3574 CharType->isUnsignedIntegerType());
3575 if (Result.hasArrayFiller())
3576 Result.getArrayFiller() = APValue(Value);
3577 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3578 Value = S->getCodeUnit(I);
3579 Result.getArrayInitializedElt(I) = APValue(Value);
3580 }
3581}
3582
3583// Expand an array so that it has more than Index filled elements.
3584static void expandArray(APValue &Array, unsigned Index) {
3585 unsigned Size = Array.getArraySize();
3586 assert(Index < Size);
3587
3588 // Always at least double the number of elements for which we store a value.
3589 unsigned OldElts = Array.getArrayInitializedElts();
3590 unsigned NewElts = std::max(Index+1, OldElts * 2);
3591 NewElts = std::min(Size, std::max(NewElts, 8u));
3592
3593 // Copy the data across.
3594 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3595 for (unsigned I = 0; I != OldElts; ++I)
3596 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3597 for (unsigned I = OldElts; I != NewElts; ++I)
3598 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3599 if (NewValue.hasArrayFiller())
3600 NewValue.getArrayFiller() = Array.getArrayFiller();
3601 Array.swap(NewValue);
3602}
3603
3604// Expand an indeterminate vector to materialize all elements.
3605static void expandVector(APValue &Vec, unsigned NumElements) {
3606 assert(Vec.isIndeterminate());
3608 Vec = APValue(Elts.data(), Elts.size());
3609}
3610
3611/// Determine whether a type would actually be read by an lvalue-to-rvalue
3612/// conversion. If it's of class type, we may assume that the copy operation
3613/// is trivial. Note that this is never true for a union type with fields
3614/// (because the copy always "reads" the active member) and always true for
3615/// a non-class type.
3616static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3618 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3619 return !RD || isReadByLvalueToRvalueConversion(RD);
3620}
3622 // FIXME: A trivial copy of a union copies the object representation, even if
3623 // the union is empty.
3624 if (RD->isUnion())
3625 return !RD->field_empty();
3626 if (RD->isEmpty())
3627 return false;
3628
3629 for (auto *Field : RD->fields())
3630 if (!Field->isUnnamedBitField() &&
3631 isReadByLvalueToRvalueConversion(Field->getType()))
3632 return true;
3633
3634 for (auto &BaseSpec : RD->bases())
3635 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3636 return true;
3637
3638 return false;
3639}
3640
3641/// Diagnose an attempt to read from any unreadable field within the specified
3642/// type, which might be a class type.
3643static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3644 QualType T) {
3645 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3646 if (!RD)
3647 return false;
3648
3649 if (!RD->hasMutableFields())
3650 return false;
3651
3652 for (auto *Field : RD->fields()) {
3653 // If we're actually going to read this field in some way, then it can't
3654 // be mutable. If we're in a union, then assigning to a mutable field
3655 // (even an empty one) can change the active member, so that's not OK.
3656 // FIXME: Add core issue number for the union case.
3657 if (Field->isMutable() &&
3658 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3659 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3660 Info.Note(Field->getLocation(), diag::note_declared_at);
3661 return true;
3662 }
3663
3664 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3665 return true;
3666 }
3667
3668 for (auto &BaseSpec : RD->bases())
3669 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3670 return true;
3671
3672 // All mutable fields were empty, and thus not actually read.
3673 return false;
3674}
3675
3676static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3678 bool MutableSubobject = false) {
3679 // A temporary or transient heap allocation we created.
3680 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3681 return true;
3682
3683 switch (Info.IsEvaluatingDecl) {
3684 case EvalInfo::EvaluatingDeclKind::None:
3685 return false;
3686
3687 case EvalInfo::EvaluatingDeclKind::Ctor:
3688 // The variable whose initializer we're evaluating.
3689 if (Info.EvaluatingDecl == Base)
3690 return true;
3691
3692 // A temporary lifetime-extended by the variable whose initializer we're
3693 // evaluating.
3694 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3695 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3696 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3697 return false;
3698
3699 case EvalInfo::EvaluatingDeclKind::Dtor:
3700 // C++2a [expr.const]p6:
3701 // [during constant destruction] the lifetime of a and its non-mutable
3702 // subobjects (but not its mutable subobjects) [are] considered to start
3703 // within e.
3704 if (MutableSubobject || Base != Info.EvaluatingDecl)
3705 return false;
3706 // FIXME: We can meaningfully extend this to cover non-const objects, but
3707 // we will need special handling: we should be able to access only
3708 // subobjects of such objects that are themselves declared const.
3709 QualType T = getType(Base);
3710 return T.isConstQualified() || T->isReferenceType();
3711 }
3712
3713 llvm_unreachable("unknown evaluating decl kind");
3714}
3715
3716static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3717 SourceLocation CallLoc = {}) {
3718 return Info.CheckArraySize(
3719 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3720 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3721 /*Diag=*/true);
3722}
3723
3724static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E,
3725 QualType SourceTy, QualType DestTy,
3726 APValue const &Original, APValue &Result) {
3727 // boolean must be checked before integer
3728 // since IsIntegerType() is true for bool
3729 if (SourceTy->isBooleanType()) {
3730 if (DestTy->isBooleanType()) {
3731 Result = Original;
3732 return true;
3733 }
3734 if (DestTy->isIntegerType() || DestTy->isRealFloatingType()) {
3735 bool BoolResult;
3736 if (!HandleConversionToBool(Original, BoolResult))
3737 return false;
3738 uint64_t IntResult = BoolResult;
3739 QualType IntType = DestTy->isIntegerType()
3740 ? DestTy
3741 : Info.Ctx.getIntTypeForBitwidth(64, false);
3742 Result = APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3743 }
3744 if (DestTy->isRealFloatingType()) {
3745 APValue Result2 = APValue(APFloat(0.0));
3746 if (!HandleIntToFloatCast(Info, E, FPO,
3747 Info.Ctx.getIntTypeForBitwidth(64, false),
3748 Result.getInt(), DestTy, Result2.getFloat()))
3749 return false;
3750 Result = std::move(Result2);
3751 }
3752 return true;
3753 }
3754 if (SourceTy->isIntegerType()) {
3755 if (DestTy->isRealFloatingType()) {
3756 Result = APValue(APFloat(0.0));
3757 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
3758 DestTy, Result.getFloat());
3759 }
3760 if (DestTy->isBooleanType()) {
3761 bool BoolResult;
3762 if (!HandleConversionToBool(Original, BoolResult))
3763 return false;
3764 uint64_t IntResult = BoolResult;
3765 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3766 return true;
3767 }
3768 if (DestTy->isIntegerType()) {
3769 Result = APValue(
3770 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
3771 return true;
3772 }
3773 } else if (SourceTy->isRealFloatingType()) {
3774 if (DestTy->isRealFloatingType()) {
3775 Result = Original;
3776 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
3777 Result.getFloat());
3778 }
3779 if (DestTy->isBooleanType()) {
3780 bool BoolResult;
3781 if (!HandleConversionToBool(Original, BoolResult))
3782 return false;
3783 uint64_t IntResult = BoolResult;
3784 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3785 return true;
3786 }
3787 if (DestTy->isIntegerType()) {
3788 Result = APValue(APSInt());
3789 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
3790 DestTy, Result.getInt());
3791 }
3792 }
3793
3794 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3795 return false;
3796}
3797
3798// do the heavy lifting for casting to aggregate types
3799// because we have to deal with bitfields specially
3800static bool constructAggregate(EvalInfo &Info, const FPOptions FPO,
3801 const Expr *E, APValue &Result,
3802 QualType ResultType,
3803 SmallVectorImpl<APValue> &Elements,
3804 SmallVectorImpl<QualType> &ElTypes) {
3805
3807 {&Result, ResultType, 0}};
3808
3809 unsigned ElI = 0;
3810 while (!WorkList.empty() && ElI < Elements.size()) {
3811 auto [Res, Type, BitWidth] = WorkList.pop_back_val();
3812
3813 if (Type->isRealFloatingType()) {
3814 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3815 *Res))
3816 return false;
3817 ElI++;
3818 continue;
3819 }
3820 if (Type->isIntegerType()) {
3821 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3822 *Res))
3823 return false;
3824 if (BitWidth > 0) {
3825 if (!Res->isInt())
3826 return false;
3827 APSInt &Int = Res->getInt();
3828 unsigned OldBitWidth = Int.getBitWidth();
3829 unsigned NewBitWidth = BitWidth;
3830 if (NewBitWidth < OldBitWidth)
3831 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
3832 }
3833 ElI++;
3834 continue;
3835 }
3836 if (Type->isVectorType()) {
3837 QualType ElTy = Type->castAs<VectorType>()->getElementType();
3838 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3839 SmallVector<APValue> Vals(NumEl);
3840 for (unsigned I = 0; I < NumEl; ++I) {
3841 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], ElTy, Elements[ElI],
3842 Vals[I]))
3843 return false;
3844 ElI++;
3845 }
3846 *Res = APValue(Vals.data(), NumEl);
3847 continue;
3848 }
3849 if (Type->isConstantArrayType()) {
3850 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
3851 ->getElementType();
3852 uint64_t Size =
3853 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3854 *Res = APValue(APValue::UninitArray(), Size, Size);
3855 for (int64_t I = Size - 1; I > -1; --I)
3856 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
3857 continue;
3858 }
3859 if (Type->isRecordType()) {
3860 const RecordDecl *RD = Type->getAsRecordDecl();
3861
3862 unsigned NumBases = 0;
3863 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3864 NumBases = CXXRD->getNumBases();
3865
3866 *Res = APValue(APValue::UninitStruct(), NumBases, RD->getNumFields());
3867
3869 // we need to traverse backwards
3870 // Visit the base classes.
3871 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3872 if (CXXRD->getNumBases() > 0) {
3873 assert(CXXRD->getNumBases() == 1);
3874 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3875 ReverseList.emplace_back(&Res->getStructBase(0), BS.getType(), 0u);
3876 }
3877 }
3878
3879 // Visit the fields.
3880 for (FieldDecl *FD : RD->fields()) {
3881 unsigned FDBW = 0;
3882 if (FD->isUnnamedBitField())
3883 continue;
3884 if (FD->isBitField()) {
3885 FDBW = FD->getBitWidthValue();
3886 }
3887
3888 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
3889 FD->getType(), FDBW);
3890 }
3891
3892 std::reverse(ReverseList.begin(), ReverseList.end());
3893 llvm::append_range(WorkList, ReverseList);
3894 continue;
3895 }
3896 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3897 return false;
3898 }
3899 return true;
3900}
3901
3902static bool handleElementwiseCast(EvalInfo &Info, const Expr *E,
3903 const FPOptions FPO,
3904 SmallVectorImpl<APValue> &Elements,
3905 SmallVectorImpl<QualType> &SrcTypes,
3906 SmallVectorImpl<QualType> &DestTypes,
3907 SmallVectorImpl<APValue> &Results) {
3908
3909 assert((Elements.size() == SrcTypes.size()) &&
3910 (Elements.size() == DestTypes.size()));
3911
3912 for (unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
3913 APValue Original = Elements[I];
3914 QualType SourceTy = SrcTypes[I];
3915 QualType DestTy = DestTypes[I];
3916
3917 if (!handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
3918 return false;
3919 }
3920 return true;
3921}
3922
3923static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy) {
3924
3925 SmallVector<QualType> WorkList = {BaseTy};
3926
3927 unsigned Size = 0;
3928 while (!WorkList.empty()) {
3929 QualType Type = WorkList.pop_back_val();
3931 Type->isBooleanType()) {
3932 ++Size;
3933 continue;
3934 }
3935 if (Type->isVectorType()) {
3936 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3937 Size += NumEl;
3938 continue;
3939 }
3940 if (Type->isConstantMatrixType()) {
3941 unsigned NumEl =
3942 Type->castAs<ConstantMatrixType>()->getNumElementsFlattened();
3943 Size += NumEl;
3944 continue;
3945 }
3946 if (Type->isConstantArrayType()) {
3947 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
3948 ->getElementType();
3949 uint64_t ArrSize =
3950 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3951 for (uint64_t I = 0; I < ArrSize; ++I) {
3952 WorkList.push_back(ElTy);
3953 }
3954 continue;
3955 }
3956 if (Type->isRecordType()) {
3957 const RecordDecl *RD = Type->getAsRecordDecl();
3958
3959 // Visit the base classes.
3960 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3961 if (CXXRD->getNumBases() > 0) {
3962 assert(CXXRD->getNumBases() == 1);
3963 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3964 WorkList.push_back(BS.getType());
3965 }
3966 }
3967
3968 // visit the fields.
3969 for (FieldDecl *FD : RD->fields()) {
3970 if (FD->isUnnamedBitField())
3971 continue;
3972 WorkList.push_back(FD->getType());
3973 }
3974 continue;
3975 }
3976 }
3977 return Size;
3978}
3979
3980static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal,
3981 QualType &SrcTy) {
3982 SrcTy = E->getType();
3983
3984 if (!Evaluate(SrcVal, Info, E))
3985 return false;
3986
3987 assert((SrcVal.isFloat() || SrcVal.isInt() ||
3988 (SrcVal.isVector() && SrcVal.getVectorLength() == 1)) &&
3989 "Not a valid HLSLAggregateSplatCast.");
3990
3991 if (SrcVal.isVector()) {
3992 assert(SrcTy->isVectorType() && "Type mismatch.");
3993 SrcTy = SrcTy->castAs<VectorType>()->getElementType();
3994 SrcVal = SrcVal.getVectorElt(0);
3995 }
3996 if (SrcVal.isMatrix()) {
3997 assert(SrcTy->isConstantMatrixType() && "Type mismatch.");
3998 SrcTy = SrcTy->castAs<ConstantMatrixType>()->getElementType();
3999 SrcVal = SrcVal.getMatrixElt(0, 0);
4000 }
4001 return true;
4002}
4003
4004static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value,
4005 QualType BaseTy, SmallVectorImpl<APValue> &Elements,
4006 SmallVectorImpl<QualType> &Types, unsigned Size) {
4007
4008 SmallVector<std::pair<APValue, QualType>> WorkList = {{Value, BaseTy}};
4009 unsigned Populated = 0;
4010 while (!WorkList.empty() && Populated < Size) {
4011 auto [Work, Type] = WorkList.pop_back_val();
4012
4013 if (Work.isFloat() || Work.isInt()) {
4014 Elements.push_back(Work);
4015 Types.push_back(Type);
4016 Populated++;
4017 continue;
4018 }
4019 if (Work.isVector()) {
4020 assert(Type->isVectorType() && "Type mismatch.");
4021 QualType ElTy = Type->castAs<VectorType>()->getElementType();
4022 for (unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4023 I++) {
4024 Elements.push_back(Work.getVectorElt(I));
4025 Types.push_back(ElTy);
4026 Populated++;
4027 }
4028 continue;
4029 }
4030 if (Work.isMatrix()) {
4031 assert(Type->isConstantMatrixType() && "Type mismatch.");
4032 const auto *MT = Type->castAs<ConstantMatrixType>();
4033 QualType ElTy = MT->getElementType();
4034 // Matrix elements are flattened in row-major order.
4035 for (unsigned Row = 0; Row < Work.getMatrixNumRows() && Populated < Size;
4036 Row++) {
4037 for (unsigned Col = 0;
4038 Col < Work.getMatrixNumColumns() && Populated < Size; Col++) {
4039 Elements.push_back(Work.getMatrixElt(Row, Col));
4040 Types.push_back(ElTy);
4041 Populated++;
4042 }
4043 }
4044 continue;
4045 }
4046 if (Work.isArray()) {
4047 assert(Type->isConstantArrayType() && "Type mismatch.");
4048 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4049 ->getElementType();
4050 for (int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4051 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4052 }
4053 continue;
4054 }
4055
4056 if (Work.isStruct()) {
4057 assert(Type->isRecordType() && "Type mismatch.");
4058
4059 const RecordDecl *RD = Type->getAsRecordDecl();
4060
4062 // Visit the fields.
4063 for (FieldDecl *FD : RD->fields()) {
4064 if (FD->isUnnamedBitField())
4065 continue;
4066 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4067 FD->getType());
4068 }
4069
4070 std::reverse(ReverseList.begin(), ReverseList.end());
4071 llvm::append_range(WorkList, ReverseList);
4072
4073 // Visit the base classes.
4074 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4075 if (CXXRD->getNumBases() > 0) {
4076 assert(CXXRD->getNumBases() == 1);
4077 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4078 const APValue &Base = Work.getStructBase(0);
4079
4080 // Can happen in error cases.
4081 if (!Base.isStruct())
4082 return false;
4083
4084 WorkList.emplace_back(Base, BS.getType());
4085 }
4086 }
4087 continue;
4088 }
4089 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4090 return false;
4091 }
4092 return true;
4093}
4094
4095namespace {
4096/// A handle to a complete object (an object that is not a subobject of
4097/// another object).
4098struct CompleteObject {
4099 /// The identity of the object.
4100 APValue::LValueBase Base;
4101 /// The value of the complete object.
4102 APValue *Value;
4103 /// The type of the complete object.
4104 QualType Type;
4105
4106 CompleteObject() : Value(nullptr) {}
4107 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
4108 : Base(Base), Value(Value), Type(Type) {}
4109
4110 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
4111 // If this isn't a "real" access (eg, if it's just accessing the type
4112 // info), allow it. We assume the type doesn't change dynamically for
4113 // subobjects of constexpr objects (even though we'd hit UB here if it
4114 // did). FIXME: Is this right?
4115 if (!isAnyAccess(AK))
4116 return true;
4117
4118 // In C++14 onwards, it is permitted to read a mutable member whose
4119 // lifetime began within the evaluation.
4120 // FIXME: Should we also allow this in C++11?
4121 if (!Info.getLangOpts().CPlusPlus14 &&
4122 AK != AccessKinds::AK_IsWithinLifetime)
4123 return false;
4124 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
4125 }
4126
4127 explicit operator bool() const { return !Type.isNull(); }
4128};
4129} // end anonymous namespace
4130
4131static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
4132 bool IsMutable = false) {
4133 // C++ [basic.type.qualifier]p1:
4134 // - A const object is an object of type const T or a non-mutable subobject
4135 // of a const object.
4136 if (ObjType.isConstQualified() && !IsMutable)
4137 SubobjType.addConst();
4138 // - A volatile object is an object of type const T or a subobject of a
4139 // volatile object.
4140 if (ObjType.isVolatileQualified())
4141 SubobjType.addVolatile();
4142 return SubobjType;
4143}
4144
4145/// Find the designated sub-object of an rvalue.
4146template <typename SubobjectHandler>
4147static typename SubobjectHandler::result_type
4148findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
4149 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4150 if (Sub.Invalid)
4151 // A diagnostic will have already been produced.
4152 return handler.failed();
4153 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4154 if (Info.getLangOpts().CPlusPlus11)
4155 Info.FFDiag(E, Sub.isOnePastTheEnd()
4156 ? diag::note_constexpr_access_past_end
4157 : diag::note_constexpr_access_unsized_array)
4158 << handler.AccessKind;
4159 else
4160 Info.FFDiag(E);
4161 return handler.failed();
4162 }
4163
4164 APValue *O = Obj.Value;
4165 QualType ObjType = Obj.Type;
4166 const FieldDecl *LastField = nullptr;
4167 const FieldDecl *VolatileField = nullptr;
4168
4169 // Walk the designator's path to find the subobject.
4170 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
4171 // Reading an indeterminate value is undefined, but assigning over one is OK.
4172 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
4173 (O->isIndeterminate() &&
4174 !isValidIndeterminateAccess(handler.AccessKind))) {
4175 // Object has ended lifetime.
4176 // If I is non-zero, some subobject (member or array element) of a
4177 // complete object has ended its lifetime, so this is valid for
4178 // IsWithinLifetime, resulting in false.
4179 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
4180 return false;
4181 if (!Info.checkingPotentialConstantExpression()) {
4182 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4183 << handler.AccessKind << O->isIndeterminate()
4184 << E->getSourceRange();
4185 NoteLValueLocation(Info, Obj.Base);
4186 }
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, Obj.Base))
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, Obj.Base);
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, APValue::LValueBase Base) {
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, APValue::LValueBase Base) {
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, APValue::LValueBase Base) {
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 NoteLValueLocation(Info, Base);
4997 return false;
4998 default:
4999 // FIXME: can this happen?
5000 Info.FFDiag(E);
5001 return false;
5002 }
5003 }
5004
5005 bool foundVector(APValue &Value, QualType SubobjType) {
5006 if (!checkConst(SubobjType))
5007 return false;
5008
5009 if (!SubobjType->isVectorType()) {
5010 Info.FFDiag(E);
5011 return false;
5012 }
5013 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
5014 }
5015
5016 bool found(APSInt &Value, QualType SubobjType) {
5017 if (!checkConst(SubobjType))
5018 return false;
5019
5020 if (!SubobjType->isIntegerType()) {
5021 // We don't support compound assignment on integer-cast-to-pointer
5022 // values.
5023 Info.FFDiag(E);
5024 return false;
5025 }
5026
5027 if (RHS.isInt()) {
5028 APSInt LHS =
5029 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
5030 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
5031 return false;
5032 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
5033 return true;
5034 } else if (RHS.isFloat()) {
5035 const FPOptions FPO = E->getFPFeaturesInEffect(
5036 Info.Ctx.getLangOpts());
5037 APFloat FValue(0.0);
5038 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
5039 PromotedLHSType, FValue) &&
5040 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
5041 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
5042 Value);
5043 }
5044
5045 Info.FFDiag(E);
5046 return false;
5047 }
5048 bool found(APFloat &Value, QualType SubobjType) {
5049 return checkConst(SubobjType) &&
5050 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
5051 Value) &&
5052 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
5053 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
5054 }
5055 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5056 if (!checkConst(SubobjType))
5057 return false;
5058
5059 QualType PointeeType;
5060 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5061 PointeeType = PT->getPointeeType();
5062
5063 if (PointeeType.isNull() || !RHS.isInt() ||
5064 (Opcode != BO_Add && Opcode != BO_Sub)) {
5065 Info.FFDiag(E);
5066 return false;
5067 }
5068
5069 APSInt Offset = RHS.getInt();
5070 if (Opcode == BO_Sub)
5071 negateAsSigned(Offset);
5072
5073 LValue LVal;
5074 LVal.setFrom(Info.Ctx, Subobj);
5075 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
5076 return false;
5077 LVal.moveInto(Subobj);
5078 return true;
5079 }
5080};
5081} // end anonymous namespace
5082
5083const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5084
5085/// Perform a compound assignment of LVal <op>= RVal.
5086static bool handleCompoundAssignment(EvalInfo &Info,
5087 const CompoundAssignOperator *E,
5088 const LValue &LVal, QualType LValType,
5089 QualType PromotedLValType,
5090 BinaryOperatorKind Opcode,
5091 const APValue &RVal) {
5092 if (LVal.Designator.Invalid)
5093 return false;
5094
5095 if (!Info.getLangOpts().CPlusPlus14) {
5096 Info.FFDiag(E);
5097 return false;
5098 }
5099
5100 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5101 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5102 RVal };
5103 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5104}
5105
5106namespace {
5107struct IncDecSubobjectHandler {
5108 EvalInfo &Info;
5109 const UnaryOperator *E;
5111 APValue *Old;
5112
5113 typedef bool result_type;
5114
5115 bool checkConst(QualType QT) {
5116 // Assigning to a const object has undefined behavior.
5117 if (QT.isConstQualified()) {
5118 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5119 return false;
5120 }
5121 return true;
5122 }
5123
5124 bool failed() { return false; }
5125 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
5126 // Stash the old value. Also clear Old, so we don't clobber it later
5127 // if we're post-incrementing a complex.
5128 if (Old) {
5129 *Old = Subobj;
5130 Old = nullptr;
5131 }
5132
5133 switch (Subobj.getKind()) {
5134 case APValue::Int:
5135 return found(Subobj.getInt(), SubobjType);
5136 case APValue::Float:
5137 return found(Subobj.getFloat(), SubobjType);
5139 return found(Subobj.getComplexIntReal(),
5140 SubobjType->castAs<ComplexType>()->getElementType()
5141 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5143 return found(Subobj.getComplexFloatReal(),
5144 SubobjType->castAs<ComplexType>()->getElementType()
5145 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5146 case APValue::LValue:
5147 return foundPointer(Subobj, SubobjType);
5148 default:
5149 // FIXME: can this happen?
5150 Info.FFDiag(E);
5151 return false;
5152 }
5153 }
5154 bool found(APSInt &Value, QualType SubobjType) {
5155 if (!checkConst(SubobjType))
5156 return false;
5157
5158 if (!SubobjType->isIntegerType()) {
5159 // We don't support increment / decrement on integer-cast-to-pointer
5160 // values.
5161 Info.FFDiag(E);
5162 return false;
5163 }
5164
5165 if (Old) *Old = APValue(Value);
5166
5167 // bool arithmetic promotes to int, and the conversion back to bool
5168 // doesn't reduce mod 2^n, so special-case it.
5169 if (SubobjType->isBooleanType()) {
5170 if (AccessKind == AK_Increment)
5171 Value = 1;
5172 else
5173 Value = !Value;
5174 return true;
5175 }
5176
5177 bool WasNegative = Value.isNegative();
5178 if (AccessKind == AK_Increment) {
5179 ++Value;
5180
5181 if (!WasNegative && Value.isNegative() && E->canOverflow() &&
5182 !SubobjType.isWrapType()) {
5183 APSInt ActualValue(Value, /*IsUnsigned*/true);
5184 return HandleOverflow(Info, E, ActualValue, SubobjType);
5185 }
5186 } else {
5187 --Value;
5188
5189 if (WasNegative && !Value.isNegative() && E->canOverflow() &&
5190 !SubobjType.isWrapType()) {
5191 unsigned BitWidth = Value.getBitWidth();
5192 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
5193 ActualValue.setBit(BitWidth);
5194 return HandleOverflow(Info, E, ActualValue, SubobjType);
5195 }
5196 }
5197 return true;
5198 }
5199 bool found(APFloat &Value, QualType SubobjType) {
5200 if (!checkConst(SubobjType))
5201 return false;
5202
5203 if (Old) *Old = APValue(Value);
5204
5205 APFloat One(Value.getSemantics(), 1);
5206 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
5207 APFloat::opStatus St;
5208 if (AccessKind == AK_Increment)
5209 St = Value.add(One, RM);
5210 else
5211 St = Value.subtract(One, RM);
5212 return checkFloatingPointResult(Info, E, St);
5213 }
5214 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5215 if (!checkConst(SubobjType))
5216 return false;
5217
5218 QualType PointeeType;
5219 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5220 PointeeType = PT->getPointeeType();
5221 else {
5222 Info.FFDiag(E);
5223 return false;
5224 }
5225
5226 LValue LVal;
5227 LVal.setFrom(Info.Ctx, Subobj);
5228 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
5229 AccessKind == AK_Increment ? 1 : -1))
5230 return false;
5231 LVal.moveInto(Subobj);
5232 return true;
5233 }
5234};
5235} // end anonymous namespace
5236
5237/// Perform an increment or decrement on LVal.
5238static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
5239 QualType LValType, bool IsIncrement, APValue *Old) {
5240 if (LVal.Designator.Invalid)
5241 return false;
5242
5243 if (!Info.getLangOpts().CPlusPlus14) {
5244 Info.FFDiag(E);
5245 return false;
5246 }
5247
5248 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
5249 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
5250 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
5251 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5252}
5253
5254/// Build an lvalue for the object argument of a member function call.
5255static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
5256 LValue &This) {
5257 if (Object->getType()->isPointerType() && Object->isPRValue())
5258 return EvaluatePointer(Object, This, Info);
5259
5260 if (Object->isGLValue())
5261 return EvaluateLValue(Object, This, Info);
5262
5263 if (Object->getType()->isLiteralType(Info.Ctx))
5264 return EvaluateTemporary(Object, This, Info);
5265
5266 if (Object->getType()->isRecordType() && Object->isPRValue())
5267 return EvaluateTemporary(Object, This, Info);
5268
5269 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5270 return false;
5271}
5272
5273/// HandleMemberPointerAccess - Evaluate a member access operation and build an
5274/// lvalue referring to the result.
5275///
5276/// \param Info - Information about the ongoing evaluation.
5277/// \param LV - An lvalue referring to the base of the member pointer.
5278/// \param RHS - The member pointer expression.
5279/// \param IncludeMember - Specifies whether the member itself is included in
5280/// the resulting LValue subobject designator. This is not possible when
5281/// creating a bound member function.
5282/// \return The field or method declaration to which the member pointer refers,
5283/// or 0 if evaluation fails.
5284static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5285 QualType LVType,
5286 LValue &LV,
5287 const Expr *RHS,
5288 bool IncludeMember = true) {
5289 MemberPtr MemPtr;
5290 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5291 return nullptr;
5292
5293 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5294 // member value, the behavior is undefined.
5295 if (!MemPtr.getDecl()) {
5296 // FIXME: Specific diagnostic.
5297 Info.FFDiag(RHS);
5298 return nullptr;
5299 }
5300
5301 if (MemPtr.isDerivedMember()) {
5302 // This is a member of some derived class. Truncate LV appropriately.
5303 // The end of the derived-to-base path for the base object must match the
5304 // derived-to-base path for the member pointer.
5305 // C++23 [expr.mptr.oper]p4:
5306 // If the result of E1 is an object [...] whose most derived object does
5307 // not contain the member to which E2 refers, the behavior is undefined.
5308 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5309 LV.Designator.Entries.size()) {
5310 Info.FFDiag(RHS);
5311 return nullptr;
5312 }
5313 unsigned PathLengthToMember =
5314 LV.Designator.Entries.size() - MemPtr.Path.size();
5315 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5316 const CXXRecordDecl *LVDecl = getAsBaseClass(
5317 LV.Designator.Entries[PathLengthToMember + I]);
5318 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5319 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5320 Info.FFDiag(RHS);
5321 return nullptr;
5322 }
5323 }
5324 // MemPtr.Path only contains the base classes of the class directly
5325 // containing the member E2. It is still necessary to check that the class
5326 // directly containing the member E2 lies on the derived-to-base path of E1
5327 // to avoid incorrectly permitting member pointer access into a sibling
5328 // class of the class containing the member E2. If this class would
5329 // correspond to the most-derived class of E1, it either isn't contained in
5330 // LV.Designator.Entries or the corresponding entry refers to an array
5331 // element instead. Therefore get the most derived class directly in this
5332 // case. Otherwise the previous entry should correpond to this class.
5333 const CXXRecordDecl *LastLVDecl =
5334 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5335 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5336 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5337 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5338 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5339 Info.FFDiag(RHS);
5340 return nullptr;
5341 }
5342
5343 // Truncate the lvalue to the appropriate derived class.
5344 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5345 PathLengthToMember))
5346 return nullptr;
5347 } else if (!MemPtr.Path.empty()) {
5348 // Extend the LValue path with the member pointer's path.
5349 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5350 MemPtr.Path.size() + IncludeMember);
5351
5352 // Walk down to the appropriate base class.
5353 if (const PointerType *PT = LVType->getAs<PointerType>())
5354 LVType = PT->getPointeeType();
5355 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5356 assert(RD && "member pointer access on non-class-type expression");
5357 // The first class in the path is that of the lvalue.
5358 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5359 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5360 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5361 return nullptr;
5362 RD = Base;
5363 }
5364 // Finally cast to the class containing the member.
5365 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5366 MemPtr.getContainingRecord()))
5367 return nullptr;
5368 }
5369
5370 // Add the member. Note that we cannot build bound member functions here.
5371 if (IncludeMember) {
5372 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5373 if (!HandleLValueMember(Info, RHS, LV, FD))
5374 return nullptr;
5375 } else if (const IndirectFieldDecl *IFD =
5376 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5377 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5378 return nullptr;
5379 } else {
5380 llvm_unreachable("can't construct reference to bound member function");
5381 }
5382 }
5383
5384 return MemPtr.getDecl();
5385}
5386
5387static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5388 const BinaryOperator *BO,
5389 LValue &LV,
5390 bool IncludeMember = true) {
5391 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5392
5393 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5394 if (Info.noteFailure()) {
5395 MemberPtr MemPtr;
5396 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5397 }
5398 return nullptr;
5399 }
5400
5401 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5402 BO->getRHS(), IncludeMember);
5403}
5404
5405/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5406/// the provided lvalue, which currently refers to the base object.
5407static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5408 LValue &Result) {
5409 SubobjectDesignator &D = Result.Designator;
5410 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5411 return false;
5412
5413 QualType TargetQT = E->getType();
5414 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5415 TargetQT = PT->getPointeeType();
5416
5417 auto InvalidCast = [&]() {
5418 if (!Info.checkingPotentialConstantExpression() ||
5419 !Result.AllowConstexprUnknown) {
5420 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5421 << D.MostDerivedType << TargetQT;
5422 }
5423 return false;
5424 };
5425
5426 // Check this cast lands within the final derived-to-base subobject path.
5427 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5428 return InvalidCast();
5429
5430 // Check the type of the final cast. We don't need to check the path,
5431 // since a cast can only be formed if the path is unique.
5432 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5433 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5434 const CXXRecordDecl *FinalType;
5435 if (NewEntriesSize == D.MostDerivedPathLength)
5436 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5437 else
5438 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5439 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5440 return InvalidCast();
5441
5442 // Truncate the lvalue to the appropriate derived class.
5443 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5444}
5445
5446/// Get the value to use for a default-initialized object of type T.
5447/// Return false if it encounters something invalid.
5449 bool Success = true;
5450
5451 // If there is already a value present don't overwrite it.
5452 if (!Result.isAbsent())
5453 return true;
5454
5455 if (auto *RD = T->getAsCXXRecordDecl()) {
5456 if (RD->isInvalidDecl()) {
5457 Result = APValue();
5458 return false;
5459 }
5460 if (RD->isUnion()) {
5461 Result = APValue((const FieldDecl *)nullptr);
5462 return true;
5463 }
5464 Result =
5465 APValue(APValue::UninitStruct(), RD->getNumBases(), RD->getNumFields());
5466
5467 unsigned Index = 0;
5468 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5469 End = RD->bases_end();
5470 I != End; ++I, ++Index)
5471 Success &=
5472 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5473
5474 for (const auto *I : RD->fields()) {
5475 if (I->isUnnamedBitField())
5476 continue;
5478 I->getType(), Result.getStructField(I->getFieldIndex()));
5479 }
5480 return Success;
5481 }
5482
5483 if (auto *AT =
5484 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5485 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5486 if (Result.hasArrayFiller())
5487 Success &=
5488 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5489
5490 return Success;
5491 }
5492
5494 return true;
5495}
5496
5497namespace {
5498enum EvalStmtResult {
5499 /// Evaluation failed.
5500 ESR_Failed,
5501 /// Hit a 'return' statement.
5502 ESR_Returned,
5503 /// Evaluation succeeded.
5504 ESR_Succeeded,
5505 /// Hit a 'continue' statement.
5506 ESR_Continue,
5507 /// Hit a 'break' statement.
5508 ESR_Break,
5509 /// Still scanning for 'case' or 'default' statement.
5510 ESR_CaseNotFound
5511};
5512}
5513/// Evaluates the initializer of a reference.
5514static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5515 const ValueDecl *D,
5516 const Expr *Init, LValue &Result,
5517 APValue &Val) {
5518 assert(Init->isGLValue() && D->getType()->isReferenceType());
5519 // A reference is an lvalue.
5520 if (!EvaluateLValue(Init, Result, Info))
5521 return false;
5522 // [C++26][decl.ref]
5523 // The object designated by such a glvalue can be outside its lifetime
5524 // Because a null pointer value or a pointer past the end of an object
5525 // does not point to an object, a reference in a well-defined program cannot
5526 // refer to such things;
5527 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5528 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5529 return false;
5530 }
5531
5532 // Save the result.
5533 Result.moveInto(Val);
5534 return true;
5535}
5536
5537static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5538 if (VD->isInvalidDecl())
5539 return false;
5540 // We don't need to evaluate the initializer for a static local.
5541 if (!VD->hasLocalStorage())
5542 return true;
5543
5544 LValue Result;
5545 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5546 ScopeKind::Block, Result);
5547
5548 const Expr *InitE = VD->getInit();
5549 if (!InitE) {
5550 if (VD->getType()->isDependentType())
5551 return Info.noteSideEffect();
5552 return handleDefaultInitValue(VD->getType(), Val);
5553 }
5554 if (InitE->isValueDependent())
5555 return false;
5556
5557 // For references to objects, check they do not designate a one-past-the-end
5558 // object.
5559 if (VD->getType()->isReferenceType()) {
5560 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5561 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5562 // Wipe out any partially-computed value, to allow tracking that this
5563 // evaluation failed.
5564 Val = APValue();
5565 return false;
5566 }
5567
5568 return true;
5569}
5570
5571static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5572 const DecompositionDecl *DD);
5573
5574static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5575 bool EvaluateConditionDecl = false) {
5576 bool OK = true;
5577 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5578 OK &= EvaluateVarDecl(Info, VD);
5579
5580 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5581 EvaluateConditionDecl && DD)
5582 OK &= EvaluateDecompositionDeclInit(Info, DD);
5583
5584 return OK;
5585}
5586
5587static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5588 const DecompositionDecl *DD) {
5589 bool OK = true;
5590 for (auto *BD : DD->flat_bindings())
5591 if (auto *VD = BD->getHoldingVar())
5592 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5593
5594 return OK;
5595}
5596
5597static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5598 const VarDecl *VD) {
5599 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5600 if (!EvaluateDecompositionDeclInit(Info, DD))
5601 return false;
5602 }
5603 return true;
5604}
5605
5606static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5607 assert(E->isValueDependent());
5608 if (Info.noteSideEffect())
5609 return true;
5610 assert(E->containsErrors() && "valid value-dependent expression should never "
5611 "reach invalid code path.");
5612 return false;
5613}
5614
5615/// Evaluate a condition (either a variable declaration or an expression).
5616static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5617 const Expr *Cond, bool &Result) {
5618 if (Cond->isValueDependent())
5619 return false;
5620 FullExpressionRAII Scope(Info);
5621 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5622 return false;
5624 return false;
5625 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5626 return false;
5627 return Scope.destroy();
5628}
5629
5630namespace {
5631/// A location where the result (returned value) of evaluating a
5632/// statement should be stored.
5633struct StmtResult {
5634 /// The APValue that should be filled in with the returned value.
5635 APValue &Value;
5636 /// The location containing the result, if any (used to support RVO).
5637 const LValue *Slot;
5638};
5639
5640struct TempVersionRAII {
5641 CallStackFrame &Frame;
5642
5643 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5644 Frame.pushTempVersion();
5645 }
5646
5647 ~TempVersionRAII() {
5648 Frame.popTempVersion();
5649 }
5650};
5651
5652}
5653
5654static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5655 const Stmt *S,
5656 const SwitchCase *SC = nullptr);
5657
5658/// Helper to implement named break/continue. Returns 'true' if the evaluation
5659/// result should be propagated up. Otherwise, it sets the evaluation result
5660/// to either Continue to continue the current loop, or Succeeded to break it.
5661static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5662 const Stmt *LoopOrSwitch,
5664 EvalStmtResult &ESR) {
5665 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5666
5667 // For loops, map Succeeded to Continue so we don't have to check for both.
5668 if (!IsSwitch && ESR == ESR_Succeeded) {
5669 ESR = ESR_Continue;
5670 return false;
5671 }
5672
5673 if (ESR != ESR_Break && ESR != ESR_Continue)
5674 return false;
5675
5676 // Are we breaking out of or continuing this statement?
5677 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5678 const Stmt *StackTop = Info.BreakContinueStack.back();
5679 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5680 Info.BreakContinueStack.pop_back();
5681 if (ESR == ESR_Break)
5682 ESR = ESR_Succeeded;
5683 return false;
5684 }
5685
5686 // We're not. Propagate the result up.
5687 for (BlockScopeRAII *S : Scopes) {
5688 if (!S->destroy()) {
5689 ESR = ESR_Failed;
5690 break;
5691 }
5692 }
5693 return true;
5694}
5695
5696/// Evaluate the body of a loop, and translate the result as appropriate.
5697static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5698 const Stmt *Body,
5699 const SwitchCase *Case = nullptr) {
5700 BlockScopeRAII Scope(Info);
5701
5702 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5703 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5704 ESR = ESR_Failed;
5705
5706 return ESR;
5707}
5708
5709/// Evaluate a switch statement.
5710static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5711 const SwitchStmt *SS) {
5712 BlockScopeRAII Scope(Info);
5713
5714 // Evaluate the switch condition.
5715 APSInt Value;
5716 {
5717 if (const Stmt *Init = SS->getInit()) {
5718 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5719 if (ESR != ESR_Succeeded) {
5720 if (ESR != ESR_Failed && !Scope.destroy())
5721 ESR = ESR_Failed;
5722 return ESR;
5723 }
5724 }
5725
5726 FullExpressionRAII CondScope(Info);
5727 if (SS->getConditionVariable() &&
5728 !EvaluateDecl(Info, SS->getConditionVariable()))
5729 return ESR_Failed;
5730 if (SS->getCond()->isValueDependent()) {
5731 // We don't know what the value is, and which branch should jump to.
5732 EvaluateDependentExpr(SS->getCond(), Info);
5733 return ESR_Failed;
5734 }
5735 if (!EvaluateInteger(SS->getCond(), Value, Info))
5736 return ESR_Failed;
5737
5739 return ESR_Failed;
5740
5741 if (!CondScope.destroy())
5742 return ESR_Failed;
5743 }
5744
5745 // Find the switch case corresponding to the value of the condition.
5746 // FIXME: Cache this lookup.
5747 const SwitchCase *Found = nullptr;
5748 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5749 SC = SC->getNextSwitchCase()) {
5750 if (isa<DefaultStmt>(SC)) {
5751 Found = SC;
5752 continue;
5753 }
5754
5755 const CaseStmt *CS = cast<CaseStmt>(SC);
5756 const Expr *LHS = CS->getLHS();
5757 const Expr *RHS = CS->getRHS();
5758 if (LHS->isValueDependent() || (RHS && RHS->isValueDependent()))
5759 return ESR_Failed;
5760 APSInt LHSValue = LHS->EvaluateKnownConstInt(Info.Ctx);
5761 APSInt RHSValue = RHS ? RHS->EvaluateKnownConstInt(Info.Ctx) : LHSValue;
5762 if (LHSValue <= Value && Value <= RHSValue) {
5763 Found = SC;
5764 break;
5765 }
5766 }
5767
5768 if (!Found)
5769 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5770
5771 // Search the switch body for the switch case and evaluate it from there.
5772 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5773 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5774 return ESR_Failed;
5775 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5776 return ESR;
5777
5778 switch (ESR) {
5779 case ESR_Break:
5780 llvm_unreachable("Should have been converted to Succeeded");
5781 case ESR_Succeeded:
5782 case ESR_Continue:
5783 case ESR_Failed:
5784 case ESR_Returned:
5785 return ESR;
5786 case ESR_CaseNotFound:
5787 // This can only happen if the switch case is nested within a statement
5788 // expression. We have no intention of supporting that.
5789 Info.FFDiag(Found->getBeginLoc(),
5790 diag::note_constexpr_stmt_expr_unsupported);
5791 return ESR_Failed;
5792 }
5793 llvm_unreachable("Invalid EvalStmtResult!");
5794}
5795
5796static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5797 // An expression E is a core constant expression unless the evaluation of E
5798 // would evaluate one of the following: [C++23] - a control flow that passes
5799 // through a declaration of a variable with static or thread storage duration
5800 // unless that variable is usable in constant expressions.
5801 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5802 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5803 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5804 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5805 return false;
5806 }
5807 return true;
5808}
5809
5810// Evaluate a statement.
5811static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5812 const Stmt *S, const SwitchCase *Case) {
5813 if (!Info.nextStep(S))
5814 return ESR_Failed;
5815
5816 // If we're hunting down a 'case' or 'default' label, recurse through
5817 // substatements until we hit the label.
5818 if (Case) {
5819 switch (S->getStmtClass()) {
5820 case Stmt::CompoundStmtClass:
5821 // FIXME: Precompute which substatement of a compound statement we
5822 // would jump to, and go straight there rather than performing a
5823 // linear scan each time.
5824 case Stmt::LabelStmtClass:
5825 case Stmt::AttributedStmtClass:
5826 case Stmt::DoStmtClass:
5827 break;
5828
5829 case Stmt::CaseStmtClass:
5830 case Stmt::DefaultStmtClass:
5831 if (Case == S)
5832 Case = nullptr;
5833 break;
5834
5835 case Stmt::IfStmtClass: {
5836 // FIXME: Precompute which side of an 'if' we would jump to, and go
5837 // straight there rather than scanning both sides.
5838 const IfStmt *IS = cast<IfStmt>(S);
5839
5840 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5841 // preceded by our switch label.
5842 BlockScopeRAII Scope(Info);
5843
5844 // Step into the init statement in case it brings an (uninitialized)
5845 // variable into scope.
5846 if (const Stmt *Init = IS->getInit()) {
5847 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5848 if (ESR != ESR_CaseNotFound) {
5849 assert(ESR != ESR_Succeeded);
5850 return ESR;
5851 }
5852 }
5853
5854 // Condition variable must be initialized if it exists.
5855 // FIXME: We can skip evaluating the body if there's a condition
5856 // variable, as there can't be any case labels within it.
5857 // (The same is true for 'for' statements.)
5858
5859 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5860 if (ESR == ESR_Failed)
5861 return ESR;
5862 if (ESR != ESR_CaseNotFound)
5863 return Scope.destroy() ? ESR : ESR_Failed;
5864 if (!IS->getElse())
5865 return ESR_CaseNotFound;
5866
5867 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5868 if (ESR == ESR_Failed)
5869 return ESR;
5870 if (ESR != ESR_CaseNotFound)
5871 return Scope.destroy() ? ESR : ESR_Failed;
5872 return ESR_CaseNotFound;
5873 }
5874
5875 case Stmt::WhileStmtClass: {
5876 EvalStmtResult ESR =
5877 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5878 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5879 return ESR;
5880 if (ESR != ESR_Continue)
5881 return ESR;
5882 break;
5883 }
5884
5885 case Stmt::ForStmtClass: {
5886 const ForStmt *FS = cast<ForStmt>(S);
5887 BlockScopeRAII Scope(Info);
5888
5889 // Step into the init statement in case it brings an (uninitialized)
5890 // variable into scope.
5891 if (const Stmt *Init = FS->getInit()) {
5892 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5893 if (ESR != ESR_CaseNotFound) {
5894 assert(ESR != ESR_Succeeded);
5895 return ESR;
5896 }
5897 }
5898
5899 EvalStmtResult ESR =
5900 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5901 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
5902 return ESR;
5903 if (ESR != ESR_Continue)
5904 return ESR;
5905 if (const auto *Inc = FS->getInc()) {
5906 if (Inc->isValueDependent()) {
5907 if (!EvaluateDependentExpr(Inc, Info))
5908 return ESR_Failed;
5909 } else {
5910 FullExpressionRAII IncScope(Info);
5911 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5912 return ESR_Failed;
5913 }
5914 }
5915 break;
5916 }
5917
5918 case Stmt::DeclStmtClass: {
5919 // Start the lifetime of any uninitialized variables we encounter. They
5920 // might be used by the selected branch of the switch.
5921 const DeclStmt *DS = cast<DeclStmt>(S);
5922 for (const auto *D : DS->decls()) {
5923 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5924 if (!CheckLocalVariableDeclaration(Info, VD))
5925 return ESR_Failed;
5926 if (VD->hasLocalStorage() && !VD->getInit())
5927 if (!EvaluateVarDecl(Info, VD))
5928 return ESR_Failed;
5929 // FIXME: If the variable has initialization that can't be jumped
5930 // over, bail out of any immediately-surrounding compound-statement
5931 // too. There can't be any case labels here.
5932 }
5933 }
5934 return ESR_CaseNotFound;
5935 }
5936
5937 default:
5938 return ESR_CaseNotFound;
5939 }
5940 }
5941
5942 switch (S->getStmtClass()) {
5943 default:
5944 if (const Expr *E = dyn_cast<Expr>(S)) {
5945 if (E->isValueDependent()) {
5946 if (!EvaluateDependentExpr(E, Info))
5947 return ESR_Failed;
5948 } else {
5949 // Don't bother evaluating beyond an expression-statement which couldn't
5950 // be evaluated.
5951 // FIXME: Do we need the FullExpressionRAII object here?
5952 // VisitExprWithCleanups should create one when necessary.
5953 FullExpressionRAII Scope(Info);
5954 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5955 return ESR_Failed;
5956 }
5957 return ESR_Succeeded;
5958 }
5959
5960 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5961 return ESR_Failed;
5962
5963 case Stmt::NullStmtClass:
5964 return ESR_Succeeded;
5965
5966 case Stmt::DeclStmtClass: {
5967 const DeclStmt *DS = cast<DeclStmt>(S);
5968 for (const auto *D : DS->decls()) {
5969 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5970 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5971 return ESR_Failed;
5972
5973 if (const auto *ESD = dyn_cast<CXXExpansionStmtDecl>(D)) {
5974 assert(ESD->getInstantiations() && "not expanded?");
5975 return EvaluateStmt(Result, Info, ESD->getInstantiations(), Case);
5976 }
5977
5978 // Each declaration initialization is its own full-expression.
5979 FullExpressionRAII Scope(Info);
5980 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
5981 !Info.noteFailure())
5982 return ESR_Failed;
5983 if (!Scope.destroy())
5984 return ESR_Failed;
5985 }
5986 return ESR_Succeeded;
5987 }
5988
5989 case Stmt::ReturnStmtClass: {
5990 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5991 FullExpressionRAII Scope(Info);
5992 if (RetExpr && RetExpr->isValueDependent()) {
5993 EvaluateDependentExpr(RetExpr, Info);
5994 // We know we returned, but we don't know what the value is.
5995 return ESR_Failed;
5996 }
5997 if (RetExpr &&
5998 !(Result.Slot
5999 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
6000 : Evaluate(Result.Value, Info, RetExpr)))
6001 return ESR_Failed;
6002 return Scope.destroy() ? ESR_Returned : ESR_Failed;
6003 }
6004
6005 case Stmt::CompoundStmtClass: {
6006 BlockScopeRAII Scope(Info);
6007
6008 const CompoundStmt *CS = cast<CompoundStmt>(S);
6009 for (const auto *BI : CS->body()) {
6010 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
6011 if (ESR == ESR_Succeeded)
6012 Case = nullptr;
6013 else if (ESR != ESR_CaseNotFound) {
6014 if (ESR != ESR_Failed && !Scope.destroy())
6015 return ESR_Failed;
6016 return ESR;
6017 }
6018 }
6019 if (Case)
6020 return ESR_CaseNotFound;
6021 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6022 }
6023
6024 case Stmt::IfStmtClass: {
6025 const IfStmt *IS = cast<IfStmt>(S);
6026
6027 // Evaluate the condition, as either a var decl or as an expression.
6028 BlockScopeRAII Scope(Info);
6029 if (const Stmt *Init = IS->getInit()) {
6030 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
6031 if (ESR != ESR_Succeeded) {
6032 if (ESR != ESR_Failed && !Scope.destroy())
6033 return ESR_Failed;
6034 return ESR;
6035 }
6036 }
6037 bool Cond;
6038 if (IS->isConsteval()) {
6040 // If we are not in a constant context, if consteval should not evaluate
6041 // to true.
6042 if (!Info.InConstantContext)
6043 Cond = !Cond;
6044 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
6045 Cond))
6046 return ESR_Failed;
6047
6048 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
6049 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
6050 if (ESR != ESR_Succeeded) {
6051 if (ESR != ESR_Failed && !Scope.destroy())
6052 return ESR_Failed;
6053 return ESR;
6054 }
6055 }
6056 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6057 }
6058
6059 case Stmt::WhileStmtClass: {
6060 const WhileStmt *WS = cast<WhileStmt>(S);
6061 while (true) {
6062 BlockScopeRAII Scope(Info);
6063 bool Continue;
6064 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
6065 Continue))
6066 return ESR_Failed;
6067 if (!Continue)
6068 break;
6069
6070 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
6071 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
6072 return ESR;
6073
6074 if (ESR != ESR_Continue) {
6075 if (ESR != ESR_Failed && !Scope.destroy())
6076 return ESR_Failed;
6077 return ESR;
6078 }
6079 if (!Scope.destroy())
6080 return ESR_Failed;
6081 }
6082 return ESR_Succeeded;
6083 }
6084
6085 case Stmt::DoStmtClass: {
6086 const DoStmt *DS = cast<DoStmt>(S);
6087 bool Continue;
6088 do {
6089 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
6090 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
6091 return ESR;
6092 if (ESR != ESR_Continue)
6093 return ESR;
6094 Case = nullptr;
6095
6096 if (DS->getCond()->isValueDependent()) {
6097 EvaluateDependentExpr(DS->getCond(), Info);
6098 // Bailout as we don't know whether to keep going or terminate the loop.
6099 return ESR_Failed;
6100 }
6101 FullExpressionRAII CondScope(Info);
6102 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
6103 !CondScope.destroy())
6104 return ESR_Failed;
6105 } while (Continue);
6106 return ESR_Succeeded;
6107 }
6108
6109 case Stmt::ForStmtClass: {
6110 const ForStmt *FS = cast<ForStmt>(S);
6111 BlockScopeRAII ForScope(Info);
6112 if (FS->getInit()) {
6113 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6114 if (ESR != ESR_Succeeded) {
6115 if (ESR != ESR_Failed && !ForScope.destroy())
6116 return ESR_Failed;
6117 return ESR;
6118 }
6119 }
6120 while (true) {
6121 BlockScopeRAII IterScope(Info);
6122 bool Continue = true;
6123 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
6124 FS->getCond(), Continue))
6125 return ESR_Failed;
6126
6127 if (!Continue) {
6128 if (!IterScope.destroy())
6129 return ESR_Failed;
6130 break;
6131 }
6132
6133 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6134 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
6135 return ESR;
6136 if (ESR != ESR_Continue) {
6137 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6138 return ESR_Failed;
6139 return ESR;
6140 }
6141
6142 if (const auto *Inc = FS->getInc()) {
6143 if (Inc->isValueDependent()) {
6144 if (!EvaluateDependentExpr(Inc, Info))
6145 return ESR_Failed;
6146 } else {
6147 FullExpressionRAII IncScope(Info);
6148 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6149 return ESR_Failed;
6150 }
6151 }
6152
6153 if (!IterScope.destroy())
6154 return ESR_Failed;
6155 }
6156 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6157 }
6158
6159 case Stmt::CXXForRangeStmtClass: {
6161 BlockScopeRAII Scope(Info);
6162
6163 // Evaluate the init-statement if present.
6164 if (FS->getInit()) {
6165 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6166 if (ESR != ESR_Succeeded) {
6167 if (ESR != ESR_Failed && !Scope.destroy())
6168 return ESR_Failed;
6169 return ESR;
6170 }
6171 }
6172
6173 // Initialize the __range variable.
6174 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
6175 if (ESR != ESR_Succeeded) {
6176 if (ESR != ESR_Failed && !Scope.destroy())
6177 return ESR_Failed;
6178 return ESR;
6179 }
6180
6181 // In error-recovery cases it's possible to get here even if we failed to
6182 // synthesize the __begin and __end variables.
6183 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
6184 return ESR_Failed;
6185
6186 // Create the __begin and __end iterators.
6187 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
6188 if (ESR != ESR_Succeeded) {
6189 if (ESR != ESR_Failed && !Scope.destroy())
6190 return ESR_Failed;
6191 return ESR;
6192 }
6193 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
6194 if (ESR != ESR_Succeeded) {
6195 if (ESR != ESR_Failed && !Scope.destroy())
6196 return ESR_Failed;
6197 return ESR;
6198 }
6199
6200 while (true) {
6201 // Condition: __begin != __end.
6202 {
6203 if (FS->getCond()->isValueDependent()) {
6204 EvaluateDependentExpr(FS->getCond(), Info);
6205 // We don't know whether to keep going or terminate the loop.
6206 return ESR_Failed;
6207 }
6208 bool Continue = true;
6209 FullExpressionRAII CondExpr(Info);
6210 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
6211 return ESR_Failed;
6212 if (!Continue)
6213 break;
6214 }
6215
6216 // User's variable declaration, initialized by *__begin.
6217 BlockScopeRAII InnerScope(Info);
6218 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
6219 if (ESR != ESR_Succeeded) {
6220 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6221 return ESR_Failed;
6222 return ESR;
6223 }
6224
6225 // Loop body.
6226 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6227 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
6228 return ESR;
6229 if (ESR != ESR_Continue) {
6230 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6231 return ESR_Failed;
6232 return ESR;
6233 }
6234 if (FS->getInc()->isValueDependent()) {
6235 if (!EvaluateDependentExpr(FS->getInc(), Info))
6236 return ESR_Failed;
6237 } else {
6238 // Increment: ++__begin
6239 if (!EvaluateIgnoredValue(Info, FS->getInc()))
6240 return ESR_Failed;
6241 }
6242
6243 if (!InnerScope.destroy())
6244 return ESR_Failed;
6245 }
6246
6247 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6248 }
6249
6250 case Stmt::CXXExpansionStmtInstantiationClass: {
6251 BlockScopeRAII Scope(Info);
6252 const auto *Expansion = cast<CXXExpansionStmtInstantiation>(S);
6253 for (const Stmt *PreambleStmt : Expansion->getPreambleStmts()) {
6254 EvalStmtResult ESR = EvaluateStmt(Result, Info, PreambleStmt);
6255 if (ESR != ESR_Succeeded) {
6256 if (ESR != ESR_Failed && !Scope.destroy())
6257 return ESR_Failed;
6258 return ESR;
6259 }
6260 }
6261
6262 // No need to push an extra scope for these since they're already
6263 // CompoundStmts.
6264 EvalStmtResult ESR = ESR_Succeeded;
6265 for (const Stmt *Instantiation : Expansion->getInstantiations()) {
6266 ESR = EvaluateStmt(Result, Info, Instantiation);
6267 if (ESR == ESR_Failed ||
6268 ShouldPropagateBreakContinue(Info, Expansion, &Scope, ESR))
6269 return ESR;
6270 if (ESR != ESR_Continue) {
6271 // Succeeded here actually means we encountered a 'break'.
6272 assert(ESR == ESR_Succeeded || ESR == ESR_Returned);
6273 break;
6274 }
6275 }
6276
6277 // Map Continue back to Succeeded if we fell off the end of the loop.
6278 if (ESR == ESR_Continue)
6279 ESR = ESR_Succeeded;
6280
6281 return Scope.destroy() ? ESR : ESR_Failed;
6282 }
6283
6284 case Stmt::SwitchStmtClass:
6285 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
6286
6287 case Stmt::ContinueStmtClass:
6288 case Stmt::BreakStmtClass: {
6289 auto *B = cast<LoopControlStmt>(S);
6290 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
6291 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
6292 }
6293
6294 case Stmt::LabelStmtClass:
6295 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
6296
6297 case Stmt::AttributedStmtClass: {
6298 const auto *AS = cast<AttributedStmt>(S);
6299 const auto *SS = AS->getSubStmt();
6300 MSConstexprContextRAII ConstexprContext(
6301 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
6302 isa<ReturnStmt>(SS));
6303
6304 auto LO = Info.Ctx.getLangOpts();
6305 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6306 for (auto *Attr : AS->getAttrs()) {
6307 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6308 if (!AA)
6309 continue;
6310
6311 auto *Assumption = AA->getAssumption();
6312 if (Assumption->isValueDependent())
6313 return ESR_Failed;
6314
6315 if (Assumption->HasSideEffects(Info.Ctx))
6316 continue;
6317
6318 bool Value;
6319 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6320 return ESR_Failed;
6321 if (!Value) {
6322 Info.CCEDiag(Assumption->getExprLoc(),
6323 diag::note_constexpr_assumption_failed);
6324 return ESR_Failed;
6325 }
6326 }
6327 }
6328
6329 return EvaluateStmt(Result, Info, SS, Case);
6330 }
6331
6332 case Stmt::CaseStmtClass:
6333 case Stmt::DefaultStmtClass:
6334 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6335 case Stmt::CXXTryStmtClass:
6336 // Evaluate try blocks by evaluating all sub statements.
6337 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6338 }
6339}
6340
6341/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6342/// default constructor. If so, we'll fold it whether or not it's marked as
6343/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6344/// so we need special handling.
6345static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6346 const CXXConstructorDecl *CD,
6347 bool IsValueInitialization) {
6348 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6349 return false;
6350
6351 // Value-initialization does not call a trivial default constructor, so such a
6352 // call is a core constant expression whether or not the constructor is
6353 // constexpr.
6354 if (!CD->isConstexpr() && !IsValueInitialization) {
6355 if (Info.getLangOpts().CPlusPlus11) {
6356 // FIXME: If DiagDecl is an implicitly-declared special member function,
6357 // we should be much more explicit about why it's not constexpr.
6358 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6359 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6360 Info.Note(CD->getLocation(), diag::note_declared_at);
6361 } else {
6362 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6363 }
6364 }
6365 return true;
6366}
6367
6368/// CheckConstexprFunction - Check that a function can be called in a constant
6369/// expression.
6370static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6372 const FunctionDecl *Definition,
6373 const Stmt *Body) {
6374 // Potential constant expressions can contain calls to declared, but not yet
6375 // defined, constexpr functions.
6376 if (Info.checkingPotentialConstantExpression() && !Definition &&
6377 Declaration->isConstexpr())
6378 return false;
6379
6380 // Bail out if the function declaration itself is invalid. We will
6381 // have produced a relevant diagnostic while parsing it, so just
6382 // note the problematic sub-expression.
6383 if (Declaration->isInvalidDecl()) {
6384 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6385 return false;
6386 }
6387
6388 // DR1872: An instantiated virtual constexpr function can't be called in a
6389 // constant expression (prior to C++20). We can still constant-fold such a
6390 // call.
6391 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6392 cast<CXXMethodDecl>(Declaration)->isVirtual())
6393 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6394
6395 if (Definition && Definition->isInvalidDecl()) {
6396 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6397 return false;
6398 }
6399
6400 // Can we evaluate this function call?
6401 if (Definition && Body &&
6402 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6403 Definition->hasAttr<MSConstexprAttr>())))
6404 return true;
6405
6406 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6407 // Special note for the assert() macro, as the normal error message falsely
6408 // implies we cannot use an assertion during constant evaluation.
6409 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6410 // FIXME: Instead of checking for an implementation-defined function,
6411 // check and evaluate the assert() macro.
6412 StringRef Name = DiagDecl->getName();
6413 bool AssertFailed =
6414 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6415 if (AssertFailed) {
6416 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6417 return false;
6418 }
6419 }
6420
6421 if (Info.getLangOpts().CPlusPlus11) {
6422 // If this function is not constexpr because it is an inherited
6423 // non-constexpr constructor, diagnose that directly.
6424 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6425 if (CD && CD->isInheritingConstructor()) {
6426 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6427 if (!Inherited->isConstexpr())
6428 DiagDecl = CD = Inherited;
6429 }
6430
6431 // FIXME: If DiagDecl is an implicitly-declared special member function
6432 // or an inheriting constructor, we should be much more explicit about why
6433 // it's not constexpr.
6434 if (CD && CD->isInheritingConstructor())
6435 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6436 << CD->getInheritedConstructor().getConstructor()->getParent();
6437 else
6438 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6439 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6440 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6441 } else {
6442 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6443 }
6444 return false;
6445}
6446
6447namespace {
6448struct CheckDynamicTypeHandler {
6450 typedef bool result_type;
6451 bool failed() { return false; }
6452 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
6453 return true;
6454 }
6455 bool found(APSInt &Value, QualType SubobjType) { return true; }
6456 bool found(APFloat &Value, QualType SubobjType) { return true; }
6457};
6458} // end anonymous namespace
6459
6460/// Check that we can access the notional vptr of an object / determine its
6461/// dynamic type.
6462static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6463 AccessKinds AK, bool Polymorphic) {
6464 if (This.Designator.Invalid)
6465 return false;
6466
6467 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6468
6469 if (!Obj)
6470 return false;
6471
6472 if (!Obj.Value) {
6473 // The object is not usable in constant expressions, so we can't inspect
6474 // its value to see if it's in-lifetime or what the active union members
6475 // are. We can still check for a one-past-the-end lvalue.
6476 if (This.Designator.isOnePastTheEnd() ||
6477 This.Designator.isMostDerivedAnUnsizedArray()) {
6478 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6479 ? diag::note_constexpr_access_past_end
6480 : diag::note_constexpr_access_unsized_array)
6481 << AK;
6482 return false;
6483 } else if (Polymorphic) {
6484 // Conservatively refuse to perform a polymorphic operation if we would
6485 // not be able to read a notional 'vptr' value.
6486 if (!Info.checkingPotentialConstantExpression() ||
6487 !This.AllowConstexprUnknown) {
6488 APValue Val;
6489 This.moveInto(Val);
6490 QualType StarThisType =
6491 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6492 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6493 << AK << Val.getAsString(Info.Ctx, StarThisType);
6494 }
6495 return false;
6496 }
6497 return true;
6498 }
6499
6500 CheckDynamicTypeHandler Handler{AK};
6501 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6502}
6503
6504/// Check that the pointee of the 'this' pointer in a member function call is
6505/// either within its lifetime or in its period of construction or destruction.
6506static bool
6508 const LValue &This,
6509 const CXXMethodDecl *NamedMember) {
6510 return checkDynamicType(
6511 Info, E, This,
6512 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6513}
6514
6516 /// The dynamic class type of the object.
6518 /// The corresponding path length in the lvalue.
6519 unsigned PathLength;
6520};
6521
6522static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6523 unsigned PathLength) {
6524 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6525 Designator.Entries.size() && "invalid path length");
6526 return (PathLength == Designator.MostDerivedPathLength)
6527 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6528 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6529}
6530
6531/// Determine the dynamic type of an object.
6532static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6533 const Expr *E,
6534 LValue &This,
6535 AccessKinds AK) {
6536 // If we don't have an lvalue denoting an object of class type, there is no
6537 // meaningful dynamic type. (We consider objects of non-class type to have no
6538 // dynamic type.)
6539 if (!checkDynamicType(Info, E, This, AK,
6540 AK != AK_TypeId || This.AllowConstexprUnknown))
6541 return std::nullopt;
6542
6543 if (This.Designator.Invalid)
6544 return std::nullopt;
6545
6546 // Refuse to compute a dynamic type in the presence of virtual bases. This
6547 // shouldn't happen other than in constant-folding situations, since literal
6548 // types can't have virtual bases.
6549 //
6550 // Note that consumers of DynamicType assume that the type has no virtual
6551 // bases, and will need modifications if this restriction is relaxed.
6552 const CXXRecordDecl *Class =
6553 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6554 if (!Class || Class->getNumVBases()) {
6555 Info.FFDiag(E);
6556 return std::nullopt;
6557 }
6558
6559 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6560 // binary search here instead. But the overwhelmingly common case is that
6561 // we're not in the middle of a constructor, so it probably doesn't matter
6562 // in practice.
6563 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6564 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6565 PathLength <= Path.size(); ++PathLength) {
6566 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6567 Path.slice(0, PathLength))) {
6568 case ConstructionPhase::Bases:
6569 case ConstructionPhase::DestroyingBases:
6570 // We're constructing or destroying a base class. This is not the dynamic
6571 // type.
6572 break;
6573
6574 case ConstructionPhase::None:
6575 case ConstructionPhase::AfterBases:
6576 case ConstructionPhase::AfterFields:
6577 case ConstructionPhase::Destroying:
6578 // We've finished constructing the base classes and not yet started
6579 // destroying them again, so this is the dynamic type.
6580 return DynamicType{getBaseClassType(This.Designator, PathLength),
6581 PathLength};
6582 }
6583 }
6584
6585 // CWG issue 1517: we're constructing a base class of the object described by
6586 // 'This', so that object has not yet begun its period of construction and
6587 // any polymorphic operation on it results in undefined behavior.
6588 Info.FFDiag(E);
6589 return std::nullopt;
6590}
6591
6592/// Perform virtual dispatch.
6594 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6595 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6596 std::optional<DynamicType> DynType = ComputeDynamicType(
6597 Info, E, This,
6599 if (!DynType)
6600 return nullptr;
6601
6602 // Find the final overrider. It must be declared in one of the classes on the
6603 // path from the dynamic type to the static type.
6604 // FIXME: If we ever allow literal types to have virtual base classes, that
6605 // won't be true.
6606 const CXXMethodDecl *Callee = Found;
6607 unsigned PathLength = DynType->PathLength;
6608 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6609 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6610 const CXXMethodDecl *Overrider =
6611 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6612 if (Overrider) {
6613 Callee = Overrider;
6614 break;
6615 }
6616 }
6617
6618 // C++2a [class.abstract]p6:
6619 // the effect of making a virtual call to a pure virtual function [...] is
6620 // undefined
6621 if (Callee->isPureVirtual()) {
6622 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6623 Info.Note(Callee->getLocation(), diag::note_declared_at);
6624 return nullptr;
6625 }
6626
6627 // If necessary, walk the rest of the path to determine the sequence of
6628 // covariant adjustment steps to apply.
6629 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6630 Found->getReturnType())) {
6631 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6632 for (unsigned CovariantPathLength = PathLength + 1;
6633 CovariantPathLength != This.Designator.Entries.size();
6634 ++CovariantPathLength) {
6635 const CXXRecordDecl *NextClass =
6636 getBaseClassType(This.Designator, CovariantPathLength);
6637 const CXXMethodDecl *Next =
6638 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6639 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6640 Next->getReturnType(), CovariantAdjustmentPath.back()))
6641 CovariantAdjustmentPath.push_back(Next->getReturnType());
6642 }
6643 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6644 CovariantAdjustmentPath.back()))
6645 CovariantAdjustmentPath.push_back(Found->getReturnType());
6646 }
6647
6648 // Perform 'this' adjustment.
6649 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6650 return nullptr;
6651
6652 return Callee;
6653}
6654
6655/// Perform the adjustment from a value returned by a virtual function to
6656/// a value of the statically expected type, which may be a pointer or
6657/// reference to a base class of the returned type.
6658static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6659 APValue &Result,
6660 ArrayRef<QualType> Path) {
6661 assert(Result.isLValue() &&
6662 "unexpected kind of APValue for covariant return");
6663 if (Result.isNullPointer())
6664 return true;
6665
6666 LValue LVal;
6667 LVal.setFrom(Info.Ctx, Result);
6668
6669 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6670 for (unsigned I = 1; I != Path.size(); ++I) {
6671 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6672 assert(OldClass && NewClass && "unexpected kind of covariant return");
6673 if (OldClass != NewClass &&
6674 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6675 return false;
6676 OldClass = NewClass;
6677 }
6678
6679 LVal.moveInto(Result);
6680 return true;
6681}
6682
6683/// Determine whether \p Base, which is known to be a direct base class of
6684/// \p Derived, is a public base class.
6685static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6686 const CXXRecordDecl *Base) {
6687 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6688 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6689 if (BaseClass && declaresSameEntity(BaseClass, Base))
6690 return BaseSpec.getAccessSpecifier() == AS_public;
6691 }
6692 llvm_unreachable("Base is not a direct base of Derived");
6693}
6694
6695/// Apply the given dynamic cast operation on the provided lvalue.
6696///
6697/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6698/// to find a suitable target subobject.
6699static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6700 LValue &Ptr) {
6701 // We can't do anything with a non-symbolic pointer value.
6702 SubobjectDesignator &D = Ptr.Designator;
6703 if (D.Invalid)
6704 return false;
6705
6706 // C++ [expr.dynamic.cast]p6:
6707 // If v is a null pointer value, the result is a null pointer value.
6708 if (Ptr.isNullPointer() && !E->isGLValue())
6709 return true;
6710
6711 // For all the other cases, we need the pointer to point to an object within
6712 // its lifetime / period of construction / destruction, and we need to know
6713 // its dynamic type.
6714 std::optional<DynamicType> DynType =
6715 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6716 if (!DynType)
6717 return false;
6718
6719 // C++ [expr.dynamic.cast]p7:
6720 // If T is "pointer to cv void", then the result is a pointer to the most
6721 // derived object
6722 if (E->getType()->isVoidPointerType())
6723 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6724
6726 assert(C && "dynamic_cast target is not void pointer nor class");
6727 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6728
6729 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6730 // C++ [expr.dynamic.cast]p9:
6731 if (!E->isGLValue()) {
6732 // The value of a failed cast to pointer type is the null pointer value
6733 // of the required result type.
6734 Ptr.setNull(Info.Ctx, E->getType());
6735 return true;
6736 }
6737
6738 // A failed cast to reference type throws [...] std::bad_cast.
6739 unsigned DiagKind;
6740 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6741 DynType->Type->isDerivedFrom(C)))
6742 DiagKind = 0;
6743 else if (!Paths || Paths->begin() == Paths->end())
6744 DiagKind = 1;
6745 else if (Paths->isAmbiguous(CQT))
6746 DiagKind = 2;
6747 else {
6748 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6749 DiagKind = 3;
6750 }
6751 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6752 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6753 << Info.Ctx.getCanonicalTagType(DynType->Type)
6754 << E->getType().getUnqualifiedType();
6755 return false;
6756 };
6757
6758 // Runtime check, phase 1:
6759 // Walk from the base subobject towards the derived object looking for the
6760 // target type.
6761 for (int PathLength = Ptr.Designator.Entries.size();
6762 PathLength >= (int)DynType->PathLength; --PathLength) {
6763 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6764 if (declaresSameEntity(Class, C))
6765 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6766 // We can only walk across public inheritance edges.
6767 if (PathLength > (int)DynType->PathLength &&
6768 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6769 Class))
6770 return RuntimeCheckFailed(nullptr);
6771 }
6772
6773 // Runtime check, phase 2:
6774 // Search the dynamic type for an unambiguous public base of type C.
6775 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6776 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6777 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6778 Paths.front().Access == AS_public) {
6779 // Downcast to the dynamic type...
6780 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6781 return false;
6782 // ... then upcast to the chosen base class subobject.
6783 for (CXXBasePathElement &Elem : Paths.front())
6784 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6785 return false;
6786 return true;
6787 }
6788
6789 // Otherwise, the runtime check fails.
6790 return RuntimeCheckFailed(&Paths);
6791}
6792
6793namespace {
6794struct StartLifetimeOfUnionMemberHandler {
6795 EvalInfo &Info;
6796 const Expr *LHSExpr;
6797 const FieldDecl *Field;
6798 bool DuringInit;
6799 bool Failed = false;
6800 static const AccessKinds AccessKind = AK_Assign;
6801
6802 typedef bool result_type;
6803 bool failed() { return Failed; }
6804 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
6805 // We are supposed to perform no initialization but begin the lifetime of
6806 // the object. We interpret that as meaning to do what default
6807 // initialization of the object would do if all constructors involved were
6808 // trivial:
6809 // * All base, non-variant member, and array element subobjects' lifetimes
6810 // begin
6811 // * No variant members' lifetimes begin
6812 // * All scalar subobjects whose lifetimes begin have indeterminate values
6813 assert(SubobjType->isUnionType());
6814 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6815 // This union member is already active. If it's also in-lifetime, there's
6816 // nothing to do.
6817 if (Subobj.getUnionValue().hasValue())
6818 return true;
6819 } else if (DuringInit) {
6820 // We're currently in the process of initializing a different union
6821 // member. If we carried on, that initialization would attempt to
6822 // store to an inactive union member, resulting in undefined behavior.
6823 Info.FFDiag(LHSExpr,
6824 diag::note_constexpr_union_member_change_during_init);
6825 return false;
6826 }
6828 Failed = !handleDefaultInitValue(Field->getType(), Result);
6829 Subobj.setUnion(Field, Result);
6830 return true;
6831 }
6832 bool found(APSInt &Value, QualType SubobjType) {
6833 llvm_unreachable("wrong value kind for union object");
6834 }
6835 bool found(APFloat &Value, QualType SubobjType) {
6836 llvm_unreachable("wrong value kind for union object");
6837 }
6838};
6839} // end anonymous namespace
6840
6841const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6842
6843/// Handle a builtin simple-assignment or a call to a trivial assignment
6844/// operator whose left-hand side might involve a union member access. If it
6845/// does, implicitly start the lifetime of any accessed union elements per
6846/// C++20 [class.union]5.
6847static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6848 const Expr *LHSExpr,
6849 const LValue &LHS) {
6850 if (LHS.InvalidBase || LHS.Designator.Invalid)
6851 return false;
6852
6854 // C++ [class.union]p5:
6855 // define the set S(E) of subexpressions of E as follows:
6856 unsigned PathLength = LHS.Designator.Entries.size();
6857 for (const Expr *E = LHSExpr; E != nullptr;) {
6858 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6859 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6860 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6861 // Note that we can't implicitly start the lifetime of a reference,
6862 // so we don't need to proceed any further if we reach one.
6863 if (!FD || FD->getType()->isReferenceType())
6864 break;
6865
6866 // ... and also contains A.B if B names a union member ...
6867 if (FD->getParent()->isUnion()) {
6868 // ... of a non-class, non-array type, or of a class type with a
6869 // trivial default constructor that is not deleted, or an array of
6870 // such types.
6871 auto *RD =
6872 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6873 if (!RD || RD->hasTrivialDefaultConstructor())
6874 UnionPathLengths.push_back({PathLength - 1, FD});
6875 }
6876
6877 E = ME->getBase();
6878 --PathLength;
6879 assert(declaresSameEntity(FD,
6880 LHS.Designator.Entries[PathLength]
6881 .getAsBaseOrMember().getPointer()));
6882
6883 // -- If E is of the form A[B] and is interpreted as a built-in array
6884 // subscripting operator, S(E) is [S(the array operand, if any)].
6885 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6886 // Step over an ArrayToPointerDecay implicit cast.
6887 auto *Base = ASE->getBase()->IgnoreImplicit();
6888 if (!Base->getType()->isArrayType())
6889 break;
6890
6891 E = Base;
6892 --PathLength;
6893
6894 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6895 // Step over a derived-to-base conversion.
6896 E = ICE->getSubExpr();
6897 if (ICE->getCastKind() == CK_NoOp)
6898 continue;
6899 if (ICE->getCastKind() != CK_DerivedToBase &&
6900 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6901 break;
6902 // Walk path backwards as we walk up from the base to the derived class.
6903 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6904 if (Elt->isVirtual()) {
6905 // A class with virtual base classes never has a trivial default
6906 // constructor, so S(E) is empty in this case.
6907 E = nullptr;
6908 break;
6909 }
6910
6911 --PathLength;
6912 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6913 LHS.Designator.Entries[PathLength]
6914 .getAsBaseOrMember().getPointer()));
6915 }
6916
6917 // -- Otherwise, S(E) is empty.
6918 } else {
6919 break;
6920 }
6921 }
6922
6923 // Common case: no unions' lifetimes are started.
6924 if (UnionPathLengths.empty())
6925 return true;
6926
6927 // if modification of X [would access an inactive union member], an object
6928 // of the type of X is implicitly created
6929 CompleteObject Obj =
6930 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6931 if (!Obj)
6932 return false;
6933 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6934 llvm::reverse(UnionPathLengths)) {
6935 // Form a designator for the union object.
6936 SubobjectDesignator D = LHS.Designator;
6937 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6938
6939 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6940 ConstructionPhase::AfterBases;
6941 StartLifetimeOfUnionMemberHandler StartLifetime{
6942 Info, LHSExpr, LengthAndField.second, DuringInit};
6943 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6944 return false;
6945 }
6946
6947 return true;
6948}
6949
6950static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6951 CallRef Call, EvalInfo &Info, bool NonNull = false,
6952 APValue **EvaluatedArg = nullptr) {
6953 LValue LV;
6954 // Create the parameter slot and register its destruction. For a vararg
6955 // argument, create a temporary.
6956 // FIXME: For calling conventions that destroy parameters in the callee,
6957 // should we consider performing destruction when the function returns
6958 // instead?
6959 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6960 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6961 ScopeKind::Call, LV);
6962 if (!EvaluateInPlace(V, Info, LV, Arg))
6963 return false;
6964
6965 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6966 // undefined behavior, so is non-constant.
6967 if (NonNull && V.isLValue() && V.isNullPointer()) {
6968 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6969 return false;
6970 }
6971
6972 if (EvaluatedArg)
6973 *EvaluatedArg = &V;
6974
6975 return true;
6976}
6977
6978/// Evaluate the arguments to a function call.
6979static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6980 EvalInfo &Info, const FunctionDecl *Callee,
6981 bool RightToLeft = false,
6982 LValue *ObjectArg = nullptr) {
6983 bool Success = true;
6984 llvm::SmallBitVector ForbiddenNullArgs;
6985 if (Callee->hasAttr<NonNullAttr>()) {
6986 ForbiddenNullArgs.resize(Args.size());
6987 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6988 if (!Attr->args_size()) {
6989 ForbiddenNullArgs.set();
6990 break;
6991 } else
6992 for (auto Idx : Attr->args()) {
6993 unsigned ASTIdx = Idx.getASTIndex();
6994 if (ASTIdx >= Args.size())
6995 continue;
6996 ForbiddenNullArgs[ASTIdx] = true;
6997 }
6998 }
6999 }
7000 for (unsigned I = 0; I < Args.size(); I++) {
7001 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
7002 const ParmVarDecl *PVD =
7003 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
7004 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
7005 APValue *That = nullptr;
7006 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
7007 // If we're checking for a potential constant expression, evaluate all
7008 // initializers even if some of them fail.
7009 if (!Info.noteFailure())
7010 return false;
7011 Success = false;
7012 }
7013 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
7014 ObjectArg->setFrom(Info.Ctx, *That);
7015 }
7016 return Success;
7017}
7018
7019/// Perform a trivial copy from Param, which is the parameter of a copy or move
7020/// constructor or assignment operator.
7021static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
7022 const Expr *E, APValue &Result,
7023 bool CopyObjectRepresentation) {
7024 // Find the reference argument.
7025 CallStackFrame *Frame = Info.CurrentCall;
7026 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
7027 if (!RefValue) {
7028 Info.FFDiag(E);
7029 return false;
7030 }
7031
7032 // Copy out the contents of the RHS object.
7033 LValue RefLValue;
7034 RefLValue.setFrom(Info.Ctx, *RefValue);
7036 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
7037 CopyObjectRepresentation);
7038}
7039
7040/// Evaluate a function call.
7042 const FunctionDecl *Callee,
7043 const LValue *ObjectArg, const Expr *E,
7044 ArrayRef<const Expr *> Args, CallRef Call,
7045 const Stmt *Body, EvalInfo &Info,
7046 APValue &Result, const LValue *ResultSlot) {
7047 if (!Info.CheckCallLimit(CallLoc))
7048 return false;
7049
7050 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
7051
7052 // For a trivial copy or move assignment, perform an APValue copy. This is
7053 // essential for unions, where the operations performed by the assignment
7054 // operator cannot be represented as statements.
7055 //
7056 // Skip this for non-union classes with no fields; in that case, the defaulted
7057 // copy/move does not actually read the object.
7058 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
7059
7060 auto IsTrivialMemoryOperation = [&](const CXXMethodDecl *MD) {
7061 if (!MD || !MD->isDefaulted())
7062 return false;
7064 return false;
7065 return MD->getParent()->isUnion() ||
7066 (MD->isTrivial() &&
7068 };
7069
7070 if (IsTrivialMemoryOperation(MD)) {
7071 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
7072 assert(ObjectArg);
7073 APValue RHSValue;
7074 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
7075 MD->getParent()->isUnion()))
7076 return false;
7077
7078 LValue Obj;
7079 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
7081 RHSValue))
7082 return false;
7083 ObjectArg->moveInto(Result);
7084 return true;
7085 } else if (MD && isLambdaCallOperator(MD)) {
7086 // We're in a lambda; determine the lambda capture field maps unless we're
7087 // just constexpr checking a lambda's call operator. constexpr checking is
7088 // done before the captures have been added to the closure object (unless
7089 // we're inferring constexpr-ness), so we don't have access to them in this
7090 // case. But since we don't need the captures to constexpr check, we can
7091 // just ignore them.
7092 if (!Info.checkingPotentialConstantExpression())
7093 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
7094 Frame.LambdaThisCaptureField);
7095 }
7096
7097 StmtResult Ret = {Result, ResultSlot};
7098 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
7099 if (ESR == ESR_Succeeded) {
7100 if (Callee->getReturnType()->isVoidType())
7101 return true;
7102 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7103 }
7104 return ESR == ESR_Returned;
7105}
7106
7107/// Evaluate a constructor call.
7108static bool HandleConstructorCall(const Expr *E, const LValue &This,
7109 CallRef Call,
7111 EvalInfo &Info, APValue &Result) {
7112 SourceLocation CallLoc = E->getExprLoc();
7113 if (!Info.CheckCallLimit(CallLoc))
7114 return false;
7115
7116 const CXXRecordDecl *RD = Definition->getParent();
7117 if (RD->getNumVBases()) {
7118 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7119 return false;
7120 }
7121
7122 EvalInfo::EvaluatingConstructorRAII EvalObj(
7123 Info,
7124 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7125 RD->getNumBases());
7126 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
7127
7128 // FIXME: Creating an APValue just to hold a nonexistent return value is
7129 // wasteful.
7130 APValue RetVal;
7131 StmtResult Ret = {RetVal, nullptr};
7132
7133 // If it's a delegating constructor, delegate.
7134 if (Definition->isDelegatingConstructor()) {
7136 if ((*I)->getInit()->isValueDependent()) {
7137 if (!EvaluateDependentExpr((*I)->getInit(), Info))
7138 return false;
7139 } else {
7140 FullExpressionRAII InitScope(Info);
7141 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
7142 !InitScope.destroy())
7143 return false;
7144 }
7145 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
7146 }
7147
7148 // For a trivial copy or move constructor, perform an APValue copy. This is
7149 // essential for unions (or classes with anonymous union members), where the
7150 // operations performed by the constructor cannot be represented by
7151 // ctor-initializers.
7152 //
7153 // Skip this for empty non-union classes; we should not perform an
7154 // lvalue-to-rvalue conversion on them because their copy constructor does not
7155 // actually read them.
7156 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
7157 (Definition->getParent()->isUnion() ||
7158 (Definition->isTrivial() &&
7160 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
7161 Definition->getParent()->isUnion());
7162 }
7163
7164 // Reserve space for the struct members.
7165 if (!Result.hasValue()) {
7166 if (!RD->isUnion())
7168 RD->getNumFields());
7169 else
7170 // A union starts with no active member.
7171 Result = APValue((const FieldDecl*)nullptr);
7172 }
7173
7174 if (RD->isInvalidDecl()) return false;
7175 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7176
7177 // A scope for temporaries lifetime-extended by reference members.
7178 BlockScopeRAII LifetimeExtendedScope(Info);
7179
7180 bool Success = true;
7181 unsigned BasesSeen = 0;
7182#ifndef NDEBUG
7184#endif
7186 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
7187 // We might be initializing the same field again if this is an indirect
7188 // field initialization.
7189 if (FieldIt == RD->field_end() ||
7190 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
7191 assert(Indirect && "fields out of order?");
7192 return;
7193 }
7194
7195 // Default-initialize any fields with no explicit initializer.
7196 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
7197 assert(FieldIt != RD->field_end() && "missing field?");
7198 if (!FieldIt->isUnnamedBitField())
7200 FieldIt->getType(),
7201 Result.getStructField(FieldIt->getFieldIndex()));
7202 }
7203 ++FieldIt;
7204 };
7205 for (const auto *I : Definition->inits()) {
7206 LValue Subobject = This;
7207 LValue SubobjectParent = This;
7208 APValue *Value = &Result;
7209
7210 // Determine the subobject to initialize.
7211 FieldDecl *FD = nullptr;
7212 if (I->isBaseInitializer()) {
7213 QualType BaseType(I->getBaseClass(), 0);
7214#ifndef NDEBUG
7215 // Non-virtual base classes are initialized in the order in the class
7216 // definition. We have already checked for virtual base classes.
7217 assert(!BaseIt->isVirtual() && "virtual base for literal type");
7218 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
7219 "base class initializers not in expected order");
7220 ++BaseIt;
7221#endif
7222 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
7223 BaseType->getAsCXXRecordDecl(), &Layout))
7224 return false;
7225 Value = &Result.getStructBase(BasesSeen++);
7226 } else if ((FD = I->getMember())) {
7227 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
7228 return false;
7229 if (RD->isUnion()) {
7230 Result = APValue(FD);
7231 Value = &Result.getUnionValue();
7232 } else {
7233 SkipToField(FD, false);
7234 Value = &Result.getStructField(FD->getFieldIndex());
7235 }
7236 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
7237 // Walk the indirect field decl's chain to find the object to initialize,
7238 // and make sure we've initialized every step along it.
7239 auto IndirectFieldChain = IFD->chain();
7240 for (auto *C : IndirectFieldChain) {
7241 FD = cast<FieldDecl>(C);
7243 // Switch the union field if it differs. This happens if we had
7244 // preceding zero-initialization, and we're now initializing a union
7245 // subobject other than the first.
7246 // FIXME: In this case, the values of the other subobjects are
7247 // specified, since zero-initialization sets all padding bits to zero.
7248 if (!Value->hasValue() ||
7249 (Value->isUnion() &&
7250 !declaresSameEntity(Value->getUnionField(), FD))) {
7251 if (CD->isUnion())
7252 *Value = APValue(FD);
7253 else
7254 // FIXME: This immediately starts the lifetime of all members of
7255 // an anonymous struct. It would be preferable to strictly start
7256 // member lifetime in initialization order.
7257 Success &= handleDefaultInitValue(Info.Ctx.getCanonicalTagType(CD),
7258 *Value);
7259 }
7260 // Store Subobject as its parent before updating it for the last element
7261 // in the chain.
7262 if (C == IndirectFieldChain.back())
7263 SubobjectParent = Subobject;
7264 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
7265 return false;
7266 if (CD->isUnion())
7267 Value = &Value->getUnionValue();
7268 else {
7269 if (C == IndirectFieldChain.front() && !RD->isUnion())
7270 SkipToField(FD, true);
7271 Value = &Value->getStructField(FD->getFieldIndex());
7272 }
7273 }
7274 } else {
7275 llvm_unreachable("unknown base initializer kind");
7276 }
7277
7278 // Need to override This for implicit field initializers as in this case
7279 // This refers to innermost anonymous struct/union containing initializer,
7280 // not to currently constructed class.
7281 const Expr *Init = I->getInit();
7282 if (Init->isValueDependent()) {
7283 if (!EvaluateDependentExpr(Init, Info))
7284 return false;
7285 } else {
7286 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7288 FullExpressionRAII InitScope(Info);
7289 if (FD && FD->getType()->isReferenceType() &&
7290 !FD->getType()->isFunctionReferenceType()) {
7291 LValue Result;
7293 *Value)) {
7294 if (!Info.noteFailure())
7295 return false;
7296 Success = false;
7297 }
7298 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
7299 (FD && FD->isBitField() &&
7300 !truncateBitfieldValue(Info, Init, *Value, FD))) {
7301 // If we're checking for a potential constant expression, evaluate all
7302 // initializers even if some of them fail.
7303 if (!Info.noteFailure())
7304 return false;
7305 Success = false;
7306 }
7307 }
7308
7309 // This is the point at which the dynamic type of the object becomes this
7310 // class type.
7311 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
7312 EvalObj.finishedConstructingBases();
7313 }
7314
7315 // Default-initialize any remaining fields.
7316 if (!RD->isUnion()) {
7317 for (; FieldIt != RD->field_end(); ++FieldIt) {
7318 if (!FieldIt->isUnnamedBitField())
7320 FieldIt->getType(),
7321 Result.getStructField(FieldIt->getFieldIndex()));
7322 }
7323 }
7324
7325 EvalObj.finishedConstructingFields();
7326
7327 return Success &&
7328 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7329 LifetimeExtendedScope.destroy();
7330}
7331
7332static bool HandleConstructorCall(const Expr *E, const LValue &This,
7335 EvalInfo &Info, APValue &Result) {
7336 CallScopeRAII CallScope(Info);
7337 CallRef Call = Info.CurrentCall->createCall(Definition);
7338 if (!EvaluateArgs(Args, Call, Info, Definition))
7339 return false;
7340
7341 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
7342 CallScope.destroy();
7343}
7344
7345static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7346 const LValue &This, APValue &Value,
7347 QualType T) {
7348 // Objects can only be destroyed while they're within their lifetimes.
7349 // FIXME: We have no representation for whether an object of type nullptr_t
7350 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7351 // as indeterminate instead?
7352 if (Value.isAbsent() && !T->isNullPtrType()) {
7353 APValue Printable;
7354 This.moveInto(Printable);
7355 Info.FFDiag(CallRange.getBegin(),
7356 diag::note_constexpr_destroy_out_of_lifetime)
7357 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7358 return false;
7359 }
7360
7361 // Invent an expression for location purposes.
7362 // FIXME: We shouldn't need to do this.
7363 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7364
7365 // For arrays, destroy elements right-to-left.
7366 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7367 uint64_t Size = CAT->getZExtSize();
7368 QualType ElemT = CAT->getElementType();
7369
7370 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7371 return false;
7372
7373 LValue ElemLV = This;
7374 ElemLV.addArray(Info, &LocE, CAT);
7375 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7376 return false;
7377
7378 // Ensure that we have actual array elements available to destroy; the
7379 // destructors might mutate the value, so we can't run them on the array
7380 // filler.
7381 if (Size && Size > Value.getArrayInitializedElts())
7382 expandArray(Value, Value.getArraySize() - 1);
7383
7384 // The size of the array might have been reduced by
7385 // a placement new.
7386 for (Size = Value.getArraySize(); Size != 0; --Size) {
7387 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7388 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7389 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7390 return false;
7391 }
7392
7393 // End the lifetime of this array now.
7394 Value = APValue();
7395 return true;
7396 }
7397
7398 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7399 if (!RD) {
7400 if (T.isDestructedType()) {
7401 Info.FFDiag(CallRange.getBegin(),
7402 diag::note_constexpr_unsupported_destruction)
7403 << T;
7404 return false;
7405 }
7406
7407 Value = APValue();
7408 return true;
7409 }
7410
7411 if (RD->getNumVBases()) {
7412 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7413 return false;
7414 }
7415
7416 const CXXDestructorDecl *DD = RD->getDestructor();
7417 if (!DD && !RD->hasTrivialDestructor()) {
7418 Info.FFDiag(CallRange.getBegin());
7419 return false;
7420 }
7421
7422 if (!DD || DD->isTrivial() ||
7423 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
7424 // A trivial destructor just ends the lifetime of the object. Check for
7425 // this case before checking for a body, because we might not bother
7426 // building a body for a trivial destructor. Note that it doesn't matter
7427 // whether the destructor is constexpr in this case; all trivial
7428 // destructors are constexpr.
7429 //
7430 // If an anonymous union would be destroyed, some enclosing destructor must
7431 // have been explicitly defined, and the anonymous union destruction should
7432 // have no effect.
7433 Value = APValue();
7434 return true;
7435 }
7436
7437 if (!Info.CheckCallLimit(CallRange.getBegin()))
7438 return false;
7439
7440 const FunctionDecl *Definition = nullptr;
7441 const Stmt *Body = DD->getBody(Definition);
7442
7443 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7444 return false;
7445
7446 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7447 CallRef());
7448
7449 // We're now in the period of destruction of this object.
7450 unsigned BasesLeft = RD->getNumBases();
7451 EvalInfo::EvaluatingDestructorRAII EvalObj(
7452 Info,
7453 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7454 if (!EvalObj.DidInsert) {
7455 // C++2a [class.dtor]p19:
7456 // the behavior is undefined if the destructor is invoked for an object
7457 // whose lifetime has ended
7458 // (Note that formally the lifetime ends when the period of destruction
7459 // begins, even though certain uses of the object remain valid until the
7460 // period of destruction ends.)
7461 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7462 return false;
7463 }
7464
7465 // FIXME: Creating an APValue just to hold a nonexistent return value is
7466 // wasteful.
7467 APValue RetVal;
7468 StmtResult Ret = {RetVal, nullptr};
7469 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7470 return false;
7471
7472 // A union destructor does not implicitly destroy its members.
7473 if (RD->isUnion())
7474 return true;
7475
7476 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7477
7478 // We don't have a good way to iterate fields in reverse, so collect all the
7479 // fields first and then walk them backwards.
7480 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7481 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7482 if (FD->isUnnamedBitField())
7483 continue;
7484
7485 LValue Subobject = This;
7486 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7487 return false;
7488
7489 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7490 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7491 FD->getType()))
7492 return false;
7493 }
7494
7495 if (BasesLeft != 0)
7496 EvalObj.startedDestroyingBases();
7497
7498 // Destroy base classes in reverse order.
7499 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7500 --BasesLeft;
7501
7502 QualType BaseType = Base.getType();
7503 LValue Subobject = This;
7504 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7505 BaseType->getAsCXXRecordDecl(), &Layout))
7506 return false;
7507
7508 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7509 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7510 BaseType))
7511 return false;
7512 }
7513 assert(BasesLeft == 0 && "NumBases was wrong?");
7514
7515 // The period of destruction ends now. The object is gone.
7516 Value = APValue();
7517 return true;
7518}
7519
7520namespace {
7521struct DestroyObjectHandler {
7522 EvalInfo &Info;
7523 const Expr *E;
7524 const LValue &This;
7525 const AccessKinds AccessKind;
7526
7527 typedef bool result_type;
7528 bool failed() { return false; }
7529 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
7530 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7531 SubobjType);
7532 }
7533 bool found(APSInt &Value, QualType SubobjType) {
7534 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7535 return false;
7536 }
7537 bool found(APFloat &Value, QualType SubobjType) {
7538 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7539 return false;
7540 }
7541};
7542}
7543
7544/// Perform a destructor or pseudo-destructor call on the given object, which
7545/// might in general not be a complete object.
7546static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7547 const LValue &This, QualType ThisType) {
7548 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7549 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7550 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7551}
7552
7553/// Destroy and end the lifetime of the given complete object.
7554static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7556 QualType T) {
7557 // If we've had an unmodeled side-effect, we can't rely on mutable state
7558 // (such as the object we're about to destroy) being correct.
7559 if (Info.EvalStatus.HasSideEffects)
7560 return false;
7561
7562 LValue LV;
7563 LV.set({LVBase});
7564 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7565}
7566
7567/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7568static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7569 LValue &Result) {
7570 if (Info.checkingPotentialConstantExpression() ||
7571 Info.SpeculativeEvaluationDepth)
7572 return false;
7573
7574 // This is permitted only within a call to std::allocator<T>::allocate.
7575 auto Caller = Info.getStdAllocatorCaller("allocate");
7576 if (!Caller) {
7577 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7578 ? diag::note_constexpr_new_untyped
7579 : diag::note_constexpr_new);
7580 return false;
7581 }
7582
7583 QualType ElemType = Caller.ElemType;
7584 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7585 Info.FFDiag(E->getExprLoc(),
7586 diag::note_constexpr_new_not_complete_object_type)
7587 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7588 return false;
7589 }
7590
7591 APSInt ByteSize;
7592 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7593 return false;
7594 bool IsNothrow = false;
7595 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7596 EvaluateIgnoredValue(Info, E->getArg(I));
7597 IsNothrow |= E->getType()->isNothrowT();
7598 }
7599
7600 CharUnits ElemSize;
7601 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7602 return false;
7603 APInt Size, Remainder;
7604 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7605 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7606 if (Remainder != 0) {
7607 // This likely indicates a bug in the implementation of 'std::allocator'.
7608 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7609 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7610 return false;
7611 }
7612
7613 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7614 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7615 if (IsNothrow) {
7616 Result.setNull(Info.Ctx, E->getType());
7617 return true;
7618 }
7619 return false;
7620 }
7621
7622 QualType AllocType = Info.Ctx.getConstantArrayType(
7623 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7624 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7625 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7626 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7627 return true;
7628}
7629
7631 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7632 if (CXXDestructorDecl *DD = RD->getDestructor())
7633 return DD->isVirtual();
7634 return false;
7635}
7636
7638 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7639 if (CXXDestructorDecl *DD = RD->getDestructor())
7640 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7641 return nullptr;
7642}
7643
7644/// Check that the given object is a suitable pointer to a heap allocation that
7645/// still exists and is of the right kind for the purpose of a deletion.
7646///
7647/// On success, returns the heap allocation to deallocate. On failure, produces
7648/// a diagnostic and returns std::nullopt.
7649static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7650 const LValue &Pointer,
7651 DynAlloc::Kind DeallocKind) {
7652 auto PointerAsString = [&] {
7653 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7654 };
7655
7656 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7657 if (!DA) {
7658 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7659 << PointerAsString();
7660 if (Pointer.Base)
7661 NoteLValueLocation(Info, Pointer.Base);
7662 return std::nullopt;
7663 }
7664
7665 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7666 if (!Alloc) {
7667 Info.FFDiag(E, diag::note_constexpr_double_delete);
7668 return std::nullopt;
7669 }
7670
7671 if (DeallocKind != (*Alloc)->getKind()) {
7672 QualType AllocType = Pointer.Base.getDynamicAllocType();
7673 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7674 << DeallocKind << (*Alloc)->getKind() << AllocType;
7675 NoteLValueLocation(Info, Pointer.Base);
7676 return std::nullopt;
7677 }
7678
7679 bool Subobject = false;
7680 if (DeallocKind == DynAlloc::New) {
7681 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7682 Pointer.Designator.isOnePastTheEnd();
7683 } else {
7684 Subobject = Pointer.Designator.Entries.size() != 1 ||
7685 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7686 }
7687 if (Subobject) {
7688 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7689 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7690 return std::nullopt;
7691 }
7692
7693 return Alloc;
7694}
7695
7696// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7697static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7698 if (Info.checkingPotentialConstantExpression() ||
7699 Info.SpeculativeEvaluationDepth)
7700 return false;
7701
7702 // This is permitted only within a call to std::allocator<T>::deallocate.
7703 if (!Info.getStdAllocatorCaller("deallocate")) {
7704 Info.FFDiag(E->getExprLoc());
7705 return true;
7706 }
7707
7708 LValue Pointer;
7709 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7710 return false;
7711 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7712 EvaluateIgnoredValue(Info, E->getArg(I));
7713
7714 if (Pointer.Designator.Invalid)
7715 return false;
7716
7717 // Deleting a null pointer would have no effect, but it's not permitted by
7718 // std::allocator<T>::deallocate's contract.
7719 if (Pointer.isNullPointer()) {
7720 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7721 return true;
7722 }
7723
7724 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7725 return false;
7726
7727 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7728 return true;
7729}
7730
7731//===----------------------------------------------------------------------===//
7732// Generic Evaluation
7733//===----------------------------------------------------------------------===//
7734namespace {
7735
7736class BitCastBuffer {
7737 // FIXME: We're going to need bit-level granularity when we support
7738 // bit-fields.
7739 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7740 // we don't support a host or target where that is the case. Still, we should
7741 // use a more generic type in case we ever do.
7742 SmallVector<std::optional<unsigned char>, 32> Bytes;
7743
7744 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7745 "Need at least 8 bit unsigned char");
7746
7747 bool TargetIsLittleEndian;
7748
7749public:
7750 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7751 : Bytes(Width.getQuantity()),
7752 TargetIsLittleEndian(TargetIsLittleEndian) {}
7753
7754 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7755 SmallVectorImpl<unsigned char> &Output) const {
7756 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7757 // If a byte of an integer is uninitialized, then the whole integer is
7758 // uninitialized.
7759 if (!Bytes[I.getQuantity()])
7760 return false;
7761 Output.push_back(*Bytes[I.getQuantity()]);
7762 }
7763 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7764 std::reverse(Output.begin(), Output.end());
7765 return true;
7766 }
7767
7768 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7769 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7770 std::reverse(Input.begin(), Input.end());
7771
7772 size_t Index = 0;
7773 for (unsigned char Byte : Input) {
7774 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7775 Bytes[Offset.getQuantity() + Index] = Byte;
7776 ++Index;
7777 }
7778 }
7779
7780 size_t size() { return Bytes.size(); }
7781};
7782
7783/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7784/// target would represent the value at runtime.
7785class APValueToBufferConverter {
7786 EvalInfo &Info;
7787 BitCastBuffer Buffer;
7788 const CastExpr *BCE;
7789
7790 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7791 const CastExpr *BCE)
7792 : Info(Info),
7793 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7794 BCE(BCE) {}
7795
7796 bool visit(const APValue &Val, QualType Ty) {
7797 return visit(Val, Ty, CharUnits::fromQuantity(0));
7798 }
7799
7800 // Write out Val with type Ty into Buffer starting at Offset.
7801 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7802 assert((size_t)Offset.getQuantity() <= Buffer.size());
7803
7804 // As a special case, nullptr_t has an indeterminate value.
7805 if (Ty->isNullPtrType())
7806 return true;
7807
7808 // Dig through Src to find the byte at SrcOffset.
7809 switch (Val.getKind()) {
7811 case APValue::None:
7812 return true;
7813
7814 case APValue::Int:
7815 return visitInt(Val.getInt(), Ty, Offset);
7816 case APValue::Float:
7817 return visitFloat(Val.getFloat(), Ty, Offset);
7818 case APValue::Array:
7819 return visitArray(Val, Ty, Offset);
7820 case APValue::Struct:
7821 return visitRecord(Val, Ty, Offset);
7822 case APValue::Vector:
7823 return visitVector(Val, Ty, Offset);
7824
7827 return visitComplex(Val, Ty, Offset);
7829 // FIXME: We should support these.
7830
7831 case APValue::LValue:
7832 case APValue::Matrix:
7833 case APValue::Union:
7836 Info.FFDiag(BCE->getBeginLoc(),
7837 diag::note_constexpr_bit_cast_unsupported_type)
7838 << Ty;
7839 return false;
7840 }
7841 }
7842 llvm_unreachable("Unhandled APValue::ValueKind");
7843 }
7844
7845 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7846 const RecordDecl *RD = Ty->getAsRecordDecl();
7847 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7848
7849 // Visit the base classes.
7850 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7851 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7852 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7853 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7854 const APValue &Base = Val.getStructBase(I);
7855
7856 // Can happen in error cases.
7857 if (!Base.isStruct())
7858 return false;
7859
7860 if (!visitRecord(Base, BS.getType(),
7861 Layout.getBaseClassOffset(BaseDecl) + Offset))
7862 return false;
7863 }
7864 }
7865
7866 // Visit the fields.
7867 unsigned FieldIdx = 0;
7868 for (FieldDecl *FD : RD->fields()) {
7869 if (FD->isBitField()) {
7870 Info.FFDiag(BCE->getBeginLoc(),
7871 diag::note_constexpr_bit_cast_unsupported_bitfield);
7872 return false;
7873 }
7874
7875 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7876
7877 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7878 "only bit-fields can have sub-char alignment");
7879 CharUnits FieldOffset =
7880 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7881 QualType FieldTy = FD->getType();
7882 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7883 return false;
7884 ++FieldIdx;
7885 }
7886
7887 return true;
7888 }
7889
7890 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7891 const auto *CAT =
7892 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7893 if (!CAT)
7894 return false;
7895
7896 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7897 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7898 unsigned ArraySize = Val.getArraySize();
7899 // First, initialize the initialized elements.
7900 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7901 const APValue &SubObj = Val.getArrayInitializedElt(I);
7902 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7903 return false;
7904 }
7905
7906 // Next, initialize the rest of the array using the filler.
7907 if (Val.hasArrayFiller()) {
7908 const APValue &Filler = Val.getArrayFiller();
7909 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7910 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7911 return false;
7912 }
7913 }
7914
7915 return true;
7916 }
7917
7918 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7919 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7920 QualType EltTy = ComplexTy->getElementType();
7921 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7922 bool IsInt = Val.isComplexInt();
7923
7924 if (IsInt) {
7925 if (!visitInt(Val.getComplexIntReal(), EltTy,
7926 Offset + (0 * EltSizeChars)))
7927 return false;
7928 if (!visitInt(Val.getComplexIntImag(), EltTy,
7929 Offset + (1 * EltSizeChars)))
7930 return false;
7931 } else {
7932 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7933 Offset + (0 * EltSizeChars)))
7934 return false;
7935 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7936 Offset + (1 * EltSizeChars)))
7937 return false;
7938 }
7939
7940 return true;
7941 }
7942
7943 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7944 const VectorType *VTy = Ty->castAs<VectorType>();
7945 QualType EltTy = VTy->getElementType();
7946 unsigned NElts = VTy->getNumElements();
7947
7948 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
7949 // Special handling for OpenCL bool vectors:
7950 // Since these vectors are stored as packed bits, but we can't write
7951 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7952 // together into an appropriately sized APInt and write them all out at
7953 // once. Because we don't accept vectors where NElts * EltSize isn't a
7954 // multiple of the char size, there will be no padding space, so we don't
7955 // have to worry about writing data which should have been left
7956 // uninitialized.
7957 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7958
7959 llvm::APInt Res = llvm::APInt::getZero(NElts);
7960 for (unsigned I = 0; I < NElts; ++I) {
7961 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7962 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7963 "bool vector element must be 1-bit unsigned integer!");
7964
7965 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7966 }
7967
7968 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7969 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7970 Buffer.writeObject(Offset, Bytes);
7971 } else {
7972 // Iterate over each of the elements and write them out to the buffer at
7973 // the appropriate offset.
7974 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7975 for (unsigned I = 0; I < NElts; ++I) {
7976 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7977 return false;
7978 }
7979 }
7980
7981 return true;
7982 }
7983
7984 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7985 APSInt AdjustedVal = Val;
7986 unsigned Width = AdjustedVal.getBitWidth();
7987 if (Ty->isBooleanType()) {
7988 Width = Info.Ctx.getTypeSize(Ty);
7989 AdjustedVal = AdjustedVal.extend(Width);
7990 }
7991
7992 SmallVector<uint8_t, 8> Bytes(Width / 8);
7993 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7994 Buffer.writeObject(Offset, Bytes);
7995 return true;
7996 }
7997
7998 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7999 APSInt AsInt(Val.bitcastToAPInt());
8000 return visitInt(AsInt, Ty, Offset);
8001 }
8002
8003public:
8004 static std::optional<BitCastBuffer>
8005 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
8006 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
8007 APValueToBufferConverter Converter(Info, DstSize, BCE);
8008 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
8009 return std::nullopt;
8010 return Converter.Buffer;
8011 }
8012};
8013
8014/// Write an BitCastBuffer into an APValue.
8015class BufferToAPValueConverter {
8016 EvalInfo &Info;
8017 const BitCastBuffer &Buffer;
8018 const CastExpr *BCE;
8019
8020 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
8021 const CastExpr *BCE)
8022 : Info(Info), Buffer(Buffer), BCE(BCE) {}
8023
8024 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
8025 // with an invalid type, so anything left is a deficiency on our part (FIXME).
8026 // Ideally this will be unreachable.
8027 std::nullopt_t unsupportedType(QualType Ty) {
8028 Info.FFDiag(BCE->getBeginLoc(),
8029 diag::note_constexpr_bit_cast_unsupported_type)
8030 << Ty;
8031 return std::nullopt;
8032 }
8033
8034 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
8035 Info.FFDiag(BCE->getBeginLoc(),
8036 diag::note_constexpr_bit_cast_unrepresentable_value)
8037 << Ty << toString(Val, /*Radix=*/10);
8038 return std::nullopt;
8039 }
8040
8041 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
8042 const EnumType *EnumSugar = nullptr) {
8043 if (T->isNullPtrType()) {
8044 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
8045 return APValue((Expr *)nullptr,
8046 /*Offset=*/CharUnits::fromQuantity(NullValue),
8047 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
8048 }
8049
8050 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
8051
8052 // Work around floating point types that contain unused padding bytes. This
8053 // is really just `long double` on x86, which is the only fundamental type
8054 // with padding bytes.
8055 if (T->isRealFloatingType()) {
8056 const llvm::fltSemantics &Semantics =
8057 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8058 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8059 assert(NumBits % 8 == 0);
8060 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
8061 if (NumBytes != SizeOf)
8062 SizeOf = NumBytes;
8063 }
8064
8065 SmallVector<uint8_t, 8> Bytes;
8066 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
8067 // If this is std::byte or unsigned char, then its okay to store an
8068 // indeterminate value.
8069 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8070 bool IsUChar =
8071 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
8072 T->isSpecificBuiltinType(BuiltinType::Char_U));
8073 if (!IsStdByte && !IsUChar) {
8074 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
8075 Info.FFDiag(BCE->getExprLoc(),
8076 diag::note_constexpr_bit_cast_indet_dest)
8077 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8078 return std::nullopt;
8079 }
8080
8082 }
8083
8084 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
8085 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8086
8087 if (T->isIntegralOrEnumerationType()) {
8088 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
8089
8090 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
8091 if (IntWidth != Val.getBitWidth()) {
8092 APSInt Truncated = Val.trunc(IntWidth);
8093 if (Truncated.extend(Val.getBitWidth()) != Val)
8094 return unrepresentableValue(QualType(T, 0), Val);
8095 Val = Truncated;
8096 }
8097
8098 return APValue(Val);
8099 }
8100
8101 if (T->isRealFloatingType()) {
8102 const llvm::fltSemantics &Semantics =
8103 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8104 return APValue(APFloat(Semantics, Val));
8105 }
8106
8107 return unsupportedType(QualType(T, 0));
8108 }
8109
8110 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
8111 const RecordDecl *RD = RTy->getAsRecordDecl();
8112 if (RD->isInvalidDecl())
8113 return std::nullopt;
8114 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8115
8116 unsigned NumBases = 0;
8117 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8118 NumBases = CXXRD->getNumBases();
8119
8120 APValue ResultVal(APValue::UninitStruct(), NumBases, RD->getNumFields());
8121
8122 // Visit the base classes.
8123 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8124 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8125 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8126 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8127
8128 std::optional<APValue> SubObj = visitType(
8129 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
8130 if (!SubObj)
8131 return std::nullopt;
8132 ResultVal.getStructBase(I) = *SubObj;
8133 }
8134 }
8135
8136 // Visit the fields.
8137 unsigned FieldIdx = 0;
8138 for (FieldDecl *FD : RD->fields()) {
8139 // FIXME: We don't currently support bit-fields. A lot of the logic for
8140 // this is in CodeGen, so we need to factor it around.
8141 if (FD->isBitField()) {
8142 Info.FFDiag(BCE->getBeginLoc(),
8143 diag::note_constexpr_bit_cast_unsupported_bitfield);
8144 return std::nullopt;
8145 }
8146
8147 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8148 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8149
8150 CharUnits FieldOffset =
8151 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
8152 Offset;
8153 QualType FieldTy = FD->getType();
8154 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8155 if (!SubObj)
8156 return std::nullopt;
8157 ResultVal.getStructField(FieldIdx) = *SubObj;
8158 ++FieldIdx;
8159 }
8160
8161 return ResultVal;
8162 }
8163
8164 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
8165 QualType RepresentationType =
8166 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8167 assert(!RepresentationType.isNull() &&
8168 "enum forward decl should be caught by Sema");
8169 const auto *AsBuiltin =
8170 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
8171 // Recurse into the underlying type. Treat std::byte transparently as
8172 // unsigned char.
8173 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
8174 }
8175
8176 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
8177 size_t Size = Ty->getLimitedSize();
8178 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
8179
8180 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8181 for (size_t I = 0; I != Size; ++I) {
8182 std::optional<APValue> ElementValue =
8183 visitType(Ty->getElementType(), Offset + I * ElementWidth);
8184 if (!ElementValue)
8185 return std::nullopt;
8186 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8187 }
8188
8189 return ArrayValue;
8190 }
8191
8192 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
8193 QualType ElementType = Ty->getElementType();
8194 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8195 bool IsInt = ElementType->isIntegerType();
8196
8197 std::optional<APValue> Values[2];
8198 for (unsigned I = 0; I != 2; ++I) {
8199 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
8200 if (!Values[I])
8201 return std::nullopt;
8202 }
8203
8204 if (IsInt)
8205 return APValue(Values[0]->getInt(), Values[1]->getInt());
8206 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8207 }
8208
8209 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
8210 QualType EltTy = VTy->getElementType();
8211 unsigned NElts = VTy->getNumElements();
8212 unsigned EltSize =
8213 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
8214
8215 SmallVector<APValue, 4> Elts;
8216 Elts.reserve(NElts);
8217 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8218 // Special handling for OpenCL bool vectors:
8219 // Since these vectors are stored as packed bits, but we can't read
8220 // individual bits from the BitCastBuffer, we'll buffer all of the
8221 // elements together into an appropriately sized APInt and write them all
8222 // out at once. Because we don't accept vectors where NElts * EltSize
8223 // isn't a multiple of the char size, there will be no padding space, so
8224 // we don't have to worry about reading any padding data which didn't
8225 // actually need to be accessed.
8226 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8227
8228 SmallVector<uint8_t, 8> Bytes;
8229 Bytes.reserve(NElts / 8);
8230 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
8231 return std::nullopt;
8232
8233 APSInt SValInt(NElts, true);
8234 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8235
8236 for (unsigned I = 0; I < NElts; ++I) {
8237 llvm::APInt Elt =
8238 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8239 Elts.emplace_back(
8240 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
8241 }
8242 } else {
8243 // Iterate over each of the elements and read them from the buffer at
8244 // the appropriate offset.
8245 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8246 for (unsigned I = 0; I < NElts; ++I) {
8247 std::optional<APValue> EltValue =
8248 visitType(EltTy, Offset + I * EltSizeChars);
8249 if (!EltValue)
8250 return std::nullopt;
8251 Elts.push_back(std::move(*EltValue));
8252 }
8253 }
8254
8255 return APValue(Elts.data(), Elts.size());
8256 }
8257
8258 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
8259 return unsupportedType(QualType(Ty, 0));
8260 }
8261
8262 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8263 QualType Can = Ty.getCanonicalType();
8264
8265 switch (Can->getTypeClass()) {
8266#define TYPE(Class, Base) \
8267 case Type::Class: \
8268 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8269#define ABSTRACT_TYPE(Class, Base)
8270#define NON_CANONICAL_TYPE(Class, Base) \
8271 case Type::Class: \
8272 llvm_unreachable("non-canonical type should be impossible!");
8273#define DEPENDENT_TYPE(Class, Base) \
8274 case Type::Class: \
8275 llvm_unreachable( \
8276 "dependent types aren't supported in the constant evaluator!");
8277#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8278 case Type::Class: \
8279 llvm_unreachable("either dependent or not canonical!");
8280#include "clang/AST/TypeNodes.inc"
8281 }
8282 llvm_unreachable("Unhandled Type::TypeClass");
8283 }
8284
8285public:
8286 // Pull out a full value of type DstType.
8287 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8288 const CastExpr *BCE) {
8289 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8290 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
8291 }
8292};
8293
8294static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8295 QualType Ty, EvalInfo *Info,
8296 const ASTContext &Ctx,
8297 bool CheckingDest) {
8298 Ty = Ty.getCanonicalType();
8299
8300 auto diag = [&](int Reason) {
8301 if (Info)
8302 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8303 << CheckingDest << (Reason == 4) << Reason;
8304 return false;
8305 };
8306 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8307 if (Info)
8308 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8309 << NoteTy << Construct << Ty;
8310 return false;
8311 };
8312
8313 if (Ty->isUnionType())
8314 return diag(0);
8315 if (Ty->isPointerType())
8316 return diag(1);
8317 if (Ty->isMemberPointerType())
8318 return diag(2);
8319 if (Ty.isVolatileQualified())
8320 return diag(3);
8321
8322 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8323 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8324 for (CXXBaseSpecifier &BS : CXXRD->bases())
8325 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8326 CheckingDest))
8327 return note(1, BS.getType(), BS.getBeginLoc());
8328 }
8329 for (FieldDecl *FD : Record->fields()) {
8330 if (FD->getType()->isReferenceType())
8331 return diag(4);
8332 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8333 CheckingDest))
8334 return note(0, FD->getType(), FD->getBeginLoc());
8335 }
8336 }
8337
8338 if (Ty->isArrayType() &&
8339 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8340 Info, Ctx, CheckingDest))
8341 return false;
8342
8343 if (const auto *VTy = Ty->getAs<VectorType>()) {
8344 QualType EltTy = VTy->getElementType();
8345 unsigned NElts = VTy->getNumElements();
8346 unsigned EltSize =
8347 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8348
8349 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8350 // The vector's size in bits is not a multiple of the target's byte size,
8351 // so its layout is unspecified. For now, we'll simply treat these cases
8352 // as unsupported (this should only be possible with OpenCL bool vectors
8353 // whose element count isn't a multiple of the byte size).
8354 if (Info)
8355 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8356 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8357 return false;
8358 }
8359
8360 if (EltTy->isRealFloatingType() &&
8361 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8362 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8363 // by both clang and LLVM, so for now we won't allow bit_casts involving
8364 // it in a constexpr context.
8365 if (Info)
8366 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8367 << EltTy;
8368 return false;
8369 }
8370 }
8371
8372 return true;
8373}
8374
8375static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8376 const ASTContext &Ctx,
8377 const CastExpr *BCE) {
8378 bool DestOK = checkBitCastConstexprEligibilityType(
8379 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8380 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8381 BCE->getBeginLoc(),
8382 BCE->getSubExpr()->getType(), Info, Ctx, false);
8383 return SourceOK;
8384}
8385
8386static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8387 const APValue &SourceRValue,
8388 const CastExpr *BCE) {
8389 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8390 "no host or target supports non 8-bit chars");
8391
8392 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8393 return false;
8394
8395 // Read out SourceValue into a char buffer.
8396 std::optional<BitCastBuffer> Buffer =
8397 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8398 if (!Buffer)
8399 return false;
8400
8401 // Write out the buffer into a new APValue.
8402 std::optional<APValue> MaybeDestValue =
8403 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8404 if (!MaybeDestValue)
8405 return false;
8406
8407 DestValue = std::move(*MaybeDestValue);
8408 return true;
8409}
8410
8411static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8412 APValue &SourceValue,
8413 const CastExpr *BCE) {
8414 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8415 "no host or target supports non 8-bit chars");
8416 assert(SourceValue.isLValue() &&
8417 "LValueToRValueBitcast requires an lvalue operand!");
8418
8419 LValue SourceLValue;
8420 APValue SourceRValue;
8421 SourceLValue.setFrom(Info.Ctx, SourceValue);
8423 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8424 SourceRValue, /*WantObjectRepresentation=*/true))
8425 return false;
8426
8427 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8428}
8429
8430template <class Derived>
8431class ExprEvaluatorBase
8432 : public ConstStmtVisitor<Derived, bool> {
8433private:
8434 Derived &getDerived() { return static_cast<Derived&>(*this); }
8435 bool DerivedSuccess(const APValue &V, const Expr *E) {
8436 return getDerived().Success(V, E);
8437 }
8438 bool DerivedZeroInitialization(const Expr *E) {
8439 return getDerived().ZeroInitialization(E);
8440 }
8441
8442 // Check whether a conditional operator with a non-constant condition is a
8443 // potential constant expression. If neither arm is a potential constant
8444 // expression, then the conditional operator is not either.
8445 template<typename ConditionalOperator>
8446 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8447 assert(Info.checkingPotentialConstantExpression());
8448
8449 // Speculatively evaluate both arms.
8450 SmallVector<PartialDiagnosticAt, 8> Diag;
8451 {
8452 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8453 StmtVisitorTy::Visit(E->getFalseExpr());
8454 if (Diag.empty())
8455 return;
8456 }
8457
8458 {
8459 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8460 Diag.clear();
8461 Info.EvalStatus.DiagEmitted = false;
8462 StmtVisitorTy::Visit(E->getTrueExpr());
8463 if (Diag.empty())
8464 return;
8465 }
8466
8467 Error(E, diag::note_constexpr_conditional_never_const);
8468 }
8469
8470
8471 template<typename ConditionalOperator>
8472 bool HandleConditionalOperator(const ConditionalOperator *E) {
8473 bool BoolResult;
8474 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8475 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8476 CheckPotentialConstantConditional(E);
8477 return false;
8478 }
8479 if (Info.noteFailure()) {
8480 StmtVisitorTy::Visit(E->getTrueExpr());
8481 StmtVisitorTy::Visit(E->getFalseExpr());
8482 }
8483 return false;
8484 }
8485
8486 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8487 return StmtVisitorTy::Visit(EvalExpr);
8488 }
8489
8490protected:
8491 EvalInfo &Info;
8492 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8493 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8494
8495 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8496 return Info.CCEDiag(E, D);
8497 }
8498
8499 bool ZeroInitialization(const Expr *E) { return Error(E); }
8500
8501 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8502 unsigned BuiltinOp = E->getBuiltinCallee();
8503 return BuiltinOp != 0 &&
8504 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8505 }
8506
8507public:
8508 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8509
8510 EvalInfo &getEvalInfo() { return Info; }
8511
8512 /// Report an evaluation error. This should only be called when an error is
8513 /// first discovered. When propagating an error, just return false.
8514 bool Error(const Expr *E, diag::kind D) {
8515 Info.FFDiag(E, D) << E->getSourceRange();
8516 return false;
8517 }
8518 bool Error(const Expr *E) {
8519 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8520 }
8521
8522 bool VisitStmt(const Stmt *) {
8523 llvm_unreachable("Expression evaluator should not be called on stmts");
8524 }
8525 bool VisitExpr(const Expr *E) {
8526 return Error(E);
8527 }
8528
8529 bool VisitEmbedExpr(const EmbedExpr *E) {
8530 const auto It = E->begin();
8531 return StmtVisitorTy::Visit(*It);
8532 }
8533
8534 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8535 return StmtVisitorTy::Visit(E->getFunctionName());
8536 }
8537 bool VisitConstantExpr(const ConstantExpr *E) {
8538 if (E->hasAPValueResult())
8539 return DerivedSuccess(E->getAPValueResult(), E);
8540
8541 return StmtVisitorTy::Visit(E->getSubExpr());
8542 }
8543
8544 bool VisitParenExpr(const ParenExpr *E)
8545 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8546 bool VisitUnaryExtension(const UnaryOperator *E)
8547 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8548 bool VisitUnaryPlus(const UnaryOperator *E)
8549 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8550 bool VisitChooseExpr(const ChooseExpr *E)
8551 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8552 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8553 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8554 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8555 { return StmtVisitorTy::Visit(E->getReplacement()); }
8556 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8557 TempVersionRAII RAII(*Info.CurrentCall);
8558 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8559 return StmtVisitorTy::Visit(E->getExpr());
8560 }
8561 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8562 TempVersionRAII RAII(*Info.CurrentCall);
8563 // The initializer may not have been parsed yet, or might be erroneous.
8564 if (!E->getExpr())
8565 return Error(E);
8566 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8567 return StmtVisitorTy::Visit(E->getExpr());
8568 }
8569
8570 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8571 FullExpressionRAII Scope(Info);
8572 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8573 }
8574
8575 // Temporaries are registered when created, so we don't care about
8576 // CXXBindTemporaryExpr.
8577 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8578 return StmtVisitorTy::Visit(E->getSubExpr());
8579 }
8580
8581 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8582 CCEDiag(E, diag::note_constexpr_invalid_cast)
8583 << diag::ConstexprInvalidCastKind::Reinterpret;
8584 return static_cast<Derived*>(this)->VisitCastExpr(E);
8585 }
8586 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8587 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8588 CCEDiag(E, diag::note_constexpr_invalid_cast)
8589 << diag::ConstexprInvalidCastKind::Dynamic;
8590 return static_cast<Derived*>(this)->VisitCastExpr(E);
8591 }
8592 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8593 return static_cast<Derived*>(this)->VisitCastExpr(E);
8594 }
8595
8596 bool VisitBinaryOperator(const BinaryOperator *E) {
8597 switch (E->getOpcode()) {
8598 default:
8599 return Error(E);
8600
8601 case BO_Comma:
8602 VisitIgnoredValue(E->getLHS());
8603 return StmtVisitorTy::Visit(E->getRHS());
8604
8605 case BO_PtrMemD:
8606 case BO_PtrMemI: {
8607 LValue Obj;
8608 if (!HandleMemberPointerAccess(Info, E, Obj))
8609 return false;
8611 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8612 return false;
8613 return DerivedSuccess(Result, E);
8614 }
8615 }
8616 }
8617
8618 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8619 return StmtVisitorTy::Visit(E->getSemanticForm());
8620 }
8621
8622 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8623 // Evaluate and cache the common expression. We treat it as a temporary,
8624 // even though it's not quite the same thing.
8625 LValue CommonLV;
8626 if (!Evaluate(Info.CurrentCall->createTemporary(
8627 E->getOpaqueValue(),
8628 getStorageType(Info.Ctx, E->getOpaqueValue()),
8629 ScopeKind::FullExpression, CommonLV),
8630 Info, E->getCommon()))
8631 return false;
8632
8633 return HandleConditionalOperator(E);
8634 }
8635
8636 bool VisitConditionalOperator(const ConditionalOperator *E) {
8637 bool IsBcpCall = false;
8638 // If the condition (ignoring parens) is a __builtin_constant_p call,
8639 // the result is a constant expression if it can be folded without
8640 // side-effects. This is an important GNU extension. See GCC PR38377
8641 // for discussion.
8642 if (const CallExpr *CallCE =
8643 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8644 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8645 IsBcpCall = true;
8646
8647 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8648 // constant expression; we can't check whether it's potentially foldable.
8649 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8650 // it would return 'false' in this mode.
8651 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8652 return false;
8653
8654 FoldConstant Fold(Info, IsBcpCall);
8655 if (!HandleConditionalOperator(E)) {
8656 Fold.keepDiagnostics();
8657 return false;
8658 }
8659
8660 return true;
8661 }
8662
8663 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8664 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8665 Value && !Value->isAbsent())
8666 return DerivedSuccess(*Value, E);
8667
8668 const Expr *Source = E->getSourceExpr();
8669 if (!Source)
8670 return Error(E);
8671 if (Source == E) {
8672 assert(0 && "OpaqueValueExpr recursively refers to itself");
8673 return Error(E);
8674 }
8675 return StmtVisitorTy::Visit(Source);
8676 }
8677
8678 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8679 for (const Expr *SemE : E->semantics()) {
8680 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8681 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8682 // result expression: there could be two different LValues that would
8683 // refer to the same object in that case, and we can't model that.
8684 if (SemE == E->getResultExpr())
8685 return Error(E);
8686
8687 // Unique OVEs get evaluated if and when we encounter them when
8688 // emitting the rest of the semantic form, rather than eagerly.
8689 if (OVE->isUnique())
8690 continue;
8691
8692 LValue LV;
8693 if (!Evaluate(Info.CurrentCall->createTemporary(
8694 OVE, getStorageType(Info.Ctx, OVE),
8695 ScopeKind::FullExpression, LV),
8696 Info, OVE->getSourceExpr()))
8697 return false;
8698 } else if (SemE == E->getResultExpr()) {
8699 if (!StmtVisitorTy::Visit(SemE))
8700 return false;
8701 } else {
8702 if (!EvaluateIgnoredValue(Info, SemE))
8703 return false;
8704 }
8705 }
8706 return true;
8707 }
8708
8709 bool VisitCallExpr(const CallExpr *E) {
8711 if (!handleCallExpr(E, Result, nullptr))
8712 return false;
8713 return DerivedSuccess(Result, E);
8714 }
8715
8716 bool handleCallExpr(const CallExpr *E, APValue &Result,
8717 const LValue *ResultSlot) {
8718 CallScopeRAII CallScope(Info);
8719
8720 const Expr *Callee = E->getCallee()->IgnoreParens();
8721 QualType CalleeType = Callee->getType();
8722
8723 const FunctionDecl *FD = nullptr;
8724 LValue *This = nullptr, ObjectArg;
8725 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8726 bool HasQualifier = false;
8727
8728 CallRef Call;
8729
8730 // Extract function decl and 'this' pointer from the callee.
8731 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8732 const CXXMethodDecl *Member = nullptr;
8733 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8734 // Explicit bound member calls, such as x.f() or p->g();
8735 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8736 return false;
8737 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8738 if (!Member)
8739 return Error(Callee);
8740 This = &ObjectArg;
8741 HasQualifier = ME->hasQualifier();
8742 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8743 // Indirect bound member calls ('.*' or '->*').
8744 const ValueDecl *D =
8745 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8746 if (!D)
8747 return false;
8748 Member = dyn_cast<CXXMethodDecl>(D);
8749 if (!Member)
8750 return Error(Callee);
8751 This = &ObjectArg;
8752 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8753 if (!Info.getLangOpts().CPlusPlus20)
8754 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8755 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8756 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8757 } else
8758 return Error(Callee);
8759 FD = Member;
8760 } else if (CalleeType->isFunctionPointerType()) {
8761 LValue CalleeLV;
8762 if (!EvaluatePointer(Callee, CalleeLV, Info))
8763 return false;
8764
8765 if (!CalleeLV.getLValueOffset().isZero())
8766 return Error(Callee);
8767 if (CalleeLV.isNullPointer()) {
8768 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8769 << const_cast<Expr *>(Callee);
8770 return false;
8771 }
8772 FD = dyn_cast_or_null<FunctionDecl>(
8773 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8774 if (!FD)
8775 return Error(Callee);
8776 // Don't call function pointers which have been cast to some other type.
8777 // Per DR (no number yet), the caller and callee can differ in noexcept.
8778 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8779 CalleeType->getPointeeType(), FD->getType())) {
8780 return Error(E);
8781 }
8782
8783 // For an (overloaded) assignment expression, evaluate the RHS before the
8784 // LHS.
8785 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8786 if (OCE && OCE->isAssignmentOp()) {
8787 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8788 Call = Info.CurrentCall->createCall(FD);
8789 bool HasThis = false;
8790 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8791 HasThis = MD->isImplicitObjectMemberFunction();
8792 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8793 /*RightToLeft=*/true, &ObjectArg))
8794 return false;
8795 }
8796
8797 // Overloaded operator calls to member functions are represented as normal
8798 // calls with '*this' as the first argument.
8799 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8800 if (MD &&
8801 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8802 // FIXME: When selecting an implicit conversion for an overloaded
8803 // operator delete, we sometimes try to evaluate calls to conversion
8804 // operators without a 'this' parameter!
8805 if (Args.empty())
8806 return Error(E);
8807
8808 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8809 return false;
8810
8811 // If we are calling a static operator, the 'this' argument needs to be
8812 // ignored after being evaluated.
8813 if (MD->isInstance())
8814 This = &ObjectArg;
8815
8816 // If this is syntactically a simple assignment using a trivial
8817 // assignment operator, start the lifetimes of union members as needed,
8818 // per C++20 [class.union]5.
8819 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8820 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8821 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8822 return false;
8823
8824 Args = Args.slice(1);
8825 } else if (MD && MD->isLambdaStaticInvoker()) {
8826 // Map the static invoker for the lambda back to the call operator.
8827 // Conveniently, we don't have to slice out the 'this' argument (as is
8828 // being done for the non-static case), since a static member function
8829 // doesn't have an implicit argument passed in.
8830 const CXXRecordDecl *ClosureClass = MD->getParent();
8831 assert(
8832 ClosureClass->captures().empty() &&
8833 "Number of captures must be zero for conversion to function-ptr");
8834
8835 const CXXMethodDecl *LambdaCallOp =
8836 ClosureClass->getLambdaCallOperator();
8837
8838 // Set 'FD', the function that will be called below, to the call
8839 // operator. If the closure object represents a generic lambda, find
8840 // the corresponding specialization of the call operator.
8841
8842 if (ClosureClass->isGenericLambda()) {
8843 assert(MD->isFunctionTemplateSpecialization() &&
8844 "A generic lambda's static-invoker function must be a "
8845 "template specialization");
8846 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8847 FunctionTemplateDecl *CallOpTemplate =
8848 LambdaCallOp->getDescribedFunctionTemplate();
8849 void *InsertPos = nullptr;
8850 FunctionDecl *CorrespondingCallOpSpecialization =
8851 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8852 assert(CorrespondingCallOpSpecialization &&
8853 "We must always have a function call operator specialization "
8854 "that corresponds to our static invoker specialization");
8855 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8856 FD = CorrespondingCallOpSpecialization;
8857 } else
8858 FD = LambdaCallOp;
8860 if (FD->getDeclName().isAnyOperatorNew()) {
8861 LValue Ptr;
8862 if (!HandleOperatorNewCall(Info, E, Ptr))
8863 return false;
8864 Ptr.moveInto(Result);
8865 return CallScope.destroy();
8866 } else {
8867 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8868 }
8869 }
8870 } else
8871 return Error(E);
8872
8873 // Evaluate the arguments now if we've not already done so.
8874 if (!Call) {
8875 Call = Info.CurrentCall->createCall(FD);
8876 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
8877 &ObjectArg))
8878 return false;
8879 }
8880
8881 SmallVector<QualType, 4> CovariantAdjustmentPath;
8882 if (This) {
8883 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8884 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8885 // Perform virtual dispatch, if necessary.
8886 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8887 CovariantAdjustmentPath);
8888 if (!FD)
8889 return false;
8890 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8891 // Check that the 'this' pointer points to an object of the right type.
8892 // FIXME: If this is an assignment operator call, we may need to change
8893 // the active union member before we check this.
8894 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8895 return false;
8896 }
8897 }
8898
8899 // Destructor calls are different enough that they have their own codepath.
8900 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8901 assert(This && "no 'this' pointer for destructor call");
8902 return HandleDestruction(Info, E, *This,
8903 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
8904 CallScope.destroy();
8905 }
8906
8907 const FunctionDecl *Definition = nullptr;
8908 Stmt *Body = FD->getBody(Definition);
8909 SourceLocation Loc = E->getExprLoc();
8910
8911 // Treat the object argument as `this` when evaluating defaulted
8912 // special menmber functions
8914 This = &ObjectArg;
8915
8916 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
8917 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
8918 Result, ResultSlot))
8919 return false;
8920
8921 if (!CovariantAdjustmentPath.empty() &&
8923 CovariantAdjustmentPath))
8924 return false;
8925
8926 return CallScope.destroy();
8927 }
8928
8929 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8930 return StmtVisitorTy::Visit(E->getInitializer());
8931 }
8932 bool VisitInitListExpr(const InitListExpr *E) {
8933 if (E->getNumInits() == 0)
8934 return DerivedZeroInitialization(E);
8935 if (E->getNumInits() == 1)
8936 return StmtVisitorTy::Visit(E->getInit(0));
8937 return Error(E);
8938 }
8939 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8940 return DerivedZeroInitialization(E);
8941 }
8942 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8943 return DerivedZeroInitialization(E);
8944 }
8945 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8946 return DerivedZeroInitialization(E);
8947 }
8948
8949 /// A member expression where the object is a prvalue is itself a prvalue.
8950 bool VisitMemberExpr(const MemberExpr *E) {
8951 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8952 "missing temporary materialization conversion");
8953 assert(!E->isArrow() && "missing call to bound member function?");
8954
8955 APValue Val;
8956 if (!Evaluate(Val, Info, E->getBase()))
8957 return false;
8958
8959 QualType BaseTy = E->getBase()->getType();
8960
8961 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8962 if (!FD) return Error(E);
8963 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8964 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
8965 FD->getParent()->getCanonicalDecl() &&
8966 "record / field mismatch");
8967
8968 // Note: there is no lvalue base here. But this case should only ever
8969 // happen in C or in C++98, where we cannot be evaluating a constexpr
8970 // constructor, which is the only case the base matters.
8971 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8972 SubobjectDesignator Designator(BaseTy);
8973 Designator.addDeclUnchecked(FD);
8974
8976 return extractSubobject(Info, E, Obj, Designator, Result) &&
8977 DerivedSuccess(Result, E);
8978 }
8979
8980 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8981 APValue Val;
8982 if (!Evaluate(Val, Info, E->getBase()))
8983 return false;
8984
8985 if (Val.isVector()) {
8986 SmallVector<uint32_t, 4> Indices;
8987 E->getEncodedElementAccess(Indices);
8988 if (Indices.size() == 1) {
8989 // Return scalar.
8990 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8991 } else {
8992 // Construct new APValue vector.
8993 SmallVector<APValue, 4> Elts;
8994 for (unsigned I = 0; I < Indices.size(); ++I) {
8995 Elts.push_back(Val.getVectorElt(Indices[I]));
8996 }
8997 APValue VecResult(Elts.data(), Indices.size());
8998 return DerivedSuccess(VecResult, E);
8999 }
9000 }
9001
9002 return false;
9003 }
9004
9005 bool VisitCastExpr(const CastExpr *E) {
9006 switch (E->getCastKind()) {
9007 default:
9008 break;
9009
9010 case CK_AtomicToNonAtomic: {
9011 APValue AtomicVal;
9012 // This does not need to be done in place even for class/array types:
9013 // atomic-to-non-atomic conversion implies copying the object
9014 // representation.
9015 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
9016 return false;
9017 return DerivedSuccess(AtomicVal, E);
9018 }
9019
9020 case CK_NoOp:
9021 case CK_UserDefinedConversion:
9022 return StmtVisitorTy::Visit(E->getSubExpr());
9023
9024 case CK_HLSLArrayRValue: {
9025 const Expr *SubExpr = E->getSubExpr();
9026 if (!SubExpr->isGLValue()) {
9027 APValue Val;
9028 if (!Evaluate(Val, Info, SubExpr))
9029 return false;
9030 return DerivedSuccess(Val, E);
9031 }
9032
9033 LValue LVal;
9034 if (!EvaluateLValue(SubExpr, LVal, Info))
9035 return false;
9036 APValue RVal;
9037 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9038 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(), LVal,
9039 RVal))
9040 return false;
9041 return DerivedSuccess(RVal, E);
9042 }
9043 case CK_LValueToRValue: {
9044 LValue LVal;
9045 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
9046 return false;
9047 APValue RVal;
9048 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9050 LVal, RVal))
9051 return false;
9052 return DerivedSuccess(RVal, E);
9053 }
9054 case CK_LValueToRValueBitCast: {
9055 APValue DestValue, SourceValue;
9056 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
9057 return false;
9058 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9059 return false;
9060 return DerivedSuccess(DestValue, E);
9061 }
9062
9063 case CK_AddressSpaceConversion: {
9064 APValue Value;
9065 if (!Evaluate(Value, Info, E->getSubExpr()))
9066 return false;
9067 return DerivedSuccess(Value, E);
9068 }
9069 }
9070
9071 return Error(E);
9072 }
9073
9074 bool VisitUnaryPostInc(const UnaryOperator *UO) {
9075 return VisitUnaryPostIncDec(UO);
9076 }
9077 bool VisitUnaryPostDec(const UnaryOperator *UO) {
9078 return VisitUnaryPostIncDec(UO);
9079 }
9080 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
9081 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9082 return Error(UO);
9083
9084 LValue LVal;
9085 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
9086 return false;
9087 APValue RVal;
9088 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
9089 UO->isIncrementOp(), &RVal))
9090 return false;
9091 return DerivedSuccess(RVal, UO);
9092 }
9093
9094 bool VisitStmtExpr(const StmtExpr *E) {
9095 // We will have checked the full-expressions inside the statement expression
9096 // when they were completed, and don't need to check them again now.
9097 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9098 false);
9099
9100 const CompoundStmt *CS = E->getSubStmt();
9101 if (CS->body_empty())
9102 return true;
9103
9104 BlockScopeRAII Scope(Info);
9106 BE = CS->body_end();
9107 /**/; ++BI) {
9108 if (BI + 1 == BE) {
9109 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9110 if (!FinalExpr) {
9111 Info.FFDiag((*BI)->getBeginLoc(),
9112 diag::note_constexpr_stmt_expr_unsupported);
9113 return false;
9114 }
9115 return this->Visit(FinalExpr) && Scope.destroy();
9116 }
9117
9119 StmtResult Result = { ReturnValue, nullptr };
9120 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
9121 if (ESR != ESR_Succeeded) {
9122 // FIXME: If the statement-expression terminated due to 'return',
9123 // 'break', or 'continue', it would be nice to propagate that to
9124 // the outer statement evaluation rather than bailing out.
9125 if (ESR != ESR_Failed)
9126 Info.FFDiag((*BI)->getBeginLoc(),
9127 diag::note_constexpr_stmt_expr_unsupported);
9128 return false;
9129 }
9130 }
9131
9132 llvm_unreachable("Return from function from the loop above.");
9133 }
9134
9135 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
9136 return StmtVisitorTy::Visit(E->getSelectedExpr());
9137 }
9138
9139 /// Visit a value which is evaluated, but whose value is ignored.
9140 void VisitIgnoredValue(const Expr *E) {
9141 EvaluateIgnoredValue(Info, E);
9142 }
9143
9144 /// Potentially visit a MemberExpr's base expression.
9145 void VisitIgnoredBaseExpression(const Expr *E) {
9146 // While MSVC doesn't evaluate the base expression, it does diagnose the
9147 // presence of side-effecting behavior.
9148 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
9149 return;
9150 VisitIgnoredValue(E);
9151 }
9152};
9153
9154} // namespace
9155
9156//===----------------------------------------------------------------------===//
9157// Common base class for lvalue and temporary evaluation.
9158//===----------------------------------------------------------------------===//
9159namespace {
9160template<class Derived>
9161class LValueExprEvaluatorBase
9162 : public ExprEvaluatorBase<Derived> {
9163protected:
9164 LValue &Result;
9165 bool InvalidBaseOK;
9166 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9167 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9168
9169 bool Success(APValue::LValueBase B) {
9170 Result.set(B);
9171 return true;
9172 }
9173
9174 bool evaluatePointer(const Expr *E, LValue &Result) {
9175 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
9176 }
9177
9178public:
9179 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
9180 : ExprEvaluatorBaseTy(Info), Result(Result),
9181 InvalidBaseOK(InvalidBaseOK) {}
9182
9183 bool Success(const APValue &V, const Expr *E) {
9184 Result.setFrom(this->Info.Ctx, V);
9185 return true;
9186 }
9187
9188 bool VisitMemberExpr(const MemberExpr *E) {
9189 // Handle non-static data members.
9190 QualType BaseTy;
9191 bool EvalOK;
9192 if (E->isArrow()) {
9193 EvalOK = evaluatePointer(E->getBase(), Result);
9194 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
9195 } else if (E->getBase()->isPRValue()) {
9196 assert(E->getBase()->getType()->isRecordType());
9197 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
9198 BaseTy = E->getBase()->getType();
9199 } else {
9200 EvalOK = this->Visit(E->getBase());
9201 BaseTy = E->getBase()->getType();
9202 }
9203 if (!EvalOK) {
9204 if (!InvalidBaseOK)
9205 return false;
9206 Result.setInvalid(E);
9207 return true;
9208 }
9209
9210 const ValueDecl *MD = E->getMemberDecl();
9211 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
9212 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9213 FD->getParent()->getCanonicalDecl() &&
9214 "record / field mismatch");
9215 (void)BaseTy;
9216 if (!HandleLValueMember(this->Info, E, Result, FD))
9217 return false;
9218 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9219 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
9220 return false;
9221 } else
9222 return this->Error(E);
9223
9224 if (MD->getType()->isReferenceType()) {
9225 APValue RefValue;
9226 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
9227 RefValue))
9228 return false;
9229 return Success(RefValue, E);
9230 }
9231 return true;
9232 }
9233
9234 bool VisitBinaryOperator(const BinaryOperator *E) {
9235 switch (E->getOpcode()) {
9236 default:
9237 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9238
9239 case BO_PtrMemD:
9240 case BO_PtrMemI:
9241 return HandleMemberPointerAccess(this->Info, E, Result);
9242 }
9243 }
9244
9245 bool VisitCastExpr(const CastExpr *E) {
9246 switch (E->getCastKind()) {
9247 default:
9248 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9249
9250 case CK_DerivedToBase:
9251 case CK_UncheckedDerivedToBase:
9252 if (!this->Visit(E->getSubExpr()))
9253 return false;
9254
9255 // Now figure out the necessary offset to add to the base LV to get from
9256 // the derived class to the base class.
9257 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
9258 Result);
9259 }
9260 }
9261};
9262}
9263
9264//===----------------------------------------------------------------------===//
9265// LValue Evaluation
9266//
9267// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
9268// function designators (in C), decl references to void objects (in C), and
9269// temporaries (if building with -Wno-address-of-temporary).
9270//
9271// LValue evaluation produces values comprising a base expression of one of the
9272// following types:
9273// - Declarations
9274// * VarDecl
9275// * FunctionDecl
9276// - Literals
9277// * CompoundLiteralExpr in C (and in global scope in C++)
9278// * StringLiteral
9279// * PredefinedExpr
9280// * ObjCStringLiteralExpr
9281// * ObjCEncodeExpr
9282// * AddrLabelExpr
9283// * BlockExpr
9284// * CallExpr for a MakeStringConstant builtin
9285// - typeid(T) expressions, as TypeInfoLValues
9286// - Locals and temporaries
9287// * MaterializeTemporaryExpr
9288// * Any Expr, with a CallIndex indicating the function in which the temporary
9289// was evaluated, for cases where the MaterializeTemporaryExpr is missing
9290// from the AST (FIXME).
9291// * A MaterializeTemporaryExpr that has static storage duration, with no
9292// CallIndex, for a lifetime-extended temporary.
9293// * The ConstantExpr that is currently being evaluated during evaluation of an
9294// immediate invocation.
9295// plus an offset in bytes.
9296//===----------------------------------------------------------------------===//
9297namespace {
9298class LValueExprEvaluator
9299 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
9300public:
9301 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
9302 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
9303
9304 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
9305 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
9306
9307 bool VisitCallExpr(const CallExpr *E);
9308 bool VisitDeclRefExpr(const DeclRefExpr *E);
9309 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
9310 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
9311 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
9312 bool VisitMemberExpr(const MemberExpr *E);
9313 bool VisitStringLiteral(const StringLiteral *E) {
9314 return Success(
9315 APValue::LValueBase(E, 0, Info.Ctx.getNextStringLiteralVersion()));
9316 }
9317 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
9318 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
9319 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
9320 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
9321 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
9322 bool VisitUnaryDeref(const UnaryOperator *E);
9323 bool VisitUnaryReal(const UnaryOperator *E);
9324 bool VisitUnaryImag(const UnaryOperator *E);
9325 bool VisitUnaryPreInc(const UnaryOperator *UO) {
9326 return VisitUnaryPreIncDec(UO);
9327 }
9328 bool VisitUnaryPreDec(const UnaryOperator *UO) {
9329 return VisitUnaryPreIncDec(UO);
9330 }
9331 bool VisitBinAssign(const BinaryOperator *BO);
9332 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
9333
9334 bool VisitCastExpr(const CastExpr *E) {
9335 switch (E->getCastKind()) {
9336 default:
9337 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9338
9339 case CK_LValueBitCast:
9340 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9341 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9342 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
9343 if (!Visit(E->getSubExpr()))
9344 return false;
9345 Result.Designator.setInvalid();
9346 return true;
9347
9348 case CK_BaseToDerived:
9349 if (!Visit(E->getSubExpr()))
9350 return false;
9351 return HandleBaseToDerivedCast(Info, E, Result);
9352
9353 case CK_Dynamic:
9354 if (!Visit(E->getSubExpr()))
9355 return false;
9357 }
9358 }
9359};
9360} // end anonymous namespace
9361
9362/// Get an lvalue to a field of a lambda's closure type.
9363static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9364 const CXXMethodDecl *MD, const FieldDecl *FD,
9365 bool LValueToRValueConversion) {
9366 // Static lambda function call operators can't have captures. We already
9367 // diagnosed this, so bail out here.
9368 if (MD->isStatic()) {
9369 assert(Info.CurrentCall->This == nullptr &&
9370 "This should not be set for a static call operator");
9371 return false;
9372 }
9373
9374 // Start with 'Result' referring to the complete closure object...
9376 // Self may be passed by reference or by value.
9377 const ParmVarDecl *Self = MD->getParamDecl(0);
9378 if (Self->getType()->isReferenceType()) {
9379 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9380 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9381 Result.setFrom(Info.Ctx, *RefValue);
9382 } else {
9383 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9384 CallStackFrame *Frame =
9385 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9386 .first;
9387 unsigned Version = Info.CurrentCall->Arguments.Version;
9388 Result.set({VD, Frame->Index, Version});
9389 }
9390 } else
9391 Result = *Info.CurrentCall->This;
9392
9393 // ... then update it to refer to the field of the closure object
9394 // that represents the capture.
9395 if (!HandleLValueMember(Info, E, Result, FD))
9396 return false;
9397
9398 // And if the field is of reference type (or if we captured '*this' by
9399 // reference), update 'Result' to refer to what
9400 // the field refers to.
9401 if (LValueToRValueConversion) {
9402 APValue RVal;
9403 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9404 return false;
9405 Result.setFrom(Info.Ctx, RVal);
9406 }
9407 return true;
9408}
9409
9410/// Evaluate an expression as an lvalue. This can be legitimately called on
9411/// expressions which are not glvalues, in three cases:
9412/// * function designators in C, and
9413/// * "extern void" objects
9414/// * @selector() expressions in Objective-C
9415static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9416 bool InvalidBaseOK) {
9417 assert(!E->isValueDependent());
9418 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9420 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9421}
9422
9423bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9424 const ValueDecl *D = E->getDecl();
9425
9426 // If we are within a lambda's call operator, check whether the 'VD' referred
9427 // to within 'E' actually represents a lambda-capture that maps to a
9428 // data-member/field within the closure object, and if so, evaluate to the
9429 // field or what the field refers to.
9430 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9432 // We don't always have a complete capture-map when checking or inferring if
9433 // the function call operator meets the requirements of a constexpr function
9434 // - but we don't need to evaluate the captures to determine constexprness
9435 // (dcl.constexpr C++17).
9436 if (Info.checkingPotentialConstantExpression())
9437 return false;
9438
9439 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9440 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9441 return HandleLambdaCapture(Info, E, Result, MD, FD,
9442 FD->getType()->isReferenceType());
9443 }
9444 }
9445
9446 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9447 UnnamedGlobalConstantDecl>(D))
9448 return Success(cast<ValueDecl>(D));
9449 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9450 return VisitVarDecl(E, VD);
9451 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9452 return Visit(BD->getBinding());
9453 return Error(E);
9454}
9455
9456bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9457 CallStackFrame *Frame = nullptr;
9458 unsigned Version = 0;
9459 if (VD->hasLocalStorage()) {
9460 // Only if a local variable was declared in the function currently being
9461 // evaluated, do we expect to be able to find its value in the current
9462 // frame. (Otherwise it was likely declared in an enclosing context and
9463 // could either have a valid evaluatable value (for e.g. a constexpr
9464 // variable) or be ill-formed (and trigger an appropriate evaluation
9465 // diagnostic)).
9466 CallStackFrame *CurrFrame = Info.CurrentCall;
9467 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9468 // Function parameters are stored in some caller's frame. (Usually the
9469 // immediate caller, but for an inherited constructor they may be more
9470 // distant.)
9471 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9472 if (CurrFrame->Arguments) {
9473 VD = CurrFrame->Arguments.getOrigParam(PVD);
9474 Frame =
9475 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9476 Version = CurrFrame->Arguments.Version;
9477 }
9478 } else {
9479 Frame = CurrFrame;
9480 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9481 }
9482 }
9483 }
9484
9485 if (!VD->getType()->isReferenceType()) {
9486 if (Frame) {
9487 Result.set({VD, Frame->Index, Version});
9488 return true;
9489 }
9490 return Success(VD);
9491 }
9492
9493 if (!Info.getLangOpts().CPlusPlus11) {
9494 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9495 << VD << VD->getType();
9496 Info.Note(VD->getLocation(), diag::note_declared_at);
9497 }
9498
9499 APValue *V;
9500 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9501 return false;
9502
9503 if (!V) {
9504 Result.set(VD);
9505 Result.AllowConstexprUnknown = true;
9506 return true;
9507 }
9508
9509 return Success(*V, E);
9510}
9511
9512bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9513 if (!IsConstantEvaluatedBuiltinCall(E))
9514 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9515
9516 switch (E->getBuiltinCallee()) {
9517 default:
9518 return false;
9519 case Builtin::BIas_const:
9520 case Builtin::BIforward:
9521 case Builtin::BIforward_like:
9522 case Builtin::BImove:
9523 case Builtin::BImove_if_noexcept:
9524 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9525 return Visit(E->getArg(0));
9526 break;
9527 }
9528
9529 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9530}
9531
9532bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9533 const MaterializeTemporaryExpr *E) {
9534 // Walk through the expression to find the materialized temporary itself.
9537 const Expr *Inner =
9538 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9539
9540 // If we passed any comma operators, evaluate their LHSs.
9541 for (const Expr *E : CommaLHSs)
9542 if (!EvaluateIgnoredValue(Info, E))
9543 return false;
9544
9545 // A materialized temporary with static storage duration can appear within the
9546 // result of a constant expression evaluation, so we need to preserve its
9547 // value for use outside this evaluation.
9548 APValue *Value;
9549 if (E->getStorageDuration() == SD_Static) {
9550 if (Info.EvalMode == EvaluationMode::ConstantFold)
9551 return false;
9552 // FIXME: What about SD_Thread?
9553 Value = E->getOrCreateValue(true);
9554 *Value = APValue();
9555 Result.set(E);
9556 } else {
9557 Value = &Info.CurrentCall->createTemporary(
9558 E, Inner->getType(),
9559 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9560 : ScopeKind::Block,
9561 Result);
9562 }
9563
9564 QualType Type = Inner->getType();
9565
9566 // Materialize the temporary itself.
9567 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9568 *Value = APValue();
9569 return false;
9570 }
9571
9572 // Adjust our lvalue to refer to the desired subobject.
9573 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9574 --I;
9575 switch (Adjustments[I].Kind) {
9577 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9578 Type, Result))
9579 return false;
9580 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9581 break;
9582
9584 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9585 return false;
9586 Type = Adjustments[I].Field->getType();
9587 break;
9588
9590 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9591 Adjustments[I].Ptr.RHS))
9592 return false;
9593 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9594 break;
9595 }
9596 }
9597
9598 return true;
9599}
9600
9601bool
9602LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9603 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9604 "lvalue compound literal in c++?");
9605 APValue *Lit;
9606 // If CompountLiteral has static storage, its value can be used outside
9607 // this expression. So evaluate it once and store it in ASTContext.
9608 if (E->hasStaticStorage()) {
9609 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9610 Result.set(E);
9611 // Reset any previously evaluated state, otherwise evaluation below might
9612 // fail.
9613 // FIXME: Should we just re-use the previously evaluated value instead?
9614 *Lit = APValue();
9615 } else {
9616 assert(!Info.getLangOpts().CPlusPlus);
9617 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9618 ScopeKind::Block, Result);
9619 }
9620 // FIXME: Evaluating in place isn't always right. We should figure out how to
9621 // use appropriate evaluation context here, see
9622 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9623 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9624 *Lit = APValue();
9625 return false;
9626 }
9627 return true;
9628}
9629
9630bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9631 TypeInfoLValue TypeInfo;
9632
9633 if (!E->isPotentiallyEvaluated()) {
9634 if (E->isTypeOperand())
9635 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9636 else
9637 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9638 } else {
9639 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9640 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9641 << E->getExprOperand()->getType()
9642 << E->getExprOperand()->getSourceRange();
9643 }
9644
9645 if (!Visit(E->getExprOperand()))
9646 return false;
9647
9648 std::optional<DynamicType> DynType =
9650 if (!DynType)
9651 return false;
9652
9653 TypeInfo = TypeInfoLValue(
9654 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9655 }
9656
9657 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9658}
9659
9660bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9661 return Success(E->getGuidDecl());
9662}
9663
9664bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9665 // Handle static data members.
9666 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9667 VisitIgnoredBaseExpression(E->getBase());
9668 return VisitVarDecl(E, VD);
9669 }
9670
9671 // Handle static member functions.
9672 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9673 if (MD->isStatic()) {
9674 VisitIgnoredBaseExpression(E->getBase());
9675 return Success(MD);
9676 }
9677 }
9678
9679 // Handle non-static data members.
9680 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9681}
9682
9683bool LValueExprEvaluator::VisitExtVectorElementExpr(
9684 const ExtVectorElementExpr *E) {
9685 bool Success = true;
9686
9687 APValue Val;
9688 if (!Evaluate(Val, Info, E->getBase())) {
9689 if (!Info.noteFailure())
9690 return false;
9691 Success = false;
9692 }
9693
9695 E->getEncodedElementAccess(Indices);
9696 // FIXME: support accessing more than one element
9697 if (Indices.size() > 1)
9698 return false;
9699
9700 if (Success) {
9701 Result.setFrom(Info.Ctx, Val);
9702 QualType BaseType = E->getBase()->getType();
9703 if (E->isArrow())
9704 BaseType = BaseType->getPointeeType();
9705 const auto *VT = BaseType->castAs<VectorType>();
9706 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9707 VT->getNumElements(), Indices[0]);
9708 }
9709
9710 return Success;
9711}
9712
9713bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9714 if (E->getBase()->getType()->isSveVLSBuiltinType())
9715 return Error(E);
9716
9717 APSInt Index;
9718 bool Success = true;
9719
9720 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9721 APValue Val;
9722 if (!Evaluate(Val, Info, E->getBase())) {
9723 if (!Info.noteFailure())
9724 return false;
9725 Success = false;
9726 }
9727
9728 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9729 if (!Info.noteFailure())
9730 return false;
9731 Success = false;
9732 }
9733
9734 if (Success) {
9735 Result.setFrom(Info.Ctx, Val);
9736 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9737 VT->getNumElements(), Index.getZExtValue());
9738 }
9739
9740 return Success;
9741 }
9742
9743 // C++17's rules require us to evaluate the LHS first, regardless of which
9744 // side is the base.
9745 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9746 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9747 : !EvaluateInteger(SubExpr, Index, Info)) {
9748 if (!Info.noteFailure())
9749 return false;
9750 Success = false;
9751 }
9752 }
9753
9754 return Success &&
9755 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9756}
9757
9758bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9759 bool Success = evaluatePointer(E->getSubExpr(), Result);
9760 // [C++26][expr.unary.op]
9761 // If the operand points to an object or function, the result
9762 // denotes that object or function; otherwise, the behavior is undefined.
9763 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9764 // immediately.
9766 return Success;
9768 E->getType())) ||
9769 Info.noteUndefinedBehavior();
9770}
9771
9772bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9773 if (!Visit(E->getSubExpr()))
9774 return false;
9775 // __real is a no-op on scalar lvalues.
9776 if (E->getSubExpr()->getType()->isAnyComplexType())
9777 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9778 return true;
9779}
9780
9781bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9782 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9783 "lvalue __imag__ on scalar?");
9784 if (!Visit(E->getSubExpr()))
9785 return false;
9786 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9787 return true;
9788}
9789
9790bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9791 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9792 return Error(UO);
9793
9794 if (!this->Visit(UO->getSubExpr()))
9795 return false;
9796
9797 return handleIncDec(
9798 this->Info, UO, Result, UO->getSubExpr()->getType(),
9799 UO->isIncrementOp(), nullptr);
9800}
9801
9802bool LValueExprEvaluator::VisitCompoundAssignOperator(
9803 const CompoundAssignOperator *CAO) {
9804 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9805 return Error(CAO);
9806
9807 bool Success = true;
9808
9809 // C++17 onwards require that we evaluate the RHS first.
9810 APValue RHS;
9811 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9812 if (!Info.noteFailure())
9813 return false;
9814 Success = false;
9815 }
9816
9817 // The overall lvalue result is the result of evaluating the LHS.
9818 if (!this->Visit(CAO->getLHS()) || !Success)
9819 return false;
9820
9822 this->Info, CAO,
9823 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9824 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9825}
9826
9827bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9828 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9829 return Error(E);
9830
9831 bool Success = true;
9832
9833 // C++17 onwards require that we evaluate the RHS first.
9834 APValue NewVal;
9835 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9836 if (!Info.noteFailure())
9837 return false;
9838 Success = false;
9839 }
9840
9841 if (!this->Visit(E->getLHS()) || !Success)
9842 return false;
9843
9844 if (Info.getLangOpts().CPlusPlus20 &&
9846 return false;
9847
9848 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9849 NewVal);
9850}
9851
9852//===----------------------------------------------------------------------===//
9853// Pointer Evaluation
9854//===----------------------------------------------------------------------===//
9855
9856/// Convenience function. LVal's base must be a call to an alloc_size
9857/// function.
9859 const LValue &LVal,
9860 llvm::APInt &Result) {
9861 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9862 "Can't get the size of a non alloc_size function");
9863 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9864 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9865 std::optional<llvm::APInt> Size =
9866 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
9867 if (!Size)
9868 return false;
9869
9870 Result = std::move(*Size);
9871 return true;
9872}
9873
9874/// Attempts to evaluate the given LValueBase as the result of a call to
9875/// a function with the alloc_size attribute. If it was possible to do so, this
9876/// function will return true, make Result's Base point to said function call,
9877/// and mark Result's Base as invalid.
9879 LValue &Result) {
9880 if (Base.isNull())
9881 return false;
9882
9883 // Because we do no form of static analysis, we only support const variables.
9884 //
9885 // Additionally, we can't support parameters, nor can we support static
9886 // variables (in the latter case, use-before-assign isn't UB; in the former,
9887 // we have no clue what they'll be assigned to).
9888 const auto *VD =
9889 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9890 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9891 return false;
9892
9893 const Expr *Init = VD->getAnyInitializer();
9894 if (!Init || Init->getType().isNull())
9895 return false;
9896
9897 const Expr *E = Init->IgnoreParens();
9898 if (!tryUnwrapAllocSizeCall(E))
9899 return false;
9900
9901 // Store E instead of E unwrapped so that the type of the LValue's base is
9902 // what the user wanted.
9903 Result.setInvalid(E);
9904
9905 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9906 Result.addUnsizedArray(Info, E, Pointee);
9907 return true;
9908}
9909
9910namespace {
9911class PointerExprEvaluator
9912 : public ExprEvaluatorBase<PointerExprEvaluator> {
9913 LValue &Result;
9914 bool InvalidBaseOK;
9915
9916 bool Success(const Expr *E) {
9917 Result.set(E);
9918 return true;
9919 }
9920
9921 bool evaluateLValue(const Expr *E, LValue &Result) {
9922 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9923 }
9924
9925 bool evaluatePointer(const Expr *E, LValue &Result) {
9926 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9927 }
9928
9929 bool visitNonBuiltinCallExpr(const CallExpr *E);
9930public:
9931
9932 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9933 : ExprEvaluatorBaseTy(info), Result(Result),
9934 InvalidBaseOK(InvalidBaseOK) {}
9935
9936 bool Success(const APValue &V, const Expr *E) {
9937 Result.setFrom(Info.Ctx, V);
9938 return true;
9939 }
9940 bool ZeroInitialization(const Expr *E) {
9941 Result.setNull(Info.Ctx, E->getType());
9942 return true;
9943 }
9944
9945 bool VisitBinaryOperator(const BinaryOperator *E);
9946 bool VisitCastExpr(const CastExpr* E);
9947 bool VisitUnaryAddrOf(const UnaryOperator *E);
9948 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9949 { return Success(E); }
9950 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9952 return Success(E);
9953 if (Info.noteFailure())
9954 EvaluateIgnoredValue(Info, E->getSubExpr());
9955 return Error(E);
9956 }
9957 bool VisitObjCArrayLiteral(const ObjCArrayLiteral *E) {
9958 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
9959 }
9960 bool VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E) {
9961 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
9962 }
9963 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9964 { return Success(E); }
9965 bool VisitCallExpr(const CallExpr *E);
9966 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9967 bool VisitBlockExpr(const BlockExpr *E) {
9968 if (!E->getBlockDecl()->hasCaptures())
9969 return Success(E);
9970 return Error(E);
9971 }
9972 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9973 auto DiagnoseInvalidUseOfThis = [&] {
9974 if (Info.getLangOpts().CPlusPlus11)
9975 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9976 else
9977 Info.FFDiag(E);
9978 };
9979
9980 // Can't look at 'this' when checking a potential constant expression.
9981 if (Info.checkingPotentialConstantExpression())
9982 return false;
9983
9984 bool IsExplicitLambda =
9985 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9986 if (!IsExplicitLambda) {
9987 if (!Info.CurrentCall->This) {
9988 DiagnoseInvalidUseOfThis();
9989 return false;
9990 }
9991
9992 Result = *Info.CurrentCall->This;
9993 }
9994
9995 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9996 // Ensure we actually have captured 'this'. If something was wrong with
9997 // 'this' capture, the error would have been previously reported.
9998 // Otherwise we can be inside of a default initialization of an object
9999 // declared by lambda's body, so no need to return false.
10000 if (!Info.CurrentCall->LambdaThisCaptureField) {
10001 if (IsExplicitLambda && !Info.CurrentCall->This) {
10002 DiagnoseInvalidUseOfThis();
10003 return false;
10004 }
10005
10006 return true;
10007 }
10008
10009 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
10010 return HandleLambdaCapture(
10011 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
10012 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
10013 }
10014 return true;
10015 }
10016
10017 bool VisitCXXNewExpr(const CXXNewExpr *E);
10018
10019 bool VisitSourceLocExpr(const SourceLocExpr *E) {
10020 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
10021 APValue LValResult = E->EvaluateInContext(
10022 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10023 Result.setFrom(Info.Ctx, LValResult);
10024 return true;
10025 }
10026
10027 bool VisitEmbedExpr(const EmbedExpr *E) {
10028 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
10029 return true;
10030 }
10031
10032 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
10033 std::string ResultStr = E->ComputeName(Info.Ctx);
10034
10035 QualType CharTy = Info.Ctx.CharTy.withConst();
10036 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
10037 ResultStr.size() + 1);
10038 QualType ArrayTy = Info.Ctx.getConstantArrayType(
10039 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
10040
10041 StringLiteral *SL =
10042 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
10043 /*Pascal*/ false, ArrayTy, E->getLocation());
10044
10045 evaluateLValue(SL, Result);
10046 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
10047 return true;
10048 }
10049
10050 // FIXME: Missing: @protocol, @selector
10051};
10052} // end anonymous namespace
10053
10054static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
10055 bool InvalidBaseOK) {
10056 assert(!E->isValueDependent());
10057 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
10058 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
10059}
10060
10061bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10062 if (E->getOpcode() != BO_Add &&
10063 E->getOpcode() != BO_Sub)
10064 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10065
10066 const Expr *PExp = E->getLHS();
10067 const Expr *IExp = E->getRHS();
10068 if (IExp->getType()->isPointerType())
10069 std::swap(PExp, IExp);
10070
10071 bool EvalPtrOK = evaluatePointer(PExp, Result);
10072 if (!EvalPtrOK && !Info.noteFailure())
10073 return false;
10074
10075 llvm::APSInt Offset;
10076 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
10077 return false;
10078
10079 if (E->getOpcode() == BO_Sub)
10080 negateAsSigned(Offset);
10081
10082 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
10083 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
10084}
10085
10086bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10087 // [C11 6.5.3.2p3]: if the operand of '&' is the result of a unary '*'
10088 // operator, neither operator is evaluated and the result is as if both were
10089 // omitted (except that the operators' constraints, already enforced by Sema,
10090 // still apply, and the result is not an lvalue). So '&*p' is just the pointer
10091 // value 'p' with no dereference, and forming it is therefore not undefined
10092 // behavior even when 'p' is null, e.g. '&*(int *)0'. Evaluate the pointer
10093 // operand directly so we don't spuriously diagnose a null dereference.
10094 if (!Info.getLangOpts().CPlusPlus) {
10095 const Expr *Sub = E->getSubExpr()->IgnoreParens();
10096 if (const auto *Deref = dyn_cast<UnaryOperator>(Sub);
10097 Deref && Deref->getOpcode() == UO_Deref)
10098 return evaluatePointer(Deref->getSubExpr(), Result);
10099 }
10100 return evaluateLValue(E->getSubExpr(), Result);
10101}
10102
10103// Is the provided decl 'std::source_location::current'?
10105 if (!FD)
10106 return false;
10107 const IdentifierInfo *FnII = FD->getIdentifier();
10108 if (!FnII || !FnII->isStr("current"))
10109 return false;
10110
10111 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
10112 if (!RD)
10113 return false;
10114
10115 const IdentifierInfo *ClassII = RD->getIdentifier();
10116 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
10117}
10118
10119bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10120 const Expr *SubExpr = E->getSubExpr();
10121
10122 switch (E->getCastKind()) {
10123 default:
10124 break;
10125 case CK_BitCast:
10126 case CK_CPointerToObjCPointerCast:
10127 case CK_BlockPointerToObjCPointerCast:
10128 case CK_AnyPointerToBlockPointerCast:
10129 case CK_AddressSpaceConversion:
10130 if (!Visit(SubExpr))
10131 return false;
10132 if (E->getType()->isFunctionPointerType() ||
10133 SubExpr->getType()->isFunctionPointerType()) {
10134 // Casting between two function pointer types, or between a function
10135 // pointer and an object pointer, is always a reinterpret_cast.
10136 CCEDiag(E, diag::note_constexpr_invalid_cast)
10137 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10138 << Info.Ctx.getLangOpts().CPlusPlus;
10139 Result.Designator.setInvalid();
10140 } else if (!E->getType()->isVoidPointerType()) {
10141 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
10142 // permitted in constant expressions in C++11. Bitcasts from cv void* are
10143 // also static_casts, but we disallow them as a resolution to DR1312.
10144 //
10145 // In some circumstances, we permit casting from void* to cv1 T*, when the
10146 // actual pointee object is actually a cv2 T.
10147 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
10148 !Result.IsNullPtr;
10149 bool VoidPtrCastMaybeOK =
10150 Result.IsNullPtr ||
10151 (HasValidResult &&
10152 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
10153 E->getType()->getPointeeType()));
10154 // 1. We'll allow it in std::allocator::allocate, and anything which that
10155 // calls.
10156 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
10157 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
10158 // We'll allow it in the body of std::source_location::current. GCC's
10159 // implementation had a parameter of type `void*`, and casts from
10160 // that back to `const __impl*` in its body.
10161 if (VoidPtrCastMaybeOK &&
10162 (Info.getStdAllocatorCaller("allocate") ||
10163 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
10164 Info.getLangOpts().CPlusPlus26)) {
10165 // Permitted.
10166 } else {
10167 if (SubExpr->getType()->isVoidPointerType() &&
10168 Info.getLangOpts().CPlusPlus) {
10169 if (HasValidResult)
10170 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10171 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
10172 << Result.Designator.getType(Info.Ctx).getCanonicalType()
10173 << E->getType()->getPointeeType();
10174 else
10175 CCEDiag(E, diag::note_constexpr_invalid_cast)
10176 << diag::ConstexprInvalidCastKind::CastFrom
10177 << SubExpr->getType();
10178 } else
10179 CCEDiag(E, diag::note_constexpr_invalid_cast)
10180 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10181 << Info.Ctx.getLangOpts().CPlusPlus;
10182 Result.Designator.setInvalid();
10183 }
10184 }
10185 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
10186 ZeroInitialization(E);
10187 return true;
10188
10189 case CK_DerivedToBase:
10190 case CK_UncheckedDerivedToBase:
10191 if (!evaluatePointer(E->getSubExpr(), Result))
10192 return false;
10193 if (!Result.Base && Result.Offset.isZero())
10194 return true;
10195
10196 // Now figure out the necessary offset to add to the base LV to get from
10197 // the derived class to the base class.
10198 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
10199 castAs<PointerType>()->getPointeeType(),
10200 Result);
10201
10202 case CK_BaseToDerived:
10203 if (!Visit(E->getSubExpr()))
10204 return false;
10205 if (!Result.Base && Result.Offset.isZero())
10206 return true;
10207 return HandleBaseToDerivedCast(Info, E, Result);
10208
10209 case CK_Dynamic:
10210 if (!Visit(E->getSubExpr()))
10211 return false;
10213
10214 case CK_NullToPointer:
10215 VisitIgnoredValue(E->getSubExpr());
10216 return ZeroInitialization(E);
10217
10218 case CK_IntegralToPointer: {
10219 CCEDiag(E, diag::note_constexpr_invalid_cast)
10220 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10221 << Info.Ctx.getLangOpts().CPlusPlus;
10222
10223 APValue Value;
10224 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
10225 break;
10226
10227 if (Value.isInt()) {
10228 unsigned Size = Info.Ctx.getTypeSize(E->getType());
10229 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
10230 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
10231 Result.setNull(Info.Ctx, E->getType());
10232 } else {
10233 Result.Base = (Expr *)nullptr;
10234 Result.InvalidBase = false;
10235 Result.Offset = CharUnits::fromQuantity(N);
10236 Result.Designator.setInvalid();
10237 Result.IsNullPtr = false;
10238 }
10239 return true;
10240 } else {
10241 // In rare instances, the value isn't an lvalue.
10242 // For example, when the value is the difference between the addresses of
10243 // two labels. We reject that as a constant expression because we can't
10244 // compute a valid offset to convert into a pointer.
10245 if (!Value.isLValue())
10246 return false;
10247
10248 // Cast is of an lvalue, no need to change value.
10249 Result.setFrom(Info.Ctx, Value);
10250 return true;
10251 }
10252 }
10253
10254 case CK_ArrayToPointerDecay: {
10255 if (SubExpr->isGLValue()) {
10256 if (!evaluateLValue(SubExpr, Result))
10257 return false;
10258 } else {
10259 APValue &Value = Info.CurrentCall->createTemporary(
10260 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
10261 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
10262 return false;
10263 }
10264 // The result is a pointer to the first element of the array.
10265 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
10266 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
10267 Result.addArray(Info, E, CAT);
10268 else
10269 Result.addUnsizedArray(Info, E, AT->getElementType());
10270 return true;
10271 }
10272
10273 case CK_FunctionToPointerDecay:
10274 return evaluateLValue(SubExpr, Result);
10275
10276 case CK_LValueToRValue: {
10277 LValue LVal;
10278 if (!evaluateLValue(E->getSubExpr(), LVal))
10279 return false;
10280
10281 APValue RVal;
10282 // Note, we use the subexpression's type in order to retain cv-qualifiers.
10284 LVal, RVal))
10285 return InvalidBaseOK &&
10286 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
10287 return Success(RVal, E);
10288 }
10289 }
10290
10291 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10292}
10293
10295 UnaryExprOrTypeTrait ExprKind) {
10296 // C++ [expr.alignof]p3:
10297 // When alignof is applied to a reference type, the result is the
10298 // alignment of the referenced type.
10299 T = T.getNonReferenceType();
10300
10301 if (T.getQualifiers().hasUnaligned())
10302 return CharUnits::One();
10303
10304 const bool AlignOfReturnsPreferred =
10305 Ctx.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver7);
10306
10307 // __alignof is defined to return the preferred alignment.
10308 // Before 8, clang returned the preferred alignment for alignof and _Alignof
10309 // as well.
10310 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10311 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
10312 // alignof and _Alignof are defined to return the ABI alignment.
10313 else if (ExprKind == UETT_AlignOf)
10314 return Ctx.getTypeAlignInChars(T.getTypePtr());
10315 else
10316 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
10317}
10318
10319// Convert a builtin ID to the canonical x86 builtin ID the constant evaluators
10320// dispatch on in their x86 target-specific cases, or 0 if \p BuiltinOp is a
10321// target builtin those cases should not handle.
10322//
10323// Target-independent builtins are returned unchanged. Target builtin IDs of
10324// different targets overlap (each target numbers its builtins from
10325// Builtin::FirstTSBuiltin), so a target builtin ID is only meaningful for the
10326// target that owns it. Determine the owning target (translating an auxiliary ID
10327// back to its canonical value) and only return the ID when x86 owns it;
10328// otherwise an overlapping ID could be misinterpreted as an unrelated x86
10329// builtin.
10331 unsigned BuiltinOp) {
10332 // Target-independent builtins have the same ID regardless of the target, so
10333 // they can be dispatched as-is. This is the common case and is intentionally
10334 // kept to a single comparison so callers can use this on hot paths (e.g. the
10335 // bytecode interpreter's builtin dispatch) without re-deriving the ID from
10336 // the call expression.
10337 if (BuiltinOp < Builtin::FirstTSBuiltin)
10338 return BuiltinOp;
10339
10340 // Determine the target that owns this builtin, translating an auxiliary ID
10341 // back to its canonical value.
10342 const TargetInfo *OwningTarget;
10343 if (Ctx.BuiltinInfo.isAuxBuiltinID(BuiltinOp)) {
10344 OwningTarget = Ctx.getAuxTargetInfo();
10345 BuiltinOp = Ctx.BuiltinInfo.getAuxBuiltinID(BuiltinOp);
10346 } else {
10347 OwningTarget = &Ctx.getTargetInfo();
10348 }
10349
10350 if (!OwningTarget)
10351 return 0;
10352
10353 // x86 and x86_64 share a single builtin set and are the only architectures
10354 // whose target-specific builtins the constant evaluators currently fold.
10355 switch (OwningTarget->getTriple().getArch()) {
10356 case llvm::Triple::x86:
10357 case llvm::Triple::x86_64:
10358 return BuiltinOp;
10359 default:
10360 return 0;
10361 }
10362}
10363
10365 const CallExpr *E) {
10367}
10368
10370 UnaryExprOrTypeTrait ExprKind) {
10371 E = E->IgnoreParens();
10372
10373 // The kinds of expressions that we have special-case logic here for
10374 // should be kept up to date with the special checks for those
10375 // expressions in Sema.
10376
10377 // alignof decl is always accepted, even if it doesn't make sense: we default
10378 // to 1 in those cases.
10379 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10380 return Ctx.getDeclAlign(DRE->getDecl(),
10381 /*RefAsPointee*/ true);
10382
10383 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10384 return Ctx.getDeclAlign(ME->getMemberDecl(),
10385 /*RefAsPointee*/ true);
10386
10387 return GetAlignOfType(Ctx, E->getType(), ExprKind);
10388}
10389
10390static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
10391 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
10392 return Info.Ctx.getDeclAlign(VD);
10393 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
10394 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
10395 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
10396}
10397
10398/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
10399/// __builtin_is_aligned and __builtin_assume_aligned.
10400static bool getAlignmentArgument(const Expr *E, QualType ForType,
10401 EvalInfo &Info, APSInt &Alignment) {
10402 if (!EvaluateInteger(E, Alignment, Info))
10403 return false;
10404 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10405 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10406 return false;
10407 }
10408 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10409 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10410 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10411 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10412 << MaxValue << ForType << Alignment;
10413 return false;
10414 }
10415 // Ensure both alignment and source value have the same bit width so that we
10416 // don't assert when computing the resulting value.
10417 APSInt ExtAlignment =
10418 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10419 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10420 "Alignment should not be changed by ext/trunc");
10421 Alignment = ExtAlignment;
10422 assert(Alignment.getBitWidth() == SrcWidth);
10423 return true;
10424}
10425
10426// To be clear: this happily visits unsupported builtins. Better name welcomed.
10427bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10428 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10429 return true;
10430
10431 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10432 return false;
10433
10434 Result.setInvalid(E);
10435 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10436 Result.addUnsizedArray(Info, E, PointeeTy);
10437 return true;
10438}
10439
10440bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10441 if (!IsConstantEvaluatedBuiltinCall(E))
10442 return visitNonBuiltinCallExpr(E);
10443 return VisitBuiltinCallExpr(E, ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E));
10444}
10445
10446// Determine if T is a character type for which we guarantee that
10447// sizeof(T) == 1.
10449 return T->isCharType() || T->isChar8Type();
10450}
10451
10452bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10453 unsigned BuiltinOp) {
10454 if (IsOpaqueConstantCall(E))
10455 return Success(E);
10456
10457 switch (BuiltinOp) {
10458 case Builtin::BIaddressof:
10459 case Builtin::BI__addressof:
10460 case Builtin::BI__builtin_addressof:
10461 return evaluateLValue(E->getArg(0), Result);
10462 case Builtin::BI__builtin_assume_aligned: {
10463 // We need to be very careful here because: if the pointer does not have the
10464 // asserted alignment, then the behavior is undefined, and undefined
10465 // behavior is non-constant.
10466 if (!evaluatePointer(E->getArg(0), Result))
10467 return false;
10468
10469 LValue OffsetResult(Result);
10470 APSInt Alignment;
10471 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10472 Alignment))
10473 return false;
10474 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10475
10476 if (E->getNumArgs() > 2) {
10477 APSInt Offset;
10478 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10479 return false;
10480
10481 int64_t AdditionalOffset = -Offset.getZExtValue();
10482 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10483 }
10484
10485 // If there is a base object, then it must have the correct alignment.
10486 if (OffsetResult.Base) {
10487 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10488
10489 if (BaseAlignment < Align) {
10490 Result.Designator.setInvalid();
10491 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10492 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10493 return false;
10494 }
10495 }
10496
10497 // The offset must also have the correct alignment.
10498 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10499 Result.Designator.setInvalid();
10500
10501 (OffsetResult.Base
10502 ? CCEDiag(E->getArg(0),
10503 diag::note_constexpr_baa_insufficient_alignment)
10504 << 1
10505 : CCEDiag(E->getArg(0),
10506 diag::note_constexpr_baa_value_insufficient_alignment))
10507 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10508 return false;
10509 }
10510
10511 return true;
10512 }
10513 case Builtin::BI__builtin_align_up:
10514 case Builtin::BI__builtin_align_down: {
10515 if (!evaluatePointer(E->getArg(0), Result))
10516 return false;
10517 APSInt Alignment;
10518 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10519 Alignment))
10520 return false;
10521 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10522 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10523 // For align_up/align_down, we can return the same value if the alignment
10524 // is known to be greater or equal to the requested value.
10525 if (PtrAlign.getQuantity() >= Alignment)
10526 return true;
10527
10528 // The alignment could be greater than the minimum at run-time, so we cannot
10529 // infer much about the resulting pointer value. One case is possible:
10530 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10531 // can infer the correct index if the requested alignment is smaller than
10532 // the base alignment so we can perform the computation on the offset.
10533 if (BaseAlignment.getQuantity() >= Alignment) {
10534 assert(Alignment.getBitWidth() <= 64 &&
10535 "Cannot handle > 64-bit address-space");
10536 uint64_t Alignment64 = Alignment.getZExtValue();
10537 CharUnits NewOffset = CharUnits::fromQuantity(
10538 BuiltinOp == Builtin::BI__builtin_align_down
10539 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10540 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10541 Result.adjustOffset(NewOffset - Result.Offset);
10542 // TODO: diagnose out-of-bounds values/only allow for arrays?
10543 return true;
10544 }
10545 // Otherwise, we cannot constant-evaluate the result.
10546 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10547 << Alignment;
10548 return false;
10549 }
10550 case Builtin::BI__builtin_operator_new:
10551 return HandleOperatorNewCall(Info, E, Result);
10552 case Builtin::BI__builtin_launder:
10553 return evaluatePointer(E->getArg(0), Result);
10554 case Builtin::BIstrchr:
10555 case Builtin::BIwcschr:
10556 case Builtin::BImemchr:
10557 case Builtin::BIwmemchr:
10558 if (Info.getLangOpts().CPlusPlus11)
10559 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10560 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10561 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10562 else
10563 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10564 [[fallthrough]];
10565 case Builtin::BI__builtin_strchr:
10566 case Builtin::BI__builtin_wcschr:
10567 case Builtin::BI__builtin_memchr:
10568 case Builtin::BI__builtin_char_memchr:
10569 case Builtin::BI__builtin_wmemchr: {
10570 if (!Visit(E->getArg(0)))
10571 return false;
10572 APSInt Desired;
10573 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10574 return false;
10575 uint64_t MaxLength = uint64_t(-1);
10576 if (BuiltinOp != Builtin::BIstrchr &&
10577 BuiltinOp != Builtin::BIwcschr &&
10578 BuiltinOp != Builtin::BI__builtin_strchr &&
10579 BuiltinOp != Builtin::BI__builtin_wcschr) {
10580 APSInt N;
10581 if (!EvaluateInteger(E->getArg(2), N, Info))
10582 return false;
10583 MaxLength = N.getZExtValue();
10584 }
10585 // We cannot find the value if there are no candidates to match against.
10586 if (MaxLength == 0u)
10587 return ZeroInitialization(E);
10588 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10589 Result.Designator.Invalid)
10590 return false;
10591 QualType CharTy = Result.Designator.getType(Info.Ctx);
10592 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10593 BuiltinOp == Builtin::BI__builtin_memchr;
10594 assert(IsRawByte ||
10595 Info.Ctx.hasSameUnqualifiedType(
10596 CharTy, E->getArg(0)->getType()->getPointeeType()));
10597 // Pointers to const void may point to objects of incomplete type.
10598 if (IsRawByte && CharTy->isIncompleteType()) {
10599 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10600 return false;
10601 }
10602 // Give up on byte-oriented matching against multibyte elements.
10603 // FIXME: We can compare the bytes in the correct order.
10604 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10605 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10606 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10607 return false;
10608 }
10609 // Figure out what value we're actually looking for (after converting to
10610 // the corresponding unsigned type if necessary).
10611 uint64_t DesiredVal;
10612 bool StopAtNull = false;
10613 switch (BuiltinOp) {
10614 case Builtin::BIstrchr:
10615 case Builtin::BI__builtin_strchr:
10616 // strchr compares directly to the passed integer, and therefore
10617 // always fails if given an int that is not a char.
10618 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10619 E->getArg(1)->getType(),
10620 Desired),
10621 Desired))
10622 return ZeroInitialization(E);
10623 StopAtNull = true;
10624 [[fallthrough]];
10625 case Builtin::BImemchr:
10626 case Builtin::BI__builtin_memchr:
10627 case Builtin::BI__builtin_char_memchr:
10628 // memchr compares by converting both sides to unsigned char. That's also
10629 // correct for strchr if we get this far (to cope with plain char being
10630 // unsigned in the strchr case).
10631 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10632 break;
10633
10634 case Builtin::BIwcschr:
10635 case Builtin::BI__builtin_wcschr:
10636 StopAtNull = true;
10637 [[fallthrough]];
10638 case Builtin::BIwmemchr:
10639 case Builtin::BI__builtin_wmemchr:
10640 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10641 DesiredVal = Desired.getZExtValue();
10642 break;
10643 }
10644
10645 for (; MaxLength; --MaxLength) {
10646 APValue Char;
10647 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10648 !Char.isInt())
10649 return false;
10650 if (Char.getInt().getZExtValue() == DesiredVal)
10651 return true;
10652 if (StopAtNull && !Char.getInt())
10653 break;
10654 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10655 return false;
10656 }
10657 // Not found: return nullptr.
10658 return ZeroInitialization(E);
10659 }
10660
10661 case Builtin::BImemcpy:
10662 case Builtin::BImemmove:
10663 case Builtin::BIwmemcpy:
10664 case Builtin::BIwmemmove:
10665 if (Info.getLangOpts().CPlusPlus11)
10666 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10667 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10668 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10669 else
10670 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10671 [[fallthrough]];
10672 case Builtin::BI__builtin_memcpy:
10673 case Builtin::BI__builtin_memmove:
10674 case Builtin::BI__builtin_wmemcpy:
10675 case Builtin::BI__builtin_wmemmove: {
10676 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10677 BuiltinOp == Builtin::BIwmemmove ||
10678 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10679 BuiltinOp == Builtin::BI__builtin_wmemmove;
10680 bool Move = BuiltinOp == Builtin::BImemmove ||
10681 BuiltinOp == Builtin::BIwmemmove ||
10682 BuiltinOp == Builtin::BI__builtin_memmove ||
10683 BuiltinOp == Builtin::BI__builtin_wmemmove;
10684
10685 // The result of mem* is the first argument.
10686 if (!Visit(E->getArg(0)))
10687 return false;
10688 LValue Dest = Result;
10689
10690 LValue Src;
10691 if (!EvaluatePointer(E->getArg(1), Src, Info))
10692 return false;
10693
10694 APSInt N;
10695 if (!EvaluateInteger(E->getArg(2), N, Info))
10696 return false;
10697 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10698
10699 // If the size is zero, we treat this as always being a valid no-op.
10700 // (Even if one of the src and dest pointers is null.)
10701 if (!N)
10702 return true;
10703
10704 // Otherwise, if either of the operands is null, we can't proceed. Don't
10705 // try to determine the type of the copied objects, because there aren't
10706 // any.
10707 if (!Src.Base || !Dest.Base) {
10708 APValue Val;
10709 (!Src.Base ? Src : Dest).moveInto(Val);
10710 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10711 << Move << WChar << !!Src.Base
10712 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10713 return false;
10714 }
10715 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10716 return false;
10717
10718 // We require that Src and Dest are both pointers to arrays of
10719 // trivially-copyable type. (For the wide version, the designator will be
10720 // invalid if the designated object is not a wchar_t.)
10721 QualType T = Dest.Designator.getType(Info.Ctx);
10722 QualType SrcT = Src.Designator.getType(Info.Ctx);
10723 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10724 // FIXME: Consider using our bit_cast implementation to support this.
10725 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10726 return false;
10727 }
10728 if (T->isIncompleteType()) {
10729 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10730 return false;
10731 }
10732 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10733 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10734 return false;
10735 }
10736
10737 // Figure out how many T's we're copying.
10738 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10739 if (TSize == 0)
10740 return false;
10741 if (!WChar) {
10742 uint64_t Remainder;
10743 llvm::APInt OrigN = N;
10744 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10745 if (Remainder) {
10746 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10747 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10748 << (unsigned)TSize;
10749 return false;
10750 }
10751 }
10752
10753 // Check that the copying will remain within the arrays, just so that we
10754 // can give a more meaningful diagnostic. This implicitly also checks that
10755 // N fits into 64 bits.
10756 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10757 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10758 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10759 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10760 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10761 << toString(N, 10, /*Signed*/false);
10762 return false;
10763 }
10764 uint64_t NElems = N.getZExtValue();
10765 uint64_t NBytes = NElems * TSize;
10766
10767 // Check for overlap.
10768 int Direction = 1;
10769 if (HasSameBase(Src, Dest)) {
10770 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10771 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10772 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10773 // Dest is inside the source region.
10774 if (!Move) {
10775 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10776 return false;
10777 }
10778 // For memmove and friends, copy backwards.
10779 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10780 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10781 return false;
10782 Direction = -1;
10783 } else if (!Move && SrcOffset >= DestOffset &&
10784 SrcOffset - DestOffset < NBytes) {
10785 // Src is inside the destination region for memcpy: invalid.
10786 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10787 return false;
10788 }
10789 }
10790
10791 while (true) {
10792 APValue Val;
10793 // FIXME: Set WantObjectRepresentation to true if we're copying a
10794 // char-like type?
10795 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10796 !handleAssignment(Info, E, Dest, T, Val))
10797 return false;
10798 // Do not iterate past the last element; if we're copying backwards, that
10799 // might take us off the start of the array.
10800 if (--NElems == 0)
10801 return true;
10802 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10803 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10804 return false;
10805 }
10806 }
10807
10808 default:
10809 return false;
10810 }
10811}
10812
10813static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10814 APValue &Result, const InitListExpr *ILE,
10815 QualType AllocType);
10816static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10817 APValue &Result,
10818 const CXXConstructExpr *CCE,
10819 QualType AllocType);
10820
10821bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10822 if (!Info.getLangOpts().CPlusPlus20)
10823 Info.CCEDiag(E, diag::note_constexpr_new);
10824
10825 // We cannot speculatively evaluate a delete expression.
10826 if (Info.SpeculativeEvaluationDepth)
10827 return false;
10828
10829 FunctionDecl *OperatorNew = E->getOperatorNew();
10830 QualType AllocType = E->getAllocatedType();
10831 QualType TargetType = AllocType;
10832
10833 bool IsNothrow = false;
10834 bool IsPlacement = false;
10835
10836 if (E->getNumPlacementArgs() == 1 &&
10837 E->getPlacementArg(0)->getType()->isNothrowT()) {
10838 // The only new-placement list we support is of the form (std::nothrow).
10839 //
10840 // FIXME: There is no restriction on this, but it's not clear that any
10841 // other form makes any sense. We get here for cases such as:
10842 //
10843 // new (std::align_val_t{N}) X(int)
10844 //
10845 // (which should presumably be valid only if N is a multiple of
10846 // alignof(int), and in any case can't be deallocated unless N is
10847 // alignof(X) and X has new-extended alignment).
10848 LValue Nothrow;
10849 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10850 return false;
10851 IsNothrow = true;
10852 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10853 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10854 (Info.CurrentCall->CanEvalMSConstexpr &&
10855 OperatorNew->hasAttr<MSConstexprAttr>())) {
10856 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10857 return false;
10858 if (Result.Designator.Invalid)
10859 return false;
10860 TargetType = E->getPlacementArg(0)->getType();
10861 IsPlacement = true;
10862 } else {
10863 Info.FFDiag(E, diag::note_constexpr_new_placement)
10864 << /*C++26 feature*/ 1 << E->getSourceRange();
10865 return false;
10866 }
10867 } else if (E->getNumPlacementArgs()) {
10868 Info.FFDiag(E, diag::note_constexpr_new_placement)
10869 << /*Unsupported*/ 0 << E->getSourceRange();
10870 return false;
10871 } else if (!OperatorNew
10872 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
10873 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10874 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10875 return false;
10876 }
10877
10878 const Expr *Init = E->getInitializer();
10879 const InitListExpr *ResizedArrayILE = nullptr;
10880 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10881 bool ValueInit = false;
10882
10883 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10884 const Expr *Stripped = *ArraySize;
10885 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10886 Stripped = ICE->getSubExpr())
10887 if (ICE->getCastKind() != CK_NoOp &&
10888 ICE->getCastKind() != CK_IntegralCast)
10889 break;
10890
10891 llvm::APSInt ArrayBound;
10892 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10893 return false;
10894
10895 // C++ [expr.new]p9:
10896 // The expression is erroneous if:
10897 // -- [...] its value before converting to size_t [or] applying the
10898 // second standard conversion sequence is less than zero
10899 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10900 if (IsNothrow)
10901 return ZeroInitialization(E);
10902
10903 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10904 << ArrayBound << (*ArraySize)->getSourceRange();
10905 return false;
10906 }
10907
10908 // -- its value is such that the size of the allocated object would
10909 // exceed the implementation-defined limit
10910 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10912 Info.Ctx, AllocType, ArrayBound),
10913 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10914 if (IsNothrow)
10915 return ZeroInitialization(E);
10916 return false;
10917 }
10918
10919 // -- the new-initializer is a braced-init-list and the number of
10920 // array elements for which initializers are provided [...]
10921 // exceeds the number of elements to initialize
10922 if (!Init) {
10923 // No initialization is performed.
10924 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10926 ValueInit = true;
10927 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10928 ResizedArrayCCE = CCE;
10929 } else {
10930 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10931 assert(CAT && "unexpected type for array initializer");
10932
10933 unsigned Bits =
10934 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10935 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10936 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10937 if (InitBound.ugt(AllocBound)) {
10938 if (IsNothrow)
10939 return ZeroInitialization(E);
10940
10941 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10942 << toString(AllocBound, 10, /*Signed=*/false)
10943 << toString(InitBound, 10, /*Signed=*/false)
10944 << (*ArraySize)->getSourceRange();
10945 return false;
10946 }
10947
10948 // If the sizes differ, we must have an initializer list, and we need
10949 // special handling for this case when we initialize.
10950 if (InitBound != AllocBound)
10951 ResizedArrayILE = cast<InitListExpr>(Init);
10952 }
10953
10954 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10955 ArraySizeModifier::Normal, 0);
10956 } else if (E->isArray()) {
10957 // We have an array new-expression whose array size could not be
10958 // determined, e.g. 'new int[]()', where the bound is neither given nor
10959 // deducible from the initializer. This is ill-formed and already
10960 // diagnosed, so bail out rather than mis-evaluating a scalar allocation
10961 // as an array (which would later crash the evaluator).
10962 return false;
10963 } else {
10964 assert(!AllocType->isArrayType() &&
10965 "array allocation with non-array new");
10966 }
10967
10968 APValue *Val;
10969 if (IsPlacement) {
10971 struct FindObjectHandler {
10972 EvalInfo &Info;
10973 const Expr *E;
10974 QualType AllocType;
10975 const AccessKinds AccessKind;
10976 APValue *Value;
10977
10978 typedef bool result_type;
10979 bool failed() { return false; }
10980 bool checkConst(QualType QT) {
10981 if (QT.isConstQualified()) {
10982 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
10983 return false;
10984 }
10985 return true;
10986 }
10987 bool found(APValue &Subobj, QualType SubobjType,
10988 APValue::LValueBase Base) {
10989 if (!checkConst(SubobjType))
10990 return false;
10991 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10992 // old name of the object to be used to name the new object.
10993 if (!Info.Ctx.hasSimilarType(SubobjType, AllocType)) {
10994 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10995 << SubobjType << AllocType;
10996 return false;
10997 }
10998 Value = &Subobj;
10999 return true;
11000 }
11001 bool found(APSInt &Value, QualType SubobjType) {
11002 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
11003 return false;
11004 }
11005 bool found(APFloat &Value, QualType SubobjType) {
11006 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
11007 return false;
11008 }
11009 } Handler = {Info, E, AllocType, AK, nullptr};
11010
11011 if (AllocType->isArrayType() &&
11012 Result.Designator.MostDerivedIsArrayElement &&
11013 Result.Designator.Entries.back().getAsArrayIndex() == 0) {
11014 // The destination of placement new is pointing to the first element
11015 // of an array. There's a special case in [expr.const]: "[...] if T is an
11016 // array type, to the first element of such an object [...]". Handle
11017 // that case here by dropping the last entry in the designator list.
11018 QualType AllocElementType =
11019 Info.Ctx.getAsArrayType(AllocType)->getElementType();
11020 if (Info.Ctx.hasSimilarType(AllocElementType,
11021 Result.Designator.MostDerivedType)) {
11022 Result.Designator.truncate(Info.Ctx, Result.Base,
11023 Result.Designator.MostDerivedPathLength - 1);
11024 }
11025 }
11026
11027 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
11028 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
11029 return false;
11030
11031 Val = Handler.Value;
11032
11033 // [basic.life]p1:
11034 // The lifetime of an object o of type T ends when [...] the storage
11035 // which the object occupies is [...] reused by an object that is not
11036 // nested within o (6.6.2).
11037 *Val = APValue();
11038 } else {
11039 // Perform the allocation and obtain a pointer to the resulting object.
11040 Val = Info.createHeapAlloc(E, AllocType, Result);
11041 if (!Val)
11042 return false;
11043 }
11044
11045 if (ValueInit) {
11046 ImplicitValueInitExpr VIE(AllocType);
11047 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
11048 return false;
11049 } else if (ResizedArrayILE) {
11050 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
11051 AllocType))
11052 return false;
11053 } else if (ResizedArrayCCE) {
11054 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
11055 AllocType))
11056 return false;
11057 } else if (Init) {
11058 if (!EvaluateInPlace(*Val, Info, Result, Init))
11059 return false;
11060 } else if (!handleDefaultInitValue(AllocType, *Val)) {
11061 return false;
11062 }
11063
11064 // Array new returns a pointer to the first element, not a pointer to the
11065 // array.
11066 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
11067 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
11068
11069 return true;
11070}
11071//===----------------------------------------------------------------------===//
11072// Member Pointer Evaluation
11073//===----------------------------------------------------------------------===//
11074
11075namespace {
11076class MemberPointerExprEvaluator
11077 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
11078 MemberPtr &Result;
11079
11080 bool Success(const ValueDecl *D) {
11081 Result = MemberPtr(D);
11082 return true;
11083 }
11084public:
11085
11086 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
11087 : ExprEvaluatorBaseTy(Info), Result(Result) {}
11088
11089 bool Success(const APValue &V, const Expr *E) {
11090 Result.setFrom(V);
11091 return true;
11092 }
11093 bool ZeroInitialization(const Expr *E) {
11094 return Success((const ValueDecl*)nullptr);
11095 }
11096
11097 bool VisitCastExpr(const CastExpr *E);
11098 bool VisitUnaryAddrOf(const UnaryOperator *E);
11099};
11100} // end anonymous namespace
11101
11102static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
11103 EvalInfo &Info) {
11104 assert(!E->isValueDependent());
11105 assert(E->isPRValue() && E->getType()->isMemberPointerType());
11106 return MemberPointerExprEvaluator(Info, Result).Visit(E);
11107}
11108
11109bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
11110 switch (E->getCastKind()) {
11111 default:
11112 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11113
11114 case CK_NullToMemberPointer:
11115 VisitIgnoredValue(E->getSubExpr());
11116 return ZeroInitialization(E);
11117
11118 case CK_BaseToDerivedMemberPointer: {
11119 if (!Visit(E->getSubExpr()))
11120 return false;
11121 if (E->path_empty())
11122 return true;
11123 // Base-to-derived member pointer casts store the path in derived-to-base
11124 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
11125 // the wrong end of the derived->base arc, so stagger the path by one class.
11126 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
11127 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
11128 PathI != PathE; ++PathI) {
11129 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11130 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
11131 if (!Result.castToDerived(Derived))
11132 return Error(E);
11133 }
11134 if (!Result.castToDerived(E->getType()
11135 ->castAs<MemberPointerType>()
11136 ->getMostRecentCXXRecordDecl()))
11137 return Error(E);
11138 return true;
11139 }
11140
11141 case CK_DerivedToBaseMemberPointer:
11142 if (!Visit(E->getSubExpr()))
11143 return false;
11144 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11145 PathE = E->path_end(); PathI != PathE; ++PathI) {
11146 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11147 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11148 if (!Result.castToBase(Base))
11149 return Error(E);
11150 }
11151 return true;
11152 }
11153}
11154
11155bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
11156 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
11157 // member can be formed.
11158 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
11159}
11160
11161//===----------------------------------------------------------------------===//
11162// Record Evaluation
11163//===----------------------------------------------------------------------===//
11164
11165namespace {
11166 class RecordExprEvaluator
11167 : public ExprEvaluatorBase<RecordExprEvaluator> {
11168 const LValue &This;
11169 APValue &Result;
11170 public:
11171
11172 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
11173 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
11174
11175 bool Success(const APValue &V, const Expr *E) {
11176 Result = V;
11177 return true;
11178 }
11179 bool ZeroInitialization(const Expr *E) {
11180 return ZeroInitialization(E, E->getType());
11181 }
11182 bool ZeroInitialization(const Expr *E, QualType T);
11183
11184 bool VisitCallExpr(const CallExpr *E) {
11185 return handleCallExpr(E, Result, &This);
11186 }
11187 bool VisitCastExpr(const CastExpr *E);
11188 bool VisitInitListExpr(const InitListExpr *E);
11189 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11190 return VisitCXXConstructExpr(E, E->getType());
11191 }
11192 bool VisitLambdaExpr(const LambdaExpr *E);
11193 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
11194 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
11195 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
11196 bool VisitBinCmp(const BinaryOperator *E);
11197 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11198 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11199 ArrayRef<Expr *> Args);
11200 bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E);
11201 };
11202}
11203
11204/// Perform zero-initialization on an object of non-union class type.
11205/// C++11 [dcl.init]p5:
11206/// To zero-initialize an object or reference of type T means:
11207/// [...]
11208/// -- if T is a (possibly cv-qualified) non-union class type,
11209/// each non-static data member and each base-class subobject is
11210/// zero-initialized
11211static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
11212 const RecordDecl *RD,
11213 const LValue &This, APValue &Result) {
11214 assert(!RD->isUnion() && "Expected non-union class type");
11215 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
11216 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
11217 RD->getNumFields());
11218
11219 if (RD->isInvalidDecl()) return false;
11220 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11221
11222 if (CD) {
11223 unsigned Index = 0;
11225 End = CD->bases_end(); I != End; ++I, ++Index) {
11226 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
11227 LValue Subobject = This;
11228 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
11229 return false;
11230 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11231 Result.getStructBase(Index)))
11232 return false;
11233 }
11234 }
11235
11236 for (const auto *I : RD->fields()) {
11237 // -- if T is a reference type, no initialization is performed.
11238 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11239 continue;
11240
11241 LValue Subobject = This;
11242 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
11243 return false;
11244
11245 ImplicitValueInitExpr VIE(I->getType());
11246 if (!EvaluateInPlace(
11247 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11248 return false;
11249 }
11250
11251 return true;
11252}
11253
11254bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
11255 const auto *RD = T->castAsRecordDecl();
11256 if (RD->isInvalidDecl()) return false;
11257 if (RD->isUnion()) {
11258 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
11259 // object's first non-static named data member is zero-initialized
11261 while (I != RD->field_end() && (*I)->isUnnamedBitField())
11262 ++I;
11263 if (I == RD->field_end()) {
11264 Result = APValue((const FieldDecl*)nullptr);
11265 return true;
11266 }
11267
11268 LValue Subobject = This;
11269 if (!HandleLValueMember(Info, E, Subobject, *I))
11270 return false;
11271 Result = APValue(*I);
11272 ImplicitValueInitExpr VIE(I->getType());
11273 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
11274 }
11275
11276 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
11277 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11278 return false;
11279 }
11280
11281 return HandleClassZeroInitialization(Info, E, RD, This, Result);
11282}
11283
11284bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
11285 switch (E->getCastKind()) {
11286 default:
11287 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11288
11289 case CK_ConstructorConversion:
11290 return Visit(E->getSubExpr());
11291
11292 case CK_DerivedToBase:
11293 case CK_UncheckedDerivedToBase: {
11294 APValue DerivedObject;
11295 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
11296 return false;
11297 if (!DerivedObject.isStruct())
11298 return Error(E->getSubExpr());
11299
11300 // Derived-to-base rvalue conversion: just slice off the derived part.
11301 APValue *Value = &DerivedObject;
11302 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
11303 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11304 PathE = E->path_end(); PathI != PathE; ++PathI) {
11305 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
11306 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11307 Value = &Value->getStructBase(getBaseIndex(RD, Base));
11308 RD = Base;
11309 }
11310 Result = *Value;
11311 return true;
11312 }
11313 case CK_HLSLAggregateSplatCast: {
11314 APValue Val;
11315 QualType ValTy;
11316
11317 if (!hlslAggSplatHelper(Info, E->getSubExpr(), Val, ValTy))
11318 return false;
11319
11320 unsigned NEls = elementwiseSize(Info, E->getType());
11321 // splat our Val
11322 SmallVector<APValue> SplatEls(NEls, Val);
11323 SmallVector<QualType> SplatType(NEls, ValTy);
11324
11325 // cast the elements and construct our struct result
11326 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11327 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
11328 SplatType))
11329 return false;
11330
11331 return true;
11332 }
11333 case CK_HLSLElementwiseCast: {
11334 SmallVector<APValue> SrcEls;
11335 SmallVector<QualType> SrcTypes;
11336
11337 if (!hlslElementwiseCastHelper(Info, E->getSubExpr(), E->getType(), SrcEls,
11338 SrcTypes))
11339 return false;
11340
11341 // cast the elements and construct our struct result
11342 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11343 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
11344 SrcTypes))
11345 return false;
11346
11347 return true;
11348 }
11349 case CK_ToUnion: {
11350 const FieldDecl *Field = E->getTargetUnionField();
11351 LValue Subobject = This;
11352 if (!HandleLValueMember(Info, E, Subobject, Field))
11353 return false;
11354 Result = APValue(Field);
11355 if (!EvaluateInPlace(Result.getUnionValue(), Info, Subobject,
11356 E->getSubExpr()))
11357 return false;
11358 if (Field->isBitField()) {
11359 if (!truncateBitfieldValue(Info, E->getSubExpr(), Result.getUnionValue(),
11360 Field))
11361 return false;
11362 }
11363 return true;
11364 }
11365 }
11366}
11367
11368bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11369 if (E->isTransparent())
11370 return Visit(E->getInit(0));
11371 return VisitCXXParenListOrInitListExpr(E, E->inits());
11372}
11373
11374bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11375 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
11376 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
11377 if (RD->isInvalidDecl()) return false;
11378 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11379 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11380
11381 EvalInfo::EvaluatingConstructorRAII EvalObj(
11382 Info,
11383 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
11384 CXXRD && CXXRD->getNumBases());
11385
11386 if (RD->isUnion()) {
11387 const FieldDecl *Field;
11388 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11389 Field = ILE->getInitializedFieldInUnion();
11390 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11391 Field = PLIE->getInitializedFieldInUnion();
11392 } else {
11393 llvm_unreachable(
11394 "Expression is neither an init list nor a C++ paren list");
11395 }
11396
11397 Result = APValue(Field);
11398 if (!Field)
11399 return true;
11400
11401 // If the initializer list for a union does not contain any elements, the
11402 // first element of the union is value-initialized.
11403 // FIXME: The element should be initialized from an initializer list.
11404 // Is this difference ever observable for initializer lists which
11405 // we don't build?
11406 ImplicitValueInitExpr VIE(Field->getType());
11407 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11408
11409 LValue Subobject = This;
11410 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
11411 return false;
11412
11413 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11414 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11415 isa<CXXDefaultInitExpr>(InitExpr));
11416
11417 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
11418 if (Field->isBitField())
11419 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
11420 Field);
11421 return true;
11422 }
11423
11424 return false;
11425 }
11426
11427 if (!Result.hasValue())
11428 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11429 RD->getNumFields());
11430 unsigned ElementNo = 0;
11431 bool Success = true;
11432
11433 // Initialize base classes.
11434 if (CXXRD && CXXRD->getNumBases()) {
11435 for (const auto &Base : CXXRD->bases()) {
11436 assert(ElementNo < Args.size() && "missing init for base class");
11437 const Expr *Init = Args[ElementNo];
11438
11439 LValue Subobject = This;
11440 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
11441 return false;
11442
11443 APValue &FieldVal = Result.getStructBase(ElementNo);
11444 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
11445 if (!Info.noteFailure())
11446 return false;
11447 Success = false;
11448 }
11449 ++ElementNo;
11450 }
11451
11452 EvalObj.finishedConstructingBases();
11453 }
11454
11455 // Initialize members.
11456 for (const auto *Field : RD->fields()) {
11457 // Anonymous bit-fields are not considered members of the class for
11458 // purposes of aggregate initialization.
11459 if (Field->isUnnamedBitField())
11460 continue;
11461
11462 LValue Subobject = This;
11463
11464 bool HaveInit = ElementNo < Args.size();
11465
11466 // FIXME: Diagnostics here should point to the end of the initializer
11467 // list, not the start.
11468 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
11469 Subobject, Field, &Layout))
11470 return false;
11471
11472 // Perform an implicit value-initialization for members beyond the end of
11473 // the initializer list.
11474 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11475 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11476
11477 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
11478 // aren't supposed to be modified.
11479 if (isa<NoInitExpr>(Init))
11480 continue;
11481
11482 if (Field->getType()->isIncompleteArrayType()) {
11483 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11484 if (!CAT->isZeroSize()) {
11485 // Bail out for now. This might sort of "work", but the rest of the
11486 // code isn't really prepared to handle it.
11487 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11488 return false;
11489 }
11490 }
11491 }
11492
11493 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11494 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11496
11497 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11498 if (Field->getType()->isReferenceType()) {
11499 LValue Result;
11501 FieldVal)) {
11502 if (!Info.noteFailure())
11503 return false;
11504 Success = false;
11505 }
11506 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11507 (Field->isBitField() &&
11508 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11509 if (!Info.noteFailure())
11510 return false;
11511 Success = false;
11512 }
11513 }
11514
11515 EvalObj.finishedConstructingFields();
11516
11517 return Success;
11518}
11519
11520bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11521 QualType T) {
11522 // Note that E's type is not necessarily the type of our class here; we might
11523 // be initializing an array element instead.
11524 const CXXConstructorDecl *FD = E->getConstructor();
11525 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11526
11527 bool ZeroInit = E->requiresZeroInitialization();
11528 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11529 if (ZeroInit)
11530 return ZeroInitialization(E, T);
11531
11532 return handleDefaultInitValue(T, Result);
11533 }
11534
11535 const FunctionDecl *Definition = nullptr;
11536 auto Body = FD->getBody(Definition);
11537
11538 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11539 return false;
11540
11541 // Avoid materializing a temporary for an elidable copy/move constructor.
11542 if (E->isElidable() && !ZeroInit) {
11543 // FIXME: This only handles the simplest case, where the source object
11544 // is passed directly as the first argument to the constructor.
11545 // This should also handle stepping though implicit casts and
11546 // and conversion sequences which involve two steps, with a
11547 // conversion operator followed by a converting constructor.
11548 const Expr *SrcObj = E->getArg(0);
11549 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11550 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11551 if (const MaterializeTemporaryExpr *ME =
11552 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11553 return Visit(ME->getSubExpr());
11554 }
11555
11556 if (ZeroInit && !ZeroInitialization(E, T))
11557 return false;
11558
11559 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11560 return HandleConstructorCall(E, This, Args,
11562 Result);
11563}
11564
11565bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11566 const CXXInheritedCtorInitExpr *E) {
11567 if (!Info.CurrentCall) {
11568 assert(Info.checkingPotentialConstantExpression());
11569 return false;
11570 }
11571
11572 const CXXConstructorDecl *FD = E->getConstructor();
11573 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11574 return false;
11575
11576 const FunctionDecl *Definition = nullptr;
11577 auto Body = FD->getBody(Definition);
11578
11579 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11580 return false;
11581
11582 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11584 Result);
11585}
11586
11587bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11588 const CXXStdInitializerListExpr *E) {
11589 const ConstantArrayType *ArrayType =
11590 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11591
11592 LValue Array;
11593 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11594 return false;
11595
11596 assert(ArrayType && "unexpected type for array initializer");
11597
11598 // Get a pointer to the first element of the array.
11599 Array.addArray(Info, E, ArrayType);
11600
11601 // FIXME: What if the initializer_list type has base classes, etc?
11602 Result = APValue(APValue::UninitStruct(), 0, 2);
11603 Array.moveInto(Result.getStructField(0));
11604
11605 auto *Record = E->getType()->castAsRecordDecl();
11606 RecordDecl::field_iterator Field = Record->field_begin();
11607 assert(Field != Record->field_end() &&
11608 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11609 ArrayType->getElementType()) &&
11610 "Expected std::initializer_list first field to be const E *");
11611 ++Field;
11612 assert(Field != Record->field_end() &&
11613 "Expected std::initializer_list to have two fields");
11614
11615 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11616 // Length.
11617 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11618 } else {
11619 // End pointer.
11620 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11621 ArrayType->getElementType()) &&
11622 "Expected std::initializer_list second field to be const E *");
11623 if (!HandleLValueArrayAdjustment(Info, E, Array,
11624 ArrayType->getElementType(),
11625 ArrayType->getZExtSize()))
11626 return false;
11627 Array.moveInto(Result.getStructField(1));
11628 }
11629
11630 assert(++Field == Record->field_end() &&
11631 "Expected std::initializer_list to only have two fields");
11632
11633 return true;
11634}
11635
11636bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11637 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11638 if (ClosureClass->isInvalidDecl())
11639 return false;
11640
11641 const size_t NumFields = ClosureClass->getNumFields();
11642
11643 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11644 E->capture_init_end()) &&
11645 "The number of lambda capture initializers should equal the number of "
11646 "fields within the closure type");
11647
11648 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11649 // Iterate through all the lambda's closure object's fields and initialize
11650 // them.
11651 auto *CaptureInitIt = E->capture_init_begin();
11652 bool Success = true;
11653 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11654 for (const auto *Field : ClosureClass->fields()) {
11655 assert(CaptureInitIt != E->capture_init_end());
11656 // Get the initializer for this field
11657 Expr *const CurFieldInit = *CaptureInitIt++;
11658
11659 // If there is no initializer, either this is a VLA or an error has
11660 // occurred.
11661 if (!CurFieldInit || CurFieldInit->containsErrors())
11662 return Error(E);
11663
11664 LValue Subobject = This;
11665
11666 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11667 return false;
11668
11669 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11670 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11671 if (!Info.keepEvaluatingAfterFailure())
11672 return false;
11673 Success = false;
11674 }
11675 }
11676 return Success;
11677}
11678
11679bool RecordExprEvaluator::VisitDesignatedInitUpdateExpr(
11680 const DesignatedInitUpdateExpr *E) {
11681 if (!Visit(E->getBase()))
11682 return false;
11683 return Visit(E->getUpdater());
11684}
11685
11686static bool EvaluateRecord(const Expr *E, const LValue &This,
11687 APValue &Result, EvalInfo &Info) {
11688 assert(!E->isValueDependent());
11689 assert(E->isPRValue() && E->getType()->isRecordType() &&
11690 "can't evaluate expression as a record rvalue");
11691 return RecordExprEvaluator(Info, This, Result).Visit(E);
11692}
11693
11694//===----------------------------------------------------------------------===//
11695// Temporary Evaluation
11696//
11697// Temporaries are represented in the AST as rvalues, but generally behave like
11698// lvalues. The full-object of which the temporary is a subobject is implicitly
11699// materialized so that a reference can bind to it.
11700//===----------------------------------------------------------------------===//
11701namespace {
11702class TemporaryExprEvaluator
11703 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11704public:
11705 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11706 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11707
11708 /// Visit an expression which constructs the value of this temporary.
11709 bool VisitConstructExpr(const Expr *E) {
11710 APValue &Value = Info.CurrentCall->createTemporary(
11711 E, E->getType(), ScopeKind::FullExpression, Result);
11712 return EvaluateInPlace(Value, Info, Result, E);
11713 }
11714
11715 bool VisitCastExpr(const CastExpr *E) {
11716 switch (E->getCastKind()) {
11717 default:
11718 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11719
11720 case CK_ConstructorConversion:
11721 return VisitConstructExpr(E->getSubExpr());
11722 }
11723 }
11724 bool VisitInitListExpr(const InitListExpr *E) {
11725 return VisitConstructExpr(E);
11726 }
11727 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11728 return VisitConstructExpr(E);
11729 }
11730 bool VisitCallExpr(const CallExpr *E) {
11731 return VisitConstructExpr(E);
11732 }
11733 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11734 return VisitConstructExpr(E);
11735 }
11736 bool VisitLambdaExpr(const LambdaExpr *E) {
11737 return VisitConstructExpr(E);
11738 }
11739};
11740} // end anonymous namespace
11741
11742/// Evaluate an expression of record type as a temporary.
11743static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11744 assert(!E->isValueDependent());
11745 assert(E->isPRValue() && E->getType()->isRecordType());
11746 return TemporaryExprEvaluator(Info, Result).Visit(E);
11747}
11748
11749//===----------------------------------------------------------------------===//
11750// Vector Evaluation
11751//===----------------------------------------------------------------------===//
11752
11753namespace {
11754 class VectorExprEvaluator
11755 : public ExprEvaluatorBase<VectorExprEvaluator> {
11756 APValue &Result;
11757 public:
11758
11759 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11760 : ExprEvaluatorBaseTy(info), Result(Result) {}
11761
11762 bool Success(ArrayRef<APValue> V, const Expr *E) {
11763 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11764 // FIXME: remove this APValue copy.
11765 Result = APValue(V.data(), V.size());
11766 return true;
11767 }
11768 bool Success(const APValue &V, const Expr *E) {
11769 assert(V.isVector());
11770 Result = V;
11771 return true;
11772 }
11773 bool ZeroInitialization(const Expr *E);
11774
11775 bool VisitUnaryReal(const UnaryOperator *E)
11776 { return Visit(E->getSubExpr()); }
11777 bool VisitCastExpr(const CastExpr* E);
11778 bool VisitInitListExpr(const InitListExpr *E);
11779 bool VisitUnaryImag(const UnaryOperator *E);
11780 bool VisitBinaryOperator(const BinaryOperator *E);
11781 bool VisitUnaryOperator(const UnaryOperator *E);
11782 bool VisitCallExpr(const CallExpr *E);
11783 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11784 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11785
11786 // FIXME: Missing: conditional operator (for GNU
11787 // conditional select), ExtVectorElementExpr
11788 };
11789} // end anonymous namespace
11790
11791static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11792 assert(E->isPRValue() && E->getType()->isVectorType() &&
11793 "not a vector prvalue");
11794 return VectorExprEvaluator(Info, Result).Visit(E);
11795}
11796
11797static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11798 assert(Val.isVector() && "expected vector APValue");
11799 unsigned NumElts = Val.getVectorLength();
11800
11801 // Each element is one bit, so create an integer with NumElts bits.
11802 llvm::APInt Result(NumElts, 0);
11803
11804 for (unsigned I = 0; I < NumElts; ++I) {
11805 const APValue &Elt = Val.getVectorElt(I);
11806 assert(Elt.isInt() && "expected integer element in bool vector");
11807
11808 if (Elt.getInt().getBoolValue())
11809 Result.setBit(I);
11810 }
11811
11812 return Result;
11813}
11814
11815bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11816 const VectorType *VTy = E->getType()->castAs<VectorType>();
11817 unsigned NElts = VTy->getNumElements();
11818
11819 const Expr *SE = E->getSubExpr();
11820 QualType SETy = SE->getType();
11821
11822 switch (E->getCastKind()) {
11823 case CK_VectorSplat: {
11824 APValue Val = APValue();
11825 if (SETy->isIntegerType()) {
11826 APSInt IntResult;
11827 if (!EvaluateInteger(SE, IntResult, Info))
11828 return false;
11829 Val = APValue(std::move(IntResult));
11830 } else if (SETy->isRealFloatingType()) {
11831 APFloat FloatResult(0.0);
11832 if (!EvaluateFloat(SE, FloatResult, Info))
11833 return false;
11834 Val = APValue(std::move(FloatResult));
11835 } else {
11836 return Error(E);
11837 }
11838
11839 // Splat and create vector APValue.
11840 SmallVector<APValue, 4> Elts(NElts, Val);
11841 return Success(Elts, E);
11842 }
11843 case CK_BitCast: {
11844 APValue SVal;
11845 if (!Evaluate(SVal, Info, SE))
11846 return false;
11847
11848 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11849 // Give up if the input isn't an int, float, or vector. For example, we
11850 // reject "(v4i16)(intptr_t)&a".
11851 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11852 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
11853 << Info.Ctx.getLangOpts().CPlusPlus;
11854 return false;
11855 }
11856
11857 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11858 return false;
11859
11860 return true;
11861 }
11862 case CK_HLSLVectorTruncation: {
11863 APValue Val;
11864 SmallVector<APValue, 4> Elements;
11865 if (!EvaluateVector(SE, Val, Info))
11866 return Error(E);
11867 for (unsigned I = 0; I < NElts; I++)
11868 Elements.push_back(Val.getVectorElt(I));
11869 return Success(Elements, E);
11870 }
11871 case CK_HLSLMatrixTruncation: {
11872 // Matrix truncation occurs in row-major order.
11873 APValue Val;
11874 if (!EvaluateMatrix(SE, Val, Info))
11875 return Error(E);
11876 SmallVector<APValue, 16> Elements;
11877 for (unsigned Row = 0;
11878 Row < Val.getMatrixNumRows() && Elements.size() < NElts; Row++)
11879 for (unsigned Col = 0;
11880 Col < Val.getMatrixNumColumns() && Elements.size() < NElts; Col++)
11881 Elements.push_back(Val.getMatrixElt(Row, Col));
11882 return Success(Elements, E);
11883 }
11884 case CK_HLSLAggregateSplatCast: {
11885 APValue Val;
11886 QualType ValTy;
11887
11888 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
11889 return false;
11890
11891 // cast our Val once.
11893 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11894 if (!handleScalarCast(Info, FPO, E, ValTy, VTy->getElementType(), Val,
11895 Result))
11896 return false;
11897
11898 SmallVector<APValue, 4> SplatEls(NElts, Result);
11899 return Success(SplatEls, E);
11900 }
11901 case CK_HLSLElementwiseCast: {
11902 SmallVector<APValue> SrcVals;
11903 SmallVector<QualType> SrcTypes;
11904
11905 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
11906 return false;
11907
11908 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11909 SmallVector<QualType, 4> DestTypes(NElts, VTy->getElementType());
11910 SmallVector<APValue, 4> ResultEls(NElts);
11911 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
11912 ResultEls))
11913 return false;
11914 return Success(ResultEls, E);
11915 }
11916 case CK_IntegralToFloating:
11917 case CK_FloatingToIntegral:
11918 case CK_IntegralCast:
11919 case CK_FloatingCast:
11920 case CK_FloatingToBoolean:
11921 case CK_IntegralToBoolean: {
11922 // These casts apply element-wise when the source is a vector type.
11923 assert(SETy->isVectorType() && "expected vector source type");
11924 APValue SrcVal;
11925 if (!EvaluateVector(SE, SrcVal, Info))
11926 return Error(E);
11927
11928 assert(SrcVal.getVectorLength() == NElts);
11929 QualType SrcEltTy = SETy->castAs<VectorType>()->getElementType();
11930 QualType DstEltTy = VTy->getElementType();
11931 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11932
11933 SmallVector<APValue, 4> ResultEls(NElts);
11934 for (unsigned I = 0; I < NElts; ++I) {
11935 if (!handleScalarCast(Info, FPO, E, SrcEltTy, DstEltTy,
11936 SrcVal.getVectorElt(I), ResultEls[I]))
11937 return Error(E);
11938 }
11939 return Success(ResultEls, E);
11940 }
11941 default:
11942 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11943 }
11944}
11945
11946bool
11947VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11948 const VectorType *VT = E->getType()->castAs<VectorType>();
11949 unsigned NumInits = E->getNumInits();
11950 unsigned NumElements = VT->getNumElements();
11951
11952 QualType EltTy = VT->getElementType();
11953 SmallVector<APValue, 4> Elements;
11954
11955 // MFloat8 type doesn't have constants and thus constant folding
11956 // is impossible.
11957 if (EltTy->isMFloat8Type())
11958 return false;
11959
11960 // The number of initializers can be less than the number of
11961 // vector elements. For OpenCL, this can be due to nested vector
11962 // initialization. For GCC compatibility, missing trailing elements
11963 // should be initialized with zeroes.
11964 unsigned CountInits = 0, CountElts = 0;
11965 while (CountElts < NumElements) {
11966 // Handle nested vector initialization.
11967 if (CountInits < NumInits
11968 && E->getInit(CountInits)->getType()->isVectorType()) {
11969 APValue v;
11970 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11971 return Error(E);
11972 unsigned vlen = v.getVectorLength();
11973 for (unsigned j = 0; j < vlen; j++)
11974 Elements.push_back(v.getVectorElt(j));
11975 CountElts += vlen;
11976 } else if (EltTy->isIntegerType()) {
11977 llvm::APSInt sInt(32);
11978 if (CountInits < NumInits) {
11979 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11980 return false;
11981 } else // trailing integer zero.
11982 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11983 Elements.push_back(APValue(sInt));
11984 CountElts++;
11985 } else {
11986 llvm::APFloat f(0.0);
11987 if (CountInits < NumInits) {
11988 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11989 return false;
11990 } else // trailing float zero.
11991 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11992 Elements.push_back(APValue(f));
11993 CountElts++;
11994 }
11995 CountInits++;
11996 }
11997 return Success(Elements, E);
11998}
11999
12000bool
12001VectorExprEvaluator::ZeroInitialization(const Expr *E) {
12002 const auto *VT = E->getType()->castAs<VectorType>();
12003 QualType EltTy = VT->getElementType();
12004 APValue ZeroElement;
12005 if (EltTy->isIntegerType())
12006 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
12007 else
12008 ZeroElement =
12009 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
12010
12011 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
12012 return Success(Elements, E);
12013}
12014
12015bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12016 VisitIgnoredValue(E->getSubExpr());
12017 return ZeroInitialization(E);
12018}
12019
12020bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12021 BinaryOperatorKind Op = E->getOpcode();
12022 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
12023 "Operation not supported on vector types");
12024
12025 if (Op == BO_Comma)
12026 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12027
12028 Expr *LHS = E->getLHS();
12029 Expr *RHS = E->getRHS();
12030
12031 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
12032 "Must both be vector types");
12033 // Checking JUST the types are the same would be fine, except shifts don't
12034 // need to have their types be the same (since you always shift by an int).
12035 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
12036 E->getType()->castAs<VectorType>()->getNumElements() &&
12037 RHS->getType()->castAs<VectorType>()->getNumElements() ==
12038 E->getType()->castAs<VectorType>()->getNumElements() &&
12039 "All operands must be the same size.");
12040
12041 APValue LHSValue;
12042 APValue RHSValue;
12043 bool LHSOK = Evaluate(LHSValue, Info, LHS);
12044 if (!LHSOK && !Info.noteFailure())
12045 return false;
12046 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
12047 return false;
12048
12049 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
12050 return false;
12051
12052 return Success(LHSValue, E);
12053}
12054
12055static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
12056 QualType ResultTy,
12058 APValue Elt) {
12059 switch (Op) {
12060 case UO_Plus:
12061 // Nothing to do here.
12062 return Elt;
12063 case UO_Minus:
12064 if (Elt.getKind() == APValue::Int) {
12065 Elt.getInt().negate();
12066 } else {
12067 assert(Elt.getKind() == APValue::Float &&
12068 "Vector can only be int or float type");
12069 Elt.getFloat().changeSign();
12070 }
12071 return Elt;
12072 case UO_Not:
12073 // This is only valid for integral types anyway, so we don't have to handle
12074 // float here.
12075 assert(Elt.getKind() == APValue::Int &&
12076 "Vector operator ~ can only be int");
12077 Elt.getInt().flipAllBits();
12078 return Elt;
12079 case UO_LNot: {
12080 if (Elt.getKind() == APValue::Int) {
12081 Elt.getInt() = !Elt.getInt();
12082 // operator ! on vectors returns -1 for 'truth', so negate it.
12083 Elt.getInt().negate();
12084 return Elt;
12085 }
12086 assert(Elt.getKind() == APValue::Float &&
12087 "Vector can only be int or float type");
12088 // Float types result in an int of the same size, but -1 for true, or 0 for
12089 // false.
12090 APSInt EltResult{Ctx.getIntWidth(ResultTy),
12091 ResultTy->isUnsignedIntegerType()};
12092 if (Elt.getFloat().isZero())
12093 EltResult.setAllBits();
12094 else
12095 EltResult.clearAllBits();
12096
12097 return APValue{EltResult};
12098 }
12099 default:
12100 // FIXME: Implement the rest of the unary operators.
12101 return std::nullopt;
12102 }
12103}
12104
12105bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12106 Expr *SubExpr = E->getSubExpr();
12107 const auto *VD = SubExpr->getType()->castAs<VectorType>();
12108 // This result element type differs in the case of negating a floating point
12109 // vector, since the result type is the a vector of the equivilant sized
12110 // integer.
12111 const QualType ResultEltTy = VD->getElementType();
12112 UnaryOperatorKind Op = E->getOpcode();
12113
12114 APValue SubExprValue;
12115 if (!Evaluate(SubExprValue, Info, SubExpr))
12116 return false;
12117
12118 // FIXME: This vector evaluator someday needs to be changed to be LValue
12119 // aware/keep LValue information around, rather than dealing with just vector
12120 // types directly. Until then, we cannot handle cases where the operand to
12121 // these unary operators is an LValue. The only case I've been able to see
12122 // cause this is operator++ assigning to a member expression (only valid in
12123 // altivec compilations) in C mode, so this shouldn't limit us too much.
12124 if (SubExprValue.isLValue())
12125 return false;
12126
12127 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
12128 "Vector length doesn't match type?");
12129
12130 SmallVector<APValue, 4> ResultElements;
12131 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
12132 std::optional<APValue> Elt = handleVectorUnaryOperator(
12133 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
12134 if (!Elt)
12135 return false;
12136 ResultElements.push_back(*Elt);
12137 }
12138 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12139}
12140
12141static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
12142 const Expr *E, QualType SourceTy,
12143 QualType DestTy, APValue const &Original,
12144 APValue &Result) {
12145 if (SourceTy->isIntegerType()) {
12146 if (DestTy->isRealFloatingType()) {
12147 Result = APValue(APFloat(0.0));
12148 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
12149 DestTy, Result.getFloat());
12150 }
12151 if (DestTy->isIntegerType()) {
12152 Result = APValue(
12153 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
12154 return true;
12155 }
12156 } else if (SourceTy->isRealFloatingType()) {
12157 if (DestTy->isRealFloatingType()) {
12158 Result = Original;
12159 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
12160 Result.getFloat());
12161 }
12162 if (DestTy->isIntegerType()) {
12163 Result = APValue(APSInt());
12164 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
12165 DestTy, Result.getInt());
12166 }
12167 }
12168
12169 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
12170 << SourceTy << DestTy;
12171 return false;
12172}
12173
12174static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
12175 llvm::function_ref<APInt(const APSInt &)> PackFn) {
12176 APValue LHS, RHS;
12177 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
12178 !EvaluateAsRValue(Info, E->getArg(1), RHS))
12179 return false;
12180
12181 unsigned LHSVecLen = LHS.getVectorLength();
12182 unsigned RHSVecLen = RHS.getVectorLength();
12183
12184 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12185 "pack builtin LHSVecLen must equal to RHSVecLen");
12186
12187 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12188 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12189
12190 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12191 QualType DstElemTy = DstVT->getElementType();
12192 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12193
12194 const unsigned SrcPerLane = 128 / SrcBits;
12195 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12196
12198 Out.reserve(LHSVecLen + RHSVecLen);
12199
12200 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12201 unsigned base = Lane * SrcPerLane;
12202 for (unsigned I = 0; I != SrcPerLane; ++I)
12203 Out.emplace_back(APValue(
12204 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12205 for (unsigned I = 0; I != SrcPerLane; ++I)
12206 Out.emplace_back(APValue(
12207 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12208 }
12209
12210 Result = APValue(Out.data(), Out.size());
12211 return true;
12212}
12213
12215 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12216 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12217 GetSourceIndex) {
12218
12219 const auto *VT = Call->getType()->getAs<VectorType>();
12220 if (!VT)
12221 return false;
12222
12223 unsigned ShuffleMask = 0;
12224 APValue A, MaskVector, B;
12225 bool IsVectorMask = false;
12226 bool IsSingleOperand = (Call->getNumArgs() == 2);
12227
12228 if (IsSingleOperand) {
12229 QualType MaskType = Call->getArg(1)->getType();
12230 if (MaskType->isVectorType()) {
12231 IsVectorMask = true;
12232 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12233 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12234 return false;
12235 B = A;
12236 } else if (MaskType->isIntegerType()) {
12237 APSInt MaskImm;
12238 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12239 return false;
12240 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12241 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12242 return false;
12243 B = A;
12244 } else {
12245 return false;
12246 }
12247 } else {
12248 QualType Arg2Type = Call->getArg(2)->getType();
12249 if (Arg2Type->isVectorType()) {
12250 IsVectorMask = true;
12251 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12252 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12253 !EvaluateAsRValue(Info, Call->getArg(2), B))
12254 return false;
12255 } else if (Arg2Type->isIntegerType()) {
12256 APSInt MaskImm;
12257 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12258 return false;
12259 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12260 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12261 !EvaluateAsRValue(Info, Call->getArg(1), B))
12262 return false;
12263 } else {
12264 return false;
12265 }
12266 }
12267
12268 unsigned NumElts = VT->getNumElements();
12269 SmallVector<APValue, 64> ResultElements;
12270 ResultElements.reserve(NumElts);
12271
12272 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12273 if (IsVectorMask) {
12274 ShuffleMask = static_cast<unsigned>(
12275 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12276 }
12277 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12278
12279 if (SrcIdx < 0) {
12280 // Zero out this element
12281 QualType ElemTy = VT->getElementType();
12282 if (ElemTy->isRealFloatingType()) {
12283 ResultElements.push_back(
12284 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12285 } else if (ElemTy->isIntegerType()) {
12286 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12287 ResultElements.push_back(APValue(Zero));
12288 } else {
12289 // Other types of fallback logic
12290 ResultElements.push_back(APValue());
12291 }
12292 } else {
12293 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12294 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12295 }
12296 }
12297
12298 Out = APValue(ResultElements.data(), ResultElements.size());
12299 return true;
12300}
12301static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E,
12302 APFloat OrigVal, APValue &Result) {
12303
12304 if (OrigVal.isInfinity()) {
12305 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 0;
12306 return false;
12307 }
12308 if (OrigVal.isNaN()) {
12309 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 1;
12310 return false;
12311 }
12312
12313 APFloat Val = OrigVal;
12314 bool LosesInfo = false;
12315 APFloat::opStatus Status = Val.convert(
12316 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
12317
12318 if (LosesInfo || Val.isDenormal()) {
12319 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic_strict);
12320 return false;
12321 }
12322
12323 if (Status != APFloat::opOK) {
12324 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12325 return false;
12326 }
12327
12328 Result = APValue(Val);
12329 return true;
12330}
12332 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12333 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
12334 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
12335
12336 APValue Source, Count;
12337 if (!EvaluateAsRValue(Info, Call->getArg(0), Source) ||
12338 !EvaluateAsRValue(Info, Call->getArg(1), Count))
12339 return false;
12340
12341 assert(Call->getNumArgs() == 2);
12342
12343 QualType SourceTy = Call->getArg(0)->getType();
12344 assert(SourceTy->isVectorType() &&
12345 Call->getArg(1)->getType()->isVectorType());
12346
12347 QualType DestEltTy = SourceTy->castAs<VectorType>()->getElementType();
12348 unsigned DestEltWidth = Source.getVectorElt(0).getInt().getBitWidth();
12349 unsigned DestLen = Source.getVectorLength();
12350 bool IsDestUnsigned = DestEltTy->isUnsignedIntegerType();
12351 unsigned CountEltWidth = Count.getVectorElt(0).getInt().getBitWidth();
12352 unsigned NumBitsInQWord = 64;
12353 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
12355 Result.reserve(DestLen);
12356
12357 uint64_t CountLQWord = 0;
12358 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
12359 uint64_t Elt = Count.getVectorElt(EltIdx).getInt().getZExtValue();
12360 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
12361 }
12362
12363 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
12364 APInt Elt = Source.getVectorElt(EltIdx).getInt();
12365 if (CountLQWord < DestEltWidth) {
12366 Result.push_back(
12367 APValue(APSInt(ShiftOp(Elt, CountLQWord), IsDestUnsigned)));
12368 } else {
12369 Result.push_back(
12370 APValue(APSInt(OverflowOp(Elt, DestEltWidth), IsDestUnsigned)));
12371 }
12372 }
12373 Out = APValue(Result.data(), Result.size());
12374 return true;
12375}
12376
12377std::optional<APFloat> EvalScalarMinMaxFp(const APFloat &A, const APFloat &B,
12378 std::optional<APSInt> RoundingMode,
12379 bool IsMin) {
12380 APSInt DefaultMode(APInt(32, 4), /*isUnsigned=*/true);
12381 if (RoundingMode.value_or(DefaultMode) != 4)
12382 return std::nullopt;
12383 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
12384 B.isInfinity() || B.isDenormal())
12385 return std::nullopt;
12386 if (A.isZero() && B.isZero())
12387 return B;
12388 return IsMin ? llvm::minimum(A, B) : llvm::maximum(A, B);
12389}
12390
12391bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12392 if (!IsConstantEvaluatedBuiltinCall(E))
12393 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12394
12395 unsigned BuiltinOp = ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E);
12396
12397 auto EvaluateBinOpExpr =
12398 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12399 APValue SourceLHS, SourceRHS;
12400 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12401 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12402 return false;
12403
12404 auto *DestTy = E->getType()->castAs<VectorType>();
12405 QualType DestEltTy = DestTy->getElementType();
12406 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12407 unsigned SourceLen = SourceLHS.getVectorLength();
12408 SmallVector<APValue, 4> ResultElements;
12409 ResultElements.reserve(SourceLen);
12410
12411 if (SourceRHS.isInt()) {
12412 const APSInt &RHS = SourceRHS.getInt();
12413 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12414 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12415 ResultElements.push_back(
12416 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12417 }
12418 } else {
12419 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12420 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12421 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12422 ResultElements.push_back(
12423 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12424 }
12425 }
12426 return Success(APValue(ResultElements.data(), SourceLen), E);
12427 };
12428
12429 auto EvaluateFpBinOpExpr =
12430 [&](llvm::function_ref<std::optional<APFloat>(
12431 const APFloat &, const APFloat &, std::optional<APSInt>)>
12432 Fn,
12433 bool IsScalar = false) {
12434 assert(E->getNumArgs() == 2 || E->getNumArgs() == 3);
12435 APValue A, B;
12436 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12437 !EvaluateAsRValue(Info, E->getArg(1), B))
12438 return false;
12439
12440 assert(A.isVector() && B.isVector());
12441 assert(A.getVectorLength() == B.getVectorLength());
12442
12443 std::optional<APSInt> RoundingMode;
12444 if (E->getNumArgs() == 3) {
12445 APSInt Imm;
12446 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12447 return false;
12448 RoundingMode = Imm;
12449 }
12450
12451 unsigned NumElems = A.getVectorLength();
12452 SmallVector<APValue, 4> ResultElements;
12453 ResultElements.reserve(NumElems);
12454
12455 for (unsigned EltNum = 0; EltNum < NumElems; ++EltNum) {
12456 if (IsScalar && EltNum > 0) {
12457 ResultElements.push_back(A.getVectorElt(EltNum));
12458 continue;
12459 }
12460 const APFloat &EltA = A.getVectorElt(EltNum).getFloat();
12461 const APFloat &EltB = B.getVectorElt(EltNum).getFloat();
12462 std::optional<APFloat> Result = Fn(EltA, EltB, RoundingMode);
12463 if (!Result)
12464 return false;
12465 ResultElements.push_back(APValue(*Result));
12466 }
12467 return Success(APValue(ResultElements.data(), NumElems), E);
12468 };
12469
12470 auto EvaluateScalarFpRoundMaskBinOp =
12471 [&](llvm::function_ref<std::optional<APFloat>(
12472 const APFloat &, const APFloat &, std::optional<APSInt>)>
12473 Fn) {
12474 assert(E->getNumArgs() == 5);
12475 APValue VecA, VecB, VecSrc;
12476 APSInt MaskVal, Rounding;
12477
12478 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
12479 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
12480 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
12481 !EvaluateInteger(E->getArg(3), MaskVal, Info) ||
12482 !EvaluateInteger(E->getArg(4), Rounding, Info))
12483 return false;
12484
12485 unsigned NumElems = VecA.getVectorLength();
12486 SmallVector<APValue, 8> ResultElements;
12487 ResultElements.reserve(NumElems);
12488
12489 if (MaskVal.getZExtValue() & 1) {
12490 const APFloat &EltA = VecA.getVectorElt(0).getFloat();
12491 const APFloat &EltB = VecB.getVectorElt(0).getFloat();
12492 std::optional<APFloat> Result = Fn(EltA, EltB, Rounding);
12493 if (!Result)
12494 return false;
12495 ResultElements.push_back(APValue(*Result));
12496 } else {
12497 ResultElements.push_back(VecSrc.getVectorElt(0));
12498 }
12499
12500 for (unsigned I = 1; I < NumElems; ++I)
12501 ResultElements.push_back(VecA.getVectorElt(I));
12502
12503 return Success(APValue(ResultElements.data(), NumElems), E);
12504 };
12505
12506 auto EvalSelectScalar = [&](unsigned Len) -> bool {
12507 APSInt Mask;
12508 APValue AVal, WVal;
12509 if (!EvaluateInteger(E->getArg(0), Mask, Info) ||
12510 !EvaluateAsRValue(Info, E->getArg(1), AVal) ||
12511 !EvaluateAsRValue(Info, E->getArg(2), WVal))
12512 return false;
12513
12514 bool TakeA0 = (Mask.getZExtValue() & 1u) != 0;
12516 Res.reserve(Len);
12517 Res.push_back(TakeA0 ? AVal.getVectorElt(0) : WVal.getVectorElt(0));
12518 for (unsigned I = 1; I < Len; ++I)
12519 Res.push_back(WVal.getVectorElt(I));
12520 APValue V(Res.data(), Res.size());
12521 return Success(V, E);
12522 };
12523
12524 auto EvalVectorDotProduct = [&](bool IsSaturating) -> bool {
12525 APValue Source, OperandA, OperandB;
12526 if (!EvaluateVector(E->getArg(0), Source, Info) ||
12527 !EvaluateVector(E->getArg(1), OperandA, Info) ||
12528 !EvaluateVector(E->getArg(2), OperandB, Info)) {
12529 return false;
12530 }
12531
12532 unsigned NumSrcElems = Source.getVectorLength();
12533 unsigned NumOperandElems = OperandA.getVectorLength();
12534 unsigned ElemsPerLane = NumOperandElems / NumSrcElems;
12535
12536 assert(OperandA.getVectorLength() == OperandB.getVectorLength());
12537
12539 Result.reserve(NumSrcElems);
12540 for (unsigned I = 0; I != NumSrcElems; ++I) {
12541 APSInt DotProduct = Source.getVectorElt(I).getInt();
12542 DotProduct = DotProduct.extend(64);
12543 for (unsigned J = 0; J != ElemsPerLane; ++J) {
12544 APSInt OpA = APSInt(
12545 OperandA.getVectorElt(ElemsPerLane * I + J).getInt().extend(64),
12546 false);
12547 APSInt OpB = APSInt(
12548 OperandB.getVectorElt(ElemsPerLane * I + J).getInt().extend(64),
12549 false);
12550 DotProduct += OpA * OpB;
12551 }
12552 if (IsSaturating) {
12553 DotProduct = APSInt(DotProduct.truncSSat(32), false);
12554 } else {
12555 DotProduct = APSInt(DotProduct.trunc(32), false);
12556 }
12557 Result.push_back(APValue(DotProduct));
12558 }
12559
12560 return Success(APValue(Result.data(), Result.size()), E);
12561 };
12562
12563 switch (BuiltinOp) {
12564 default:
12565 return false;
12566 case Builtin::BI__builtin_elementwise_popcount:
12567 case Builtin::BI__builtin_elementwise_bitreverse: {
12568 APValue Source;
12569 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12570 return false;
12571
12572 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12573 unsigned SourceLen = Source.getVectorLength();
12574 SmallVector<APValue, 4> ResultElements;
12575 ResultElements.reserve(SourceLen);
12576
12577 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12578 APSInt Elt = Source.getVectorElt(EltNum).getInt();
12579 switch (BuiltinOp) {
12580 case Builtin::BI__builtin_elementwise_popcount:
12581 ResultElements.push_back(APValue(
12582 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
12583 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12584 break;
12585 case Builtin::BI__builtin_elementwise_bitreverse:
12586 ResultElements.push_back(
12587 APValue(APSInt(Elt.reverseBits(),
12588 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12589 break;
12590 }
12591 }
12592
12593 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12594 }
12595 case Builtin::BI__builtin_elementwise_abs: {
12596 APValue Source;
12597 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12598 return false;
12599
12600 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12601 unsigned SourceLen = Source.getVectorLength();
12602 SmallVector<APValue, 4> ResultElements;
12603 ResultElements.reserve(SourceLen);
12604
12605 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12606 APValue CurrentEle = Source.getVectorElt(EltNum);
12607 APValue Val = DestEltTy->isFloatingType()
12608 ? APValue(llvm::abs(CurrentEle.getFloat()))
12609 : APValue(APSInt(
12610 CurrentEle.getInt().abs(),
12611 DestEltTy->isUnsignedIntegerOrEnumerationType()));
12612 ResultElements.push_back(Val);
12613 }
12614
12615 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12616 }
12617
12618 case Builtin::BI__builtin_elementwise_add_sat:
12619 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12620 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
12621 });
12622
12623 case Builtin::BI__builtin_elementwise_sub_sat:
12624 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12625 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
12626 });
12627
12628 case X86::BI__builtin_ia32_extract128i256:
12629 case X86::BI__builtin_ia32_vextractf128_pd256:
12630 case X86::BI__builtin_ia32_vextractf128_ps256:
12631 case X86::BI__builtin_ia32_vextractf128_si256: {
12632 APValue SourceVec, SourceImm;
12633 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12634 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
12635 return false;
12636
12637 if (!SourceVec.isVector())
12638 return false;
12639
12640 const auto *RetVT = E->getType()->castAs<VectorType>();
12641 unsigned RetLen = RetVT->getNumElements();
12642 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
12643
12644 SmallVector<APValue, 32> ResultElements;
12645 ResultElements.reserve(RetLen);
12646
12647 for (unsigned I = 0; I < RetLen; I++)
12648 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
12649
12650 return Success(APValue(ResultElements.data(), RetLen), E);
12651 }
12652
12653 case clang::X86::BI__builtin_ia32_cvtmask2b128:
12654 case clang::X86::BI__builtin_ia32_cvtmask2b256:
12655 case clang::X86::BI__builtin_ia32_cvtmask2b512:
12656 case clang::X86::BI__builtin_ia32_cvtmask2w128:
12657 case clang::X86::BI__builtin_ia32_cvtmask2w256:
12658 case clang::X86::BI__builtin_ia32_cvtmask2w512:
12659 case clang::X86::BI__builtin_ia32_cvtmask2d128:
12660 case clang::X86::BI__builtin_ia32_cvtmask2d256:
12661 case clang::X86::BI__builtin_ia32_cvtmask2d512:
12662 case clang::X86::BI__builtin_ia32_cvtmask2q128:
12663 case clang::X86::BI__builtin_ia32_cvtmask2q256:
12664 case clang::X86::BI__builtin_ia32_cvtmask2q512: {
12665 assert(E->getNumArgs() == 1);
12666 APSInt Mask;
12667 if (!EvaluateInteger(E->getArg(0), Mask, Info))
12668 return false;
12669
12670 QualType VecTy = E->getType();
12671 const VectorType *VT = VecTy->castAs<VectorType>();
12672 unsigned VectorLen = VT->getNumElements();
12673 QualType ElemTy = VT->getElementType();
12674 unsigned ElemWidth = Info.Ctx.getTypeSize(ElemTy);
12675
12677 for (unsigned I = 0; I != VectorLen; ++I) {
12678 bool BitSet = Mask[I];
12679 APSInt ElemVal(ElemWidth, /*isUnsigned=*/false);
12680 if (BitSet) {
12681 ElemVal.setAllBits();
12682 }
12683 Elems.push_back(APValue(ElemVal));
12684 }
12685 return Success(APValue(Elems.data(), VectorLen), E);
12686 }
12687
12688 case X86::BI__builtin_ia32_extracti32x4_256_mask:
12689 case X86::BI__builtin_ia32_extractf32x4_256_mask:
12690 case X86::BI__builtin_ia32_extracti32x4_mask:
12691 case X86::BI__builtin_ia32_extractf32x4_mask:
12692 case X86::BI__builtin_ia32_extracti32x8_mask:
12693 case X86::BI__builtin_ia32_extractf32x8_mask:
12694 case X86::BI__builtin_ia32_extracti64x2_256_mask:
12695 case X86::BI__builtin_ia32_extractf64x2_256_mask:
12696 case X86::BI__builtin_ia32_extracti64x2_512_mask:
12697 case X86::BI__builtin_ia32_extractf64x2_512_mask:
12698 case X86::BI__builtin_ia32_extracti64x4_mask:
12699 case X86::BI__builtin_ia32_extractf64x4_mask: {
12700 APValue SourceVec, MergeVec;
12701 APSInt Imm, MaskImm;
12702
12703 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12704 !EvaluateInteger(E->getArg(1), Imm, Info) ||
12705 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
12706 !EvaluateInteger(E->getArg(3), MaskImm, Info))
12707 return false;
12708
12709 const auto *RetVT = E->getType()->castAs<VectorType>();
12710 unsigned RetLen = RetVT->getNumElements();
12711
12712 if (!SourceVec.isVector() || !MergeVec.isVector())
12713 return false;
12714 unsigned SrcLen = SourceVec.getVectorLength();
12715 unsigned Lanes = SrcLen / RetLen;
12716 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
12717 unsigned Base = Lane * RetLen;
12718
12719 SmallVector<APValue, 32> ResultElements;
12720 ResultElements.reserve(RetLen);
12721 for (unsigned I = 0; I < RetLen; ++I) {
12722 if (MaskImm[I])
12723 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
12724 else
12725 ResultElements.push_back(MergeVec.getVectorElt(I));
12726 }
12727 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12728 }
12729
12730 case clang::X86::BI__builtin_ia32_pavgb128:
12731 case clang::X86::BI__builtin_ia32_pavgw128:
12732 case clang::X86::BI__builtin_ia32_pavgb256:
12733 case clang::X86::BI__builtin_ia32_pavgw256:
12734 case clang::X86::BI__builtin_ia32_pavgb512:
12735 case clang::X86::BI__builtin_ia32_pavgw512:
12736 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
12737
12738 case clang::X86::BI__builtin_ia32_pmulhrsw128:
12739 case clang::X86::BI__builtin_ia32_pmulhrsw256:
12740 case clang::X86::BI__builtin_ia32_pmulhrsw512:
12741 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12742 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
12743 .extractBits(16, 1);
12744 });
12745
12746 case clang::X86::BI__builtin_ia32_psadbw128:
12747 case clang::X86::BI__builtin_ia32_psadbw256:
12748 case clang::X86::BI__builtin_ia32_psadbw512: {
12749 APValue SourceLHS, SourceRHS;
12750 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12751 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12752 return false;
12753
12754 assert(SourceLHS.isVector() && SourceRHS.isVector());
12755 unsigned SourceLen = SourceLHS.getVectorLength();
12756 assert(SourceLen == SourceRHS.getVectorLength());
12757 assert((SourceLen % 8) == 0);
12758
12759 auto *DestTy = E->getType()->castAs<VectorType>();
12760 QualType DestEltTy = DestTy->getElementType();
12761 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12762 SmallVector<APValue, 8> ResultElements;
12763 ResultElements.reserve(SourceLen / 8);
12764
12765 for (unsigned Lane = 0; Lane != SourceLen; Lane += 8) {
12766 APInt Sum(64, 0);
12767 for (unsigned I = 0; I != 8; ++I) {
12768 APInt LHS = SourceLHS.getVectorElt(Lane + I).getInt().extOrTrunc(8);
12769 APInt RHS = SourceRHS.getVectorElt(Lane + I).getInt().extOrTrunc(8);
12770 Sum += llvm::APIntOps::abdu(LHS, RHS).zext(64);
12771 }
12772 ResultElements.push_back(APValue(APSInt(Sum, DestUnsigned)));
12773 }
12774
12775 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12776 }
12777
12778 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12779 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12780 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12781 case clang::X86::BI__builtin_ia32_pmaddwd128:
12782 case clang::X86::BI__builtin_ia32_pmaddwd256:
12783 case clang::X86::BI__builtin_ia32_pmaddwd512: {
12784 APValue SourceLHS, SourceRHS;
12785 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12786 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12787 return false;
12788
12789 auto *DestTy = E->getType()->castAs<VectorType>();
12790 QualType DestEltTy = DestTy->getElementType();
12791 unsigned SourceLen = SourceLHS.getVectorLength();
12792 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12793 SmallVector<APValue, 4> ResultElements;
12794 ResultElements.reserve(SourceLen / 2);
12795
12796 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12797 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
12798 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
12799 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
12800 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
12801 unsigned BitWidth = 2 * LoLHS.getBitWidth();
12802
12803 switch (BuiltinOp) {
12804 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12805 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12806 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12807 ResultElements.push_back(APValue(
12808 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
12809 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
12810 DestUnsigned)));
12811 break;
12812 case clang::X86::BI__builtin_ia32_pmaddwd128:
12813 case clang::X86::BI__builtin_ia32_pmaddwd256:
12814 case clang::X86::BI__builtin_ia32_pmaddwd512:
12815 ResultElements.push_back(
12816 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
12817 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
12818 DestUnsigned)));
12819 break;
12820 }
12821 }
12822
12823 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12824 }
12825
12826 case clang::X86::BI__builtin_ia32_bmacor16x16x16_v16hi:
12827 case clang::X86::BI__builtin_ia32_bmacor16x16x16_v32hi:
12828 case clang::X86::BI__builtin_ia32_bmacxor16x16x16_v16hi:
12829 case clang::X86::BI__builtin_ia32_bmacxor16x16x16_v32hi: {
12830 // Bit Matrix Multiply and Accumulate (AVX512BMM). Each 256-bit lane holds
12831 // a 16x16 bit matrix as 16 x i16 elements; element i is row i and bit j of
12832 // that element is entry [i][j]. The accumulator (third argument, src1 in
12833 // the AMD ISA) provides the initial value of each result bit, into which
12834 // the bit-matrix product of the first two arguments (src2 * src3) is
12835 // reduced with OR (vbmacor) or XOR (vbmacxor):
12836 // for i in 0..15, j in 0..15:
12837 // bit = C[16*i+j]
12838 // for k in 0..15: bit OP= A[16*i+k] & B[16*k+j]
12839 // dest[16*i+j] = bit
12840 APValue SourceA, SourceB, SourceC;
12841 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
12842 !EvaluateAsRValue(Info, E->getArg(1), SourceB) ||
12843 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
12844 return false;
12845
12846 bool IsXor = E->getBuiltinCallee() ==
12847 clang::X86::BI__builtin_ia32_bmacxor16x16x16_v16hi ||
12848 E->getBuiltinCallee() ==
12849 clang::X86::BI__builtin_ia32_bmacxor16x16x16_v32hi;
12850
12851 unsigned SourceLen = SourceA.getVectorLength();
12852 assert(SourceLen % 16 == 0 && "BMM operates on 256-bit lanes of 16 x i16");
12853 auto *DestTy = E->getType()->castAs<VectorType>();
12854 QualType DestEltTy = DestTy->getElementType();
12855 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12856
12857 SmallVector<APValue, 32> ResultElements(SourceLen);
12858 for (unsigned Lane = 0; Lane != SourceLen; Lane += 16) {
12859 for (unsigned I = 0; I != 16; ++I) {
12860 uint16_t A =
12861 (uint16_t)SourceA.getVectorElt(Lane + I).getInt().getZExtValue();
12862 uint16_t Dst =
12863 (uint16_t)SourceC.getVectorElt(Lane + I).getInt().getZExtValue();
12864 for (unsigned J = 0; J != 16; ++J) {
12865 // Seed the reduction with the accumulator bit, then fold in each
12866 // product term with the same operator (OR for vbmacor, XOR for
12867 // vbmacxor).
12868 unsigned Bit = (Dst >> J) & 1u;
12869 for (unsigned K = 0; K != 16; ++K) {
12870 uint16_t B = (uint16_t)SourceB.getVectorElt(Lane + K)
12871 .getInt()
12872 .getZExtValue();
12873 unsigned Product = ((A >> K) & 1u) & ((B >> J) & 1u);
12874 Bit = IsXor ? (Bit ^ Product) : (Bit | Product);
12875 }
12876 Dst = (Dst & ~(uint16_t(1) << J)) | (uint16_t(Bit) << J);
12877 }
12878 ResultElements[Lane + I] =
12879 APValue(APSInt(APInt(16, Dst), DestUnsigned));
12880 }
12881 }
12882 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12883 }
12884
12885 case clang::X86::BI__builtin_ia32_dbpsadbw128:
12886 case clang::X86::BI__builtin_ia32_dbpsadbw256:
12887 case clang::X86::BI__builtin_ia32_dbpsadbw512: {
12888 APValue SourceA, SourceB, SourceImm;
12889 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
12890 !EvaluateAsRValue(Info, E->getArg(1), SourceB) ||
12891 !EvaluateAsRValue(Info, E->getArg(2), SourceImm))
12892 return false;
12893
12894 unsigned SourceLen = SourceA.getVectorLength();
12895 constexpr unsigned LaneSize = 16; // 128-bit lane = 16 bytes
12896 unsigned Imm = SourceImm.getInt().getZExtValue();
12897
12898 auto *DestTy = E->getType()->castAs<VectorType>();
12899 QualType DestEltTy = DestTy->getElementType();
12900 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12901 SmallVector<APValue, 32> ResultElements;
12902 ResultElements.reserve(SourceLen / 2);
12903
12904 // Phase 1: Shuffle SourceB using all four 2-bit fields of imm8.
12905 // Within each 128-bit lane, for group j (0..3), select a 4-byte block
12906 // from SourceB based on bits [2*j+1:2*j] of imm8.
12907 SmallVector<uint8_t, 64> Shuffled(SourceLen);
12908 for (unsigned I = 0; I < SourceLen; I += LaneSize) {
12909 for (unsigned J = 0; J < 4; ++J) {
12910 unsigned Part = (Imm >> (2 * J)) & 3;
12911 for (unsigned K = 0; K < 4; ++K) {
12912 Shuffled[I + 4 * J + K] = static_cast<uint8_t>(
12913 SourceB.getVectorElt(I + 4 * Part + K).getInt().getZExtValue());
12914 }
12915 }
12916 }
12917
12918 // Phase 2: Sliding SAD computation.
12919 // For every group of 4 output u16 values, compute absolute differences
12920 // using overlapping windows into SourceA and the shuffled array.
12921 unsigned Size = SourceLen / 2; // number of output u16 elements
12922 for (unsigned I = 0; I < Size; I += 4) {
12923 unsigned Sad[4] = {0, 0, 0, 0};
12924 for (unsigned J = 0; J < 4; ++J) {
12925 uint8_t A1 = static_cast<uint8_t>(
12926 SourceA.getVectorElt(2 * I + J).getInt().getZExtValue());
12927 uint8_t A2 = static_cast<uint8_t>(
12928 SourceA.getVectorElt(2 * I + J + 4).getInt().getZExtValue());
12929 uint8_t B0 = Shuffled[2 * I + J];
12930 uint8_t B1 = Shuffled[2 * I + J + 1];
12931 uint8_t B2 = Shuffled[2 * I + J + 2];
12932 uint8_t B3 = Shuffled[2 * I + J + 3];
12933 Sad[0] += (A1 > B0) ? (A1 - B0) : (B0 - A1);
12934 Sad[1] += (A1 > B1) ? (A1 - B1) : (B1 - A1);
12935 Sad[2] += (A2 > B2) ? (A2 - B2) : (B2 - A2);
12936 Sad[3] += (A2 > B3) ? (A2 - B3) : (B3 - A2);
12937 }
12938 for (unsigned R = 0; R < 4; ++R)
12939 ResultElements.push_back(
12940 APValue(APSInt(APInt(16, Sad[R]), DestUnsigned)));
12941 }
12942
12943 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12944 }
12945
12946 case clang::X86::BI__builtin_ia32_mpsadbw128:
12947 case clang::X86::BI__builtin_ia32_mpsadbw256: {
12948 APValue SourceA, SourceB;
12949 APSInt SourceImm;
12950 if (!EvaluateVector(E->getArg(0), SourceA, Info) ||
12951 !EvaluateVector(E->getArg(1), SourceB, Info) ||
12952 !EvaluateInteger(E->getArg(2), SourceImm, Info))
12953 return false;
12954 unsigned SourceLen = SourceA.getVectorLength();
12955 constexpr unsigned LaneSize = 16;
12956 assert((SourceLen == LaneSize || SourceLen == 2 * LaneSize) &&
12957 "MPSADBW operates on 128-bit or 256-bit vectors");
12958 unsigned NumLanes = SourceLen / LaneSize;
12959 unsigned Imm = SourceImm.getZExtValue();
12960
12961 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12962 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12963 SmallVector<APValue, 16> ResultElements;
12964 ResultElements.reserve(SourceLen / 2);
12965
12966 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
12967 unsigned Ctrl = (Imm >> (3 * Lane)) & 0x7;
12968 unsigned AOff = ((Ctrl >> 2) & 1) * 4;
12969 unsigned BOff = (Ctrl & 3) * 4;
12970 for (unsigned J = 0; J != 8; ++J) {
12971 uint16_t Sad = 0;
12972 for (unsigned K = 0; K != 4; ++K) {
12973 uint8_t A = static_cast<uint8_t>(
12974 SourceA.getVectorElt(Lane * LaneSize + AOff + J + K)
12975 .getInt()
12976 .getZExtValue());
12977 uint8_t B = static_cast<uint8_t>(
12978 SourceB.getVectorElt(Lane * LaneSize + BOff + K)
12979 .getInt()
12980 .getZExtValue());
12981 Sad += (A > B) ? (A - B) : (B - A);
12982 }
12983 ResultElements.push_back(APValue(APSInt(APInt(16, Sad), DestUnsigned)));
12984 }
12985 }
12986 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12987 }
12988
12989 case clang::X86::BI__builtin_ia32_pmulhuw128:
12990 case clang::X86::BI__builtin_ia32_pmulhuw256:
12991 case clang::X86::BI__builtin_ia32_pmulhuw512:
12992 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
12993
12994 case clang::X86::BI__builtin_ia32_pmulhw128:
12995 case clang::X86::BI__builtin_ia32_pmulhw256:
12996 case clang::X86::BI__builtin_ia32_pmulhw512:
12997 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
12998
12999 case clang::X86::BI__builtin_ia32_psllv2di:
13000 case clang::X86::BI__builtin_ia32_psllv4di:
13001 case clang::X86::BI__builtin_ia32_psllv4si:
13002 case clang::X86::BI__builtin_ia32_psllv8di:
13003 case clang::X86::BI__builtin_ia32_psllv8hi:
13004 case clang::X86::BI__builtin_ia32_psllv8si:
13005 case clang::X86::BI__builtin_ia32_psllv16hi:
13006 case clang::X86::BI__builtin_ia32_psllv16si:
13007 case clang::X86::BI__builtin_ia32_psllv32hi:
13008 case clang::X86::BI__builtin_ia32_psllwi128:
13009 case clang::X86::BI__builtin_ia32_pslldi128:
13010 case clang::X86::BI__builtin_ia32_psllqi128:
13011 case clang::X86::BI__builtin_ia32_psllwi256:
13012 case clang::X86::BI__builtin_ia32_pslldi256:
13013 case clang::X86::BI__builtin_ia32_psllqi256:
13014 case clang::X86::BI__builtin_ia32_psllwi512:
13015 case clang::X86::BI__builtin_ia32_pslldi512:
13016 case clang::X86::BI__builtin_ia32_psllqi512:
13017 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13018 if (RHS.uge(LHS.getBitWidth())) {
13019 return APInt::getZero(LHS.getBitWidth());
13020 }
13021 return LHS.shl(RHS.getZExtValue());
13022 });
13023
13024 case clang::X86::BI__builtin_ia32_psrav4si:
13025 case clang::X86::BI__builtin_ia32_psrav8di:
13026 case clang::X86::BI__builtin_ia32_psrav8hi:
13027 case clang::X86::BI__builtin_ia32_psrav8si:
13028 case clang::X86::BI__builtin_ia32_psrav16hi:
13029 case clang::X86::BI__builtin_ia32_psrav16si:
13030 case clang::X86::BI__builtin_ia32_psrav32hi:
13031 case clang::X86::BI__builtin_ia32_psravq128:
13032 case clang::X86::BI__builtin_ia32_psravq256:
13033 case clang::X86::BI__builtin_ia32_psrawi128:
13034 case clang::X86::BI__builtin_ia32_psradi128:
13035 case clang::X86::BI__builtin_ia32_psraqi128:
13036 case clang::X86::BI__builtin_ia32_psrawi256:
13037 case clang::X86::BI__builtin_ia32_psradi256:
13038 case clang::X86::BI__builtin_ia32_psraqi256:
13039 case clang::X86::BI__builtin_ia32_psrawi512:
13040 case clang::X86::BI__builtin_ia32_psradi512:
13041 case clang::X86::BI__builtin_ia32_psraqi512:
13042 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13043 if (RHS.uge(LHS.getBitWidth())) {
13044 return LHS.ashr(LHS.getBitWidth() - 1);
13045 }
13046 return LHS.ashr(RHS.getZExtValue());
13047 });
13048
13049 case clang::X86::BI__builtin_ia32_psrlv2di:
13050 case clang::X86::BI__builtin_ia32_psrlv4di:
13051 case clang::X86::BI__builtin_ia32_psrlv4si:
13052 case clang::X86::BI__builtin_ia32_psrlv8di:
13053 case clang::X86::BI__builtin_ia32_psrlv8hi:
13054 case clang::X86::BI__builtin_ia32_psrlv8si:
13055 case clang::X86::BI__builtin_ia32_psrlv16hi:
13056 case clang::X86::BI__builtin_ia32_psrlv16si:
13057 case clang::X86::BI__builtin_ia32_psrlv32hi:
13058 case clang::X86::BI__builtin_ia32_psrlwi128:
13059 case clang::X86::BI__builtin_ia32_psrldi128:
13060 case clang::X86::BI__builtin_ia32_psrlqi128:
13061 case clang::X86::BI__builtin_ia32_psrlwi256:
13062 case clang::X86::BI__builtin_ia32_psrldi256:
13063 case clang::X86::BI__builtin_ia32_psrlqi256:
13064 case clang::X86::BI__builtin_ia32_psrlwi512:
13065 case clang::X86::BI__builtin_ia32_psrldi512:
13066 case clang::X86::BI__builtin_ia32_psrlqi512:
13067 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13068 if (RHS.uge(LHS.getBitWidth())) {
13069 return APInt::getZero(LHS.getBitWidth());
13070 }
13071 return LHS.lshr(RHS.getZExtValue());
13072 });
13073 case X86::BI__builtin_ia32_packsswb128:
13074 case X86::BI__builtin_ia32_packsswb256:
13075 case X86::BI__builtin_ia32_packsswb512:
13076 case X86::BI__builtin_ia32_packssdw128:
13077 case X86::BI__builtin_ia32_packssdw256:
13078 case X86::BI__builtin_ia32_packssdw512:
13079 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
13080 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
13081 });
13082 case X86::BI__builtin_ia32_packusdw128:
13083 case X86::BI__builtin_ia32_packusdw256:
13084 case X86::BI__builtin_ia32_packusdw512:
13085 case X86::BI__builtin_ia32_packuswb128:
13086 case X86::BI__builtin_ia32_packuswb256:
13087 case X86::BI__builtin_ia32_packuswb512:
13088 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
13089 return APSInt(Src).truncSSatU(Src.getBitWidth() / 2);
13090 });
13091 case clang::X86::BI__builtin_ia32_selectss_128:
13092 return EvalSelectScalar(4);
13093 case clang::X86::BI__builtin_ia32_selectsd_128:
13094 return EvalSelectScalar(2);
13095 case clang::X86::BI__builtin_ia32_selectsh_128:
13096 case clang::X86::BI__builtin_ia32_selectsbf_128:
13097 return EvalSelectScalar(8);
13098 case clang::X86::BI__builtin_ia32_pmuldq128:
13099 case clang::X86::BI__builtin_ia32_pmuldq256:
13100 case clang::X86::BI__builtin_ia32_pmuldq512:
13101 case clang::X86::BI__builtin_ia32_pmuludq128:
13102 case clang::X86::BI__builtin_ia32_pmuludq256:
13103 case clang::X86::BI__builtin_ia32_pmuludq512: {
13104 APValue SourceLHS, SourceRHS;
13105 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13106 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13107 return false;
13108
13109 unsigned SourceLen = SourceLHS.getVectorLength();
13110 SmallVector<APValue, 4> ResultElements;
13111 ResultElements.reserve(SourceLen / 2);
13112
13113 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
13114 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13115 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
13116
13117 switch (BuiltinOp) {
13118 case clang::X86::BI__builtin_ia32_pmuludq128:
13119 case clang::X86::BI__builtin_ia32_pmuludq256:
13120 case clang::X86::BI__builtin_ia32_pmuludq512:
13121 ResultElements.push_back(
13122 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
13123 break;
13124 case clang::X86::BI__builtin_ia32_pmuldq128:
13125 case clang::X86::BI__builtin_ia32_pmuldq256:
13126 case clang::X86::BI__builtin_ia32_pmuldq512:
13127 ResultElements.push_back(
13128 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
13129 break;
13130 }
13131 }
13132
13133 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13134 }
13135
13136 case X86::BI__builtin_ia32_vpmadd52luq128:
13137 case X86::BI__builtin_ia32_vpmadd52luq256:
13138 case X86::BI__builtin_ia32_vpmadd52luq512: {
13139 APValue A, B, C;
13140 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
13141 !EvaluateAsRValue(Info, E->getArg(1), B) ||
13142 !EvaluateAsRValue(Info, E->getArg(2), C))
13143 return false;
13144
13145 unsigned ALen = A.getVectorLength();
13146 SmallVector<APValue, 4> ResultElements;
13147 ResultElements.reserve(ALen);
13148
13149 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
13150 APInt AElt = A.getVectorElt(EltNum).getInt();
13151 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
13152 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
13153 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
13154 ResultElements.push_back(APValue(ResElt));
13155 }
13156
13157 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13158 }
13159 case X86::BI__builtin_ia32_vpmadd52huq128:
13160 case X86::BI__builtin_ia32_vpmadd52huq256:
13161 case X86::BI__builtin_ia32_vpmadd52huq512: {
13162 APValue A, B, C;
13163 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
13164 !EvaluateAsRValue(Info, E->getArg(1), B) ||
13165 !EvaluateAsRValue(Info, E->getArg(2), C))
13166 return false;
13167
13168 unsigned ALen = A.getVectorLength();
13169 SmallVector<APValue, 4> ResultElements;
13170 ResultElements.reserve(ALen);
13171
13172 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
13173 APInt AElt = A.getVectorElt(EltNum).getInt();
13174 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
13175 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
13176 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
13177 ResultElements.push_back(APValue(ResElt));
13178 }
13179
13180 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13181 }
13182
13183 case clang::X86::BI__builtin_ia32_vprotbi:
13184 case clang::X86::BI__builtin_ia32_vprotdi:
13185 case clang::X86::BI__builtin_ia32_vprotqi:
13186 case clang::X86::BI__builtin_ia32_vprotwi:
13187 case clang::X86::BI__builtin_ia32_prold128:
13188 case clang::X86::BI__builtin_ia32_prold256:
13189 case clang::X86::BI__builtin_ia32_prold512:
13190 case clang::X86::BI__builtin_ia32_prolq128:
13191 case clang::X86::BI__builtin_ia32_prolq256:
13192 case clang::X86::BI__builtin_ia32_prolq512:
13193 return EvaluateBinOpExpr(
13194 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
13195
13196 case clang::X86::BI__builtin_ia32_prord128:
13197 case clang::X86::BI__builtin_ia32_prord256:
13198 case clang::X86::BI__builtin_ia32_prord512:
13199 case clang::X86::BI__builtin_ia32_prorq128:
13200 case clang::X86::BI__builtin_ia32_prorq256:
13201 case clang::X86::BI__builtin_ia32_prorq512:
13202 return EvaluateBinOpExpr(
13203 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
13204
13205 case Builtin::BI__builtin_elementwise_max:
13206 case Builtin::BI__builtin_elementwise_min: {
13207 APValue SourceLHS, SourceRHS;
13208 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13209 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13210 return false;
13211
13212 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13213
13214 if (!DestEltTy->isIntegerType())
13215 return false;
13216
13217 unsigned SourceLen = SourceLHS.getVectorLength();
13218 SmallVector<APValue, 4> ResultElements;
13219 ResultElements.reserve(SourceLen);
13220
13221 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13222 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13223 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
13224 switch (BuiltinOp) {
13225 case Builtin::BI__builtin_elementwise_max:
13226 ResultElements.push_back(
13227 APValue(APSInt(std::max(LHS, RHS),
13228 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13229 break;
13230 case Builtin::BI__builtin_elementwise_min:
13231 ResultElements.push_back(
13232 APValue(APSInt(std::min(LHS, RHS),
13233 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13234 break;
13235 }
13236 }
13237
13238 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13239 }
13240 case X86::BI__builtin_ia32_vpshldd128:
13241 case X86::BI__builtin_ia32_vpshldd256:
13242 case X86::BI__builtin_ia32_vpshldd512:
13243 case X86::BI__builtin_ia32_vpshldq128:
13244 case X86::BI__builtin_ia32_vpshldq256:
13245 case X86::BI__builtin_ia32_vpshldq512:
13246 case X86::BI__builtin_ia32_vpshldw128:
13247 case X86::BI__builtin_ia32_vpshldw256:
13248 case X86::BI__builtin_ia32_vpshldw512: {
13249 APValue SourceHi, SourceLo, SourceAmt;
13250 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
13251 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
13252 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
13253 return false;
13254
13255 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13256 unsigned SourceLen = SourceHi.getVectorLength();
13257 SmallVector<APValue, 32> ResultElements;
13258 ResultElements.reserve(SourceLen);
13259
13260 APInt Amt = SourceAmt.getInt();
13261 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13262 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
13263 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
13264 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
13265 ResultElements.push_back(
13267 }
13268
13269 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13270 }
13271 case X86::BI__builtin_ia32_vpshrdd128:
13272 case X86::BI__builtin_ia32_vpshrdd256:
13273 case X86::BI__builtin_ia32_vpshrdd512:
13274 case X86::BI__builtin_ia32_vpshrdq128:
13275 case X86::BI__builtin_ia32_vpshrdq256:
13276 case X86::BI__builtin_ia32_vpshrdq512:
13277 case X86::BI__builtin_ia32_vpshrdw128:
13278 case X86::BI__builtin_ia32_vpshrdw256:
13279 case X86::BI__builtin_ia32_vpshrdw512: {
13280 // NOTE: Reversed Hi/Lo operands.
13281 APValue SourceHi, SourceLo, SourceAmt;
13282 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
13283 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
13284 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
13285 return false;
13286
13287 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13288 unsigned SourceLen = SourceHi.getVectorLength();
13289 SmallVector<APValue, 32> ResultElements;
13290 ResultElements.reserve(SourceLen);
13291
13292 APInt Amt = SourceAmt.getInt();
13293 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13294 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
13295 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
13296 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
13297 ResultElements.push_back(
13299 }
13300
13301 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13302 }
13303 case X86::BI__builtin_ia32_compressdf128_mask:
13304 case X86::BI__builtin_ia32_compressdf256_mask:
13305 case X86::BI__builtin_ia32_compressdf512_mask:
13306 case X86::BI__builtin_ia32_compressdi128_mask:
13307 case X86::BI__builtin_ia32_compressdi256_mask:
13308 case X86::BI__builtin_ia32_compressdi512_mask:
13309 case X86::BI__builtin_ia32_compresshi128_mask:
13310 case X86::BI__builtin_ia32_compresshi256_mask:
13311 case X86::BI__builtin_ia32_compresshi512_mask:
13312 case X86::BI__builtin_ia32_compressqi128_mask:
13313 case X86::BI__builtin_ia32_compressqi256_mask:
13314 case X86::BI__builtin_ia32_compressqi512_mask:
13315 case X86::BI__builtin_ia32_compresssf128_mask:
13316 case X86::BI__builtin_ia32_compresssf256_mask:
13317 case X86::BI__builtin_ia32_compresssf512_mask:
13318 case X86::BI__builtin_ia32_compresssi128_mask:
13319 case X86::BI__builtin_ia32_compresssi256_mask:
13320 case X86::BI__builtin_ia32_compresssi512_mask: {
13321 APValue Source, Passthru;
13322 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13323 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13324 return false;
13325 APSInt Mask;
13326 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13327 return false;
13328
13329 unsigned NumElts = Source.getVectorLength();
13330 SmallVector<APValue, 64> ResultElements;
13331 ResultElements.reserve(NumElts);
13332
13333 for (unsigned I = 0; I != NumElts; ++I) {
13334 if (Mask[I])
13335 ResultElements.push_back(Source.getVectorElt(I));
13336 }
13337 for (unsigned I = ResultElements.size(); I != NumElts; ++I) {
13338 ResultElements.push_back(Passthru.getVectorElt(I));
13339 }
13340
13341 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13342 }
13343 case X86::BI__builtin_ia32_expanddf128_mask:
13344 case X86::BI__builtin_ia32_expanddf256_mask:
13345 case X86::BI__builtin_ia32_expanddf512_mask:
13346 case X86::BI__builtin_ia32_expanddi128_mask:
13347 case X86::BI__builtin_ia32_expanddi256_mask:
13348 case X86::BI__builtin_ia32_expanddi512_mask:
13349 case X86::BI__builtin_ia32_expandhi128_mask:
13350 case X86::BI__builtin_ia32_expandhi256_mask:
13351 case X86::BI__builtin_ia32_expandhi512_mask:
13352 case X86::BI__builtin_ia32_expandqi128_mask:
13353 case X86::BI__builtin_ia32_expandqi256_mask:
13354 case X86::BI__builtin_ia32_expandqi512_mask:
13355 case X86::BI__builtin_ia32_expandsf128_mask:
13356 case X86::BI__builtin_ia32_expandsf256_mask:
13357 case X86::BI__builtin_ia32_expandsf512_mask:
13358 case X86::BI__builtin_ia32_expandsi128_mask:
13359 case X86::BI__builtin_ia32_expandsi256_mask:
13360 case X86::BI__builtin_ia32_expandsi512_mask: {
13361 APValue Source, Passthru;
13362 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13363 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13364 return false;
13365 APSInt Mask;
13366 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13367 return false;
13368
13369 unsigned NumElts = Source.getVectorLength();
13370 SmallVector<APValue, 64> ResultElements;
13371 ResultElements.reserve(NumElts);
13372
13373 unsigned SourceIdx = 0;
13374 for (unsigned I = 0; I != NumElts; ++I) {
13375 if (Mask[I])
13376 ResultElements.push_back(Source.getVectorElt(SourceIdx++));
13377 else
13378 ResultElements.push_back(Passthru.getVectorElt(I));
13379 }
13380 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13381 }
13382 case X86::BI__builtin_ia32_vpconflictsi_128:
13383 case X86::BI__builtin_ia32_vpconflictsi_256:
13384 case X86::BI__builtin_ia32_vpconflictsi_512:
13385 case X86::BI__builtin_ia32_vpconflictdi_128:
13386 case X86::BI__builtin_ia32_vpconflictdi_256:
13387 case X86::BI__builtin_ia32_vpconflictdi_512: {
13388 APValue Source;
13389
13390 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13391 return false;
13392
13393 unsigned SourceLen = Source.getVectorLength();
13394 SmallVector<APValue, 32> ResultElements;
13395 ResultElements.reserve(SourceLen);
13396
13397 const auto *VecT = E->getType()->castAs<VectorType>();
13398 bool DestUnsigned =
13399 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
13400
13401 for (unsigned I = 0; I != SourceLen; ++I) {
13402 const APValue &EltI = Source.getVectorElt(I);
13403
13404 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
13405 for (unsigned J = 0; J != I; ++J) {
13406 const APValue &EltJ = Source.getVectorElt(J);
13407 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
13408 }
13409 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
13410 }
13411 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13412 }
13413 case X86::BI__builtin_ia32_blendpd:
13414 case X86::BI__builtin_ia32_blendpd256:
13415 case X86::BI__builtin_ia32_blendps:
13416 case X86::BI__builtin_ia32_blendps256:
13417 case X86::BI__builtin_ia32_pblendw128:
13418 case X86::BI__builtin_ia32_pblendw256:
13419 case X86::BI__builtin_ia32_pblendd128:
13420 case X86::BI__builtin_ia32_pblendd256: {
13421 APValue SourceF, SourceT, SourceC;
13422 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13423 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13424 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13425 return false;
13426
13427 const APInt &C = SourceC.getInt();
13428 unsigned SourceLen = SourceF.getVectorLength();
13429 SmallVector<APValue, 32> ResultElements;
13430 ResultElements.reserve(SourceLen);
13431 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
13432 const APValue &F = SourceF.getVectorElt(EltNum);
13433 const APValue &T = SourceT.getVectorElt(EltNum);
13434 ResultElements.push_back(C[EltNum % 8] ? T : F);
13435 }
13436
13437 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13438 }
13439
13440 case X86::BI__builtin_ia32_psignb128:
13441 case X86::BI__builtin_ia32_psignb256:
13442 case X86::BI__builtin_ia32_psignw128:
13443 case X86::BI__builtin_ia32_psignw256:
13444 case X86::BI__builtin_ia32_psignd128:
13445 case X86::BI__builtin_ia32_psignd256:
13446 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
13447 if (BElem.isZero())
13448 return APInt::getZero(AElem.getBitWidth());
13449 if (BElem.isNegative())
13450 return -AElem;
13451 return AElem;
13452 });
13453
13454 case X86::BI__builtin_ia32_blendvpd:
13455 case X86::BI__builtin_ia32_blendvpd256:
13456 case X86::BI__builtin_ia32_blendvps:
13457 case X86::BI__builtin_ia32_blendvps256:
13458 case X86::BI__builtin_ia32_pblendvb128:
13459 case X86::BI__builtin_ia32_pblendvb256: {
13460 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
13461 APValue SourceF, SourceT, SourceC;
13462 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13463 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13464 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13465 return false;
13466
13467 unsigned SourceLen = SourceF.getVectorLength();
13468 SmallVector<APValue, 32> ResultElements;
13469 ResultElements.reserve(SourceLen);
13470
13471 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13472 const APValue &F = SourceF.getVectorElt(EltNum);
13473 const APValue &T = SourceT.getVectorElt(EltNum);
13474 const APValue &C = SourceC.getVectorElt(EltNum);
13475 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
13476 ResultElements.push_back(M.isNegative() ? T : F);
13477 }
13478
13479 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13480 }
13481 case X86::BI__builtin_ia32_selectb_128:
13482 case X86::BI__builtin_ia32_selectb_256:
13483 case X86::BI__builtin_ia32_selectb_512:
13484 case X86::BI__builtin_ia32_selectw_128:
13485 case X86::BI__builtin_ia32_selectw_256:
13486 case X86::BI__builtin_ia32_selectw_512:
13487 case X86::BI__builtin_ia32_selectd_128:
13488 case X86::BI__builtin_ia32_selectd_256:
13489 case X86::BI__builtin_ia32_selectd_512:
13490 case X86::BI__builtin_ia32_selectq_128:
13491 case X86::BI__builtin_ia32_selectq_256:
13492 case X86::BI__builtin_ia32_selectq_512:
13493 case X86::BI__builtin_ia32_selectph_128:
13494 case X86::BI__builtin_ia32_selectph_256:
13495 case X86::BI__builtin_ia32_selectph_512:
13496 case X86::BI__builtin_ia32_selectpbf_128:
13497 case X86::BI__builtin_ia32_selectpbf_256:
13498 case X86::BI__builtin_ia32_selectpbf_512:
13499 case X86::BI__builtin_ia32_selectps_128:
13500 case X86::BI__builtin_ia32_selectps_256:
13501 case X86::BI__builtin_ia32_selectps_512:
13502 case X86::BI__builtin_ia32_selectpd_128:
13503 case X86::BI__builtin_ia32_selectpd_256:
13504 case X86::BI__builtin_ia32_selectpd_512: {
13505 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
13506 APValue SourceMask, SourceLHS, SourceRHS;
13507 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
13508 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
13509 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
13510 return false;
13511
13512 APSInt Mask = SourceMask.getInt();
13513 unsigned SourceLen = SourceLHS.getVectorLength();
13514 SmallVector<APValue, 4> ResultElements;
13515 ResultElements.reserve(SourceLen);
13516
13517 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13518 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
13519 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
13520 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
13521 }
13522
13523 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13524 }
13525
13526 case X86::BI__builtin_ia32_cvtsd2ss: {
13527 APValue VecA, VecB;
13528 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13529 !EvaluateAsRValue(Info, E->getArg(1), VecB))
13530 return false;
13531
13532 SmallVector<APValue, 4> Elements;
13533
13534 APValue ResultVal;
13535 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13536 ResultVal))
13537 return false;
13538
13539 Elements.push_back(ResultVal);
13540
13541 unsigned NumEltsA = VecA.getVectorLength();
13542 for (unsigned I = 1; I < NumEltsA; ++I) {
13543 Elements.push_back(VecA.getVectorElt(I));
13544 }
13545
13546 return Success(Elements, E);
13547 }
13548 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: {
13549 APValue VecA, VecB, VecSrc, MaskValue;
13550
13551 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13552 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
13553 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
13554 !EvaluateAsRValue(Info, E->getArg(3), MaskValue))
13555 return false;
13556
13557 unsigned Mask = MaskValue.getInt().getZExtValue();
13558 SmallVector<APValue, 4> Elements;
13559
13560 if (Mask & 1) {
13561 APValue ResultVal;
13562 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13563 ResultVal))
13564 return false;
13565 Elements.push_back(ResultVal);
13566 } else {
13567 Elements.push_back(VecSrc.getVectorElt(0));
13568 }
13569
13570 unsigned NumEltsA = VecA.getVectorLength();
13571 for (unsigned I = 1; I < NumEltsA; ++I) {
13572 Elements.push_back(VecA.getVectorElt(I));
13573 }
13574
13575 return Success(Elements, E);
13576 }
13577 case X86::BI__builtin_ia32_cvtpd2ps:
13578 case X86::BI__builtin_ia32_cvtpd2ps256:
13579 case X86::BI__builtin_ia32_cvtpd2ps_mask:
13580 case X86::BI__builtin_ia32_cvtpd2ps512_mask: {
13581
13582 const auto BuiltinID = BuiltinOp;
13583 bool IsMasked = (BuiltinID == X86::BI__builtin_ia32_cvtpd2ps_mask ||
13584 BuiltinID == X86::BI__builtin_ia32_cvtpd2ps512_mask);
13585
13586 APValue InputValue;
13587 if (!EvaluateAsRValue(Info, E->getArg(0), InputValue))
13588 return false;
13589
13590 APValue MergeValue;
13591 unsigned Mask = 0xFFFFFFFF;
13592 bool NeedsMerge = false;
13593 if (IsMasked) {
13594 APValue MaskValue;
13595 if (!EvaluateAsRValue(Info, E->getArg(2), MaskValue))
13596 return false;
13597 Mask = MaskValue.getInt().getZExtValue();
13598 auto NumEltsResult = E->getType()->getAs<VectorType>()->getNumElements();
13599 for (unsigned I = 0; I < NumEltsResult; ++I) {
13600 if (!((Mask >> I) & 1)) {
13601 NeedsMerge = true;
13602 break;
13603 }
13604 }
13605 if (NeedsMerge) {
13606 if (!EvaluateAsRValue(Info, E->getArg(1), MergeValue))
13607 return false;
13608 }
13609 }
13610
13611 unsigned NumEltsResult =
13612 E->getType()->getAs<VectorType>()->getNumElements();
13613 unsigned NumEltsInput = InputValue.getVectorLength();
13614 SmallVector<APValue, 8> Elements;
13615 for (unsigned I = 0; I < NumEltsResult; ++I) {
13616 if (IsMasked && !((Mask >> I) & 1)) {
13617 if (!NeedsMerge) {
13618 return false;
13619 }
13620 Elements.push_back(MergeValue.getVectorElt(I));
13621 continue;
13622 }
13623
13624 if (I >= NumEltsInput) {
13625 Elements.push_back(APValue(APFloat::getZero(APFloat::IEEEsingle())));
13626 continue;
13627 }
13628
13629 APValue ResultVal;
13631 Info, E, InputValue.getVectorElt(I).getFloat(), ResultVal))
13632 return false;
13633
13634 Elements.push_back(ResultVal);
13635 }
13636 return Success(Elements, E);
13637 }
13638
13639 case X86::BI__builtin_ia32_shufps:
13640 case X86::BI__builtin_ia32_shufps256:
13641 case X86::BI__builtin_ia32_shufps512: {
13642 APValue R;
13643 if (!evalShuffleGeneric(
13644 Info, E, R,
13645 [](unsigned DstIdx,
13646 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13647 constexpr unsigned LaneBits = 128u;
13648 unsigned NumElemPerLane = LaneBits / 32;
13649 unsigned NumSelectableElems = NumElemPerLane / 2;
13650 unsigned BitsPerElem = 2;
13651 unsigned IndexMask = (1u << BitsPerElem) - 1;
13652 unsigned MaskBits = 8;
13653 unsigned Lane = DstIdx / NumElemPerLane;
13654 unsigned ElemInLane = DstIdx % NumElemPerLane;
13655 unsigned LaneOffset = Lane * NumElemPerLane;
13656 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13657 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13658 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13659 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13660 }))
13661 return false;
13662 return Success(R, E);
13663 }
13664 case X86::BI__builtin_ia32_shufpd:
13665 case X86::BI__builtin_ia32_shufpd256:
13666 case X86::BI__builtin_ia32_shufpd512: {
13667 APValue R;
13668 if (!evalShuffleGeneric(
13669 Info, E, R,
13670 [](unsigned DstIdx,
13671 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13672 constexpr unsigned LaneBits = 128u;
13673 unsigned NumElemPerLane = LaneBits / 64;
13674 unsigned NumSelectableElems = NumElemPerLane / 2;
13675 unsigned BitsPerElem = 1;
13676 unsigned IndexMask = (1u << BitsPerElem) - 1;
13677 unsigned MaskBits = 8;
13678 unsigned Lane = DstIdx / NumElemPerLane;
13679 unsigned ElemInLane = DstIdx % NumElemPerLane;
13680 unsigned LaneOffset = Lane * NumElemPerLane;
13681 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13682 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13683 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13684 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13685 }))
13686 return false;
13687 return Success(R, E);
13688 }
13689 case X86::BI__builtin_ia32_insertps128: {
13690 APValue R;
13691 if (!evalShuffleGeneric(
13692 Info, E, R,
13693 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13694 // Bits [3:0]: zero mask - if bit is set, zero this element
13695 if ((Mask & (1 << DstIdx)) != 0) {
13696 return {0, -1};
13697 }
13698 // Bits [7:6]: select element from source vector Y (0-3)
13699 // Bits [5:4]: select destination position (0-3)
13700 unsigned SrcElem = (Mask >> 6) & 0x3;
13701 unsigned DstElem = (Mask >> 4) & 0x3;
13702 if (DstIdx == DstElem) {
13703 // Insert element from source vector (B) at this position
13704 return {1, static_cast<int>(SrcElem)};
13705 } else {
13706 // Copy from destination vector (A)
13707 return {0, static_cast<int>(DstIdx)};
13708 }
13709 }))
13710 return false;
13711 return Success(R, E);
13712 }
13713 case X86::BI__builtin_ia32_pshufb128:
13714 case X86::BI__builtin_ia32_pshufb256:
13715 case X86::BI__builtin_ia32_pshufb512: {
13716 APValue R;
13717 if (!evalShuffleGeneric(
13718 Info, E, R,
13719 [](unsigned DstIdx,
13720 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13721 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
13722 if (Ctlb & 0x80)
13723 return std::make_pair(0, -1);
13724
13725 unsigned LaneBase = (DstIdx / 16) * 16;
13726 unsigned SrcOffset = Ctlb & 0x0F;
13727 unsigned SrcIdx = LaneBase + SrcOffset;
13728 return std::make_pair(0, static_cast<int>(SrcIdx));
13729 }))
13730 return false;
13731 return Success(R, E);
13732 }
13733
13734 case X86::BI__builtin_ia32_pshuflw:
13735 case X86::BI__builtin_ia32_pshuflw256:
13736 case X86::BI__builtin_ia32_pshuflw512: {
13737 APValue R;
13738 if (!evalShuffleGeneric(
13739 Info, E, R,
13740 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13741 constexpr unsigned LaneBits = 128u;
13742 constexpr unsigned ElemBits = 16u;
13743 constexpr unsigned LaneElts = LaneBits / ElemBits;
13744 constexpr unsigned HalfSize = 4;
13745 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13746 unsigned LaneIdx = DstIdx % LaneElts;
13747 if (LaneIdx < HalfSize) {
13748 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13749 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13750 }
13751 return std::make_pair(0, static_cast<int>(DstIdx));
13752 }))
13753 return false;
13754 return Success(R, E);
13755 }
13756
13757 case X86::BI__builtin_ia32_pshufhw:
13758 case X86::BI__builtin_ia32_pshufhw256:
13759 case X86::BI__builtin_ia32_pshufhw512: {
13760 APValue R;
13761 if (!evalShuffleGeneric(
13762 Info, E, R,
13763 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13764 constexpr unsigned LaneBits = 128u;
13765 constexpr unsigned ElemBits = 16u;
13766 constexpr unsigned LaneElts = LaneBits / ElemBits;
13767 constexpr unsigned HalfSize = 4;
13768 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13769 unsigned LaneIdx = DstIdx % LaneElts;
13770 if (LaneIdx >= HalfSize) {
13771 unsigned Rel = LaneIdx - HalfSize;
13772 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
13773 return std::make_pair(
13774 0, static_cast<int>(LaneBase + HalfSize + Sel));
13775 }
13776 return std::make_pair(0, static_cast<int>(DstIdx));
13777 }))
13778 return false;
13779 return Success(R, E);
13780 }
13781
13782 case X86::BI__builtin_ia32_pshufd:
13783 case X86::BI__builtin_ia32_pshufd256:
13784 case X86::BI__builtin_ia32_pshufd512:
13785 case X86::BI__builtin_ia32_vpermilps:
13786 case X86::BI__builtin_ia32_vpermilps256:
13787 case X86::BI__builtin_ia32_vpermilps512: {
13788 APValue R;
13789 if (!evalShuffleGeneric(
13790 Info, E, R,
13791 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13792 constexpr unsigned LaneBits = 128u;
13793 constexpr unsigned ElemBits = 32u;
13794 constexpr unsigned LaneElts = LaneBits / ElemBits;
13795 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13796 unsigned LaneIdx = DstIdx % LaneElts;
13797 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13798 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13799 }))
13800 return false;
13801 return Success(R, E);
13802 }
13803
13804 case X86::BI__builtin_ia32_vpermilvarpd:
13805 case X86::BI__builtin_ia32_vpermilvarpd256:
13806 case X86::BI__builtin_ia32_vpermilvarpd512: {
13807 APValue R;
13808 if (!evalShuffleGeneric(
13809 Info, E, R,
13810 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13811 unsigned NumElemPerLane = 2;
13812 unsigned Lane = DstIdx / NumElemPerLane;
13813 unsigned Offset = Mask & 0b10 ? 1 : 0;
13814 return std::make_pair(
13815 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13816 }))
13817 return false;
13818 return Success(R, E);
13819 }
13820
13821 case X86::BI__builtin_ia32_vpermilpd:
13822 case X86::BI__builtin_ia32_vpermilpd256:
13823 case X86::BI__builtin_ia32_vpermilpd512: {
13824 APValue R;
13825 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13826 unsigned NumElemPerLane = 2;
13827 unsigned BitsPerElem = 1;
13828 unsigned MaskBits = 8;
13829 unsigned IndexMask = 0x1;
13830 unsigned Lane = DstIdx / NumElemPerLane;
13831 unsigned LaneOffset = Lane * NumElemPerLane;
13832 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13833 unsigned Index = (Control >> BitIndex) & IndexMask;
13834 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
13835 }))
13836 return false;
13837 return Success(R, E);
13838 }
13839
13840 case X86::BI__builtin_ia32_permdf256:
13841 case X86::BI__builtin_ia32_permdi256: {
13842 APValue R;
13843 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
13844 // permute4x64 operates on 4 64-bit elements
13845 // For element i (0-3), extract bits [2*i+1:2*i] from Control
13846 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
13847 return std::make_pair(0, static_cast<int>(Index));
13848 }))
13849 return false;
13850 return Success(R, E);
13851 }
13852
13853 case X86::BI__builtin_ia32_vpermilvarps:
13854 case X86::BI__builtin_ia32_vpermilvarps256:
13855 case X86::BI__builtin_ia32_vpermilvarps512: {
13856 APValue R;
13857 if (!evalShuffleGeneric(
13858 Info, E, R,
13859 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13860 unsigned NumElemPerLane = 4;
13861 unsigned Lane = DstIdx / NumElemPerLane;
13862 unsigned Offset = Mask & 0b11;
13863 return std::make_pair(
13864 0, static_cast<int>(Lane * NumElemPerLane + Offset));
13865 }))
13866 return false;
13867 return Success(R, E);
13868 }
13869
13870 case X86::BI__builtin_ia32_vpmultishiftqb128:
13871 case X86::BI__builtin_ia32_vpmultishiftqb256:
13872 case X86::BI__builtin_ia32_vpmultishiftqb512: {
13873 assert(E->getNumArgs() == 2);
13874
13875 APValue A, B;
13876 if (!Evaluate(A, Info, E->getArg(0)) || !Evaluate(B, Info, E->getArg(1)))
13877 return false;
13878
13879 assert(A.getVectorLength() == B.getVectorLength());
13880 unsigned NumBytesInQWord = 8;
13881 unsigned NumBitsInByte = 8;
13882 unsigned NumBytes = A.getVectorLength();
13883 unsigned NumQWords = NumBytes / NumBytesInQWord;
13885 Result.reserve(NumBytes);
13886
13887 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
13888 APInt BQWord(64, 0);
13889 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13890 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13891 uint64_t Byte = B.getVectorElt(Idx).getInt().getZExtValue();
13892 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
13893 }
13894
13895 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
13896 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
13897 uint64_t Ctrl = A.getVectorElt(Idx).getInt().getZExtValue() & 0x3F;
13898
13899 APInt Byte(8, 0);
13900 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
13901 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
13902 }
13903 Result.push_back(APValue(APSInt(Byte, /*isUnsigned*/ true)));
13904 }
13905 }
13906 return Success(APValue(Result.data(), Result.size()), E);
13907 }
13908
13909 case X86::BI__builtin_ia32_phminposuw128: {
13910 APValue Source;
13911 if (!Evaluate(Source, Info, E->getArg(0)))
13912 return false;
13913 unsigned SourceLen = Source.getVectorLength();
13914 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
13915 QualType ElemQT = VT->getElementType();
13916 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
13917
13918 APInt MinIndex(ElemBitWidth, 0);
13919 APInt MinVal = Source.getVectorElt(0).getInt();
13920 for (unsigned I = 1; I != SourceLen; ++I) {
13921 APInt Val = Source.getVectorElt(I).getInt();
13922 if (MinVal.ugt(Val)) {
13923 MinVal = Val;
13924 MinIndex = I;
13925 }
13926 }
13927
13928 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
13929 ->castAs<VectorType>()
13930 ->getElementType()
13931 ->isUnsignedIntegerOrEnumerationType();
13932
13934 Result.reserve(SourceLen);
13935 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
13936 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
13937 for (unsigned I = 0; I != SourceLen - 2; ++I) {
13938 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
13939 }
13940 return Success(APValue(Result.data(), Result.size()), E);
13941 }
13942
13943 case X86::BI__builtin_ia32_psraq128:
13944 case X86::BI__builtin_ia32_psraq256:
13945 case X86::BI__builtin_ia32_psraq512:
13946 case X86::BI__builtin_ia32_psrad128:
13947 case X86::BI__builtin_ia32_psrad256:
13948 case X86::BI__builtin_ia32_psrad512:
13949 case X86::BI__builtin_ia32_psraw128:
13950 case X86::BI__builtin_ia32_psraw256:
13951 case X86::BI__builtin_ia32_psraw512: {
13952 APValue R;
13953 if (!evalShiftWithCount(
13954 Info, E, R,
13955 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
13956 [](const APInt &Elt, unsigned Width) {
13957 return Elt.ashr(Width - 1);
13958 }))
13959 return false;
13960 return Success(R, E);
13961 }
13962
13963 case X86::BI__builtin_ia32_psllq128:
13964 case X86::BI__builtin_ia32_psllq256:
13965 case X86::BI__builtin_ia32_psllq512:
13966 case X86::BI__builtin_ia32_pslld128:
13967 case X86::BI__builtin_ia32_pslld256:
13968 case X86::BI__builtin_ia32_pslld512:
13969 case X86::BI__builtin_ia32_psllw128:
13970 case X86::BI__builtin_ia32_psllw256:
13971 case X86::BI__builtin_ia32_psllw512: {
13972 APValue R;
13973 if (!evalShiftWithCount(
13974 Info, E, R,
13975 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
13976 [](const APInt &Elt, unsigned Width) {
13977 return APInt::getZero(Width);
13978 }))
13979 return false;
13980 return Success(R, E);
13981 }
13982
13983 case X86::BI__builtin_ia32_psrlq128:
13984 case X86::BI__builtin_ia32_psrlq256:
13985 case X86::BI__builtin_ia32_psrlq512:
13986 case X86::BI__builtin_ia32_psrld128:
13987 case X86::BI__builtin_ia32_psrld256:
13988 case X86::BI__builtin_ia32_psrld512:
13989 case X86::BI__builtin_ia32_psrlw128:
13990 case X86::BI__builtin_ia32_psrlw256:
13991 case X86::BI__builtin_ia32_psrlw512: {
13992 APValue R;
13993 if (!evalShiftWithCount(
13994 Info, E, R,
13995 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
13996 [](const APInt &Elt, unsigned Width) {
13997 return APInt::getZero(Width);
13998 }))
13999 return false;
14000 return Success(R, E);
14001 }
14002
14003 case X86::BI__builtin_ia32_pternlogd128_mask:
14004 case X86::BI__builtin_ia32_pternlogd256_mask:
14005 case X86::BI__builtin_ia32_pternlogd512_mask:
14006 case X86::BI__builtin_ia32_pternlogq128_mask:
14007 case X86::BI__builtin_ia32_pternlogq256_mask:
14008 case X86::BI__builtin_ia32_pternlogq512_mask: {
14009 APValue AValue, BValue, CValue, ImmValue, UValue;
14010 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
14011 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
14012 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
14013 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
14014 !EvaluateAsRValue(Info, E->getArg(4), UValue))
14015 return false;
14016
14017 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14018 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14019 APInt Imm = ImmValue.getInt();
14020 APInt U = UValue.getInt();
14021 unsigned ResultLen = AValue.getVectorLength();
14022 SmallVector<APValue, 16> ResultElements;
14023 ResultElements.reserve(ResultLen);
14024
14025 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
14026 APInt ALane = AValue.getVectorElt(EltNum).getInt();
14027 APInt BLane = BValue.getVectorElt(EltNum).getInt();
14028 APInt CLane = CValue.getVectorElt(EltNum).getInt();
14029
14030 if (U[EltNum]) {
14031 unsigned BitWidth = ALane.getBitWidth();
14032 APInt ResLane(BitWidth, 0);
14033
14034 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
14035 unsigned ABit = ALane[Bit];
14036 unsigned BBit = BLane[Bit];
14037 unsigned CBit = CLane[Bit];
14038
14039 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
14040 ResLane.setBitVal(Bit, Imm[Idx]);
14041 }
14042 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
14043 } else {
14044 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
14045 }
14046 }
14047 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14048 }
14049 case X86::BI__builtin_ia32_pternlogd128_maskz:
14050 case X86::BI__builtin_ia32_pternlogd256_maskz:
14051 case X86::BI__builtin_ia32_pternlogd512_maskz:
14052 case X86::BI__builtin_ia32_pternlogq128_maskz:
14053 case X86::BI__builtin_ia32_pternlogq256_maskz:
14054 case X86::BI__builtin_ia32_pternlogq512_maskz: {
14055 APValue AValue, BValue, CValue, ImmValue, UValue;
14056 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
14057 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
14058 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
14059 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
14060 !EvaluateAsRValue(Info, E->getArg(4), UValue))
14061 return false;
14062
14063 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14064 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14065 APInt Imm = ImmValue.getInt();
14066 APInt U = UValue.getInt();
14067 unsigned ResultLen = AValue.getVectorLength();
14068 SmallVector<APValue, 16> ResultElements;
14069 ResultElements.reserve(ResultLen);
14070
14071 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
14072 APInt ALane = AValue.getVectorElt(EltNum).getInt();
14073 APInt BLane = BValue.getVectorElt(EltNum).getInt();
14074 APInt CLane = CValue.getVectorElt(EltNum).getInt();
14075
14076 unsigned BitWidth = ALane.getBitWidth();
14077 APInt ResLane(BitWidth, 0);
14078
14079 if (U[EltNum]) {
14080 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
14081 unsigned ABit = ALane[Bit];
14082 unsigned BBit = BLane[Bit];
14083 unsigned CBit = CLane[Bit];
14084
14085 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
14086 ResLane.setBitVal(Bit, Imm[Idx]);
14087 }
14088 }
14089 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
14090 }
14091 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14092 }
14093
14094 case Builtin::BI__builtin_elementwise_clzg:
14095 case Builtin::BI__builtin_elementwise_ctzg: {
14096 APValue SourceLHS;
14097 std::optional<APValue> Fallback;
14098 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
14099 return false;
14100 if (E->getNumArgs() > 1) {
14101 APValue FallbackTmp;
14102 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
14103 return false;
14104 Fallback = FallbackTmp;
14105 }
14106
14107 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14108 unsigned SourceLen = SourceLHS.getVectorLength();
14109 SmallVector<APValue, 4> ResultElements;
14110 ResultElements.reserve(SourceLen);
14111
14112 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14113 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
14114 if (!LHS) {
14115 // Without a fallback, a zero element is undefined
14116 if (!Fallback) {
14117 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
14118 << /*IsTrailing=*/(BuiltinOp ==
14119 Builtin::BI__builtin_elementwise_ctzg);
14120 return false;
14121 }
14122 ResultElements.push_back(Fallback->getVectorElt(EltNum));
14123 continue;
14124 }
14125 switch (BuiltinOp) {
14126 case Builtin::BI__builtin_elementwise_clzg:
14127 ResultElements.push_back(APValue(
14128 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
14129 DestEltTy->isUnsignedIntegerOrEnumerationType())));
14130 break;
14131 case Builtin::BI__builtin_elementwise_ctzg:
14132 ResultElements.push_back(APValue(
14133 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
14134 DestEltTy->isUnsignedIntegerOrEnumerationType())));
14135 break;
14136 }
14137 }
14138
14139 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14140 }
14141
14142 case Builtin::BI__builtin_elementwise_fma: {
14143 APValue SourceX, SourceY, SourceZ;
14144 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
14145 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
14146 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
14147 return false;
14148
14149 unsigned SourceLen = SourceX.getVectorLength();
14150 SmallVector<APValue> ResultElements;
14151 ResultElements.reserve(SourceLen);
14152 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14153 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14154 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
14155 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
14156 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
14157 APFloat Result(X);
14158 (void)Result.fusedMultiplyAdd(Y, Z, RM);
14159 ResultElements.push_back(APValue(Result));
14160 }
14161 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14162 }
14163
14164 case clang::X86::BI__builtin_ia32_phaddw128:
14165 case clang::X86::BI__builtin_ia32_phaddw256:
14166 case clang::X86::BI__builtin_ia32_phaddd128:
14167 case clang::X86::BI__builtin_ia32_phaddd256:
14168 case clang::X86::BI__builtin_ia32_phaddsw128:
14169 case clang::X86::BI__builtin_ia32_phaddsw256:
14170
14171 case clang::X86::BI__builtin_ia32_phsubw128:
14172 case clang::X86::BI__builtin_ia32_phsubw256:
14173 case clang::X86::BI__builtin_ia32_phsubd128:
14174 case clang::X86::BI__builtin_ia32_phsubd256:
14175 case clang::X86::BI__builtin_ia32_phsubsw128:
14176 case clang::X86::BI__builtin_ia32_phsubsw256: {
14177 APValue SourceLHS, SourceRHS;
14178 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14179 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14180 return false;
14181 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14182 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14183
14184 unsigned NumElts = SourceLHS.getVectorLength();
14185 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
14186 unsigned EltsPerLane = 128 / EltBits;
14187 SmallVector<APValue, 4> ResultElements;
14188 ResultElements.reserve(NumElts);
14189
14190 for (unsigned LaneStart = 0; LaneStart != NumElts;
14191 LaneStart += EltsPerLane) {
14192 for (unsigned I = 0; I != EltsPerLane; I += 2) {
14193 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
14194 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
14195 switch (BuiltinOp) {
14196 case clang::X86::BI__builtin_ia32_phaddw128:
14197 case clang::X86::BI__builtin_ia32_phaddw256:
14198 case clang::X86::BI__builtin_ia32_phaddd128:
14199 case clang::X86::BI__builtin_ia32_phaddd256: {
14200 APSInt Res(LHSA + LHSB, DestUnsigned);
14201 ResultElements.push_back(APValue(Res));
14202 break;
14203 }
14204 case clang::X86::BI__builtin_ia32_phaddsw128:
14205 case clang::X86::BI__builtin_ia32_phaddsw256: {
14206 APSInt Res(LHSA.sadd_sat(LHSB));
14207 ResultElements.push_back(APValue(Res));
14208 break;
14209 }
14210 case clang::X86::BI__builtin_ia32_phsubw128:
14211 case clang::X86::BI__builtin_ia32_phsubw256:
14212 case clang::X86::BI__builtin_ia32_phsubd128:
14213 case clang::X86::BI__builtin_ia32_phsubd256: {
14214 APSInt Res(LHSA - LHSB, DestUnsigned);
14215 ResultElements.push_back(APValue(Res));
14216 break;
14217 }
14218 case clang::X86::BI__builtin_ia32_phsubsw128:
14219 case clang::X86::BI__builtin_ia32_phsubsw256: {
14220 APSInt Res(LHSA.ssub_sat(LHSB));
14221 ResultElements.push_back(APValue(Res));
14222 break;
14223 }
14224 }
14225 }
14226 for (unsigned I = 0; I != EltsPerLane; I += 2) {
14227 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
14228 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
14229 switch (BuiltinOp) {
14230 case clang::X86::BI__builtin_ia32_phaddw128:
14231 case clang::X86::BI__builtin_ia32_phaddw256:
14232 case clang::X86::BI__builtin_ia32_phaddd128:
14233 case clang::X86::BI__builtin_ia32_phaddd256: {
14234 APSInt Res(RHSA + RHSB, DestUnsigned);
14235 ResultElements.push_back(APValue(Res));
14236 break;
14237 }
14238 case clang::X86::BI__builtin_ia32_phaddsw128:
14239 case clang::X86::BI__builtin_ia32_phaddsw256: {
14240 APSInt Res(RHSA.sadd_sat(RHSB));
14241 ResultElements.push_back(APValue(Res));
14242 break;
14243 }
14244 case clang::X86::BI__builtin_ia32_phsubw128:
14245 case clang::X86::BI__builtin_ia32_phsubw256:
14246 case clang::X86::BI__builtin_ia32_phsubd128:
14247 case clang::X86::BI__builtin_ia32_phsubd256: {
14248 APSInt Res(RHSA - RHSB, DestUnsigned);
14249 ResultElements.push_back(APValue(Res));
14250 break;
14251 }
14252 case clang::X86::BI__builtin_ia32_phsubsw128:
14253 case clang::X86::BI__builtin_ia32_phsubsw256: {
14254 APSInt Res(RHSA.ssub_sat(RHSB));
14255 ResultElements.push_back(APValue(Res));
14256 break;
14257 }
14258 }
14259 }
14260 }
14261 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14262 }
14263 case clang::X86::BI__builtin_ia32_haddpd:
14264 case clang::X86::BI__builtin_ia32_haddps:
14265 case clang::X86::BI__builtin_ia32_haddps256:
14266 case clang::X86::BI__builtin_ia32_haddpd256:
14267 case clang::X86::BI__builtin_ia32_hsubpd:
14268 case clang::X86::BI__builtin_ia32_hsubps:
14269 case clang::X86::BI__builtin_ia32_hsubps256:
14270 case clang::X86::BI__builtin_ia32_hsubpd256: {
14271 APValue SourceLHS, SourceRHS;
14272 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14273 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14274 return false;
14275 unsigned NumElts = SourceLHS.getVectorLength();
14276 SmallVector<APValue, 4> ResultElements;
14277 ResultElements.reserve(NumElts);
14278 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14279 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14280 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
14281 unsigned NumLanes = NumElts * EltBits / 128;
14282 unsigned NumElemsPerLane = NumElts / NumLanes;
14283 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
14284
14285 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
14286 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
14287 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
14288 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
14289 switch (BuiltinOp) {
14290 case clang::X86::BI__builtin_ia32_haddpd:
14291 case clang::X86::BI__builtin_ia32_haddps:
14292 case clang::X86::BI__builtin_ia32_haddps256:
14293 case clang::X86::BI__builtin_ia32_haddpd256:
14294 LHSA.add(LHSB, RM);
14295 break;
14296 case clang::X86::BI__builtin_ia32_hsubpd:
14297 case clang::X86::BI__builtin_ia32_hsubps:
14298 case clang::X86::BI__builtin_ia32_hsubps256:
14299 case clang::X86::BI__builtin_ia32_hsubpd256:
14300 LHSA.subtract(LHSB, RM);
14301 break;
14302 }
14303 ResultElements.push_back(APValue(LHSA));
14304 }
14305 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
14306 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
14307 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
14308 switch (BuiltinOp) {
14309 case clang::X86::BI__builtin_ia32_haddpd:
14310 case clang::X86::BI__builtin_ia32_haddps:
14311 case clang::X86::BI__builtin_ia32_haddps256:
14312 case clang::X86::BI__builtin_ia32_haddpd256:
14313 RHSA.add(RHSB, RM);
14314 break;
14315 case clang::X86::BI__builtin_ia32_hsubpd:
14316 case clang::X86::BI__builtin_ia32_hsubps:
14317 case clang::X86::BI__builtin_ia32_hsubps256:
14318 case clang::X86::BI__builtin_ia32_hsubpd256:
14319 RHSA.subtract(RHSB, RM);
14320 break;
14321 }
14322 ResultElements.push_back(APValue(RHSA));
14323 }
14324 }
14325 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14326 }
14327 case clang::X86::BI__builtin_ia32_addsubpd:
14328 case clang::X86::BI__builtin_ia32_addsubps:
14329 case clang::X86::BI__builtin_ia32_addsubpd256:
14330 case clang::X86::BI__builtin_ia32_addsubps256: {
14331 // Addsub: alternates between subtraction and addition
14332 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
14333 APValue SourceLHS, SourceRHS;
14334 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14335 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14336 return false;
14337 unsigned NumElems = SourceLHS.getVectorLength();
14338 SmallVector<APValue, 8> ResultElements;
14339 ResultElements.reserve(NumElems);
14340 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14341
14342 for (unsigned I = 0; I != NumElems; ++I) {
14343 APFloat LHS = SourceLHS.getVectorElt(I).getFloat();
14344 APFloat RHS = SourceRHS.getVectorElt(I).getFloat();
14345 if (I % 2 == 0) {
14346 // Even indices: subtract
14347 LHS.subtract(RHS, RM);
14348 } else {
14349 // Odd indices: add
14350 LHS.add(RHS, RM);
14351 }
14352 ResultElements.push_back(APValue(LHS));
14353 }
14354 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14355 }
14356 case clang::X86::BI__builtin_ia32_pclmulqdq128:
14357 case clang::X86::BI__builtin_ia32_pclmulqdq256:
14358 case clang::X86::BI__builtin_ia32_pclmulqdq512: {
14359 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
14360 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
14361 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
14362 APValue SourceLHS, SourceRHS;
14363 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14364 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14365 return false;
14366
14367 APSInt Imm8;
14368 if (!EvaluateInteger(E->getArg(2), Imm8, Info))
14369 return false;
14370
14371 // Extract bits 0 and 4 from imm8
14372 bool SelectUpperA = (Imm8 & 0x01) != 0;
14373 bool SelectUpperB = (Imm8 & 0x10) != 0;
14374
14375 unsigned NumElems = SourceLHS.getVectorLength();
14376 SmallVector<APValue, 8> ResultElements;
14377 ResultElements.reserve(NumElems);
14378 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14379 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14380
14381 // Process each 128-bit lane
14382 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
14383 // Get the two 64-bit halves of the first operand
14384 APSInt A0 = SourceLHS.getVectorElt(Lane + 0).getInt();
14385 APSInt A1 = SourceLHS.getVectorElt(Lane + 1).getInt();
14386 // Get the two 64-bit halves of the second operand
14387 APSInt B0 = SourceRHS.getVectorElt(Lane + 0).getInt();
14388 APSInt B1 = SourceRHS.getVectorElt(Lane + 1).getInt();
14389
14390 // Select the appropriate 64-bit values based on imm8
14391 APInt A = SelectUpperA ? A1 : A0;
14392 APInt B = SelectUpperB ? B1 : B0;
14393
14394 // Extend both operands to 128 bits for carry-less multiplication
14395 APInt A128 = A.zext(128);
14396 APInt B128 = B.zext(128);
14397
14398 // Use APIntOps::clmul for carry-less multiplication
14399 APInt Result = llvm::APIntOps::clmul(A128, B128);
14400
14401 // Split the 128-bit result into two 64-bit halves
14402 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
14403 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
14404
14405 ResultElements.push_back(APValue(ResultLow));
14406 ResultElements.push_back(APValue(ResultHigh));
14407 }
14408
14409 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14410 }
14411 case Builtin::BI__builtin_elementwise_clmul:
14412 return EvaluateBinOpExpr(llvm::APIntOps::clmul);
14413 case Builtin::BI__builtin_elementwise_pext:
14414 return EvaluateBinOpExpr(llvm::APIntOps::pext);
14415 case Builtin::BI__builtin_elementwise_pdep:
14416 return EvaluateBinOpExpr(llvm::APIntOps::pdep);
14417 case Builtin::BI__builtin_elementwise_fshl:
14418 case Builtin::BI__builtin_elementwise_fshr: {
14419 APValue SourceHi, SourceLo, SourceShift;
14420 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
14421 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
14422 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
14423 return false;
14424
14425 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14426 if (!DestEltTy->isIntegerType())
14427 return false;
14428
14429 unsigned SourceLen = SourceHi.getVectorLength();
14430 SmallVector<APValue> ResultElements;
14431 ResultElements.reserve(SourceLen);
14432 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14433 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
14434 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
14435 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
14436 switch (BuiltinOp) {
14437 case Builtin::BI__builtin_elementwise_fshl:
14438 ResultElements.push_back(APValue(
14439 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
14440 break;
14441 case Builtin::BI__builtin_elementwise_fshr:
14442 ResultElements.push_back(APValue(
14443 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
14444 break;
14445 }
14446 }
14447
14448 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14449 }
14450
14451 case X86::BI__builtin_ia32_shuf_f32x4_256:
14452 case X86::BI__builtin_ia32_shuf_i32x4_256:
14453 case X86::BI__builtin_ia32_shuf_f64x2_256:
14454 case X86::BI__builtin_ia32_shuf_i64x2_256:
14455 case X86::BI__builtin_ia32_shuf_f32x4:
14456 case X86::BI__builtin_ia32_shuf_i32x4:
14457 case X86::BI__builtin_ia32_shuf_f64x2:
14458 case X86::BI__builtin_ia32_shuf_i64x2: {
14459 APValue SourceA, SourceB;
14460 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
14461 !EvaluateAsRValue(Info, E->getArg(1), SourceB))
14462 return false;
14463
14464 APSInt Imm;
14465 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14466 return false;
14467
14468 // Destination and sources A, B all have the same type.
14469 unsigned NumElems = SourceA.getVectorLength();
14470 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14471 QualType ElemQT = VT->getElementType();
14472 unsigned ElemBits = Info.Ctx.getTypeSize(ElemQT);
14473 unsigned LaneBits = 128u;
14474 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
14475 unsigned NumElemsPerLane = LaneBits / ElemBits;
14476
14477 unsigned DstLen = SourceA.getVectorLength();
14478 SmallVector<APValue, 16> ResultElements;
14479 ResultElements.reserve(DstLen);
14480
14481 APValue R;
14482 if (!evalShuffleGeneric(
14483 Info, E, R,
14484 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask)
14485 -> std::pair<unsigned, int> {
14486 // DstIdx determines source. ShuffleMask selects lane in source.
14487 unsigned BitsPerElem = NumLanes / 2;
14488 unsigned IndexMask = (1u << BitsPerElem) - 1;
14489 unsigned Lane = DstIdx / NumElemsPerLane;
14490 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
14491 unsigned BitIdx = BitsPerElem * Lane;
14492 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
14493 unsigned ElemInLane = DstIdx % NumElemsPerLane;
14494 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
14495 return {SrcIdx, IdxToPick};
14496 }))
14497 return false;
14498 return Success(R, E);
14499 }
14500
14501 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14502 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14503 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
14504 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
14505 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
14506 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi: {
14507
14508 APValue X, A;
14509 APSInt Imm;
14510 if (!EvaluateAsRValue(Info, E->getArg(0), X) ||
14511 !EvaluateAsRValue(Info, E->getArg(1), A) ||
14512 !EvaluateInteger(E->getArg(2), Imm, Info))
14513 return false;
14514
14515 assert(X.isVector() && A.isVector());
14516 assert(X.getVectorLength() == A.getVectorLength());
14517
14518 bool IsInverse = false;
14519 switch (BuiltinOp) {
14520 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14521 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14522 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi: {
14523 IsInverse = true;
14524 }
14525 }
14526
14527 unsigned NumBitsInByte = 8;
14528 unsigned NumBytesInQWord = 8;
14529 unsigned NumBitsInQWord = 64;
14530 unsigned NumBytes = A.getVectorLength();
14531 unsigned NumQWords = NumBytes / NumBytesInQWord;
14533 Result.reserve(NumBytes);
14534
14535 // computing A*X + Imm
14536 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
14537 // Extract the QWords from X, A
14538 APInt XQWord(NumBitsInQWord, 0);
14539 APInt AQWord(NumBitsInQWord, 0);
14540 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14541 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
14542 APInt XByte = X.getVectorElt(Idx).getInt();
14543 APInt AByte = A.getVectorElt(Idx).getInt();
14544 XQWord.insertBits(XByte, ByteIdx * NumBitsInByte);
14545 AQWord.insertBits(AByte, ByteIdx * NumBitsInByte);
14546 }
14547
14548 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14549 uint8_t XByte =
14550 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
14551 Result.push_back(APValue(APSInt(
14552 APInt(8, GFNIAffine(XByte, AQWord, Imm, IsInverse)), false)));
14553 }
14554 }
14555
14556 return Success(APValue(Result.data(), Result.size()), E);
14557 }
14558
14559 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
14560 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
14561 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi: {
14562 APValue A, B;
14563 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
14564 !EvaluateAsRValue(Info, E->getArg(1), B))
14565 return false;
14566
14567 assert(A.isVector() && B.isVector());
14568 assert(A.getVectorLength() == B.getVectorLength());
14569
14570 unsigned NumBytes = A.getVectorLength();
14572 Result.reserve(NumBytes);
14573
14574 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
14575 uint8_t AByte = A.getVectorElt(ByteIdx).getInt().getZExtValue();
14576 uint8_t BByte = B.getVectorElt(ByteIdx).getInt().getZExtValue();
14577 Result.push_back(APValue(
14578 APSInt(APInt(8, GFNIMul(AByte, BByte)), /*IsUnsigned=*/false)));
14579 }
14580
14581 return Success(APValue(Result.data(), Result.size()), E);
14582 }
14583
14584 case X86::BI__builtin_ia32_insertf32x4_256:
14585 case X86::BI__builtin_ia32_inserti32x4_256:
14586 case X86::BI__builtin_ia32_insertf64x2_256:
14587 case X86::BI__builtin_ia32_inserti64x2_256:
14588 case X86::BI__builtin_ia32_insertf32x4:
14589 case X86::BI__builtin_ia32_inserti32x4:
14590 case X86::BI__builtin_ia32_insertf64x2_512:
14591 case X86::BI__builtin_ia32_inserti64x2_512:
14592 case X86::BI__builtin_ia32_insertf32x8:
14593 case X86::BI__builtin_ia32_inserti32x8:
14594 case X86::BI__builtin_ia32_insertf64x4:
14595 case X86::BI__builtin_ia32_inserti64x4:
14596 case X86::BI__builtin_ia32_vinsertf128_ps256:
14597 case X86::BI__builtin_ia32_vinsertf128_pd256:
14598 case X86::BI__builtin_ia32_vinsertf128_si256:
14599 case X86::BI__builtin_ia32_insert128i256: {
14600 APValue SourceDst, SourceSub;
14601 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
14602 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
14603 return false;
14604
14605 APSInt Imm;
14606 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14607 return false;
14608
14609 assert(SourceDst.isVector() && SourceSub.isVector());
14610 unsigned DstLen = SourceDst.getVectorLength();
14611 unsigned SubLen = SourceSub.getVectorLength();
14612 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
14613 unsigned NumLanes = DstLen / SubLen;
14614 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
14615
14616 SmallVector<APValue, 16> ResultElements;
14617 ResultElements.reserve(DstLen);
14618
14619 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
14620 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
14621 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
14622 else
14623 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
14624 }
14625
14626 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14627 }
14628
14629 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
14630 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
14631 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
14632 case clang::X86::BI__builtin_ia32_vec_set_v4si:
14633 case clang::X86::BI__builtin_ia32_vec_set_v2di:
14634 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
14635 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
14636 case clang::X86::BI__builtin_ia32_vec_set_v8si:
14637 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
14638 APValue VecVal;
14639 APSInt Scalar, IndexAPS;
14640 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
14641 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
14642 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
14643 return false;
14644
14645 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
14646 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
14647 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
14648 Scalar.setIsUnsigned(ElemUnsigned);
14649 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
14650 APValue ElemAV(ElemAPS);
14651
14652 unsigned NumElems = VecVal.getVectorLength();
14653 unsigned Index =
14654 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
14655
14657 Elems.reserve(NumElems);
14658 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
14659 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
14660
14661 return Success(APValue(Elems.data(), NumElems), E);
14662 }
14663
14664 case X86::BI__builtin_ia32_pslldqi128_byteshift:
14665 case X86::BI__builtin_ia32_pslldqi256_byteshift:
14666 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
14667 APValue R;
14668 if (!evalShuffleGeneric(
14669 Info, E, R,
14670 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14671 unsigned LaneBase = (DstIdx / 16) * 16;
14672 unsigned LaneIdx = DstIdx % 16;
14673 if (LaneIdx < Shift)
14674 return std::make_pair(0, -1);
14675
14676 return std::make_pair(
14677 0, static_cast<int>(LaneBase + LaneIdx - Shift));
14678 }))
14679 return false;
14680 return Success(R, E);
14681 }
14682
14683 case X86::BI__builtin_ia32_psrldqi128_byteshift:
14684 case X86::BI__builtin_ia32_psrldqi256_byteshift:
14685 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
14686 APValue R;
14687 if (!evalShuffleGeneric(
14688 Info, E, R,
14689 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14690 unsigned LaneBase = (DstIdx / 16) * 16;
14691 unsigned LaneIdx = DstIdx % 16;
14692 if (LaneIdx + Shift < 16)
14693 return std::make_pair(
14694 0, static_cast<int>(LaneBase + LaneIdx + Shift));
14695
14696 return std::make_pair(0, -1);
14697 }))
14698 return false;
14699 return Success(R, E);
14700 }
14701
14702 case X86::BI__builtin_ia32_palignr128:
14703 case X86::BI__builtin_ia32_palignr256:
14704 case X86::BI__builtin_ia32_palignr512: {
14705 APValue R;
14706 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
14707 // Default to -1 → zero-fill this destination element
14708 unsigned VecIdx = 1;
14709 int ElemIdx = -1;
14710
14711 int Lane = DstIdx / 16;
14712 int Offset = DstIdx % 16;
14713
14714 // Elements come from VecB first, then VecA after the shift boundary
14715 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
14716 if (ShiftedIdx < 16) { // from VecB
14717 ElemIdx = ShiftedIdx + (Lane * 16);
14718 } else if (ShiftedIdx < 32) { // from VecA
14719 VecIdx = 0;
14720 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
14721 }
14722
14723 return std::pair<unsigned, int>{VecIdx, ElemIdx};
14724 }))
14725 return false;
14726 return Success(R, E);
14727 }
14728 case X86::BI__builtin_ia32_alignd128:
14729 case X86::BI__builtin_ia32_alignd256:
14730 case X86::BI__builtin_ia32_alignd512:
14731 case X86::BI__builtin_ia32_alignq128:
14732 case X86::BI__builtin_ia32_alignq256:
14733 case X86::BI__builtin_ia32_alignq512: {
14734 APValue R;
14735 unsigned NumElems = E->getType()->castAs<VectorType>()->getNumElements();
14736 if (!evalShuffleGeneric(Info, E, R,
14737 [NumElems](unsigned DstIdx, unsigned Shift) {
14738 unsigned Imm = Shift & 0xFF;
14739 unsigned EffectiveShift = Imm & (NumElems - 1);
14740 unsigned SourcePos = DstIdx + EffectiveShift;
14741 unsigned VecIdx = SourcePos < NumElems ? 1 : 0;
14742 unsigned ElemIdx = SourcePos & (NumElems - 1);
14743
14744 return std::pair<unsigned, int>{
14745 VecIdx, static_cast<int>(ElemIdx)};
14746 }))
14747 return false;
14748 return Success(R, E);
14749 }
14750 case X86::BI__builtin_ia32_permvarsi256:
14751 case X86::BI__builtin_ia32_permvarsf256:
14752 case X86::BI__builtin_ia32_permvardf512:
14753 case X86::BI__builtin_ia32_permvardi512:
14754 case X86::BI__builtin_ia32_permvarhi128: {
14755 APValue R;
14756 if (!evalShuffleGeneric(Info, E, R,
14757 [](unsigned DstIdx, unsigned ShuffleMask) {
14758 int Offset = ShuffleMask & 0x7;
14759 return std::pair<unsigned, int>{0, Offset};
14760 }))
14761 return false;
14762 return Success(R, E);
14763 }
14764 case X86::BI__builtin_ia32_permvarqi128:
14765 case X86::BI__builtin_ia32_permvarhi256:
14766 case X86::BI__builtin_ia32_permvarsi512:
14767 case X86::BI__builtin_ia32_permvarsf512: {
14768 APValue R;
14769 if (!evalShuffleGeneric(Info, E, R,
14770 [](unsigned DstIdx, unsigned ShuffleMask) {
14771 int Offset = ShuffleMask & 0xF;
14772 return std::pair<unsigned, int>{0, Offset};
14773 }))
14774 return false;
14775 return Success(R, E);
14776 }
14777 case X86::BI__builtin_ia32_permvardi256:
14778 case X86::BI__builtin_ia32_permvardf256: {
14779 APValue R;
14780 if (!evalShuffleGeneric(Info, E, R,
14781 [](unsigned DstIdx, unsigned ShuffleMask) {
14782 int Offset = ShuffleMask & 0x3;
14783 return std::pair<unsigned, int>{0, Offset};
14784 }))
14785 return false;
14786 return Success(R, E);
14787 }
14788 case X86::BI__builtin_ia32_permvarqi256:
14789 case X86::BI__builtin_ia32_permvarhi512: {
14790 APValue R;
14791 if (!evalShuffleGeneric(Info, E, R,
14792 [](unsigned DstIdx, unsigned ShuffleMask) {
14793 int Offset = ShuffleMask & 0x1F;
14794 return std::pair<unsigned, int>{0, Offset};
14795 }))
14796 return false;
14797 return Success(R, E);
14798 }
14799 case X86::BI__builtin_ia32_permvarqi512: {
14800 APValue R;
14801 if (!evalShuffleGeneric(Info, E, R,
14802 [](unsigned DstIdx, unsigned ShuffleMask) {
14803 int Offset = ShuffleMask & 0x3F;
14804 return std::pair<unsigned, int>{0, Offset};
14805 }))
14806 return false;
14807 return Success(R, E);
14808 }
14809 case X86::BI__builtin_ia32_vpermi2varq128:
14810 case X86::BI__builtin_ia32_vpermi2varpd128: {
14811 APValue R;
14812 if (!evalShuffleGeneric(Info, E, R,
14813 [](unsigned DstIdx, unsigned ShuffleMask) {
14814 int Offset = ShuffleMask & 0x1;
14815 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
14816 return std::pair<unsigned, int>{SrcIdx, Offset};
14817 }))
14818 return false;
14819 return Success(R, E);
14820 }
14821 case X86::BI__builtin_ia32_vpermi2vard128:
14822 case X86::BI__builtin_ia32_vpermi2varps128:
14823 case X86::BI__builtin_ia32_vpermi2varq256:
14824 case X86::BI__builtin_ia32_vpermi2varpd256: {
14825 APValue R;
14826 if (!evalShuffleGeneric(Info, E, R,
14827 [](unsigned DstIdx, unsigned ShuffleMask) {
14828 int Offset = ShuffleMask & 0x3;
14829 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
14830 return std::pair<unsigned, int>{SrcIdx, Offset};
14831 }))
14832 return false;
14833 return Success(R, E);
14834 }
14835 case X86::BI__builtin_ia32_vpermi2varhi128:
14836 case X86::BI__builtin_ia32_vpermi2vard256:
14837 case X86::BI__builtin_ia32_vpermi2varps256:
14838 case X86::BI__builtin_ia32_vpermi2varq512:
14839 case X86::BI__builtin_ia32_vpermi2varpd512: {
14840 APValue R;
14841 if (!evalShuffleGeneric(Info, E, R,
14842 [](unsigned DstIdx, unsigned ShuffleMask) {
14843 int Offset = ShuffleMask & 0x7;
14844 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
14845 return std::pair<unsigned, int>{SrcIdx, Offset};
14846 }))
14847 return false;
14848 return Success(R, E);
14849 }
14850 case X86::BI__builtin_ia32_vpermi2varqi128:
14851 case X86::BI__builtin_ia32_vpermi2varhi256:
14852 case X86::BI__builtin_ia32_vpermi2vard512:
14853 case X86::BI__builtin_ia32_vpermi2varps512: {
14854 APValue R;
14855 if (!evalShuffleGeneric(Info, E, R,
14856 [](unsigned DstIdx, unsigned ShuffleMask) {
14857 int Offset = ShuffleMask & 0xF;
14858 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
14859 return std::pair<unsigned, int>{SrcIdx, Offset};
14860 }))
14861 return false;
14862 return Success(R, E);
14863 }
14864 case X86::BI__builtin_ia32_vpermi2varqi256:
14865 case X86::BI__builtin_ia32_vpermi2varhi512: {
14866 APValue R;
14867 if (!evalShuffleGeneric(Info, E, R,
14868 [](unsigned DstIdx, unsigned ShuffleMask) {
14869 int Offset = ShuffleMask & 0x1F;
14870 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
14871 return std::pair<unsigned, int>{SrcIdx, Offset};
14872 }))
14873 return false;
14874 return Success(R, E);
14875 }
14876 case X86::BI__builtin_ia32_vpermi2varqi512: {
14877 APValue R;
14878 if (!evalShuffleGeneric(Info, E, R,
14879 [](unsigned DstIdx, unsigned ShuffleMask) {
14880 int Offset = ShuffleMask & 0x3F;
14881 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
14882 return std::pair<unsigned, int>{SrcIdx, Offset};
14883 }))
14884 return false;
14885 return Success(R, E);
14886 }
14887
14888 case clang::X86::BI__builtin_ia32_minps:
14889 case clang::X86::BI__builtin_ia32_minpd:
14890 case clang::X86::BI__builtin_ia32_minps256:
14891 case clang::X86::BI__builtin_ia32_minpd256:
14892 case clang::X86::BI__builtin_ia32_minps512:
14893 case clang::X86::BI__builtin_ia32_minpd512:
14894 case clang::X86::BI__builtin_ia32_minph128:
14895 case clang::X86::BI__builtin_ia32_minph256:
14896 case clang::X86::BI__builtin_ia32_minph512:
14897 return EvaluateFpBinOpExpr(
14898 [](const APFloat &A, const APFloat &B,
14899 std::optional<APSInt>) -> std::optional<APFloat> {
14900 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
14901 B.isInfinity() || B.isDenormal())
14902 return std::nullopt;
14903 if (A.isZero() && B.isZero())
14904 return B;
14905 return llvm::minimum(A, B);
14906 });
14907
14908 case clang::X86::BI__builtin_ia32_minss:
14909 case clang::X86::BI__builtin_ia32_minsd:
14910 return EvaluateFpBinOpExpr(
14911 [](const APFloat &A, const APFloat &B,
14912 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14913 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/true);
14914 },
14915 /*IsScalar=*/true);
14916
14917 case clang::X86::BI__builtin_ia32_minsd_round_mask:
14918 case clang::X86::BI__builtin_ia32_minss_round_mask:
14919 case clang::X86::BI__builtin_ia32_minsh_round_mask:
14920 case clang::X86::BI__builtin_ia32_maxsd_round_mask:
14921 case clang::X86::BI__builtin_ia32_maxss_round_mask:
14922 case clang::X86::BI__builtin_ia32_maxsh_round_mask: {
14923 bool IsMin = BuiltinOp == clang::X86::BI__builtin_ia32_minsd_round_mask ||
14924 BuiltinOp == clang::X86::BI__builtin_ia32_minss_round_mask ||
14925 BuiltinOp == clang::X86::BI__builtin_ia32_minsh_round_mask;
14926 return EvaluateScalarFpRoundMaskBinOp(
14927 [IsMin](const APFloat &A, const APFloat &B,
14928 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14929 return EvalScalarMinMaxFp(A, B, RoundingMode, IsMin);
14930 });
14931 }
14932
14933 case clang::X86::BI__builtin_ia32_maxps:
14934 case clang::X86::BI__builtin_ia32_maxpd:
14935 case clang::X86::BI__builtin_ia32_maxps256:
14936 case clang::X86::BI__builtin_ia32_maxpd256:
14937 case clang::X86::BI__builtin_ia32_maxps512:
14938 case clang::X86::BI__builtin_ia32_maxpd512:
14939 case clang::X86::BI__builtin_ia32_maxph128:
14940 case clang::X86::BI__builtin_ia32_maxph256:
14941 case clang::X86::BI__builtin_ia32_maxph512:
14942 return EvaluateFpBinOpExpr(
14943 [](const APFloat &A, const APFloat &B,
14944 std::optional<APSInt>) -> std::optional<APFloat> {
14945 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
14946 B.isInfinity() || B.isDenormal())
14947 return std::nullopt;
14948 if (A.isZero() && B.isZero())
14949 return B;
14950 return llvm::maximum(A, B);
14951 });
14952
14953 case clang::X86::BI__builtin_ia32_maxss:
14954 case clang::X86::BI__builtin_ia32_maxsd:
14955 return EvaluateFpBinOpExpr(
14956 [](const APFloat &A, const APFloat &B,
14957 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
14958 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/false);
14959 },
14960 /*IsScalar=*/true);
14961
14962 case clang::X86::BI__builtin_ia32_vcvtps2ph:
14963 case clang::X86::BI__builtin_ia32_vcvtps2ph256: {
14964 APValue SrcVec;
14965 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec))
14966 return false;
14967
14968 APSInt Imm;
14969 if (!EvaluateInteger(E->getArg(1), Imm, Info))
14970 return false;
14971
14972 const auto *SrcVTy = E->getArg(0)->getType()->castAs<VectorType>();
14973 unsigned SrcNumElems = SrcVTy->getNumElements();
14974 const auto *DstVTy = E->getType()->castAs<VectorType>();
14975 unsigned DstNumElems = DstVTy->getNumElements();
14976 QualType DstElemTy = DstVTy->getElementType();
14977
14978 const llvm::fltSemantics &HalfSem =
14979 Info.Ctx.getFloatTypeSemantics(Info.Ctx.HalfTy);
14980
14981 int ImmVal = Imm.getZExtValue();
14982 bool UseMXCSR = (ImmVal & 4) != 0;
14983 bool IsFPConstrained =
14984 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained();
14985
14986 llvm::RoundingMode RM;
14987 if (!UseMXCSR) {
14988 switch (ImmVal & 3) {
14989 case 0:
14990 RM = llvm::RoundingMode::NearestTiesToEven;
14991 break;
14992 case 1:
14993 RM = llvm::RoundingMode::TowardNegative;
14994 break;
14995 case 2:
14996 RM = llvm::RoundingMode::TowardPositive;
14997 break;
14998 case 3:
14999 RM = llvm::RoundingMode::TowardZero;
15000 break;
15001 default:
15002 llvm_unreachable("Invalid immediate rounding mode");
15003 }
15004 } else {
15005 RM = llvm::RoundingMode::NearestTiesToEven;
15006 }
15007
15008 SmallVector<APValue, 8> ResultElements;
15009 ResultElements.reserve(DstNumElems);
15010
15011 for (unsigned I = 0; I < SrcNumElems; ++I) {
15012 APFloat SrcVal = SrcVec.getVectorElt(I).getFloat();
15013
15014 bool LostInfo;
15015 APFloat::opStatus St = SrcVal.convert(HalfSem, RM, &LostInfo);
15016
15017 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
15018 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
15019 return false;
15020 }
15021
15022 APSInt DstInt(SrcVal.bitcastToAPInt(),
15024 ResultElements.push_back(APValue(DstInt));
15025 }
15026
15027 if (DstNumElems > SrcNumElems) {
15028 APSInt Zero = Info.Ctx.MakeIntValue(0, DstElemTy);
15029 for (unsigned I = SrcNumElems; I < DstNumElems; ++I) {
15030 ResultElements.push_back(APValue(Zero));
15031 }
15032 }
15033
15034 return Success(ResultElements, E);
15035 }
15036 case X86::BI__builtin_ia32_vperm2f128_pd256:
15037 case X86::BI__builtin_ia32_vperm2f128_ps256:
15038 case X86::BI__builtin_ia32_vperm2f128_si256:
15039 case X86::BI__builtin_ia32_permti256: {
15040 unsigned NumElements =
15041 E->getArg(0)->getType()->getAs<VectorType>()->getNumElements();
15042 unsigned PreservedBitsCnt = NumElements >> 2;
15043 APValue R;
15044 if (!evalShuffleGeneric(
15045 Info, E, R,
15046 [PreservedBitsCnt](unsigned DstIdx, unsigned ShuffleMask) {
15047 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
15048 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
15049
15050 if (ControlBits & 0b1000)
15051 return std::make_pair(0u, -1);
15052
15053 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
15054 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
15055 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
15056 (DstIdx & PreservedBitsMask);
15057 return std::make_pair(SrcVecIdx, SrcIdx);
15058 }))
15059 return false;
15060 return Success(R, E);
15061 }
15062 case X86::BI__builtin_ia32_vpdpwssd128:
15063 case X86::BI__builtin_ia32_vpdpwssd256:
15064 case X86::BI__builtin_ia32_vpdpwssd512:
15065 case X86::BI__builtin_ia32_vpdpbusd128:
15066 case X86::BI__builtin_ia32_vpdpbusd256:
15067 case X86::BI__builtin_ia32_vpdpbusd512:
15068 return EvalVectorDotProduct(false);
15069 case X86::BI__builtin_ia32_vpdpwssds128:
15070 case X86::BI__builtin_ia32_vpdpwssds256:
15071 case X86::BI__builtin_ia32_vpdpwssds512:
15072 case X86::BI__builtin_ia32_vpdpbusds128:
15073 case X86::BI__builtin_ia32_vpdpbusds256:
15074 case X86::BI__builtin_ia32_vpdpbusds512:
15075 return EvalVectorDotProduct(true);
15076 }
15077}
15078
15079bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
15080 APValue Source;
15081 QualType SourceVecType = E->getSrcExpr()->getType();
15082 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
15083 return false;
15084
15085 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
15086 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
15087
15088 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15089
15090 auto SourceLen = Source.getVectorLength();
15091 SmallVector<APValue, 4> ResultElements;
15092 ResultElements.reserve(SourceLen);
15093 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
15094 APValue Elt;
15095 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
15096 Source.getVectorElt(EltNum), Elt))
15097 return false;
15098 ResultElements.push_back(std::move(Elt));
15099 }
15100
15101 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
15102}
15103
15104static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
15105 QualType ElemType, APValue const &VecVal1,
15106 APValue const &VecVal2, unsigned EltNum,
15107 APValue &Result) {
15108 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
15109 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
15110
15111 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
15112 int64_t index = IndexVal.getExtValue();
15113 // The spec says that -1 should be treated as undef for optimizations,
15114 // but in constexpr we'd have to produce an APValue::Indeterminate,
15115 // which is prohibited from being a top-level constant value. Emit a
15116 // diagnostic instead.
15117 if (index == -1) {
15118 Info.FFDiag(
15119 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
15120 << EltNum;
15121 return false;
15122 }
15123
15124 if (index < 0 ||
15125 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
15126 llvm_unreachable("Out of bounds shuffle index");
15127
15128 if (index >= TotalElementsInInputVector1)
15129 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
15130 else
15131 Result = VecVal1.getVectorElt(index);
15132 return true;
15133}
15134
15135bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
15136 // FIXME: Unary shuffle with mask not currently supported.
15137 if (E->getNumSubExprs() == 2)
15138 return Error(E);
15139 APValue VecVal1;
15140 const Expr *Vec1 = E->getExpr(0);
15141 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
15142 return false;
15143 APValue VecVal2;
15144 const Expr *Vec2 = E->getExpr(1);
15145 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
15146 return false;
15147
15148 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
15149 QualType DestElTy = DestVecTy->getElementType();
15150
15151 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
15152
15153 SmallVector<APValue, 4> ResultElements;
15154 ResultElements.reserve(TotalElementsInOutputVector);
15155 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
15156 APValue Elt;
15157 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
15158 return false;
15159 ResultElements.push_back(std::move(Elt));
15160 }
15161
15162 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
15163}
15164
15165//===----------------------------------------------------------------------===//
15166// Matrix Evaluation
15167//===----------------------------------------------------------------------===//
15168
15169namespace {
15170class MatrixExprEvaluator : public ExprEvaluatorBase<MatrixExprEvaluator> {
15171 APValue &Result;
15172
15173public:
15174 MatrixExprEvaluator(EvalInfo &Info, APValue &Result)
15175 : ExprEvaluatorBaseTy(Info), Result(Result) {}
15176
15177 bool Success(ArrayRef<APValue> M, const Expr *E) {
15178 auto *CMTy = E->getType()->castAs<ConstantMatrixType>();
15179 assert(M.size() == CMTy->getNumElementsFlattened());
15180 // FIXME: remove this APValue copy.
15181 Result = APValue(M.data(), CMTy->getNumRows(), CMTy->getNumColumns());
15182 return true;
15183 }
15184 bool Success(const APValue &M, const Expr *E) {
15185 assert(M.isMatrix() && "expected matrix");
15186 Result = M;
15187 return true;
15188 }
15189
15190 bool VisitCastExpr(const CastExpr *E);
15191 bool VisitInitListExpr(const InitListExpr *E);
15192};
15193} // end anonymous namespace
15194
15195static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info) {
15196 assert(E->isPRValue() && E->getType()->isConstantMatrixType() &&
15197 "not a matrix prvalue");
15198 return MatrixExprEvaluator(Info, Result).Visit(E);
15199}
15200
15201bool MatrixExprEvaluator::VisitCastExpr(const CastExpr *E) {
15202 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
15203 unsigned NumRows = MT->getNumRows();
15204 unsigned NumCols = MT->getNumColumns();
15205 unsigned NElts = NumRows * NumCols;
15206 QualType EltTy = MT->getElementType();
15207 const Expr *SE = E->getSubExpr();
15208
15209 switch (E->getCastKind()) {
15210 case CK_HLSLAggregateSplatCast: {
15211 APValue Val;
15212 QualType ValTy;
15213
15214 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
15215 return false;
15216
15217 APValue CastedVal;
15218 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15219 if (!handleScalarCast(Info, FPO, E, ValTy, EltTy, Val, CastedVal))
15220 return false;
15221
15222 SmallVector<APValue, 16> SplatEls(NElts, CastedVal);
15223 return Success(SplatEls, E);
15224 }
15225 case CK_HLSLElementwiseCast: {
15226 SmallVector<APValue> SrcVals;
15227 SmallVector<QualType> SrcTypes;
15228
15229 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
15230 return false;
15231
15232 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15233 SmallVector<QualType, 16> DestTypes(NElts, EltTy);
15234 SmallVector<APValue, 16> ResultEls(NElts);
15235 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
15236 ResultEls))
15237 return false;
15238 return Success(ResultEls, E);
15239 }
15240 default:
15241 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15242 }
15243}
15244
15245bool MatrixExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
15246 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
15247 QualType EltTy = MT->getElementType();
15248
15249 assert(E->getNumInits() == MT->getNumElementsFlattened() &&
15250 "Expected number of elements in initializer list to match the number "
15251 "of matrix elements");
15252
15253 SmallVector<APValue, 16> Elements;
15254 Elements.reserve(MT->getNumElementsFlattened());
15255
15256 // The following loop assumes the elements of the matrix InitListExpr are in
15257 // row-major order, which matches the row-major ordering assumption of the
15258 // matrix APValue.
15259 for (unsigned I = 0, N = MT->getNumElementsFlattened(); I < N; ++I) {
15260 if (EltTy->isIntegerType()) {
15261 llvm::APSInt IntVal;
15262 if (!EvaluateInteger(E->getInit(I), IntVal, Info))
15263 return false;
15264 Elements.push_back(APValue(IntVal));
15265 } else {
15266 llvm::APFloat FloatVal(0.0);
15267 if (!EvaluateFloat(E->getInit(I), FloatVal, Info))
15268 return false;
15269 Elements.push_back(APValue(FloatVal));
15270 }
15271 }
15272
15273 return Success(Elements, E);
15274}
15275
15276//===----------------------------------------------------------------------===//
15277// Array Evaluation
15278//===----------------------------------------------------------------------===//
15279
15280namespace {
15281 class ArrayExprEvaluator
15282 : public ExprEvaluatorBase<ArrayExprEvaluator> {
15283 const LValue &This;
15284 APValue &Result;
15285 public:
15286
15287 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
15288 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
15289
15290 bool Success(const APValue &V, const Expr *E) {
15291 assert(V.isArray() && "expected array");
15292 Result = V;
15293 return true;
15294 }
15295
15296 bool ZeroInitialization(const Expr *E) {
15297 const ConstantArrayType *CAT =
15298 Info.Ctx.getAsConstantArrayType(E->getType());
15299 if (!CAT) {
15300 if (E->getType()->isIncompleteArrayType()) {
15301 // We can be asked to zero-initialize a flexible array member; this
15302 // is represented as an ImplicitValueInitExpr of incomplete array
15303 // type. In this case, the array has zero elements.
15304 Result = APValue(APValue::UninitArray(), 0, 0);
15305 return true;
15306 }
15307 // FIXME: We could handle VLAs here.
15308 return Error(E);
15309 }
15310
15311 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
15312 if (!Result.hasArrayFiller())
15313 return true;
15314
15315 // Zero-initialize all elements.
15316 LValue Subobject = This;
15317 Subobject.addArray(Info, E, CAT);
15318 ImplicitValueInitExpr VIE(CAT->getElementType());
15319 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
15320 }
15321
15322 bool VisitCallExpr(const CallExpr *E) {
15323 return handleCallExpr(E, Result, &This);
15324 }
15325 bool VisitCastExpr(const CastExpr *E);
15326 bool VisitInitListExpr(const InitListExpr *E,
15327 QualType AllocType = QualType());
15328 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
15329 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
15330 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
15331 const LValue &Subobject,
15332 APValue *Value, QualType Type);
15333 bool VisitStringLiteral(const StringLiteral *E,
15334 QualType AllocType = QualType()) {
15335 expandStringLiteral(Info, E, Result, AllocType);
15336 return true;
15337 }
15338 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
15339 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
15340 ArrayRef<Expr *> Args,
15341 const Expr *ArrayFiller,
15342 QualType AllocType = QualType());
15343 bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E);
15344 };
15345} // end anonymous namespace
15346
15347static bool EvaluateArray(const Expr *E, const LValue &This,
15348 APValue &Result, EvalInfo &Info) {
15349 assert(!E->isValueDependent());
15350 assert(E->isPRValue() && E->getType()->isArrayType() &&
15351 "not an array prvalue");
15352 return ArrayExprEvaluator(Info, This, Result).Visit(E);
15353}
15354
15355static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
15356 APValue &Result, const InitListExpr *ILE,
15357 QualType AllocType) {
15358 assert(!ILE->isValueDependent());
15359 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
15360 "not an array prvalue");
15361 return ArrayExprEvaluator(Info, This, Result)
15362 .VisitInitListExpr(ILE, AllocType);
15363}
15364
15365static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
15366 APValue &Result,
15367 const CXXConstructExpr *CCE,
15368 QualType AllocType) {
15369 assert(!CCE->isValueDependent());
15370 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
15371 "not an array prvalue");
15372 return ArrayExprEvaluator(Info, This, Result)
15373 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
15374}
15375
15376// Return true iff the given array filler may depend on the element index.
15377static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
15378 // For now, just allow non-class value-initialization and initialization
15379 // lists comprised of them.
15380 if (isa<ImplicitValueInitExpr>(FillerExpr))
15381 return false;
15382 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
15383 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
15384 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
15385 return true;
15386 }
15387
15388 if (ILE->hasArrayFiller() &&
15389 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
15390 return true;
15391
15392 return false;
15393 }
15394 return true;
15395}
15396
15397bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
15398 const Expr *SE = E->getSubExpr();
15399
15400 switch (E->getCastKind()) {
15401 default:
15402 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15403 case CK_HLSLAggregateSplatCast: {
15404 APValue Val;
15405 QualType ValTy;
15406
15407 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
15408 return false;
15409
15410 unsigned NEls = elementwiseSize(Info, E->getType());
15411
15412 SmallVector<APValue> SplatEls(NEls, Val);
15413 SmallVector<QualType> SplatType(NEls, ValTy);
15414
15415 // cast the elements
15416 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15417 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
15418 SplatType))
15419 return false;
15420
15421 return true;
15422 }
15423 case CK_HLSLElementwiseCast: {
15424 SmallVector<APValue> SrcEls;
15425 SmallVector<QualType> SrcTypes;
15426
15427 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
15428 return false;
15429
15430 // cast the elements
15431 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15432 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
15433 SrcTypes))
15434 return false;
15435 return true;
15436 }
15437 }
15438}
15439
15440bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
15441 QualType AllocType) {
15442 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15443 AllocType.isNull() ? E->getType() : AllocType);
15444 if (!CAT)
15445 return Error(E);
15446
15447 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
15448 // an appropriately-typed string literal enclosed in braces.
15449 if (E->isStringLiteralInit()) {
15450 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
15451 // FIXME: Support ObjCEncodeExpr here once we support it in
15452 // ArrayExprEvaluator generally.
15453 if (!SL)
15454 return Error(E);
15455 return VisitStringLiteral(SL, AllocType);
15456 }
15457 // Any other transparent list init will need proper handling of the
15458 // AllocType; we can't just recurse to the inner initializer.
15459 assert(!E->isTransparent() &&
15460 "transparent array list initialization is not string literal init?");
15461
15462 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
15463 AllocType);
15464}
15465
15466bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
15467 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
15468 QualType AllocType) {
15469 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15470 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
15471
15472 bool Success = true;
15473
15474 unsigned NumEltsToInit = Args.size();
15475 unsigned NumElts = CAT->getZExtSize();
15476
15477 // If the initializer might depend on the array index, run it for each
15478 // array element.
15479 if (NumEltsToInit != NumElts &&
15480 MaybeElementDependentArrayFiller(ArrayFiller)) {
15481 NumEltsToInit = NumElts;
15482 } else {
15483 // Add additional elements represented by EmbedExpr.
15484 for (auto *Init : Args) {
15485 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
15486 NumEltsToInit += EmbedS->getDataElementCount() - 1;
15487 }
15488 // If we have extra elements in the list, they will be discarded.
15489 if (NumEltsToInit > NumElts)
15490 NumEltsToInit = NumElts;
15491 // If we're overwriting memory which already has an object, make sure we
15492 // don't reduce the number of non-filler elements. (It's possible to
15493 // optimize this in some cases, but the logic gets really complicated.)
15494 if (Result.hasValue() && NumEltsToInit < Result.getArrayInitializedElts())
15495 NumEltsToInit = Result.getArrayInitializedElts();
15496 }
15497
15498 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
15499 << NumEltsToInit << ".\n");
15500
15501 if (!Result.hasValue()) {
15502 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15503 } else if (Result.getArrayInitializedElts() != NumEltsToInit) {
15504 // Number of inititalized elts changed. Recreate the APValue, and copy over
15505 // the relevant elements. (This is essentially just fixing the internal
15506 // representation of the value, because it's tied to the number of
15507 // non-filler elements.)
15508 //
15509 // This should be hit rarely, but there are some edge cases:
15510 //
15511 // - The array could be zero-initialized.
15512 // - There could be a DesignatedInitListExpr.
15513 // - operator new[] can be used to start the lifetime early.
15514 APValue NewResult = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15515 // First copy existing elements.
15516 unsigned NumOldElts = Result.getArrayInitializedElts();
15517 for (unsigned I = 0; I < NumOldElts; ++I) {
15518 NewResult.getArrayInitializedElt(I) =
15519 std::move(Result.getArrayInitializedElt(I));
15520 }
15521 // Then copy the array filler over the remaining elements.
15522 for (unsigned I = Result.getArrayInitializedElts(); I < NumEltsToInit; ++I)
15524 if (NewResult.hasArrayFiller() && Result.hasArrayFiller())
15525 NewResult.getArrayFiller() = Result.getArrayFiller();
15526 Result = std::move(NewResult);
15527 }
15528
15529 LValue Subobject = This;
15530 Subobject.addArray(Info, ExprToVisit, CAT);
15531 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
15532 if (Init->isValueDependent())
15533 return EvaluateDependentExpr(Init, Info);
15534
15535 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
15536 // aren't supposed to be modified.
15537 if (isa<NoInitExpr>(Init))
15538 return true;
15539
15540 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
15541 Subobject, Init) ||
15542 !HandleLValueArrayAdjustment(Info, Init, Subobject,
15543 CAT->getElementType(), 1)) {
15544 if (!Info.noteFailure())
15545 return false;
15546 Success = false;
15547 }
15548 return true;
15549 };
15550 unsigned ArrayIndex = 0;
15551 QualType DestTy = CAT->getElementType();
15552 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
15553 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
15554 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
15555 if (ArrayIndex >= NumEltsToInit)
15556 break;
15557 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
15558 StringLiteral *SL = EmbedS->getDataStringLiteral();
15559 for (unsigned I = EmbedS->getStartingElementPos(),
15560 N = EmbedS->getDataElementCount();
15561 I != EmbedS->getStartingElementPos() + N; ++I) {
15562 Value = SL->getCodeUnit(I);
15563 if (DestTy->isIntegerType()) {
15564 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
15565 } else {
15566 assert(DestTy->isFloatingType() && "unexpected type");
15567 const FPOptions FPO =
15568 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15569 APFloat FValue(0.0);
15570 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
15571 DestTy, FValue))
15572 return false;
15573 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
15574 }
15575 ArrayIndex++;
15576 }
15577 } else {
15578 if (!Eval(Init, ArrayIndex))
15579 return false;
15580 ++ArrayIndex;
15581 }
15582 }
15583
15584 if (!Result.hasArrayFiller())
15585 return Success;
15586
15587 // If we get here, we have a trivial filler, which we can just evaluate
15588 // once and splat over the rest of the array elements.
15589 assert(ArrayFiller && "no array filler for incomplete init list");
15590 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
15591 ArrayFiller) &&
15592 Success;
15593}
15594
15595bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
15596 LValue CommonLV;
15597 if (E->getCommonExpr() &&
15598 !Evaluate(Info.CurrentCall->createTemporary(
15599 E->getCommonExpr(),
15600 getStorageType(Info.Ctx, E->getCommonExpr()),
15601 ScopeKind::FullExpression, CommonLV),
15602 Info, E->getCommonExpr()->getSourceExpr()))
15603 return false;
15604
15606
15607 uint64_t Elements = CAT->getZExtSize();
15608 Result = APValue(APValue::UninitArray(), Elements, Elements);
15609
15610 LValue Subobject = This;
15611 Subobject.addArray(Info, E, CAT);
15612
15613 bool Success = true;
15614 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
15615 // C++ [class.temporary]/5
15616 // There are four contexts in which temporaries are destroyed at a different
15617 // point than the end of the full-expression. [...] The second context is
15618 // when a copy constructor is called to copy an element of an array while
15619 // the entire array is copied [...]. In either case, if the constructor has
15620 // one or more default arguments, the destruction of every temporary created
15621 // in a default argument is sequenced before the construction of the next
15622 // array element, if any.
15623 FullExpressionRAII Scope(Info);
15624
15625 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
15626 Info, Subobject, E->getSubExpr()) ||
15627 !HandleLValueArrayAdjustment(Info, E, Subobject,
15628 CAT->getElementType(), 1)) {
15629 if (!Info.noteFailure())
15630 return false;
15631 Success = false;
15632 }
15633
15634 // Make sure we run the destructors too.
15635 Scope.destroy();
15636 }
15637
15638 return Success;
15639}
15640
15641bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
15642 return VisitCXXConstructExpr(E, This, &Result, E->getType());
15643}
15644
15645bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
15646 const LValue &Subobject,
15647 APValue *Value,
15648 QualType Type) {
15649 bool HadZeroInit = Value->hasValue();
15650
15651 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
15652 unsigned FinalSize = CAT->getZExtSize();
15653
15654 // Preserve the array filler if we had prior zero-initialization.
15655 APValue Filler =
15656 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
15657 : APValue();
15658
15659 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
15660 if (FinalSize == 0)
15661 return true;
15662
15663 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
15664 Info, E->getExprLoc(), E->getConstructor(),
15666 LValue ArrayElt = Subobject;
15667 ArrayElt.addArray(Info, E, CAT);
15668 // We do the whole initialization in two passes, first for just one element,
15669 // then for the whole array. It's possible we may find out we can't do const
15670 // init in the first pass, in which case we avoid allocating a potentially
15671 // large array. We don't do more passes because expanding array requires
15672 // copying the data, which is wasteful.
15673 for (const unsigned N : {1u, FinalSize}) {
15674 unsigned OldElts = Value->getArrayInitializedElts();
15675 if (OldElts == N)
15676 break;
15677
15678 // Expand the array to appropriate size.
15679 APValue NewValue(APValue::UninitArray(), N, FinalSize);
15680 for (unsigned I = 0; I < OldElts; ++I)
15681 NewValue.getArrayInitializedElt(I).swap(
15682 Value->getArrayInitializedElt(I));
15683 Value->swap(NewValue);
15684
15685 if (HadZeroInit)
15686 for (unsigned I = OldElts; I < N; ++I)
15687 Value->getArrayInitializedElt(I) = Filler;
15688
15689 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
15690 // If we have a trivial constructor, only evaluate it once and copy
15691 // the result into all the array elements.
15692 APValue &FirstResult = Value->getArrayInitializedElt(0);
15693 for (unsigned I = OldElts; I < FinalSize; ++I)
15694 Value->getArrayInitializedElt(I) = FirstResult;
15695 } else {
15696 for (unsigned I = OldElts; I < N; ++I) {
15697 if (!VisitCXXConstructExpr(E, ArrayElt,
15698 &Value->getArrayInitializedElt(I),
15699 CAT->getElementType()) ||
15700 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
15701 CAT->getElementType(), 1))
15702 return false;
15703 // When checking for const initilization any diagnostic is considered
15704 // an error.
15705 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
15706 !Info.keepEvaluatingAfterFailure())
15707 return false;
15708 }
15709 }
15710 }
15711
15712 return true;
15713 }
15714
15715 if (!Type->isRecordType())
15716 return Error(E);
15717
15718 return RecordExprEvaluator(Info, Subobject, *Value)
15719 .VisitCXXConstructExpr(E, Type);
15720}
15721
15722bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
15723 const CXXParenListInitExpr *E) {
15724 assert(E->getType()->isConstantArrayType() &&
15725 "Expression result is not a constant array type");
15726
15727 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
15728 E->getArrayFiller());
15729}
15730
15731bool ArrayExprEvaluator::VisitDesignatedInitUpdateExpr(
15732 const DesignatedInitUpdateExpr *E) {
15733 if (!Visit(E->getBase()))
15734 return false;
15735 return Visit(E->getUpdater());
15736}
15737
15738//===----------------------------------------------------------------------===//
15739// Integer Evaluation
15740//
15741// As a GNU extension, we support casting pointers to sufficiently-wide integer
15742// types and back in constant folding. Integer values are thus represented
15743// either as an integer-valued APValue, or as an lvalue-valued APValue.
15744//===----------------------------------------------------------------------===//
15745
15746namespace {
15747class IntExprEvaluator
15748 : public ExprEvaluatorBase<IntExprEvaluator> {
15749 APValue &Result;
15750public:
15751 IntExprEvaluator(EvalInfo &info, APValue &result)
15752 : ExprEvaluatorBaseTy(info), Result(result) {}
15753
15754 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
15755 assert(E->getType()->isIntegralOrEnumerationType() &&
15756 "Invalid evaluation result.");
15757 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
15758 "Invalid evaluation result.");
15759 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15760 "Invalid evaluation result.");
15761 Result = APValue(SI);
15762 return true;
15763 }
15764 bool Success(const llvm::APSInt &SI, const Expr *E) {
15765 return Success(SI, E, Result);
15766 }
15767
15768 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
15769 assert(E->getType()->isIntegralOrEnumerationType() &&
15770 "Invalid evaluation result.");
15771 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15772 "Invalid evaluation result.");
15773 Result = APValue(APSInt(I));
15774 Result.getInt().setIsUnsigned(
15776 return true;
15777 }
15778 bool Success(const llvm::APInt &I, const Expr *E) {
15779 return Success(I, E, Result);
15780 }
15781
15782 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
15783 assert(E->getType()->isIntegralOrEnumerationType() &&
15784 "Invalid evaluation result.");
15785 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
15786 return true;
15787 }
15788 bool Success(uint64_t Value, const Expr *E) {
15789 return Success(Value, E, Result);
15790 }
15791
15792 bool Success(CharUnits Size, const Expr *E) {
15793 return Success(Size.getQuantity(), E);
15794 }
15795
15796 bool Success(const APValue &V, const Expr *E) {
15797 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
15798 // pointer allow further evaluation of the value.
15799 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
15800 V.allowConstexprUnknown()) {
15801 Result = V;
15802 return true;
15803 }
15804 return Success(V.getInt(), E);
15805 }
15806
15807 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
15808
15809 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
15810 const CallExpr *);
15811
15812 //===--------------------------------------------------------------------===//
15813 // Visitor Methods
15814 //===--------------------------------------------------------------------===//
15815
15816 bool VisitIntegerLiteral(const IntegerLiteral *E) {
15817 return Success(E->getValue(), E);
15818 }
15819 bool VisitCharacterLiteral(const CharacterLiteral *E) {
15820 return Success(E->getValue(), E);
15821 }
15822
15823 bool CheckReferencedDecl(const Expr *E, const Decl *D);
15824 bool VisitDeclRefExpr(const DeclRefExpr *E) {
15825 if (CheckReferencedDecl(E, E->getDecl()))
15826 return true;
15827
15828 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
15829 }
15830 bool VisitMemberExpr(const MemberExpr *E) {
15831 if (CheckReferencedDecl(E, E->getMemberDecl())) {
15832 VisitIgnoredBaseExpression(E->getBase());
15833 return true;
15834 }
15835
15836 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
15837 }
15838
15839 bool VisitCallExpr(const CallExpr *E);
15840 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
15841 bool VisitBinaryOperator(const BinaryOperator *E);
15842 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
15843 bool VisitUnaryOperator(const UnaryOperator *E);
15844
15845 bool VisitCastExpr(const CastExpr* E);
15846 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
15847
15848 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
15849 return Success(E->getValue(), E);
15850 }
15851
15852 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
15853 return Success(E->getValue(), E);
15854 }
15855
15856 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
15857 if (Info.ArrayInitIndex == uint64_t(-1)) {
15858 // We were asked to evaluate this subexpression independent of the
15859 // enclosing ArrayInitLoopExpr. We can't do that.
15860 Info.FFDiag(E);
15861 return false;
15862 }
15863 return Success(Info.ArrayInitIndex, E);
15864 }
15865
15866 // Note, GNU defines __null as an integer, not a pointer.
15867 bool VisitGNUNullExpr(const GNUNullExpr *E) {
15868 return ZeroInitialization(E);
15869 }
15870
15871 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
15872 if (E->isStoredAsBoolean())
15873 return Success(E->getBoolValue(), E);
15874 if (E->getAPValue().isAbsent())
15875 return false;
15876 assert(E->getAPValue().isInt() && "APValue type not supported");
15877 return Success(E->getAPValue().getInt(), E);
15878 }
15879
15880 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
15881 return Success(E->getValue(), E);
15882 }
15883
15884 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
15885 return Success(E->getValue(), E);
15886 }
15887
15888 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
15889 // This should not be evaluated during constant expr evaluation, as it
15890 // should always be in an unevaluated context (the args list of a 'gang' or
15891 // 'tile' clause).
15892 return Error(E);
15893 }
15894
15895 bool VisitUnaryReal(const UnaryOperator *E);
15896 bool VisitUnaryImag(const UnaryOperator *E);
15897
15898 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
15899 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
15900 bool VisitSourceLocExpr(const SourceLocExpr *E);
15901 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
15902 bool VisitRequiresExpr(const RequiresExpr *E);
15903 // FIXME: Missing: array subscript of vector, member of vector
15904};
15905
15906class FixedPointExprEvaluator
15907 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
15908 APValue &Result;
15909
15910 public:
15911 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
15912 : ExprEvaluatorBaseTy(info), Result(result) {}
15913
15914 bool Success(const llvm::APInt &I, const Expr *E) {
15915 return Success(
15916 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15917 }
15918
15919 bool Success(uint64_t Value, const Expr *E) {
15920 return Success(
15921 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
15922 }
15923
15924 bool Success(const APValue &V, const Expr *E) {
15925 return Success(V.getFixedPoint(), E);
15926 }
15927
15928 bool Success(const APFixedPoint &V, const Expr *E) {
15929 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
15930 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15931 "Invalid evaluation result.");
15932 Result = APValue(V);
15933 return true;
15934 }
15935
15936 bool ZeroInitialization(const Expr *E) {
15937 return Success(0, E);
15938 }
15939
15940 //===--------------------------------------------------------------------===//
15941 // Visitor Methods
15942 //===--------------------------------------------------------------------===//
15943
15944 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
15945 return Success(E->getValue(), E);
15946 }
15947
15948 bool VisitCastExpr(const CastExpr *E);
15949 bool VisitUnaryOperator(const UnaryOperator *E);
15950 bool VisitBinaryOperator(const BinaryOperator *E);
15951};
15952} // end anonymous namespace
15953
15954/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
15955/// produce either the integer value or a pointer.
15956///
15957/// GCC has a heinous extension which folds casts between pointer types and
15958/// pointer-sized integral types. We support this by allowing the evaluation of
15959/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
15960/// Some simple arithmetic on such values is supported (they are treated much
15961/// like char*).
15963 EvalInfo &Info) {
15964 assert(!E->isValueDependent());
15965 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
15966 return IntExprEvaluator(Info, Result).Visit(E);
15967}
15968
15969static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
15970 assert(!E->isValueDependent());
15971 APValue Val;
15972 if (!EvaluateIntegerOrLValue(E, Val, Info))
15973 return false;
15974 if (!Val.isInt()) {
15975 // FIXME: It would be better to produce the diagnostic for casting
15976 // a pointer to an integer.
15977 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15978 return false;
15979 }
15980 Result = Val.getInt();
15981 return true;
15982}
15983
15984bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
15986 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
15987 return Success(Evaluated, E);
15988}
15989
15990static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
15991 EvalInfo &Info) {
15992 assert(!E->isValueDependent());
15993 if (E->getType()->isFixedPointType()) {
15994 APValue Val;
15995 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
15996 return false;
15997 if (!Val.isFixedPoint())
15998 return false;
15999
16000 Result = Val.getFixedPoint();
16001 return true;
16002 }
16003 return false;
16004}
16005
16006static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
16007 EvalInfo &Info) {
16008 assert(!E->isValueDependent());
16009 if (E->getType()->isIntegerType()) {
16010 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
16011 APSInt Val;
16012 if (!EvaluateInteger(E, Val, Info))
16013 return false;
16014 Result = APFixedPoint(Val, FXSema);
16015 return true;
16016 } else if (E->getType()->isFixedPointType()) {
16017 return EvaluateFixedPoint(E, Result, Info);
16018 }
16019 return false;
16020}
16021
16022/// Check whether the given declaration can be directly converted to an integral
16023/// rvalue. If not, no diagnostic is produced; there are other things we can
16024/// try.
16025bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
16026 // Enums are integer constant exprs.
16027 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
16028 // Check for signedness/width mismatches between E type and ECD value.
16029 bool SameSign = (ECD->getInitVal().isSigned()
16031 bool SameWidth = (ECD->getInitVal().getBitWidth()
16032 == Info.Ctx.getIntWidth(E->getType()));
16033 if (SameSign && SameWidth)
16034 return Success(ECD->getInitVal(), E);
16035 else {
16036 // Get rid of mismatch (otherwise Success assertions will fail)
16037 // by computing a new value matching the type of E.
16038 llvm::APSInt Val = ECD->getInitVal();
16039 if (!SameSign)
16040 Val.setIsSigned(!ECD->getInitVal().isSigned());
16041 if (!SameWidth)
16042 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
16043 return Success(Val, E);
16044 }
16045 }
16046 return false;
16047}
16048
16049/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
16050/// as GCC.
16052 const LangOptions &LangOpts) {
16053 assert(!T->isDependentType() && "unexpected dependent type");
16054
16055 QualType CanTy = T.getCanonicalType();
16056
16057 switch (CanTy->getTypeClass()) {
16058#define TYPE(ID, BASE)
16059#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
16060#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
16061#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
16062#include "clang/AST/TypeNodes.inc"
16063 case Type::Auto:
16064 case Type::DeducedTemplateSpecialization:
16065 llvm_unreachable("unexpected non-canonical or dependent type");
16066
16067 case Type::Builtin:
16068 switch (cast<BuiltinType>(CanTy)->getKind()) {
16069#define BUILTIN_TYPE(ID, SINGLETON_ID)
16070#define SIGNED_TYPE(ID, SINGLETON_ID) \
16071 case BuiltinType::ID: return GCCTypeClass::Integer;
16072#define FLOATING_TYPE(ID, SINGLETON_ID) \
16073 case BuiltinType::ID: return GCCTypeClass::RealFloat;
16074#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
16075 case BuiltinType::ID: break;
16076#include "clang/AST/BuiltinTypes.def"
16077 case BuiltinType::Void:
16078 return GCCTypeClass::Void;
16079
16080 case BuiltinType::Bool:
16081 return GCCTypeClass::Bool;
16082
16083 case BuiltinType::Char_U:
16084 case BuiltinType::UChar:
16085 case BuiltinType::WChar_U:
16086 case BuiltinType::Char8:
16087 case BuiltinType::Char16:
16088 case BuiltinType::Char32:
16089 case BuiltinType::UShort:
16090 case BuiltinType::UInt:
16091 case BuiltinType::ULong:
16092 case BuiltinType::ULongLong:
16093 case BuiltinType::UInt128:
16094 return GCCTypeClass::Integer;
16095
16096 case BuiltinType::UShortAccum:
16097 case BuiltinType::UAccum:
16098 case BuiltinType::ULongAccum:
16099 case BuiltinType::UShortFract:
16100 case BuiltinType::UFract:
16101 case BuiltinType::ULongFract:
16102 case BuiltinType::SatUShortAccum:
16103 case BuiltinType::SatUAccum:
16104 case BuiltinType::SatULongAccum:
16105 case BuiltinType::SatUShortFract:
16106 case BuiltinType::SatUFract:
16107 case BuiltinType::SatULongFract:
16108 return GCCTypeClass::None;
16109
16110 case BuiltinType::NullPtr:
16111
16112 case BuiltinType::ObjCId:
16113 case BuiltinType::ObjCClass:
16114 case BuiltinType::ObjCSel:
16115#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16116 case BuiltinType::Id:
16117#include "clang/Basic/OpenCLImageTypes.def"
16118#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16119 case BuiltinType::Id:
16120#include "clang/Basic/OpenCLExtensionTypes.def"
16121 case BuiltinType::OCLSampler:
16122 case BuiltinType::OCLEvent:
16123 case BuiltinType::OCLClkEvent:
16124 case BuiltinType::OCLQueue:
16125 case BuiltinType::OCLReserveID:
16126#define SVE_TYPE(Name, Id, SingletonId) \
16127 case BuiltinType::Id:
16128#include "clang/Basic/AArch64ACLETypes.def"
16129#define PPC_VECTOR_TYPE(Name, Id, Size) \
16130 case BuiltinType::Id:
16131#include "clang/Basic/PPCTypes.def"
16132#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16133#include "clang/Basic/RISCVVTypes.def"
16134#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16135#include "clang/Basic/WebAssemblyReferenceTypes.def"
16136#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
16137#include "clang/Basic/AMDGPUTypes.def"
16138#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16139#include "clang/Basic/HLSLIntangibleTypes.def"
16140 return GCCTypeClass::None;
16141
16142 case BuiltinType::Dependent:
16143 llvm_unreachable("unexpected dependent type");
16144 };
16145 llvm_unreachable("unexpected placeholder type");
16146
16147 case Type::Enum:
16148 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
16149
16150 case Type::Pointer:
16151 case Type::ConstantArray:
16152 case Type::VariableArray:
16153 case Type::IncompleteArray:
16154 case Type::FunctionNoProto:
16155 case Type::FunctionProto:
16156 case Type::ArrayParameter:
16157 return GCCTypeClass::Pointer;
16158
16159 case Type::MemberPointer:
16160 return CanTy->isMemberDataPointerType()
16163
16164 case Type::Complex:
16165 return GCCTypeClass::Complex;
16166
16167 case Type::Record:
16168 return CanTy->isUnionType() ? GCCTypeClass::Union
16170
16171 case Type::Atomic:
16172 // GCC classifies _Atomic T the same as T.
16174 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
16175
16176 case Type::Vector:
16177 case Type::ExtVector:
16178 return GCCTypeClass::Vector;
16179
16180 case Type::BlockPointer:
16181 case Type::ConstantMatrix:
16182 case Type::ObjCObject:
16183 case Type::ObjCInterface:
16184 case Type::ObjCObjectPointer:
16185 case Type::Pipe:
16186 case Type::HLSLAttributedResource:
16187 case Type::HLSLInlineSpirv:
16188 case Type::OverflowBehavior:
16189 // Classify all other types that don't fit into the regular
16190 // classification the same way.
16191 return GCCTypeClass::None;
16192
16193 case Type::BitInt:
16194 return GCCTypeClass::BitInt;
16195
16196 case Type::LValueReference:
16197 case Type::RValueReference:
16198 llvm_unreachable("invalid type for expression");
16199 }
16200
16201 llvm_unreachable("unexpected type class");
16202}
16203
16204/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
16205/// as GCC.
16206static GCCTypeClass
16208 // If no argument was supplied, default to None. This isn't
16209 // ideal, however it is what gcc does.
16210 if (E->getNumArgs() == 0)
16211 return GCCTypeClass::None;
16212
16213 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
16214 // being an ICE, but still folds it to a constant using the type of the first
16215 // argument.
16216 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
16217}
16218
16219/// EvaluateBuiltinConstantPForLValue - Determine the result of
16220/// __builtin_constant_p when applied to the given pointer.
16221///
16222/// A pointer is only "constant" if it is null (or a pointer cast to integer)
16223/// or it points to the first character of a string literal.
16226 if (Base.isNull()) {
16227 // A null base is acceptable.
16228 return true;
16229 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
16230 if (!isa<StringLiteral>(E))
16231 return false;
16232 return LV.getLValueOffset().isZero();
16233 } else if (Base.is<TypeInfoLValue>()) {
16234 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
16235 // evaluate to true.
16236 return true;
16237 } else {
16238 // Any other base is not constant enough for GCC.
16239 return false;
16240 }
16241}
16242
16243/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
16244/// GCC as we can manage.
16245static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
16246 // This evaluation is not permitted to have side-effects, so evaluate it in
16247 // a speculative evaluation context.
16248 SpeculativeEvaluationRAII SpeculativeEval(Info);
16249
16250 // Constant-folding is always enabled for the operand of __builtin_constant_p
16251 // (even when the enclosing evaluation context otherwise requires a strict
16252 // language-specific constant expression).
16253 FoldConstant Fold(Info, true);
16254
16255 QualType ArgType = Arg->getType();
16256
16257 // __builtin_constant_p always has one operand. The rules which gcc follows
16258 // are not precisely documented, but are as follows:
16259 //
16260 // - If the operand is of integral, floating, complex or enumeration type,
16261 // and can be folded to a known value of that type, it returns 1.
16262 // - If the operand can be folded to a pointer to the first character
16263 // of a string literal (or such a pointer cast to an integral type)
16264 // or to a null pointer or an integer cast to a pointer, it returns 1.
16265 //
16266 // Otherwise, it returns 0.
16267 //
16268 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
16269 // its support for this did not work prior to GCC 9 and is not yet well
16270 // understood.
16271 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
16272 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
16273 ArgType->isNullPtrType()) {
16274 APValue V;
16275 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
16276 Fold.keepDiagnostics();
16277 return false;
16278 }
16279
16280 // For a pointer (possibly cast to integer), there are special rules.
16281 if (V.getKind() == APValue::LValue)
16283
16284 // Otherwise, any constant value is good enough.
16285 return V.hasValue();
16286 }
16287
16288 // Anything else isn't considered to be sufficiently constant.
16289 return false;
16290}
16291
16292/// Retrieves the "underlying object type" of the given expression,
16293/// as used by __builtin_object_size.
16295 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
16296 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
16297 return VD->getType();
16298 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
16300 return E->getType();
16301 } else if (B.is<TypeInfoLValue>()) {
16302 return B.getTypeInfoType();
16303 } else if (B.is<DynamicAllocLValue>()) {
16304 return B.getDynamicAllocType();
16305 }
16306
16307 return QualType();
16308}
16309
16310/// A more selective version of E->IgnoreParenCasts for
16311/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
16312/// to change the type of E.
16313/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
16314///
16315/// Always returns an RValue with a pointer representation.
16316static const Expr *ignorePointerCastsAndParens(const Expr *E) {
16317 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
16318
16319 const Expr *NoParens = E->IgnoreParens();
16320 const auto *Cast = dyn_cast<CastExpr>(NoParens);
16321 if (Cast == nullptr)
16322 return NoParens;
16323
16324 // We only conservatively allow a few kinds of casts, because this code is
16325 // inherently a simple solution that seeks to support the common case.
16326 auto CastKind = Cast->getCastKind();
16327 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
16328 CastKind != CK_AddressSpaceConversion)
16329 return NoParens;
16330
16331 const auto *SubExpr = Cast->getSubExpr();
16332 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
16333 return NoParens;
16334 return ignorePointerCastsAndParens(SubExpr);
16335}
16336
16337/// Checks to see if the given LValue's Designator is at the end of the LValue's
16338/// record layout. e.g.
16339/// struct { struct { int a, b; } fst, snd; } obj;
16340/// obj.fst // no
16341/// obj.snd // yes
16342/// obj.fst.a // no
16343/// obj.fst.b // no
16344/// obj.snd.a // no
16345/// obj.snd.b // yes
16346///
16347/// Please note: this function is specialized for how __builtin_object_size
16348/// views "objects".
16349///
16350/// If this encounters an invalid RecordDecl or otherwise cannot determine the
16351/// correct result, it will always return true.
16352static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
16353 assert(!LVal.Designator.Invalid);
16354
16355 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
16356 const RecordDecl *Parent = FD->getParent();
16357 if (Parent->isInvalidDecl() || Parent->isUnion())
16358 return true;
16359 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
16360 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
16361 };
16362
16363 auto &Base = LVal.getLValueBase();
16364 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
16365 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
16366 if (!IsLastOrInvalidFieldDecl(FD))
16367 return false;
16368 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
16369 for (auto *FD : IFD->chain()) {
16370 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
16371 return false;
16372 }
16373 }
16374 }
16375
16376 unsigned I = 0;
16377 QualType BaseType = getType(Base);
16378 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
16379 // If we don't know the array bound, conservatively assume we're looking at
16380 // the final array element.
16381 ++I;
16382 if (BaseType->isIncompleteArrayType())
16383 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
16384 else
16385 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
16386 }
16387
16388 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
16389 const auto &Entry = LVal.Designator.Entries[I];
16390 if (BaseType->isArrayType()) {
16391 // Because __builtin_object_size treats arrays as objects, we can ignore
16392 // the index iff this is the last array in the Designator.
16393 if (I + 1 == E)
16394 return true;
16395 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
16396 uint64_t Index = Entry.getAsArrayIndex();
16397 if (Index + 1 != CAT->getZExtSize())
16398 return false;
16399 BaseType = CAT->getElementType();
16400 } else if (BaseType->isAnyComplexType()) {
16401 const auto *CT = BaseType->castAs<ComplexType>();
16402 uint64_t Index = Entry.getAsArrayIndex();
16403 if (Index != 1)
16404 return false;
16405 BaseType = CT->getElementType();
16406 } else if (auto *FD = getAsField(Entry)) {
16407 if (!IsLastOrInvalidFieldDecl(FD))
16408 return false;
16409 BaseType = FD->getType();
16410 } else {
16411 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
16412 return false;
16413 }
16414 }
16415 return true;
16416}
16417
16418/// Tests to see if the LValue has a user-specified designator (that isn't
16419/// necessarily valid). Note that this always returns 'true' if the LValue has
16420/// an unsized array as its first designator entry, because there's currently no
16421/// way to tell if the user typed *foo or foo[0].
16422static bool refersToCompleteObject(const LValue &LVal) {
16423 if (LVal.Designator.Invalid)
16424 return false;
16425
16426 if (!LVal.Designator.Entries.empty())
16427 return LVal.Designator.isMostDerivedAnUnsizedArray();
16428
16429 if (!LVal.InvalidBase)
16430 return true;
16431
16432 // If `E` is a MemberExpr, then the first part of the designator is hiding in
16433 // the LValueBase.
16434 const auto *E = LVal.Base.dyn_cast<const Expr *>();
16435 return !E || !isa<MemberExpr>(E);
16436}
16437
16438/// Attempts to detect a user writing into a piece of memory that's impossible
16439/// to figure out the size of by just using types.
16440static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
16441 const SubobjectDesignator &Designator = LVal.Designator;
16442 // Notes:
16443 // - Users can only write off of the end when we have an invalid base. Invalid
16444 // bases imply we don't know where the memory came from.
16445 // - We used to be a bit more aggressive here; we'd only be conservative if
16446 // the array at the end was flexible, or if it had 0 or 1 elements. This
16447 // broke some common standard library extensions (PR30346), but was
16448 // otherwise seemingly fine. It may be useful to reintroduce this behavior
16449 // with some sort of list. OTOH, it seems that GCC is always
16450 // conservative with the last element in structs (if it's an array), so our
16451 // current behavior is more compatible than an explicit list approach would
16452 // be.
16453 auto isFlexibleArrayMember = [&] {
16455 FAMKind StrictFlexArraysLevel =
16456 Ctx.getLangOpts().getStrictFlexArraysLevel();
16457
16458 if (Designator.isMostDerivedAnUnsizedArray())
16459 return true;
16460
16461 if (StrictFlexArraysLevel == FAMKind::Default)
16462 return true;
16463
16464 if (Designator.getMostDerivedArraySize() == 0 &&
16465 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
16466 return true;
16467
16468 if (Designator.getMostDerivedArraySize() == 1 &&
16469 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
16470 return true;
16471
16472 return false;
16473 };
16474
16475 return LVal.InvalidBase &&
16476 Designator.Entries.size() == Designator.MostDerivedPathLength &&
16477 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
16478 isDesignatorAtObjectEnd(Ctx, LVal);
16479}
16480
16481/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
16482/// Fails if the conversion would cause loss of precision.
16483static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
16484 CharUnits &Result) {
16485 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
16486 if (Int.ugt(CharUnitsMax))
16487 return false;
16488 Result = CharUnits::fromQuantity(Int.getZExtValue());
16489 return true;
16490}
16491
16492/// If we're evaluating the object size of an instance of a struct that
16493/// contains a flexible array member, add the size of the initializer.
16494static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
16495 const LValue &LV, CharUnits &Size) {
16496 if (!T.isNull() && T->isStructureType() &&
16497 T->castAsRecordDecl()->hasFlexibleArrayMember())
16498 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
16499 if (const auto *VD = dyn_cast<VarDecl>(V))
16500 if (VD->hasInit())
16501 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
16502}
16503
16504/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
16505/// determine how many bytes exist from the beginning of the object to either
16506/// the end of the current subobject, or the end of the object itself, depending
16507/// on what the LValue looks like + the value of Type.
16508///
16509/// If this returns false, the value of Result is undefined.
16510static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
16511 unsigned Type, const LValue &LVal,
16512 CharUnits &EndOffset) {
16513 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
16514
16515 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
16516 if (Ty.isNull())
16517 return false;
16518
16519 Ty = Ty.getNonReferenceType();
16520
16521 if (Ty->isIncompleteType() || Ty->isFunctionType())
16522 return false;
16523
16524 return HandleSizeof(Info, ExprLoc, Ty, Result);
16525 };
16526
16527 // We want to evaluate the size of the entire object. This is a valid fallback
16528 // for when Type=1 and the designator is invalid, because we're asked for an
16529 // upper-bound.
16530 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
16531 // Type=3 wants a lower bound, so we can't fall back to this.
16532 if (Type == 3 && !DetermineForCompleteObject)
16533 return false;
16534
16535 llvm::APInt APEndOffset;
16536 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16537 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16538 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16539
16540 if (LVal.InvalidBase)
16541 return false;
16542
16543 QualType BaseTy = getObjectType(LVal.getLValueBase());
16544 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
16545 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
16546 return Ret;
16547 }
16548
16549 // We want to evaluate the size of a subobject.
16550 const SubobjectDesignator &Designator = LVal.Designator;
16551
16552 // The following is a moderately common idiom in C:
16553 //
16554 // struct Foo { int a; char c[1]; };
16555 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
16556 // strcpy(&F->c[0], Bar);
16557 //
16558 // In order to not break too much legacy code, we need to support it.
16559 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
16560 // If we can resolve this to an alloc_size call, we can hand that back,
16561 // because we know for certain how many bytes there are to write to.
16562 llvm::APInt APEndOffset;
16563 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16564 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16565 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16566
16567 // If we cannot determine the size of the initial allocation, then we can't
16568 // given an accurate upper-bound. However, we are still able to give
16569 // conservative lower-bounds for Type=3.
16570 if (Type == 1)
16571 return false;
16572 }
16573
16574 CharUnits BytesPerElem;
16575 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
16576 return false;
16577
16578 // According to the GCC documentation, we want the size of the subobject
16579 // denoted by the pointer. But that's not quite right -- what we actually
16580 // want is the size of the immediately-enclosing array, if there is one.
16581 int64_t ElemsRemaining;
16582 if (Designator.MostDerivedIsArrayElement &&
16583 Designator.Entries.size() == Designator.MostDerivedPathLength) {
16584 uint64_t ArraySize = Designator.getMostDerivedArraySize();
16585 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
16586 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
16587 } else {
16588 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
16589 }
16590
16591 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
16592 return true;
16593}
16594
16595/// Tries to evaluate the __builtin_object_size for @p E. If successful,
16596/// returns true and stores the result in @p Size.
16597///
16598/// If @p WasError is non-null, this will report whether the failure to evaluate
16599/// is to be treated as an Error in IntExprEvaluator.
16600///
16601/// If @p IsDynamic is true (i.e. we're evaluating
16602/// __builtin_dynamic_object_size) and the operand designates a flexible array
16603/// member annotated with 'counted_by', we refuse to fold so that IR generation
16604/// can emit the count-based runtime size computation.
16605static std::optional<uint64_t>
16606tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info,
16607 bool IsDynamic = false) {
16608
16609 // Determine the denoted object.
16610 LValue LVal;
16611 {
16612 // The operand of __builtin_object_size is never evaluated for side-effects.
16613 // If there are any, but we can determine the pointed-to object anyway, then
16614 // ignore the side-effects.
16615 SpeculativeEvaluationRAII SpeculativeEval(Info);
16616 IgnoreSideEffectsRAII Fold(Info);
16617
16618 if (E->isGLValue()) {
16619 // It's possible for us to be given GLValues if we're called via
16620 // Expr::tryEvaluateObjectSize.
16621 APValue RVal;
16622 if (!EvaluateAsRValue(Info, E, RVal))
16623 return std::nullopt;
16624 LVal.setFrom(Info.Ctx, RVal);
16625 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
16626 /*InvalidBaseOK=*/true))
16627 return std::nullopt;
16628 }
16629
16630 // If we point to before the start of the object, there are no accessible
16631 // bytes.
16632 if (LVal.getLValueOffset().isNegative())
16633 return 0;
16634
16635 // For __builtin_dynamic_object_size on a counted_by-annotated flexible
16636 // array member, defer to IR generation (emitCountedBySize in CGBuiltin):
16637 // its runtime computation uses the live 'count' field and is more accurate
16638 // than the layout/initializer-derived size we'd produce here. Use the same
16639 // findStructFieldAccess form-recognition CGBuiltin does, so we refuse to
16640 // fold on exactly the shapes that path handles (and, importantly, *not*
16641 // on '&af.fam' which designates the array-as-a-whole and stays on the
16642 // layout-derived path to match GCC). Checked after the negative-offset
16643 // early return above so that obviously out-of-bounds operands still fold
16644 // to 0, preserving existing behavior.
16645 if (IsDynamic) {
16646 const auto *ME = dyn_cast_or_null<MemberExpr>(findStructFieldAccess(E));
16647 const auto *FD = ME ? dyn_cast<FieldDecl>(ME->getMemberDecl()) : nullptr;
16648 if (FD && FD->getType()->isCountAttributedType())
16649 return std::nullopt;
16650 }
16651
16652 CharUnits EndOffset;
16653 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
16654 return std::nullopt;
16655
16656 // If we've fallen outside of the end offset, just pretend there's nothing to
16657 // write to/read from.
16658 if (EndOffset <= LVal.getLValueOffset())
16659 return 0;
16660 return (EndOffset - LVal.getLValueOffset()).getQuantity();
16661}
16662
16663bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
16664 if (!IsConstantEvaluatedBuiltinCall(E))
16665 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16666 return VisitBuiltinCallExpr(E, ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E));
16667}
16668
16669static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
16670 APValue &Val, APSInt &Alignment) {
16671 QualType SrcTy = E->getArg(0)->getType();
16672 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
16673 return false;
16674 // Even though we are evaluating integer expressions we could get a pointer
16675 // argument for the __builtin_is_aligned() case.
16676 if (SrcTy->isPointerType()) {
16677 LValue Ptr;
16678 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
16679 return false;
16680 Ptr.moveInto(Val);
16681 } else if (!SrcTy->isIntegralOrEnumerationType()) {
16682 Info.FFDiag(E->getArg(0));
16683 return false;
16684 } else {
16685 APSInt SrcInt;
16686 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
16687 return false;
16688 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
16689 "Bit widths must be the same");
16690 Val = APValue(SrcInt);
16691 }
16692 assert(Val.hasValue());
16693 return true;
16694}
16695
16696bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
16697 unsigned BuiltinOp) {
16698 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
16699 Fn) {
16700 APValue SourceLHS, SourceRHS;
16701 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
16702 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
16703 return false;
16704
16705 unsigned SourceLen = SourceLHS.getVectorLength();
16706 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
16707 QualType ElemQT = VT->getElementType();
16708 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
16709
16710 APInt AWide(LaneWidth * SourceLen, 0);
16711 APInt BWide(LaneWidth * SourceLen, 0);
16712
16713 for (unsigned I = 0; I != SourceLen; ++I) {
16714 APInt ALane;
16715 APInt BLane;
16716 if (ElemQT->isIntegerType()) { // Get value.
16717 ALane = SourceLHS.getVectorElt(I).getInt();
16718 BLane = SourceRHS.getVectorElt(I).getInt();
16719 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
16720 ALane =
16721 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16722 BLane =
16723 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16724 } else { // Must be integer or floating type.
16725 return false;
16726 }
16727 AWide.insertBits(ALane, I * LaneWidth);
16728 BWide.insertBits(BLane, I * LaneWidth);
16729 }
16730 return Success(Fn(AWide, BWide), E);
16731 };
16732
16733 auto HandleMaskBinOp =
16734 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
16735 -> bool {
16736 APValue LHS, RHS;
16737 if (!Evaluate(LHS, Info, E->getArg(0)) ||
16738 !Evaluate(RHS, Info, E->getArg(1)))
16739 return false;
16740
16741 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
16742
16743 return Success(APValue(ResultInt), E);
16744 };
16745
16746 auto HandleCRC32 = [&](unsigned DataBytes) -> bool {
16747 APSInt CRC, Data;
16748 if (!EvaluateInteger(E->getArg(0), CRC, Info) ||
16749 !EvaluateInteger(E->getArg(1), Data, Info))
16750 return false;
16751
16752 uint64_t CRCVal = CRC.getZExtValue();
16753 uint64_t DataVal = Data.getZExtValue();
16754
16755 // CRC32C polynomial (iSCSI polynomial, bit-reversed)
16756 static const uint32_t CRC32C_POLY = 0x82F63B78;
16757
16758 // Process each byte
16759 uint32_t Result = static_cast<uint32_t>(CRCVal);
16760 for (unsigned I = 0; I != DataBytes; ++I) {
16761 uint8_t Byte = static_cast<uint8_t>((DataVal >> (I * 8)) & 0xFF);
16762 Result ^= Byte;
16763 for (int J = 0; J != 8; ++J) {
16764 Result = (Result >> 1) ^ ((Result & 1) ? CRC32C_POLY : 0);
16765 }
16766 }
16767
16768 return Success(Result, E);
16769 };
16770
16771 switch (BuiltinOp) {
16772 default:
16773 return false;
16774
16775 case X86::BI__builtin_ia32_crc32qi:
16776 return HandleCRC32(1);
16777 case X86::BI__builtin_ia32_crc32hi:
16778 return HandleCRC32(2);
16779 case X86::BI__builtin_ia32_crc32si:
16780 return HandleCRC32(4);
16781 case X86::BI__builtin_ia32_crc32di:
16782 return HandleCRC32(8);
16783
16784 case Builtin::BI__builtin_dynamic_object_size:
16785 case Builtin::BI__builtin_object_size: {
16786 // The type was checked when we built the expression.
16787 unsigned Type =
16788 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16789 assert(Type <= 3 && "unexpected type");
16790
16791 bool IsDynamic = BuiltinOp == Builtin::BI__builtin_dynamic_object_size;
16792 if (std::optional<uint64_t> Size =
16793 tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, IsDynamic))
16794 return Success(*Size, E);
16795
16796 if (E->getArg(0)->HasSideEffects(Info.Ctx))
16797 return Success((Type & 2) ? 0 : -1, E);
16798
16799 // Expression had no side effects, but we couldn't statically determine the
16800 // size of the referenced object.
16801 switch (Info.EvalMode) {
16802 case EvaluationMode::ConstantExpression:
16803 case EvaluationMode::ConstantFold:
16804 case EvaluationMode::IgnoreSideEffects:
16805 // Leave it to IR generation.
16806 return Error(E);
16807 case EvaluationMode::ConstantExpressionUnevaluated:
16808 // Reduce it to a constant now.
16809 return Success((Type & 2) ? 0 : -1, E);
16810 }
16811
16812 llvm_unreachable("unexpected EvalMode");
16813 }
16814
16815 case Builtin::BI__builtin_os_log_format_buffer_size: {
16816 analyze_os_log::OSLogBufferLayout Layout;
16817 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
16818 return Success(Layout.size().getQuantity(), E);
16819 }
16820
16821 case Builtin::BI__builtin_is_aligned: {
16822 APValue Src;
16823 APSInt Alignment;
16824 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16825 return false;
16826 if (Src.isLValue()) {
16827 // If we evaluated a pointer, check the minimum known alignment.
16828 LValue Ptr;
16829 Ptr.setFrom(Info.Ctx, Src);
16830 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
16831 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
16832 // We can return true if the known alignment at the computed offset is
16833 // greater than the requested alignment.
16834 assert(PtrAlign.isPowerOfTwo());
16835 assert(Alignment.isPowerOf2());
16836 if (PtrAlign.getQuantity() >= Alignment)
16837 return Success(1, E);
16838 // If the alignment is not known to be sufficient, some cases could still
16839 // be aligned at run time. However, if the requested alignment is less or
16840 // equal to the base alignment and the offset is not aligned, we know that
16841 // the run-time value can never be aligned.
16842 if (BaseAlignment.getQuantity() >= Alignment &&
16843 PtrAlign.getQuantity() < Alignment)
16844 return Success(0, E);
16845 // Otherwise we can't infer whether the value is sufficiently aligned.
16846 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
16847 // in cases where we can't fully evaluate the pointer.
16848 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
16849 << Alignment;
16850 return false;
16851 }
16852 assert(Src.isInt());
16853 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
16854 }
16855 case Builtin::BI__builtin_align_up: {
16856 APValue Src;
16857 APSInt Alignment;
16858 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16859 return false;
16860 if (!Src.isInt())
16861 return Error(E);
16862 APSInt AlignedVal =
16863 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
16864 Src.getInt().isUnsigned());
16865 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16866 return Success(AlignedVal, E);
16867 }
16868 case Builtin::BI__builtin_align_down: {
16869 APValue Src;
16870 APSInt Alignment;
16871 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
16872 return false;
16873 if (!Src.isInt())
16874 return Error(E);
16875 APSInt AlignedVal =
16876 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
16877 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
16878 return Success(AlignedVal, E);
16879 }
16880
16881 case Builtin::BI__builtin_bitreverseg:
16882 case Builtin::BI__builtin_bitreverse8:
16883 case Builtin::BI__builtin_bitreverse16:
16884 case Builtin::BI__builtin_bitreverse32:
16885 case Builtin::BI__builtin_bitreverse64:
16886 case Builtin::BI__builtin_elementwise_bitreverse: {
16887 APSInt Val;
16888 if (!EvaluateInteger(E->getArg(0), Val, Info))
16889 return false;
16890
16891 return Success(Val.reverseBits(), E);
16892 }
16893 case Builtin::BI__builtin_bswapg:
16894 case Builtin::BI__builtin_bswap16:
16895 case Builtin::BI__builtin_bswap32:
16896 case Builtin::BI__builtin_bswap64:
16897 case Builtin::BIstdc_memreverse8u8:
16898 case Builtin::BIstdc_memreverse8u16:
16899 case Builtin::BIstdc_memreverse8u32:
16900 case Builtin::BIstdc_memreverse8u64: {
16901 APSInt Val;
16902 if (!EvaluateInteger(E->getArg(0), Val, Info))
16903 return false;
16904 if (Val.getBitWidth() == 8 || Val.getBitWidth() == 1)
16905 return Success(Val, E);
16906
16907 return Success(Val.byteSwap(), E);
16908 }
16909
16910 case Builtin::BI__builtin_classify_type:
16911 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
16912
16913 case Builtin::BI__builtin_clrsb:
16914 case Builtin::BI__builtin_clrsbl:
16915 case Builtin::BI__builtin_clrsbll: {
16916 APSInt Val;
16917 if (!EvaluateInteger(E->getArg(0), Val, Info))
16918 return false;
16919
16920 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
16921 }
16922
16923 case Builtin::BI__builtin_clz:
16924 case Builtin::BI__builtin_clzl:
16925 case Builtin::BI__builtin_clzll:
16926 case Builtin::BI__builtin_clzs:
16927 case Builtin::BI__builtin_clzg:
16928 case Builtin::BI__builtin_elementwise_clzg:
16929 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
16930 case Builtin::BI__lzcnt:
16931 case Builtin::BI__lzcnt64: {
16932 APSInt Val;
16933 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
16934 APValue Vec;
16935 if (!EvaluateVector(E->getArg(0), Vec, Info))
16936 return false;
16937 Val = ConvertBoolVectorToInt(Vec);
16938 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
16939 return false;
16940 }
16941
16942 std::optional<APSInt> Fallback;
16943 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
16944 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
16945 E->getNumArgs() > 1) {
16946 APSInt FallbackTemp;
16947 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
16948 return false;
16949 Fallback = FallbackTemp;
16950 }
16951
16952 if (!Val) {
16953 if (Fallback)
16954 return Success(*Fallback, E);
16955
16956 // When the argument is 0, the result of GCC builtins is undefined,
16957 // whereas for Microsoft intrinsics, the result is the bit-width of the
16958 // argument.
16959 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
16960 BuiltinOp != Builtin::BI__lzcnt &&
16961 BuiltinOp != Builtin::BI__lzcnt64;
16962
16963 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
16964 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
16965 << /*IsTrailing=*/false;
16966 }
16967
16968 if (ZeroIsUndefined)
16969 return Error(E);
16970 }
16971
16972 return Success(Val.countl_zero(), E);
16973 }
16974
16975 case Builtin::BI__builtin_constant_p: {
16976 const Expr *Arg = E->getArg(0);
16977 if (EvaluateBuiltinConstantP(Info, Arg))
16978 return Success(true, E);
16979 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
16980 // Outside a constant context, eagerly evaluate to false in the presence
16981 // of side-effects in order to avoid -Wunsequenced false-positives in
16982 // a branch on __builtin_constant_p(expr).
16983 return Success(false, E);
16984 }
16985 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16986 return false;
16987 }
16988
16989 case Builtin::BI__noop:
16990 // __noop always evaluates successfully and returns 0.
16991 return Success(0, E);
16992
16993 case Builtin::BI__builtin_is_constant_evaluated: {
16994 const auto *Callee = Info.CurrentCall->getCallee();
16995 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
16996 (Info.CallStackDepth == 1 ||
16997 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
16998 Callee->getIdentifier() &&
16999 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
17000 // FIXME: Find a better way to avoid duplicated diagnostics.
17001 if (Info.EvalStatus.Diag)
17002 Info.report((Info.CallStackDepth == 1)
17003 ? E->getExprLoc()
17004 : Info.CurrentCall->getCallRange().getBegin(),
17005 diag::warn_is_constant_evaluated_always_true_constexpr)
17006 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
17007 : "std::is_constant_evaluated");
17008 }
17009
17010 return Success(Info.InConstantContext, E);
17011 }
17012
17013 case Builtin::BI__builtin_is_within_lifetime:
17014 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
17015 return Success(*result, E);
17016 return false;
17017
17018 case Builtin::BI__builtin_ctz:
17019 case Builtin::BI__builtin_ctzl:
17020 case Builtin::BI__builtin_ctzll:
17021 case Builtin::BI__builtin_ctzs:
17022 case Builtin::BI__builtin_ctzg:
17023 case Builtin::BI__builtin_elementwise_ctzg: {
17024 APSInt Val;
17025 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
17026 APValue Vec;
17027 if (!EvaluateVector(E->getArg(0), Vec, Info))
17028 return false;
17029 Val = ConvertBoolVectorToInt(Vec);
17030 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
17031 return false;
17032 }
17033
17034 std::optional<APSInt> Fallback;
17035 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
17036 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
17037 E->getNumArgs() > 1) {
17038 APSInt FallbackTemp;
17039 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
17040 return false;
17041 Fallback = FallbackTemp;
17042 }
17043
17044 if (!Val) {
17045 if (Fallback)
17046 return Success(*Fallback, E);
17047
17048 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
17049 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
17050 << /*IsTrailing=*/true;
17051 }
17052 return Error(E);
17053 }
17054
17055 return Success(Val.countr_zero(), E);
17056 }
17057
17058 case Builtin::BI__builtin_eh_return_data_regno: {
17059 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
17060 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
17061 return Success(Operand, E);
17062 }
17063
17064 case Builtin::BI__builtin_elementwise_abs: {
17065 APSInt Val;
17066 if (!EvaluateInteger(E->getArg(0), Val, Info))
17067 return false;
17068
17069 return Success(Val.abs(), E);
17070 }
17071
17072 case Builtin::BI__builtin_expect:
17073 case Builtin::BI__builtin_expect_with_probability:
17074 return Visit(E->getArg(0));
17075
17076 case Builtin::BI__builtin_ptrauth_string_discriminator: {
17077 const auto *Literal =
17079 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
17080 return Success(Result, E);
17081 }
17082
17083 case Builtin::BI__builtin_infer_alloc_token: {
17084 // If we fail to infer a type, this fails to be a constant expression; this
17085 // can be checked with __builtin_constant_p(...).
17086 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
17087 if (AllocType.isNull())
17088 return Error(
17089 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
17090 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
17091 if (!ATMD)
17092 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
17093 auto Mode =
17094 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
17095 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
17096 auto MaxTokensOpt = Info.getLangOpts().AllocTokenMax;
17097 uint64_t MaxTokens =
17098 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
17099 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
17100 if (!MaybeToken)
17101 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
17102 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
17103 }
17104
17105 case Builtin::BI__builtin_ffs:
17106 case Builtin::BI__builtin_ffsl:
17107 case Builtin::BI__builtin_ffsll: {
17108 APSInt Val;
17109 if (!EvaluateInteger(E->getArg(0), Val, Info))
17110 return false;
17111
17112 unsigned N = Val.countr_zero();
17113 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
17114 }
17115
17116 case Builtin::BI__builtin_fpclassify: {
17117 APFloat Val(0.0);
17118 if (!EvaluateFloat(E->getArg(5), Val, Info))
17119 return false;
17120 unsigned Arg;
17121 switch (Val.getCategory()) {
17122 case APFloat::fcNaN: Arg = 0; break;
17123 case APFloat::fcInfinity: Arg = 1; break;
17124 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
17125 case APFloat::fcZero: Arg = 4; break;
17126 }
17127 return Visit(E->getArg(Arg));
17128 }
17129
17130 case Builtin::BI__builtin_isinf_sign: {
17131 APFloat Val(0.0);
17132 return EvaluateFloat(E->getArg(0), Val, Info) &&
17133 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
17134 }
17135
17136 case Builtin::BI__builtin_isinf: {
17137 APFloat Val(0.0);
17138 return EvaluateFloat(E->getArg(0), Val, Info) &&
17139 Success(Val.isInfinity() ? 1 : 0, E);
17140 }
17141
17142 case Builtin::BI__builtin_isfinite: {
17143 APFloat Val(0.0);
17144 return EvaluateFloat(E->getArg(0), Val, Info) &&
17145 Success(Val.isFinite() ? 1 : 0, E);
17146 }
17147
17148 case Builtin::BI__builtin_isnan: {
17149 APFloat Val(0.0);
17150 return EvaluateFloat(E->getArg(0), Val, Info) &&
17151 Success(Val.isNaN() ? 1 : 0, E);
17152 }
17153
17154 case Builtin::BI__builtin_isnormal: {
17155 APFloat Val(0.0);
17156 return EvaluateFloat(E->getArg(0), Val, Info) &&
17157 Success(Val.isNormal() ? 1 : 0, E);
17158 }
17159
17160 case Builtin::BI__builtin_issubnormal: {
17161 APFloat Val(0.0);
17162 return EvaluateFloat(E->getArg(0), Val, Info) &&
17163 Success(Val.isDenormal() ? 1 : 0, E);
17164 }
17165
17166 case Builtin::BI__builtin_iszero: {
17167 APFloat Val(0.0);
17168 return EvaluateFloat(E->getArg(0), Val, Info) &&
17169 Success(Val.isZero() ? 1 : 0, E);
17170 }
17171
17172 case Builtin::BI__builtin_signbit:
17173 case Builtin::BI__builtin_signbitf:
17174 case Builtin::BI__builtin_signbitl: {
17175 APFloat Val(0.0);
17176 return EvaluateFloat(E->getArg(0), Val, Info) &&
17177 Success(Val.isNegative() ? 1 : 0, E);
17178 }
17179
17180 case Builtin::BI__builtin_isgreater:
17181 case Builtin::BI__builtin_isgreaterequal:
17182 case Builtin::BI__builtin_isless:
17183 case Builtin::BI__builtin_islessequal:
17184 case Builtin::BI__builtin_islessgreater:
17185 case Builtin::BI__builtin_isunordered: {
17186 APFloat LHS(0.0);
17187 APFloat RHS(0.0);
17188 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
17189 !EvaluateFloat(E->getArg(1), RHS, Info))
17190 return false;
17191
17192 return Success(
17193 [&] {
17194 switch (BuiltinOp) {
17195 case Builtin::BI__builtin_isgreater:
17196 return LHS > RHS;
17197 case Builtin::BI__builtin_isgreaterequal:
17198 return LHS >= RHS;
17199 case Builtin::BI__builtin_isless:
17200 return LHS < RHS;
17201 case Builtin::BI__builtin_islessequal:
17202 return LHS <= RHS;
17203 case Builtin::BI__builtin_islessgreater: {
17204 APFloat::cmpResult cmp = LHS.compare(RHS);
17205 return cmp == APFloat::cmpResult::cmpLessThan ||
17206 cmp == APFloat::cmpResult::cmpGreaterThan;
17207 }
17208 case Builtin::BI__builtin_isunordered:
17209 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
17210 default:
17211 llvm_unreachable("Unexpected builtin ID: Should be a floating "
17212 "point comparison function");
17213 }
17214 }()
17215 ? 1
17216 : 0,
17217 E);
17218 }
17219
17220 case Builtin::BI__builtin_issignaling: {
17221 APFloat Val(0.0);
17222 return EvaluateFloat(E->getArg(0), Val, Info) &&
17223 Success(Val.isSignaling() ? 1 : 0, E);
17224 }
17225
17226 case Builtin::BI__builtin_isfpclass: {
17227 APSInt MaskVal;
17228 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
17229 return false;
17230 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
17231 APFloat Val(0.0);
17232 return EvaluateFloat(E->getArg(0), Val, Info) &&
17233 Success((Val.classify() & Test) ? 1 : 0, E);
17234 }
17235
17236 case Builtin::BI__builtin_parity:
17237 case Builtin::BI__builtin_parityl:
17238 case Builtin::BI__builtin_parityll: {
17239 APSInt Val;
17240 if (!EvaluateInteger(E->getArg(0), Val, Info))
17241 return false;
17242
17243 return Success(Val.popcount() % 2, E);
17244 }
17245
17246 case Builtin::BI__builtin_abs:
17247 case Builtin::BI__builtin_labs:
17248 case Builtin::BI__builtin_llabs: {
17249 APSInt Val;
17250 if (!EvaluateInteger(E->getArg(0), Val, Info))
17251 return false;
17252 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
17253 /*IsUnsigned=*/false))
17254 return false;
17255 if (Val.isNegative())
17256 Val.negate();
17257 return Success(Val, E);
17258 }
17259
17260 case Builtin::BI__builtin_popcount:
17261 case Builtin::BI__builtin_popcountl:
17262 case Builtin::BI__builtin_popcountll:
17263 case Builtin::BI__builtin_popcountg:
17264 case Builtin::BI__builtin_elementwise_popcount:
17265 case Builtin::BI__popcnt16: // Microsoft variants of popcount
17266 case Builtin::BI__popcnt:
17267 case Builtin::BI__popcnt64: {
17268 APSInt Val;
17269 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
17270 APValue Vec;
17271 if (!EvaluateVector(E->getArg(0), Vec, Info))
17272 return false;
17273 Val = ConvertBoolVectorToInt(Vec);
17274 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
17275 return false;
17276 }
17277
17278 return Success(Val.popcount(), E);
17279 }
17280
17281 case Builtin::BI__builtin_rotateleft8:
17282 case Builtin::BI__builtin_rotateleft16:
17283 case Builtin::BI__builtin_rotateleft32:
17284 case Builtin::BI__builtin_rotateleft64:
17285 case Builtin::BI__builtin_rotateright8:
17286 case Builtin::BI__builtin_rotateright16:
17287 case Builtin::BI__builtin_rotateright32:
17288 case Builtin::BI__builtin_rotateright64:
17289 case Builtin::BI__builtin_stdc_rotate_left:
17290 case Builtin::BI__builtin_stdc_rotate_right:
17291 case Builtin::BIstdc_rotate_left_uc:
17292 case Builtin::BIstdc_rotate_left_us:
17293 case Builtin::BIstdc_rotate_left_ui:
17294 case Builtin::BIstdc_rotate_left_ul:
17295 case Builtin::BIstdc_rotate_left_ull:
17296 case Builtin::BIstdc_rotate_right_uc:
17297 case Builtin::BIstdc_rotate_right_us:
17298 case Builtin::BIstdc_rotate_right_ui:
17299 case Builtin::BIstdc_rotate_right_ul:
17300 case Builtin::BIstdc_rotate_right_ull:
17301 case Builtin::BI_rotl8: // Microsoft variants of rotate left
17302 case Builtin::BI_rotl16:
17303 case Builtin::BI_rotl:
17304 case Builtin::BI_lrotl:
17305 case Builtin::BI_rotl64:
17306 case Builtin::BI_rotr8: // Microsoft variants of rotate right
17307 case Builtin::BI_rotr16:
17308 case Builtin::BI_rotr:
17309 case Builtin::BI_lrotr:
17310 case Builtin::BI_rotr64: {
17311 APSInt Value, Amount;
17312 if (!EvaluateInteger(E->getArg(0), Value, Info) ||
17313 !EvaluateInteger(E->getArg(1), Amount, Info))
17314 return false;
17315
17316 Amount = NormalizeRotateAmount(Value, Amount);
17317
17318 switch (BuiltinOp) {
17319 case Builtin::BI__builtin_rotateright8:
17320 case Builtin::BI__builtin_rotateright16:
17321 case Builtin::BI__builtin_rotateright32:
17322 case Builtin::BI__builtin_rotateright64:
17323 case Builtin::BI__builtin_stdc_rotate_right:
17324 case Builtin::BIstdc_rotate_right_uc:
17325 case Builtin::BIstdc_rotate_right_us:
17326 case Builtin::BIstdc_rotate_right_ui:
17327 case Builtin::BIstdc_rotate_right_ul:
17328 case Builtin::BIstdc_rotate_right_ull:
17329 case Builtin::BI_rotr8:
17330 case Builtin::BI_rotr16:
17331 case Builtin::BI_rotr:
17332 case Builtin::BI_lrotr:
17333 case Builtin::BI_rotr64:
17334 return Success(
17335 APSInt(Value.rotr(Amount.getZExtValue()), Value.isUnsigned()), E);
17336 default:
17337 return Success(
17338 APSInt(Value.rotl(Amount.getZExtValue()), Value.isUnsigned()), E);
17339 }
17340 }
17341
17342 case Builtin::BIstdc_leading_zeros_uc:
17343 case Builtin::BIstdc_leading_zeros_us:
17344 case Builtin::BIstdc_leading_zeros_ui:
17345 case Builtin::BIstdc_leading_zeros_ul:
17346 case Builtin::BIstdc_leading_zeros_ull:
17347 case Builtin::BIstdc_leading_ones_uc:
17348 case Builtin::BIstdc_leading_ones_us:
17349 case Builtin::BIstdc_leading_ones_ui:
17350 case Builtin::BIstdc_leading_ones_ul:
17351 case Builtin::BIstdc_leading_ones_ull:
17352 case Builtin::BIstdc_trailing_zeros_uc:
17353 case Builtin::BIstdc_trailing_zeros_us:
17354 case Builtin::BIstdc_trailing_zeros_ui:
17355 case Builtin::BIstdc_trailing_zeros_ul:
17356 case Builtin::BIstdc_trailing_zeros_ull:
17357 case Builtin::BIstdc_trailing_ones_uc:
17358 case Builtin::BIstdc_trailing_ones_us:
17359 case Builtin::BIstdc_trailing_ones_ui:
17360 case Builtin::BIstdc_trailing_ones_ul:
17361 case Builtin::BIstdc_trailing_ones_ull:
17362 case Builtin::BIstdc_first_leading_zero_uc:
17363 case Builtin::BIstdc_first_leading_zero_us:
17364 case Builtin::BIstdc_first_leading_zero_ui:
17365 case Builtin::BIstdc_first_leading_zero_ul:
17366 case Builtin::BIstdc_first_leading_zero_ull:
17367 case Builtin::BIstdc_first_leading_one_uc:
17368 case Builtin::BIstdc_first_leading_one_us:
17369 case Builtin::BIstdc_first_leading_one_ui:
17370 case Builtin::BIstdc_first_leading_one_ul:
17371 case Builtin::BIstdc_first_leading_one_ull:
17372 case Builtin::BIstdc_first_trailing_zero_uc:
17373 case Builtin::BIstdc_first_trailing_zero_us:
17374 case Builtin::BIstdc_first_trailing_zero_ui:
17375 case Builtin::BIstdc_first_trailing_zero_ul:
17376 case Builtin::BIstdc_first_trailing_zero_ull:
17377 case Builtin::BIstdc_first_trailing_one_uc:
17378 case Builtin::BIstdc_first_trailing_one_us:
17379 case Builtin::BIstdc_first_trailing_one_ui:
17380 case Builtin::BIstdc_first_trailing_one_ul:
17381 case Builtin::BIstdc_first_trailing_one_ull:
17382 case Builtin::BIstdc_count_zeros_uc:
17383 case Builtin::BIstdc_count_zeros_us:
17384 case Builtin::BIstdc_count_zeros_ui:
17385 case Builtin::BIstdc_count_zeros_ul:
17386 case Builtin::BIstdc_count_zeros_ull:
17387 case Builtin::BIstdc_count_ones_uc:
17388 case Builtin::BIstdc_count_ones_us:
17389 case Builtin::BIstdc_count_ones_ui:
17390 case Builtin::BIstdc_count_ones_ul:
17391 case Builtin::BIstdc_count_ones_ull:
17392 case Builtin::BIstdc_has_single_bit_uc:
17393 case Builtin::BIstdc_has_single_bit_us:
17394 case Builtin::BIstdc_has_single_bit_ui:
17395 case Builtin::BIstdc_has_single_bit_ul:
17396 case Builtin::BIstdc_has_single_bit_ull:
17397 case Builtin::BIstdc_bit_width_uc:
17398 case Builtin::BIstdc_bit_width_us:
17399 case Builtin::BIstdc_bit_width_ui:
17400 case Builtin::BIstdc_bit_width_ul:
17401 case Builtin::BIstdc_bit_width_ull:
17402 case Builtin::BIstdc_bit_floor_uc:
17403 case Builtin::BIstdc_bit_floor_us:
17404 case Builtin::BIstdc_bit_floor_ui:
17405 case Builtin::BIstdc_bit_floor_ul:
17406 case Builtin::BIstdc_bit_floor_ull:
17407 case Builtin::BIstdc_bit_ceil_uc:
17408 case Builtin::BIstdc_bit_ceil_us:
17409 case Builtin::BIstdc_bit_ceil_ui:
17410 case Builtin::BIstdc_bit_ceil_ul:
17411 case Builtin::BIstdc_bit_ceil_ull:
17412 case Builtin::BI__builtin_stdc_leading_zeros:
17413 case Builtin::BI__builtin_stdc_leading_ones:
17414 case Builtin::BI__builtin_stdc_trailing_zeros:
17415 case Builtin::BI__builtin_stdc_trailing_ones:
17416 case Builtin::BI__builtin_stdc_first_leading_zero:
17417 case Builtin::BI__builtin_stdc_first_leading_one:
17418 case Builtin::BI__builtin_stdc_first_trailing_zero:
17419 case Builtin::BI__builtin_stdc_first_trailing_one:
17420 case Builtin::BI__builtin_stdc_count_zeros:
17421 case Builtin::BI__builtin_stdc_count_ones:
17422 case Builtin::BI__builtin_stdc_has_single_bit:
17423 case Builtin::BI__builtin_stdc_bit_width:
17424 case Builtin::BI__builtin_stdc_bit_floor:
17425 case Builtin::BI__builtin_stdc_bit_ceil: {
17426 APSInt Val;
17427 if (!EvaluateInteger(E->getArg(0), Val, Info))
17428 return false;
17429
17430 unsigned BitWidth = Val.getBitWidth();
17431 const unsigned ResBitWidth = Info.Ctx.getIntWidth(E->getType());
17432
17433 switch (BuiltinOp) {
17434 case Builtin::BIstdc_leading_zeros_uc:
17435 case Builtin::BIstdc_leading_zeros_us:
17436 case Builtin::BIstdc_leading_zeros_ui:
17437 case Builtin::BIstdc_leading_zeros_ul:
17438 case Builtin::BIstdc_leading_zeros_ull:
17439 case Builtin::BI__builtin_stdc_leading_zeros:
17440 return Success(APInt(ResBitWidth, Val.countl_zero()), E);
17441 case Builtin::BIstdc_leading_ones_uc:
17442 case Builtin::BIstdc_leading_ones_us:
17443 case Builtin::BIstdc_leading_ones_ui:
17444 case Builtin::BIstdc_leading_ones_ul:
17445 case Builtin::BIstdc_leading_ones_ull:
17446 case Builtin::BI__builtin_stdc_leading_ones:
17447 return Success(APInt(ResBitWidth, Val.countl_one()), E);
17448 case Builtin::BIstdc_trailing_zeros_uc:
17449 case Builtin::BIstdc_trailing_zeros_us:
17450 case Builtin::BIstdc_trailing_zeros_ui:
17451 case Builtin::BIstdc_trailing_zeros_ul:
17452 case Builtin::BIstdc_trailing_zeros_ull:
17453 case Builtin::BI__builtin_stdc_trailing_zeros:
17454 return Success(APInt(ResBitWidth, Val.countr_zero()), E);
17455 case Builtin::BIstdc_trailing_ones_uc:
17456 case Builtin::BIstdc_trailing_ones_us:
17457 case Builtin::BIstdc_trailing_ones_ui:
17458 case Builtin::BIstdc_trailing_ones_ul:
17459 case Builtin::BIstdc_trailing_ones_ull:
17460 case Builtin::BI__builtin_stdc_trailing_ones:
17461 return Success(APInt(ResBitWidth, Val.countr_one()), E);
17462 case Builtin::BIstdc_first_leading_zero_uc:
17463 case Builtin::BIstdc_first_leading_zero_us:
17464 case Builtin::BIstdc_first_leading_zero_ui:
17465 case Builtin::BIstdc_first_leading_zero_ul:
17466 case Builtin::BIstdc_first_leading_zero_ull:
17467 case Builtin::BI__builtin_stdc_first_leading_zero:
17468 return Success(
17469 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countl_one() + 1), E);
17470 case Builtin::BIstdc_first_leading_one_uc:
17471 case Builtin::BIstdc_first_leading_one_us:
17472 case Builtin::BIstdc_first_leading_one_ui:
17473 case Builtin::BIstdc_first_leading_one_ul:
17474 case Builtin::BIstdc_first_leading_one_ull:
17475 case Builtin::BI__builtin_stdc_first_leading_one:
17476 return Success(
17477 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countl_zero() + 1), E);
17478 case Builtin::BIstdc_first_trailing_zero_uc:
17479 case Builtin::BIstdc_first_trailing_zero_us:
17480 case Builtin::BIstdc_first_trailing_zero_ui:
17481 case Builtin::BIstdc_first_trailing_zero_ul:
17482 case Builtin::BIstdc_first_trailing_zero_ull:
17483 case Builtin::BI__builtin_stdc_first_trailing_zero:
17484 return Success(
17485 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countr_one() + 1), E);
17486 case Builtin::BIstdc_first_trailing_one_uc:
17487 case Builtin::BIstdc_first_trailing_one_us:
17488 case Builtin::BIstdc_first_trailing_one_ui:
17489 case Builtin::BIstdc_first_trailing_one_ul:
17490 case Builtin::BIstdc_first_trailing_one_ull:
17491 case Builtin::BI__builtin_stdc_first_trailing_one:
17492 return Success(
17493 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countr_zero() + 1), E);
17494 case Builtin::BIstdc_count_zeros_uc:
17495 case Builtin::BIstdc_count_zeros_us:
17496 case Builtin::BIstdc_count_zeros_ui:
17497 case Builtin::BIstdc_count_zeros_ul:
17498 case Builtin::BIstdc_count_zeros_ull:
17499 case Builtin::BI__builtin_stdc_count_zeros: {
17500 APInt Cnt(ResBitWidth, BitWidth - Val.popcount());
17501 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
17502 }
17503 case Builtin::BIstdc_count_ones_uc:
17504 case Builtin::BIstdc_count_ones_us:
17505 case Builtin::BIstdc_count_ones_ui:
17506 case Builtin::BIstdc_count_ones_ul:
17507 case Builtin::BIstdc_count_ones_ull:
17508 case Builtin::BI__builtin_stdc_count_ones: {
17509 APInt Cnt(ResBitWidth, Val.popcount());
17510 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
17511 }
17512 case Builtin::BIstdc_has_single_bit_uc:
17513 case Builtin::BIstdc_has_single_bit_us:
17514 case Builtin::BIstdc_has_single_bit_ui:
17515 case Builtin::BIstdc_has_single_bit_ul:
17516 case Builtin::BIstdc_has_single_bit_ull:
17517 case Builtin::BI__builtin_stdc_has_single_bit: {
17518 APInt Res(ResBitWidth, Val.popcount() == 1 ? 1 : 0);
17519 return Success(APSInt(Res, /*IsUnsigned*/ true), E);
17520 }
17521 case Builtin::BIstdc_bit_width_uc:
17522 case Builtin::BIstdc_bit_width_us:
17523 case Builtin::BIstdc_bit_width_ui:
17524 case Builtin::BIstdc_bit_width_ul:
17525 case Builtin::BIstdc_bit_width_ull:
17526 case Builtin::BI__builtin_stdc_bit_width:
17527 return Success(APInt(ResBitWidth, BitWidth - Val.countl_zero()), E);
17528 case Builtin::BIstdc_bit_floor_uc:
17529 case Builtin::BIstdc_bit_floor_us:
17530 case Builtin::BIstdc_bit_floor_ui:
17531 case Builtin::BIstdc_bit_floor_ul:
17532 case Builtin::BIstdc_bit_floor_ull:
17533 case Builtin::BI__builtin_stdc_bit_floor: {
17534 if (Val.isZero())
17535 return Success(APInt(BitWidth, 0), E);
17536 unsigned Exp = BitWidth - Val.countl_zero() - 1;
17537 return Success(
17538 APSInt(APInt::getOneBitSet(BitWidth, Exp), /*IsUnsigned*/ true), E);
17539 }
17540 case Builtin::BIstdc_bit_ceil_uc:
17541 case Builtin::BIstdc_bit_ceil_us:
17542 case Builtin::BIstdc_bit_ceil_ui:
17543 case Builtin::BIstdc_bit_ceil_ul:
17544 case Builtin::BIstdc_bit_ceil_ull:
17545 case Builtin::BI__builtin_stdc_bit_ceil: {
17546 if (Val.ule(1))
17547 return Success(APSInt(APInt(BitWidth, 1), /*IsUnsigned*/ true), E);
17548 APInt ValMinusOne = Val - 1;
17549 unsigned LZ = ValMinusOne.countl_zero();
17550 if (LZ == 0)
17551 return Success(APSInt(APInt(BitWidth, 0), /*IsUnsigned*/ true),
17552 E); // overflows; wrap to 0
17553 APInt Result = APInt::getOneBitSet(BitWidth, BitWidth - LZ);
17554 return Success(APSInt(Result, /*IsUnsigned*/ true), E);
17555 }
17556 default:
17557 llvm_unreachable("Unknown stdc builtin");
17558 }
17559 }
17560
17561 case Builtin::BI__builtin_elementwise_add_sat: {
17562 APSInt LHS, RHS;
17563 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17564 !EvaluateInteger(E->getArg(1), RHS, Info))
17565 return false;
17566
17567 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
17568 return Success(APSInt(Result, !LHS.isSigned()), E);
17569 }
17570 case Builtin::BI__builtin_elementwise_sub_sat: {
17571 APSInt LHS, RHS;
17572 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17573 !EvaluateInteger(E->getArg(1), RHS, Info))
17574 return false;
17575
17576 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
17577 return Success(APSInt(Result, !LHS.isSigned()), E);
17578 }
17579 case Builtin::BI__builtin_elementwise_max: {
17580 APSInt LHS, RHS;
17581 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17582 !EvaluateInteger(E->getArg(1), RHS, Info))
17583 return false;
17584
17585 APInt Result = std::max(LHS, RHS);
17586 return Success(APSInt(Result, !LHS.isSigned()), E);
17587 }
17588 case Builtin::BI__builtin_elementwise_min: {
17589 APSInt LHS, RHS;
17590 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17591 !EvaluateInteger(E->getArg(1), RHS, Info))
17592 return false;
17593
17594 APInt Result = std::min(LHS, RHS);
17595 return Success(APSInt(Result, !LHS.isSigned()), E);
17596 }
17597 case Builtin::BI__builtin_elementwise_clmul: {
17598 APSInt LHS, RHS;
17599 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17600 !EvaluateInteger(E->getArg(1), RHS, Info))
17601 return false;
17602
17603 APInt Result = llvm::APIntOps::clmul(LHS, RHS);
17604 return Success(APSInt(Result, LHS.isUnsigned()), E);
17605 }
17606 case Builtin::BI__builtin_elementwise_fshl:
17607 case Builtin::BI__builtin_elementwise_fshr: {
17608 APSInt Hi, Lo, Shift;
17609 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
17610 !EvaluateInteger(E->getArg(1), Lo, Info) ||
17611 !EvaluateInteger(E->getArg(2), Shift, Info))
17612 return false;
17613
17614 switch (BuiltinOp) {
17615 case Builtin::BI__builtin_elementwise_fshl: {
17616 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
17617 return Success(Result, E);
17618 }
17619 case Builtin::BI__builtin_elementwise_fshr: {
17620 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
17621 return Success(Result, E);
17622 }
17623 }
17624 llvm_unreachable("Fully covered switch above");
17625 }
17626 case Builtin::BIstrlen:
17627 case Builtin::BIwcslen:
17628 // A call to strlen is not a constant expression.
17629 if (Info.getLangOpts().CPlusPlus11)
17630 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17631 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17632 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17633 else
17634 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17635 [[fallthrough]];
17636 case Builtin::BI__builtin_strlen:
17637 case Builtin::BI__builtin_wcslen: {
17638 // As an extension, we support __builtin_strlen() as a constant expression,
17639 // and support folding strlen() to a constant.
17640 if (std::optional<uint64_t> StrLen =
17641 EvaluateBuiltinStrLen(E->getArg(0), Info))
17642 return Success(*StrLen, E);
17643 return false;
17644 }
17645
17646 case Builtin::BIstrcmp:
17647 case Builtin::BIwcscmp:
17648 case Builtin::BIstrncmp:
17649 case Builtin::BIwcsncmp:
17650 case Builtin::BImemcmp:
17651 case Builtin::BIbcmp:
17652 case Builtin::BIwmemcmp:
17653 // A call to strlen is not a constant expression.
17654 if (Info.getLangOpts().CPlusPlus11)
17655 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17656 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17657 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17658 else
17659 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17660 [[fallthrough]];
17661 case Builtin::BI__builtin_strcmp:
17662 case Builtin::BI__builtin_wcscmp:
17663 case Builtin::BI__builtin_strncmp:
17664 case Builtin::BI__builtin_wcsncmp:
17665 case Builtin::BI__builtin_memcmp:
17666 case Builtin::BI__builtin_bcmp:
17667 case Builtin::BI__builtin_wmemcmp: {
17668 LValue String1, String2;
17669 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
17670 !EvaluatePointer(E->getArg(1), String2, Info))
17671 return false;
17672
17673 uint64_t MaxLength = uint64_t(-1);
17674 if (BuiltinOp != Builtin::BIstrcmp &&
17675 BuiltinOp != Builtin::BIwcscmp &&
17676 BuiltinOp != Builtin::BI__builtin_strcmp &&
17677 BuiltinOp != Builtin::BI__builtin_wcscmp) {
17678 APSInt N;
17679 if (!EvaluateInteger(E->getArg(2), N, Info))
17680 return false;
17681 MaxLength = N.getZExtValue();
17682 }
17683
17684 // Empty substrings compare equal by definition.
17685 if (MaxLength == 0u)
17686 return Success(0, E);
17687
17688 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17689 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17690 String1.Designator.Invalid || String2.Designator.Invalid)
17691 return false;
17692
17693 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
17694 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
17695
17696 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
17697 BuiltinOp == Builtin::BIbcmp ||
17698 BuiltinOp == Builtin::BI__builtin_memcmp ||
17699 BuiltinOp == Builtin::BI__builtin_bcmp;
17700
17701 assert(IsRawByte ||
17702 (Info.Ctx.hasSameUnqualifiedType(
17703 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
17704 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
17705
17706 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
17707 // 'char8_t', but no other types.
17708 if (IsRawByte &&
17709 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
17710 // FIXME: Consider using our bit_cast implementation to support this.
17711 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
17712 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
17713 << CharTy2;
17714 return false;
17715 }
17716
17717 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
17718 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
17719 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
17720 Char1.isInt() && Char2.isInt();
17721 };
17722 const auto &AdvanceElems = [&] {
17723 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
17724 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
17725 };
17726
17727 bool StopAtNull =
17728 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
17729 BuiltinOp != Builtin::BIwmemcmp &&
17730 BuiltinOp != Builtin::BI__builtin_memcmp &&
17731 BuiltinOp != Builtin::BI__builtin_bcmp &&
17732 BuiltinOp != Builtin::BI__builtin_wmemcmp);
17733 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
17734 BuiltinOp == Builtin::BIwcsncmp ||
17735 BuiltinOp == Builtin::BIwmemcmp ||
17736 BuiltinOp == Builtin::BI__builtin_wcscmp ||
17737 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
17738 BuiltinOp == Builtin::BI__builtin_wmemcmp;
17739
17740 for (; MaxLength; --MaxLength) {
17741 APValue Char1, Char2;
17742 if (!ReadCurElems(Char1, Char2))
17743 return false;
17744 if (Char1.getInt().ne(Char2.getInt())) {
17745 if (IsWide) // wmemcmp compares with wchar_t signedness.
17746 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
17747 // memcmp always compares unsigned chars.
17748 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
17749 }
17750 if (StopAtNull && !Char1.getInt())
17751 return Success(0, E);
17752 assert(!(StopAtNull && !Char2.getInt()));
17753 if (!AdvanceElems())
17754 return false;
17755 }
17756 // We hit the strncmp / memcmp limit.
17757 return Success(0, E);
17758 }
17759
17760 case Builtin::BI__atomic_always_lock_free:
17761 case Builtin::BI__atomic_is_lock_free:
17762 case Builtin::BI__c11_atomic_is_lock_free: {
17763 APSInt SizeVal;
17764 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
17765 return false;
17766
17767 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
17768 // of two less than or equal to the maximum inline atomic width, we know it
17769 // is lock-free. If the size isn't a power of two, or greater than the
17770 // maximum alignment where we promote atomics, we know it is not lock-free
17771 // (at least not in the sense of atomic_is_lock_free). Otherwise,
17772 // the answer can only be determined at runtime; for example, 16-byte
17773 // atomics have lock-free implementations on some, but not all,
17774 // x86-64 processors.
17775
17776 // Check power-of-two.
17777 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
17778 if (Size.isPowerOfTwo()) {
17779 // Check against inlining width.
17780 unsigned InlineWidthBits =
17781 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
17782 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
17783 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
17784 Size == CharUnits::One())
17785 return Success(1, E);
17786
17787 // If the pointer argument can be evaluated to a compile-time constant
17788 // integer (or nullptr), check if that value is appropriately aligned.
17789 const Expr *PtrArg = E->getArg(1);
17790 Expr::EvalResult ExprResult;
17791 APSInt IntResult;
17792 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
17793 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
17794 Info.Ctx) &&
17795 IntResult.isAligned(Size.getAsAlign()))
17796 return Success(1, E);
17797
17798 // Otherwise, check if the type's alignment against Size.
17799 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
17800 // Drop the potential implicit-cast to 'const volatile void*', getting
17801 // the underlying type.
17802 if (ICE->getCastKind() == CK_BitCast)
17803 PtrArg = ICE->getSubExpr();
17804 }
17805
17806 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
17807 QualType PointeeType = PtrTy->getPointeeType();
17808 if (!PointeeType->isIncompleteType() &&
17809 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
17810 // OK, we will inline operations on this object.
17811 return Success(1, E);
17812 }
17813 }
17814 }
17815 }
17816
17817 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
17818 Success(0, E) : Error(E);
17819 }
17820 case Builtin::BI__builtin_addcb:
17821 case Builtin::BI__builtin_addcs:
17822 case Builtin::BI__builtin_addc:
17823 case Builtin::BI__builtin_addcl:
17824 case Builtin::BI__builtin_addcll:
17825 case Builtin::BI__builtin_subcb:
17826 case Builtin::BI__builtin_subcs:
17827 case Builtin::BI__builtin_subc:
17828 case Builtin::BI__builtin_subcl:
17829 case Builtin::BI__builtin_subcll: {
17830 LValue CarryOutLValue;
17831 APSInt LHS, RHS, CarryIn, CarryOut, Result;
17832 QualType ResultType = E->getArg(0)->getType();
17833 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17834 !EvaluateInteger(E->getArg(1), RHS, Info) ||
17835 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
17836 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
17837 return false;
17838 // Copy the number of bits and sign.
17839 Result = LHS;
17840 CarryOut = LHS;
17841
17842 bool FirstOverflowed = false;
17843 bool SecondOverflowed = false;
17844 switch (BuiltinOp) {
17845 default:
17846 llvm_unreachable("Invalid value for BuiltinOp");
17847 case Builtin::BI__builtin_addcb:
17848 case Builtin::BI__builtin_addcs:
17849 case Builtin::BI__builtin_addc:
17850 case Builtin::BI__builtin_addcl:
17851 case Builtin::BI__builtin_addcll:
17852 Result =
17853 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
17854 break;
17855 case Builtin::BI__builtin_subcb:
17856 case Builtin::BI__builtin_subcs:
17857 case Builtin::BI__builtin_subc:
17858 case Builtin::BI__builtin_subcl:
17859 case Builtin::BI__builtin_subcll:
17860 Result =
17861 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
17862 break;
17863 }
17864
17865 // It is possible for both overflows to happen but CGBuiltin uses an OR so
17866 // this is consistent.
17867 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
17868 APValue APV{CarryOut};
17869 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
17870 return false;
17871 return Success(Result, E);
17872 }
17873 case Builtin::BI__builtin_add_overflow:
17874 case Builtin::BI__builtin_sub_overflow:
17875 case Builtin::BI__builtin_mul_overflow:
17876 case Builtin::BI__builtin_sadd_overflow:
17877 case Builtin::BI__builtin_uadd_overflow:
17878 case Builtin::BI__builtin_uaddl_overflow:
17879 case Builtin::BI__builtin_uaddll_overflow:
17880 case Builtin::BI__builtin_usub_overflow:
17881 case Builtin::BI__builtin_usubl_overflow:
17882 case Builtin::BI__builtin_usubll_overflow:
17883 case Builtin::BI__builtin_umul_overflow:
17884 case Builtin::BI__builtin_umull_overflow:
17885 case Builtin::BI__builtin_umulll_overflow:
17886 case Builtin::BI__builtin_saddl_overflow:
17887 case Builtin::BI__builtin_saddll_overflow:
17888 case Builtin::BI__builtin_ssub_overflow:
17889 case Builtin::BI__builtin_ssubl_overflow:
17890 case Builtin::BI__builtin_ssubll_overflow:
17891 case Builtin::BI__builtin_smul_overflow:
17892 case Builtin::BI__builtin_smull_overflow:
17893 case Builtin::BI__builtin_smulll_overflow: {
17894 LValue ResultLValue;
17895 APSInt LHS, RHS;
17896
17897 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
17898 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17899 !EvaluateInteger(E->getArg(1), RHS, Info) ||
17900 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
17901 return false;
17902
17903 APSInt Result;
17904 bool DidOverflow = false;
17905
17906 // If the types don't have to match, enlarge all 3 to the largest of them.
17907 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
17908 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
17909 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
17910 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
17912 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
17914 uint64_t LHSSize = LHS.getBitWidth();
17915 uint64_t RHSSize = RHS.getBitWidth();
17916 uint64_t ResultSize = Info.Ctx.getIntWidth(ResultType);
17917 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
17918
17919 // Add an additional bit if the signedness isn't uniformly agreed to. We
17920 // could do this ONLY if there is a signed and an unsigned that both have
17921 // MaxBits, but the code to check that is pretty nasty. The issue will be
17922 // caught in the shrink-to-result later anyway.
17923 if (IsSigned && !AllSigned)
17924 ++MaxBits;
17925
17926 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
17927 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
17928 Result = APSInt(MaxBits, !IsSigned);
17929 }
17930
17931 // Find largest int.
17932 switch (BuiltinOp) {
17933 default:
17934 llvm_unreachable("Invalid value for BuiltinOp");
17935 case Builtin::BI__builtin_add_overflow:
17936 case Builtin::BI__builtin_sadd_overflow:
17937 case Builtin::BI__builtin_saddl_overflow:
17938 case Builtin::BI__builtin_saddll_overflow:
17939 case Builtin::BI__builtin_uadd_overflow:
17940 case Builtin::BI__builtin_uaddl_overflow:
17941 case Builtin::BI__builtin_uaddll_overflow:
17942 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
17943 : LHS.uadd_ov(RHS, DidOverflow);
17944 break;
17945 case Builtin::BI__builtin_sub_overflow:
17946 case Builtin::BI__builtin_ssub_overflow:
17947 case Builtin::BI__builtin_ssubl_overflow:
17948 case Builtin::BI__builtin_ssubll_overflow:
17949 case Builtin::BI__builtin_usub_overflow:
17950 case Builtin::BI__builtin_usubl_overflow:
17951 case Builtin::BI__builtin_usubll_overflow:
17952 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
17953 : LHS.usub_ov(RHS, DidOverflow);
17954 break;
17955 case Builtin::BI__builtin_mul_overflow:
17956 case Builtin::BI__builtin_smul_overflow:
17957 case Builtin::BI__builtin_smull_overflow:
17958 case Builtin::BI__builtin_smulll_overflow:
17959 case Builtin::BI__builtin_umul_overflow:
17960 case Builtin::BI__builtin_umull_overflow:
17961 case Builtin::BI__builtin_umulll_overflow:
17962 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
17963 : LHS.umul_ov(RHS, DidOverflow);
17964 break;
17965 }
17966
17967 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
17968 // since it will give us the behavior of a TruncOrSelf in the case where
17969 // its parameter <= its size. We previously set Result to be at least the
17970 // integer width of the result, so getIntWidth(ResultType) <=
17971 // Result.BitWidth will work exactly like TruncOrSelf.
17972 APSInt Temp = Result.extOrTrunc(Info.Ctx.getIntWidth(ResultType));
17973 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
17974
17975 // In the case where multiple sizes are allowed, truncate and see if
17976 // the values are the same.
17977 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
17978 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
17979 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
17980 if (!APSInt::isSameValue(Temp, Result))
17981 DidOverflow = true;
17982 }
17983 Result = Temp;
17984
17985 APValue APV{Result};
17986 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
17987 return false;
17988 return Success(DidOverflow, E);
17989 }
17990
17991 case Builtin::BI__builtin_reduce_add:
17992 case Builtin::BI__builtin_reduce_mul:
17993 case Builtin::BI__builtin_reduce_and:
17994 case Builtin::BI__builtin_reduce_or:
17995 case Builtin::BI__builtin_reduce_xor:
17996 case Builtin::BI__builtin_reduce_min:
17997 case Builtin::BI__builtin_reduce_max: {
17998 APValue Source;
17999 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
18000 return false;
18001
18002 unsigned SourceLen = Source.getVectorLength();
18003 APSInt Reduced = Source.getVectorElt(0).getInt();
18004 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
18005 switch (BuiltinOp) {
18006 default:
18007 return false;
18008 case Builtin::BI__builtin_reduce_add: {
18010 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
18011 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
18012 return false;
18013 break;
18014 }
18015 case Builtin::BI__builtin_reduce_mul: {
18017 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
18018 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
18019 return false;
18020 break;
18021 }
18022 case Builtin::BI__builtin_reduce_and: {
18023 Reduced &= Source.getVectorElt(EltNum).getInt();
18024 break;
18025 }
18026 case Builtin::BI__builtin_reduce_or: {
18027 Reduced |= Source.getVectorElt(EltNum).getInt();
18028 break;
18029 }
18030 case Builtin::BI__builtin_reduce_xor: {
18031 Reduced ^= Source.getVectorElt(EltNum).getInt();
18032 break;
18033 }
18034 case Builtin::BI__builtin_reduce_min: {
18035 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
18036 break;
18037 }
18038 case Builtin::BI__builtin_reduce_max: {
18039 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
18040 break;
18041 }
18042 }
18043 }
18044
18045 return Success(Reduced, E);
18046 }
18047
18048 case clang::X86::BI__builtin_ia32_addcarryx_u32:
18049 case clang::X86::BI__builtin_ia32_addcarryx_u64:
18050 case clang::X86::BI__builtin_ia32_subborrow_u32:
18051 case clang::X86::BI__builtin_ia32_subborrow_u64: {
18052 LValue ResultLValue;
18053 APSInt CarryIn, LHS, RHS;
18054 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
18055 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
18056 !EvaluateInteger(E->getArg(1), LHS, Info) ||
18057 !EvaluateInteger(E->getArg(2), RHS, Info) ||
18058 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
18059 return false;
18060
18061 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
18062 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
18063
18064 unsigned BitWidth = LHS.getBitWidth();
18065 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
18066 APInt ExResult =
18067 IsAdd
18068 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
18069 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
18070
18071 APInt Result = ExResult.extractBits(BitWidth, 0);
18072 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
18073
18074 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
18075 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
18076 return false;
18077 return Success(CarryOut, E);
18078 }
18079
18080 case clang::X86::BI__builtin_ia32_movmskps:
18081 case clang::X86::BI__builtin_ia32_movmskpd:
18082 case clang::X86::BI__builtin_ia32_pmovmskb128:
18083 case clang::X86::BI__builtin_ia32_pmovmskb256:
18084 case clang::X86::BI__builtin_ia32_movmskps256:
18085 case clang::X86::BI__builtin_ia32_movmskpd256: {
18086 APValue Source;
18087 if (!Evaluate(Source, Info, E->getArg(0)))
18088 return false;
18089 unsigned SourceLen = Source.getVectorLength();
18090 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
18091 QualType ElemQT = VT->getElementType();
18092 unsigned ResultLen = Info.Ctx.getTypeSize(
18093 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
18094 APInt Result(ResultLen, 0);
18095
18096 for (unsigned I = 0; I != SourceLen; ++I) {
18097 APInt Elem;
18098 if (ElemQT->isIntegerType()) {
18099 Elem = Source.getVectorElt(I).getInt();
18100 } else if (ElemQT->isRealFloatingType()) {
18101 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
18102 } else {
18103 return false;
18104 }
18105 Result.setBitVal(I, Elem.isNegative());
18106 }
18107 return Success(Result, E);
18108 }
18109
18110 case clang::X86::BI__builtin_ia32_bextr_u32:
18111 case clang::X86::BI__builtin_ia32_bextr_u64:
18112 case clang::X86::BI__builtin_ia32_bextri_u32:
18113 case clang::X86::BI__builtin_ia32_bextri_u64: {
18114 APSInt Val, Idx;
18115 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18116 !EvaluateInteger(E->getArg(1), Idx, Info))
18117 return false;
18118
18119 unsigned BitWidth = Val.getBitWidth();
18120 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
18121 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
18122 Length = Length > BitWidth ? BitWidth : Length;
18123
18124 // Handle out of bounds cases.
18125 if (Length == 0 || Shift >= BitWidth)
18126 return Success(0, E);
18127
18128 uint64_t Result = Val.getZExtValue() >> Shift;
18129 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
18130 return Success(Result, E);
18131 }
18132
18133 case clang::X86::BI__builtin_ia32_bzhi_si:
18134 case clang::X86::BI__builtin_ia32_bzhi_di: {
18135 APSInt Val, Idx;
18136 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18137 !EvaluateInteger(E->getArg(1), Idx, Info))
18138 return false;
18139
18140 unsigned BitWidth = Val.getBitWidth();
18141 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
18142 if (Index < BitWidth)
18143 Val.clearHighBits(BitWidth - Index);
18144 return Success(Val, E);
18145 }
18146
18147 case clang::X86::BI__builtin_ia32_ktestcqi:
18148 case clang::X86::BI__builtin_ia32_ktestchi:
18149 case clang::X86::BI__builtin_ia32_ktestcsi:
18150 case clang::X86::BI__builtin_ia32_ktestcdi: {
18151 APSInt A, B;
18152 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18153 !EvaluateInteger(E->getArg(1), B, Info))
18154 return false;
18155
18156 return Success((~A & B) == 0, E);
18157 }
18158
18159 case clang::X86::BI__builtin_ia32_ktestzqi:
18160 case clang::X86::BI__builtin_ia32_ktestzhi:
18161 case clang::X86::BI__builtin_ia32_ktestzsi:
18162 case clang::X86::BI__builtin_ia32_ktestzdi: {
18163 APSInt A, B;
18164 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18165 !EvaluateInteger(E->getArg(1), B, Info))
18166 return false;
18167
18168 return Success((A & B) == 0, E);
18169 }
18170
18171 case clang::X86::BI__builtin_ia32_kortestcqi:
18172 case clang::X86::BI__builtin_ia32_kortestchi:
18173 case clang::X86::BI__builtin_ia32_kortestcsi:
18174 case clang::X86::BI__builtin_ia32_kortestcdi: {
18175 APSInt A, B;
18176 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18177 !EvaluateInteger(E->getArg(1), B, Info))
18178 return false;
18179
18180 return Success(~(A | B) == 0, E);
18181 }
18182
18183 case clang::X86::BI__builtin_ia32_kortestzqi:
18184 case clang::X86::BI__builtin_ia32_kortestzhi:
18185 case clang::X86::BI__builtin_ia32_kortestzsi:
18186 case clang::X86::BI__builtin_ia32_kortestzdi: {
18187 APSInt A, B;
18188 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18189 !EvaluateInteger(E->getArg(1), B, Info))
18190 return false;
18191
18192 return Success((A | B) == 0, E);
18193 }
18194
18195 case clang::X86::BI__builtin_ia32_kunpckhi:
18196 case clang::X86::BI__builtin_ia32_kunpckdi:
18197 case clang::X86::BI__builtin_ia32_kunpcksi: {
18198 APSInt A, B;
18199 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18200 !EvaluateInteger(E->getArg(1), B, Info))
18201 return false;
18202
18203 // Generic kunpack: extract lower half of each operand and concatenate
18204 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
18205 unsigned BW = A.getBitWidth();
18206 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
18207 return Success(Result, E);
18208 }
18209
18210 case clang::X86::BI__builtin_ia32_lzcnt_u16:
18211 case clang::X86::BI__builtin_ia32_lzcnt_u32:
18212 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
18213 APSInt Val;
18214 if (!EvaluateInteger(E->getArg(0), Val, Info))
18215 return false;
18216 return Success(Val.countLeadingZeros(), E);
18217 }
18218
18219 case clang::X86::BI__builtin_ia32_tzcnt_u16:
18220 case clang::X86::BI__builtin_ia32_tzcnt_u32:
18221 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
18222 APSInt Val;
18223 if (!EvaluateInteger(E->getArg(0), Val, Info))
18224 return false;
18225 return Success(Val.countTrailingZeros(), E);
18226 }
18227
18228 case clang::X86::BI__builtin_ia32_pdep_si:
18229 case clang::X86::BI__builtin_ia32_pdep_di:
18230 case Builtin::BI__builtin_elementwise_pdep: {
18231 APSInt Val, Msk;
18232 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18233 !EvaluateInteger(E->getArg(1), Msk, Info))
18234 return false;
18235 return Success(llvm::APIntOps::pdep(Val, Msk), E);
18236 }
18237
18238 case clang::X86::BI__builtin_ia32_pext_si:
18239 case clang::X86::BI__builtin_ia32_pext_di:
18240 case Builtin::BI__builtin_elementwise_pext: {
18241 APSInt Val, Msk;
18242 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18243 !EvaluateInteger(E->getArg(1), Msk, Info))
18244 return false;
18245 return Success(llvm::APIntOps::pext(Val, Msk), E);
18246 }
18247 case X86::BI__builtin_ia32_ptestz128:
18248 case X86::BI__builtin_ia32_ptestz256:
18249 case X86::BI__builtin_ia32_vtestzps:
18250 case X86::BI__builtin_ia32_vtestzps256:
18251 case X86::BI__builtin_ia32_vtestzpd:
18252 case X86::BI__builtin_ia32_vtestzpd256: {
18253 return EvalTestOp(
18254 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
18255 }
18256 case X86::BI__builtin_ia32_ptestc128:
18257 case X86::BI__builtin_ia32_ptestc256:
18258 case X86::BI__builtin_ia32_vtestcps:
18259 case X86::BI__builtin_ia32_vtestcps256:
18260 case X86::BI__builtin_ia32_vtestcpd:
18261 case X86::BI__builtin_ia32_vtestcpd256: {
18262 return EvalTestOp(
18263 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
18264 }
18265 case X86::BI__builtin_ia32_ptestnzc128:
18266 case X86::BI__builtin_ia32_ptestnzc256:
18267 case X86::BI__builtin_ia32_vtestnzcps:
18268 case X86::BI__builtin_ia32_vtestnzcps256:
18269 case X86::BI__builtin_ia32_vtestnzcpd:
18270 case X86::BI__builtin_ia32_vtestnzcpd256: {
18271 return EvalTestOp([](const APInt &A, const APInt &B) {
18272 return ((A & B) != 0) && ((~A & B) != 0);
18273 });
18274 }
18275 case X86::BI__builtin_ia32_kandqi:
18276 case X86::BI__builtin_ia32_kandhi:
18277 case X86::BI__builtin_ia32_kandsi:
18278 case X86::BI__builtin_ia32_kanddi: {
18279 return HandleMaskBinOp(
18280 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
18281 }
18282
18283 case X86::BI__builtin_ia32_kandnqi:
18284 case X86::BI__builtin_ia32_kandnhi:
18285 case X86::BI__builtin_ia32_kandnsi:
18286 case X86::BI__builtin_ia32_kandndi: {
18287 return HandleMaskBinOp(
18288 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
18289 }
18290
18291 case X86::BI__builtin_ia32_korqi:
18292 case X86::BI__builtin_ia32_korhi:
18293 case X86::BI__builtin_ia32_korsi:
18294 case X86::BI__builtin_ia32_kordi: {
18295 return HandleMaskBinOp(
18296 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
18297 }
18298
18299 case X86::BI__builtin_ia32_kxnorqi:
18300 case X86::BI__builtin_ia32_kxnorhi:
18301 case X86::BI__builtin_ia32_kxnorsi:
18302 case X86::BI__builtin_ia32_kxnordi: {
18303 return HandleMaskBinOp(
18304 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
18305 }
18306
18307 case X86::BI__builtin_ia32_kxorqi:
18308 case X86::BI__builtin_ia32_kxorhi:
18309 case X86::BI__builtin_ia32_kxorsi:
18310 case X86::BI__builtin_ia32_kxordi: {
18311 return HandleMaskBinOp(
18312 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
18313 }
18314
18315 case X86::BI__builtin_ia32_knotqi:
18316 case X86::BI__builtin_ia32_knothi:
18317 case X86::BI__builtin_ia32_knotsi:
18318 case X86::BI__builtin_ia32_knotdi: {
18319 APSInt Val;
18320 if (!EvaluateInteger(E->getArg(0), Val, Info))
18321 return false;
18322 APSInt Result = ~Val;
18323 return Success(APValue(Result), E);
18324 }
18325
18326 case X86::BI__builtin_ia32_kaddqi:
18327 case X86::BI__builtin_ia32_kaddhi:
18328 case X86::BI__builtin_ia32_kaddsi:
18329 case X86::BI__builtin_ia32_kadddi: {
18330 return HandleMaskBinOp(
18331 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
18332 }
18333
18334 case X86::BI__builtin_ia32_kmovb:
18335 case X86::BI__builtin_ia32_kmovw:
18336 case X86::BI__builtin_ia32_kmovd:
18337 case X86::BI__builtin_ia32_kmovq: {
18338 APSInt Val;
18339 if (!EvaluateInteger(E->getArg(0), Val, Info))
18340 return false;
18341 return Success(Val, E);
18342 }
18343
18344 case X86::BI__builtin_ia32_kshiftliqi:
18345 case X86::BI__builtin_ia32_kshiftlihi:
18346 case X86::BI__builtin_ia32_kshiftlisi:
18347 case X86::BI__builtin_ia32_kshiftlidi: {
18348 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
18349 unsigned Amt = RHS.getZExtValue() & 0xFF;
18350 if (Amt >= LHS.getBitWidth())
18351 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18352 return APSInt(LHS.shl(Amt), LHS.isUnsigned());
18353 });
18354 }
18355
18356 case X86::BI__builtin_ia32_kshiftriqi:
18357 case X86::BI__builtin_ia32_kshiftrihi:
18358 case X86::BI__builtin_ia32_kshiftrisi:
18359 case X86::BI__builtin_ia32_kshiftridi: {
18360 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
18361 unsigned Amt = RHS.getZExtValue() & 0xFF;
18362 if (Amt >= LHS.getBitWidth())
18363 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18364 return APSInt(LHS.lshr(Amt), LHS.isUnsigned());
18365 });
18366 }
18367
18368 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
18369 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
18370 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
18371 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
18372 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
18373 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
18374 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
18375 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
18376 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
18377 APValue Vec;
18378 APSInt IdxAPS;
18379 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
18380 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
18381 return false;
18382 unsigned N = Vec.getVectorLength();
18383 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
18384 return Success(Vec.getVectorElt(Idx).getInt(), E);
18385 }
18386
18387 case clang::X86::BI__builtin_ia32_cvtb2mask128:
18388 case clang::X86::BI__builtin_ia32_cvtb2mask256:
18389 case clang::X86::BI__builtin_ia32_cvtb2mask512:
18390 case clang::X86::BI__builtin_ia32_cvtw2mask128:
18391 case clang::X86::BI__builtin_ia32_cvtw2mask256:
18392 case clang::X86::BI__builtin_ia32_cvtw2mask512:
18393 case clang::X86::BI__builtin_ia32_cvtd2mask128:
18394 case clang::X86::BI__builtin_ia32_cvtd2mask256:
18395 case clang::X86::BI__builtin_ia32_cvtd2mask512:
18396 case clang::X86::BI__builtin_ia32_cvtq2mask128:
18397 case clang::X86::BI__builtin_ia32_cvtq2mask256:
18398 case clang::X86::BI__builtin_ia32_cvtq2mask512: {
18399 assert(E->getNumArgs() == 1);
18400 APValue Vec;
18401 if (!EvaluateVector(E->getArg(0), Vec, Info))
18402 return false;
18403
18404 unsigned VectorLen = Vec.getVectorLength();
18405 unsigned RetWidth = Info.Ctx.getIntWidth(E->getType());
18406 llvm::APInt Bits(RetWidth, 0);
18407
18408 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
18409 const APSInt &A = Vec.getVectorElt(ElemNum).getInt();
18410 unsigned MSB = A[A.getBitWidth() - 1];
18411 Bits.setBitVal(ElemNum, MSB);
18412 }
18413
18414 APSInt RetMask(Bits, /*isUnsigned=*/true);
18415 return Success(APValue(RetMask), E);
18416 }
18417
18418 case clang::X86::BI__builtin_ia32_cmpb128_mask:
18419 case clang::X86::BI__builtin_ia32_cmpw128_mask:
18420 case clang::X86::BI__builtin_ia32_cmpd128_mask:
18421 case clang::X86::BI__builtin_ia32_cmpq128_mask:
18422 case clang::X86::BI__builtin_ia32_cmpb256_mask:
18423 case clang::X86::BI__builtin_ia32_cmpw256_mask:
18424 case clang::X86::BI__builtin_ia32_cmpd256_mask:
18425 case clang::X86::BI__builtin_ia32_cmpq256_mask:
18426 case clang::X86::BI__builtin_ia32_cmpb512_mask:
18427 case clang::X86::BI__builtin_ia32_cmpw512_mask:
18428 case clang::X86::BI__builtin_ia32_cmpd512_mask:
18429 case clang::X86::BI__builtin_ia32_cmpq512_mask:
18430 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
18431 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
18432 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
18433 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
18434 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
18435 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
18436 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
18437 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
18438 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
18439 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
18440 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
18441 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
18442 assert(E->getNumArgs() == 4);
18443
18444 bool IsUnsigned =
18445 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
18446 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpw512_mask);
18447
18448 APValue LHS, RHS;
18449 APSInt Mask, Opcode;
18450 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
18451 !EvaluateVector(E->getArg(1), RHS, Info) ||
18452 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
18453 !EvaluateInteger(E->getArg(3), Mask, Info))
18454 return false;
18455
18456 assert(LHS.getVectorLength() == RHS.getVectorLength());
18457
18458 unsigned VectorLen = LHS.getVectorLength();
18459 unsigned RetWidth = Mask.getBitWidth();
18460
18461 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
18462
18463 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
18464 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
18465 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
18466 bool Result = false;
18467
18468 switch (Opcode.getExtValue() & 0x7) {
18469 case 0: // _MM_CMPINT_EQ
18470 Result = (A == B);
18471 break;
18472 case 1: // _MM_CMPINT_LT
18473 Result = IsUnsigned ? A.ult(B) : A.slt(B);
18474 break;
18475 case 2: // _MM_CMPINT_LE
18476 Result = IsUnsigned ? A.ule(B) : A.sle(B);
18477 break;
18478 case 3: // _MM_CMPINT_FALSE
18479 Result = false;
18480 break;
18481 case 4: // _MM_CMPINT_NE
18482 Result = (A != B);
18483 break;
18484 case 5: // _MM_CMPINT_NLT (>=)
18485 Result = IsUnsigned ? A.uge(B) : A.sge(B);
18486 break;
18487 case 6: // _MM_CMPINT_NLE (>)
18488 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
18489 break;
18490 case 7: // _MM_CMPINT_TRUE
18491 Result = true;
18492 break;
18493 }
18494
18495 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
18496 }
18497
18498 return Success(APValue(RetMask), E);
18499 }
18500 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
18501 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
18502 case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
18503 assert(E->getNumArgs() == 3);
18504
18505 APValue Source, ShuffleMask;
18506 APSInt ZeroMask;
18507 if (!EvaluateVector(E->getArg(0), Source, Info) ||
18508 !EvaluateVector(E->getArg(1), ShuffleMask, Info) ||
18509 !EvaluateInteger(E->getArg(2), ZeroMask, Info))
18510 return false;
18511
18512 assert(Source.getVectorLength() == ShuffleMask.getVectorLength());
18513 assert(ZeroMask.getBitWidth() == Source.getVectorLength());
18514
18515 unsigned NumBytesInQWord = 8;
18516 unsigned NumBitsInByte = 8;
18517 unsigned NumBytes = Source.getVectorLength();
18518 unsigned NumQWords = NumBytes / NumBytesInQWord;
18519 unsigned RetWidth = ZeroMask.getBitWidth();
18520 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
18521
18522 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
18523 APInt SourceQWord(64, 0);
18524 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
18525 uint64_t Byte = Source.getVectorElt(QWordId * NumBytesInQWord + ByteIdx)
18526 .getInt()
18527 .getZExtValue();
18528 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
18529 }
18530
18531 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
18532 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
18533 unsigned M =
18534 ShuffleMask.getVectorElt(SelIdx).getInt().getZExtValue() & 0x3F;
18535 if (ZeroMask[SelIdx]) {
18536 RetMask.setBitVal(SelIdx, SourceQWord[M]);
18537 }
18538 }
18539 }
18540 return Success(APValue(RetMask), E);
18541 }
18542 }
18543}
18544
18545/// Determine whether this is a pointer past the end of the complete
18546/// object referred to by the lvalue.
18548 const LValue &LV) {
18549 // A null pointer can be viewed as being "past the end" but we don't
18550 // choose to look at it that way here.
18551 if (!LV.getLValueBase())
18552 return false;
18553
18554 // If the designator is valid and refers to a subobject, we're not pointing
18555 // past the end.
18556 if (!LV.getLValueDesignator().Invalid &&
18557 !LV.getLValueDesignator().isOnePastTheEnd())
18558 return false;
18559
18560 // A pointer to an incomplete type might be past-the-end if the type's size is
18561 // zero. We cannot tell because the type is incomplete.
18562 QualType Ty = getType(LV.getLValueBase());
18563 if (Ty->isIncompleteType())
18564 return true;
18565
18566 // Can't be past the end of an invalid object.
18567 if (LV.getLValueDesignator().Invalid)
18568 return false;
18569
18570 // We're a past-the-end pointer if we point to the byte after the object,
18571 // no matter what our type or path is.
18572 auto Size = Ctx.getTypeSizeInChars(Ty);
18573 return LV.getLValueOffset() == Size;
18574}
18575
18576namespace {
18577
18578/// Data recursive integer evaluator of certain binary operators.
18579///
18580/// We use a data recursive algorithm for binary operators so that we are able
18581/// to handle extreme cases of chained binary operators without causing stack
18582/// overflow.
18583class DataRecursiveIntBinOpEvaluator {
18584 struct EvalResult {
18585 APValue Val;
18586 bool Failed = false;
18587
18588 EvalResult() = default;
18589
18590 void swap(EvalResult &RHS) {
18591 Val.swap(RHS.Val);
18592 Failed = RHS.Failed;
18593 RHS.Failed = false;
18594 }
18595 };
18596
18597 struct Job {
18598 const Expr *E;
18599 EvalResult LHSResult; // meaningful only for binary operator expression.
18600 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
18601
18602 Job() = default;
18603 Job(Job &&) = default;
18604
18605 void startSpeculativeEval(EvalInfo &Info) {
18606 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
18607 }
18608
18609 private:
18610 SpeculativeEvaluationRAII SpecEvalRAII;
18611 };
18612
18613 SmallVector<Job, 16> Queue;
18614
18615 IntExprEvaluator &IntEval;
18616 EvalInfo &Info;
18617 APValue &FinalResult;
18618
18619public:
18620 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
18621 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
18622
18623 /// True if \param E is a binary operator that we are going to handle
18624 /// data recursively.
18625 /// We handle binary operators that are comma, logical, or that have operands
18626 /// with integral or enumeration type.
18627 static bool shouldEnqueue(const BinaryOperator *E) {
18628 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
18632 }
18633
18634 bool Traverse(const BinaryOperator *E) {
18635 enqueue(E);
18636 EvalResult PrevResult;
18637 while (!Queue.empty())
18638 process(PrevResult);
18639
18640 if (PrevResult.Failed) return false;
18641
18642 FinalResult.swap(PrevResult.Val);
18643 return true;
18644 }
18645
18646private:
18647 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
18648 return IntEval.Success(Value, E, Result);
18649 }
18650 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
18651 return IntEval.Success(Value, E, Result);
18652 }
18653 bool Error(const Expr *E) {
18654 return IntEval.Error(E);
18655 }
18656 bool Error(const Expr *E, diag::kind D) {
18657 return IntEval.Error(E, D);
18658 }
18659
18660 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
18661 return Info.CCEDiag(E, D);
18662 }
18663
18664 // Returns true if visiting the RHS is necessary, false otherwise.
18665 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18666 bool &SuppressRHSDiags);
18667
18668 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18669 const BinaryOperator *E, APValue &Result);
18670
18671 void EvaluateExpr(const Expr *E, EvalResult &Result) {
18672 Result.Failed = !Evaluate(Result.Val, Info, E);
18673 if (Result.Failed)
18674 Result.Val = APValue();
18675 }
18676
18677 void process(EvalResult &Result);
18678
18679 void enqueue(const Expr *E) {
18680 E = E->IgnoreParens();
18681 Queue.resize(Queue.size()+1);
18682 Queue.back().E = E;
18683 Queue.back().Kind = Job::AnyExprKind;
18684 }
18685};
18686
18687}
18688
18689bool DataRecursiveIntBinOpEvaluator::
18690 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18691 bool &SuppressRHSDiags) {
18692 if (E->getOpcode() == BO_Comma) {
18693 // Ignore LHS but note if we could not evaluate it.
18694 if (LHSResult.Failed)
18695 return Info.noteSideEffect();
18696 return true;
18697 }
18698
18699 if (E->isLogicalOp()) {
18700 bool LHSAsBool;
18701 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
18702 // We were able to evaluate the LHS, see if we can get away with not
18703 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
18704 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
18705 Success(LHSAsBool, E, LHSResult.Val);
18706 return false; // Ignore RHS
18707 }
18708 } else {
18709 LHSResult.Failed = true;
18710
18711 // Since we weren't able to evaluate the left hand side, it
18712 // might have had side effects.
18713 if (!Info.noteSideEffect())
18714 return false;
18715
18716 // We can't evaluate the LHS; however, sometimes the result
18717 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18718 // Don't ignore RHS and suppress diagnostics from this arm.
18719 SuppressRHSDiags = true;
18720 }
18721
18722 return true;
18723 }
18724
18725 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18727
18728 if (LHSResult.Failed && !Info.noteFailure())
18729 return false; // Ignore RHS;
18730
18731 return true;
18732}
18733
18734static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
18735 bool IsSub) {
18736 // Compute the new offset in the appropriate width, wrapping at 64 bits.
18737 // FIXME: When compiling for a 32-bit target, we should use 32-bit
18738 // offsets.
18739 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
18740 CharUnits &Offset = LVal.getLValueOffset();
18741 uint64_t Offset64 = Offset.getQuantity();
18742 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
18743 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
18744 : Offset64 + Index64);
18745}
18746
18747bool DataRecursiveIntBinOpEvaluator::
18748 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18749 const BinaryOperator *E, APValue &Result) {
18750 if (E->getOpcode() == BO_Comma) {
18751 if (RHSResult.Failed)
18752 return false;
18753 Result = RHSResult.Val;
18754 return true;
18755 }
18756
18757 if (E->isLogicalOp()) {
18758 bool lhsResult, rhsResult;
18759 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
18760 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
18761
18762 if (LHSIsOK) {
18763 if (RHSIsOK) {
18764 if (E->getOpcode() == BO_LOr)
18765 return Success(lhsResult || rhsResult, E, Result);
18766 else
18767 return Success(lhsResult && rhsResult, E, Result);
18768 }
18769 } else {
18770 if (RHSIsOK) {
18771 // We can't evaluate the LHS; however, sometimes the result
18772 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18773 if (rhsResult == (E->getOpcode() == BO_LOr))
18774 return Success(rhsResult, E, Result);
18775 }
18776 }
18777
18778 return false;
18779 }
18780
18781 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18783
18784 if (LHSResult.Failed || RHSResult.Failed)
18785 return false;
18786
18787 const APValue &LHSVal = LHSResult.Val;
18788 const APValue &RHSVal = RHSResult.Val;
18789
18790 // Handle cases like (unsigned long)&a + 4.
18791 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
18792 Result = LHSVal;
18793 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
18794 return true;
18795 }
18796
18797 // Handle cases like 4 + (unsigned long)&a
18798 if (E->getOpcode() == BO_Add &&
18799 RHSVal.isLValue() && LHSVal.isInt()) {
18800 Result = RHSVal;
18801 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
18802 return true;
18803 }
18804
18805 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
18806 // Handle (intptr_t)&&A - (intptr_t)&&B.
18807 if (!LHSVal.getLValueOffset().isZero() ||
18808 !RHSVal.getLValueOffset().isZero())
18809 return false;
18810 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
18811 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
18812 if (!LHSExpr || !RHSExpr)
18813 return false;
18814 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
18815 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
18816 if (!LHSAddrExpr || !RHSAddrExpr)
18817 return false;
18818 // Make sure both labels come from the same function.
18819 if (LHSAddrExpr->getLabel()->getDeclContext() !=
18820 RHSAddrExpr->getLabel()->getDeclContext())
18821 return false;
18822 Result = APValue(LHSAddrExpr, RHSAddrExpr);
18823 return true;
18824 }
18825
18826 // All the remaining cases expect both operands to be an integer
18827 if (!LHSVal.isInt() || !RHSVal.isInt())
18828 return Error(E);
18829
18830 // Set up the width and signedness manually, in case it can't be deduced
18831 // from the operation we're performing.
18832 // FIXME: Don't do this in the cases where we can deduce it.
18833 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
18835 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
18836 RHSVal.getInt(), Value))
18837 return false;
18838 return Success(Value, E, Result);
18839}
18840
18841void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
18842 Job &job = Queue.back();
18843
18844 switch (job.Kind) {
18845 case Job::AnyExprKind: {
18846 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
18847 if (shouldEnqueue(Bop)) {
18848 job.Kind = Job::BinOpKind;
18849 enqueue(Bop->getLHS());
18850 return;
18851 }
18852 }
18853
18854 EvaluateExpr(job.E, Result);
18855 Queue.pop_back();
18856 return;
18857 }
18858
18859 case Job::BinOpKind: {
18860 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
18861 bool SuppressRHSDiags = false;
18862 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
18863 Queue.pop_back();
18864 return;
18865 }
18866 if (SuppressRHSDiags)
18867 job.startSpeculativeEval(Info);
18868 job.LHSResult.swap(Result);
18869 job.Kind = Job::BinOpVisitedLHSKind;
18870 enqueue(Bop->getRHS());
18871 return;
18872 }
18873
18874 case Job::BinOpVisitedLHSKind: {
18875 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
18876 EvalResult RHS;
18877 RHS.swap(Result);
18878 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
18879 Queue.pop_back();
18880 return;
18881 }
18882 }
18883
18884 llvm_unreachable("Invalid Job::Kind!");
18885}
18886
18887namespace {
18888enum class CmpResult {
18889 Unequal,
18890 Less,
18891 Equal,
18892 Greater,
18893 Unordered,
18894};
18895}
18896
18897template <class SuccessCB, class AfterCB>
18898static bool
18900 SuccessCB &&Success, AfterCB &&DoAfter) {
18901 assert(!E->isValueDependent());
18902 assert(E->isComparisonOp() && "expected comparison operator");
18903 assert((E->getOpcode() == BO_Cmp ||
18905 "unsupported binary expression evaluation");
18906 auto Error = [&](const Expr *E) {
18907 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
18908 return false;
18909 };
18910
18911 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
18912 bool IsEquality = E->isEqualityOp();
18913
18914 QualType LHSTy = E->getLHS()->getType();
18915 QualType RHSTy = E->getRHS()->getType();
18916
18917 if (LHSTy->isIntegralOrEnumerationType() &&
18918 RHSTy->isIntegralOrEnumerationType()) {
18919 APSInt LHS, RHS;
18920 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
18921 if (!LHSOK && !Info.noteFailure())
18922 return false;
18923 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
18924 return false;
18925 if (LHS < RHS)
18926 return Success(CmpResult::Less, E);
18927 if (LHS > RHS)
18928 return Success(CmpResult::Greater, E);
18929 return Success(CmpResult::Equal, E);
18930 }
18931
18932 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
18933 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
18934 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
18935
18936 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
18937 if (!LHSOK && !Info.noteFailure())
18938 return false;
18939 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
18940 return false;
18941 if (LHSFX < RHSFX)
18942 return Success(CmpResult::Less, E);
18943 if (LHSFX > RHSFX)
18944 return Success(CmpResult::Greater, E);
18945 return Success(CmpResult::Equal, E);
18946 }
18947
18948 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
18949 ComplexValue LHS, RHS;
18950 bool LHSOK;
18951 if (E->isAssignmentOp()) {
18952 LValue LV;
18953 EvaluateLValue(E->getLHS(), LV, Info);
18954 LHSOK = false;
18955 } else if (LHSTy->isRealFloatingType()) {
18956 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
18957 if (LHSOK) {
18958 LHS.makeComplexFloat();
18959 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
18960 }
18961 } else {
18962 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
18963 }
18964 if (!LHSOK && !Info.noteFailure())
18965 return false;
18966
18967 if (E->getRHS()->getType()->isRealFloatingType()) {
18968 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
18969 return false;
18970 RHS.makeComplexFloat();
18971 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
18972 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
18973 return false;
18974
18975 if (LHS.isComplexFloat()) {
18976 APFloat::cmpResult CR_r =
18977 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
18978 APFloat::cmpResult CR_i =
18979 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
18980 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
18981 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
18982 } else {
18983 assert(IsEquality && "invalid complex comparison");
18984 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
18985 LHS.getComplexIntImag() == RHS.getComplexIntImag();
18986 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
18987 }
18988 }
18989
18990 if (LHSTy->isRealFloatingType() &&
18991 RHSTy->isRealFloatingType()) {
18992 APFloat RHS(0.0), LHS(0.0);
18993
18994 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
18995 if (!LHSOK && !Info.noteFailure())
18996 return false;
18997
18998 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
18999 return false;
19000
19001 assert(E->isComparisonOp() && "Invalid binary operator!");
19002 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
19003 if (!Info.InConstantContext &&
19004 APFloatCmpResult == APFloat::cmpUnordered &&
19005 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
19006 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
19007 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
19008 return false;
19009 }
19010 auto GetCmpRes = [&]() {
19011 switch (APFloatCmpResult) {
19012 case APFloat::cmpEqual:
19013 return CmpResult::Equal;
19014 case APFloat::cmpLessThan:
19015 return CmpResult::Less;
19016 case APFloat::cmpGreaterThan:
19017 return CmpResult::Greater;
19018 case APFloat::cmpUnordered:
19019 return CmpResult::Unordered;
19020 }
19021 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
19022 };
19023 return Success(GetCmpRes(), E);
19024 }
19025
19026 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
19027 LValue LHSValue, RHSValue;
19028
19029 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
19030 if (!LHSOK && !Info.noteFailure())
19031 return false;
19032
19033 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19034 return false;
19035
19036 // Reject differing bases from the normal codepath; we special-case
19037 // comparisons to null.
19038 if (!HasSameBase(LHSValue, RHSValue)) {
19039 // Bail out early if we're checking potential constant expression.
19040 // Otherwise, prefer to diagnose other issues.
19041 if (Info.checkingPotentialConstantExpression() &&
19042 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
19043 return false;
19044 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
19045 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
19046 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
19047 Info.FFDiag(E, DiagID)
19048 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
19049 return false;
19050 };
19051 // Inequalities and subtractions between unrelated pointers have
19052 // unspecified or undefined behavior.
19053 if (!IsEquality)
19054 return DiagComparison(
19055 diag::note_constexpr_pointer_comparison_unspecified);
19056 // A constant address may compare equal to the address of a symbol.
19057 // The one exception is that address of an object cannot compare equal
19058 // to a null pointer constant.
19059 // TODO: Should we restrict this to actual null pointers, and exclude the
19060 // case of zero cast to pointer type?
19061 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
19062 (!RHSValue.Base && !RHSValue.Offset.isZero()))
19063 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
19064 !RHSValue.Base);
19065 // C++2c [intro.object]/10:
19066 // Two objects [...] may have the same address if [...] they are both
19067 // potentially non-unique objects.
19068 // C++2c [intro.object]/9:
19069 // An object is potentially non-unique if it is a string literal object,
19070 // the backing array of an initializer list, or a subobject thereof.
19071 //
19072 // This makes the comparison result unspecified, so it's not a constant
19073 // expression.
19074 //
19075 // TODO: Do we need to handle the initializer list case here?
19076 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
19077 return DiagComparison(diag::note_constexpr_literal_comparison);
19078 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
19079 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
19080 !IsOpaqueConstantCall(LHSValue));
19081 // We can't tell whether weak symbols will end up pointing to the same
19082 // object.
19083 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
19084 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
19085 !IsWeakLValue(LHSValue));
19086 // We can't compare the address of the start of one object with the
19087 // past-the-end address of another object, per C++ DR1652.
19088 if (LHSValue.Base && LHSValue.Offset.isZero() &&
19089 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
19090 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
19091 true);
19092 if (RHSValue.Base && RHSValue.Offset.isZero() &&
19093 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
19094 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
19095 false);
19096 // We can't tell whether an object is at the same address as another
19097 // zero sized object.
19098 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
19099 (LHSValue.Base && isZeroSized(RHSValue)))
19100 return DiagComparison(
19101 diag::note_constexpr_pointer_comparison_zero_sized);
19102 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
19103 return DiagComparison(
19104 diag::note_constexpr_pointer_comparison_unspecified);
19105 // FIXME: Verify both variables are live.
19106 return Success(CmpResult::Unequal, E);
19107 }
19108
19109 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
19110 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
19111
19112 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
19113 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
19114
19115 // C++11 [expr.rel]p2:
19116 // - If two pointers point to non-static data members of the same object,
19117 // or to subobjects or array elements fo such members, recursively, the
19118 // pointer to the later declared member compares greater provided the
19119 // two members have the same access control and provided their class is
19120 // not a union.
19121 // [...]
19122 // - Otherwise pointer comparisons are unspecified.
19123 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
19124 bool WasArrayIndex;
19125 unsigned Mismatch = FindDesignatorMismatch(
19126 LHSValue.Base.isNull() ? QualType()
19127 : getType(LHSValue.Base).getNonReferenceType(),
19128 LHSDesignator, RHSDesignator, WasArrayIndex);
19129 // At the point where the designators diverge, the comparison has a
19130 // specified value if:
19131 // - we are comparing array indices
19132 // - we are comparing fields of a union, or fields with the same access
19133 // Otherwise, the result is unspecified and thus the comparison is not a
19134 // constant expression.
19135 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
19136 Mismatch < RHSDesignator.Entries.size()) {
19137 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
19138 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
19139 if (!LF && !RF)
19140 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
19141 else if (!LF)
19142 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
19143 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
19144 << RF->getParent() << RF;
19145 else if (!RF)
19146 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
19147 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
19148 << LF->getParent() << LF;
19149 else if (!LF->getParent()->isUnion() &&
19150 LF->getAccess() != RF->getAccess())
19151 Info.CCEDiag(E,
19152 diag::note_constexpr_pointer_comparison_differing_access)
19153 << LF << LF->getAccess() << RF << RF->getAccess()
19154 << LF->getParent();
19155 }
19156 }
19157
19158 // The comparison here must be unsigned, and performed with the same
19159 // width as the pointer.
19160 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
19161 uint64_t CompareLHS = LHSOffset.getQuantity();
19162 uint64_t CompareRHS = RHSOffset.getQuantity();
19163 assert(PtrSize <= 64 && "Unexpected pointer width");
19164 uint64_t Mask = ~0ULL >> (64 - PtrSize);
19165 CompareLHS &= Mask;
19166 CompareRHS &= Mask;
19167
19168 // If there is a base and this is a relational operator, we can only
19169 // compare pointers within the object in question; otherwise, the result
19170 // depends on where the object is located in memory.
19171 if (!LHSValue.Base.isNull() && IsRelational) {
19172 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
19173 if (BaseTy->isIncompleteType())
19174 return Error(E);
19175 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
19176 uint64_t OffsetLimit = Size.getQuantity();
19177 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
19178 return Error(E);
19179 }
19180
19181 if (CompareLHS < CompareRHS)
19182 return Success(CmpResult::Less, E);
19183 if (CompareLHS > CompareRHS)
19184 return Success(CmpResult::Greater, E);
19185 return Success(CmpResult::Equal, E);
19186 }
19187
19188 if (LHSTy->isMemberPointerType()) {
19189 assert(IsEquality && "unexpected member pointer operation");
19190 assert(RHSTy->isMemberPointerType() && "invalid comparison");
19191
19192 MemberPtr LHSValue, RHSValue;
19193
19194 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
19195 if (!LHSOK && !Info.noteFailure())
19196 return false;
19197
19198 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19199 return false;
19200
19201 // If either operand is a pointer to a weak function, the comparison is not
19202 // constant.
19203 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
19204 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
19205 << LHSValue.getDecl();
19206 return false;
19207 }
19208 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
19209 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
19210 << RHSValue.getDecl();
19211 return false;
19212 }
19213
19214 // C++11 [expr.eq]p2:
19215 // If both operands are null, they compare equal. Otherwise if only one is
19216 // null, they compare unequal.
19217 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
19218 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
19219 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
19220 }
19221
19222 // Otherwise if either is a pointer to a virtual member function, the
19223 // result is unspecified.
19224 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
19225 if (MD->isVirtual())
19226 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
19227 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
19228 if (MD->isVirtual())
19229 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
19230
19231 // Otherwise they compare equal if and only if they would refer to the
19232 // same member of the same most derived object or the same subobject if
19233 // they were dereferenced with a hypothetical object of the associated
19234 // class type.
19235 bool Equal = LHSValue == RHSValue;
19236 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
19237 }
19238
19239 if (LHSTy->isNullPtrType()) {
19240 assert(E->isComparisonOp() && "unexpected nullptr operation");
19241 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
19242 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
19243 // are compared, the result is true of the operator is <=, >= or ==, and
19244 // false otherwise.
19245 LValue Res;
19246 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
19247 !EvaluatePointer(E->getRHS(), Res, Info))
19248 return false;
19249 return Success(CmpResult::Equal, E);
19250 }
19251
19252 return DoAfter();
19253}
19254
19255bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
19256 if (!CheckLiteralType(Info, E))
19257 return false;
19258
19259 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
19261 switch (CR) {
19262 case CmpResult::Unequal:
19263 llvm_unreachable("should never produce Unequal for three-way comparison");
19264 case CmpResult::Less:
19265 CCR = ComparisonCategoryResult::Less;
19266 break;
19267 case CmpResult::Equal:
19268 CCR = ComparisonCategoryResult::Equal;
19269 break;
19270 case CmpResult::Greater:
19271 CCR = ComparisonCategoryResult::Greater;
19272 break;
19273 case CmpResult::Unordered:
19274 CCR = ComparisonCategoryResult::Unordered;
19275 break;
19276 }
19277 // Evaluation succeeded. Lookup the information for the comparison category
19278 // type and fetch the VarDecl for the result.
19279 const ComparisonCategoryInfo &CmpInfo =
19280 Info.Ctx.CompCategories.getInfoForType(E->getType());
19281 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
19282 // Check and evaluate the result as a constant expression.
19283 LValue LV;
19284 LV.set(VD);
19285 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
19286 return false;
19287 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
19288 ConstantExprKind::Normal);
19289 };
19290 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
19291 return ExprEvaluatorBaseTy::VisitBinCmp(E);
19292 });
19293}
19294
19295bool RecordExprEvaluator::VisitCXXParenListInitExpr(
19296 const CXXParenListInitExpr *E) {
19297 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
19298}
19299
19300bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19301 // We don't support assignment in C. C++ assignments don't get here because
19302 // assignment is an lvalue in C++.
19303 if (E->isAssignmentOp()) {
19304 Error(E);
19305 if (!Info.noteFailure())
19306 return false;
19307 }
19308
19309 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
19310 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
19311
19312 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
19314 "DataRecursiveIntBinOpEvaluator should have handled integral types");
19315
19316 if (E->isComparisonOp()) {
19317 // Evaluate builtin binary comparisons by evaluating them as three-way
19318 // comparisons and then translating the result.
19319 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
19320 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
19321 "should only produce Unequal for equality comparisons");
19322 bool IsEqual = CR == CmpResult::Equal,
19323 IsLess = CR == CmpResult::Less,
19324 IsGreater = CR == CmpResult::Greater;
19325 auto Op = E->getOpcode();
19326 switch (Op) {
19327 default:
19328 llvm_unreachable("unsupported binary operator");
19329 case BO_EQ:
19330 case BO_NE:
19331 return Success(IsEqual == (Op == BO_EQ), E);
19332 case BO_LT:
19333 return Success(IsLess, E);
19334 case BO_GT:
19335 return Success(IsGreater, E);
19336 case BO_LE:
19337 return Success(IsEqual || IsLess, E);
19338 case BO_GE:
19339 return Success(IsEqual || IsGreater, E);
19340 }
19341 };
19342 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
19343 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19344 });
19345 }
19346
19347 QualType LHSTy = E->getLHS()->getType();
19348 QualType RHSTy = E->getRHS()->getType();
19349
19350 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
19351 E->getOpcode() == BO_Sub) {
19352 LValue LHSValue, RHSValue;
19353
19354 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
19355 if (!LHSOK && !Info.noteFailure())
19356 return false;
19357
19358 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19359 return false;
19360
19361 // Reject differing bases from the normal codepath; we special-case
19362 // comparisons to null.
19363 if (!HasSameBase(LHSValue, RHSValue)) {
19364 if (Info.checkingPotentialConstantExpression() &&
19365 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
19366 return false;
19367
19368 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
19369 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
19370
19371 auto DiagArith = [&](unsigned DiagID) {
19372 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
19373 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
19374 Info.FFDiag(E, DiagID) << LHS << RHS;
19375 if (LHSExpr && LHSExpr == RHSExpr)
19376 Info.Note(LHSExpr->getExprLoc(),
19377 diag::note_constexpr_repeated_literal_eval)
19378 << LHSExpr->getSourceRange();
19379 return false;
19380 };
19381
19382 if (!LHSExpr || !RHSExpr)
19383 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
19384
19385 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
19386 return DiagArith(diag::note_constexpr_literal_arith);
19387
19388 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
19389 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
19390 if (!LHSAddrExpr || !RHSAddrExpr)
19391 return Error(E);
19392 // Make sure both labels come from the same function.
19393 if (LHSAddrExpr->getLabel()->getDeclContext() !=
19394 RHSAddrExpr->getLabel()->getDeclContext())
19395 return Error(E);
19396 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
19397 }
19398 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
19399 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
19400
19401 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
19402 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
19403
19404 // C++11 [expr.add]p6:
19405 // Unless both pointers point to elements of the same array object, or
19406 // one past the last element of the array object, the behavior is
19407 // undefined.
19408 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
19409 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
19410 RHSDesignator))
19411 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
19412
19413 QualType Type = E->getLHS()->getType();
19414 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
19415
19416 CharUnits ElementSize;
19417 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
19418 return false;
19419
19420 // As an extension, a type may have zero size (empty struct or union in
19421 // C, array of zero length). Pointer subtraction in such cases has
19422 // undefined behavior, so is not constant.
19423 if (ElementSize.isZero()) {
19424 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
19425 << ElementType;
19426 return false;
19427 }
19428
19429 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
19430 // and produce incorrect results when it overflows. Such behavior
19431 // appears to be non-conforming, but is common, so perhaps we should
19432 // assume the standard intended for such cases to be undefined behavior
19433 // and check for them.
19434
19435 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
19436 // overflow in the final conversion to ptrdiff_t.
19437 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
19438 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
19439 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
19440 false);
19441 APSInt TrueResult = (LHS - RHS) / ElemSize;
19442 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
19443
19444 if (Result.extend(65) != TrueResult &&
19445 !HandleOverflow(Info, E, TrueResult, E->getType()))
19446 return false;
19447 return Success(Result, E);
19448 }
19449
19450 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19451}
19452
19453/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
19454/// a result as the expression's type.
19455bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
19456 const UnaryExprOrTypeTraitExpr *E) {
19457 switch(E->getKind()) {
19458 case UETT_PreferredAlignOf:
19459 case UETT_AlignOf: {
19460 if (E->isArgumentType())
19461 return Success(
19462 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
19463 else
19464 return Success(
19465 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
19466 }
19467
19468 case UETT_PtrAuthTypeDiscriminator: {
19469 if (E->getArgumentType()->isDependentType())
19470 return false;
19471 return Success(
19472 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
19473 }
19474 case UETT_VecStep: {
19475 QualType Ty = E->getTypeOfArgument();
19476
19477 if (Ty->isVectorType()) {
19478 unsigned n = Ty->castAs<VectorType>()->getNumElements();
19479
19480 // The vec_step built-in functions that take a 3-component
19481 // vector return 4. (OpenCL 1.1 spec 6.11.12)
19482 if (n == 3)
19483 n = 4;
19484
19485 return Success(n, E);
19486 } else
19487 return Success(1, E);
19488 }
19489
19490 case UETT_DataSizeOf:
19491 case UETT_SizeOf: {
19492 QualType SrcTy = E->getTypeOfArgument();
19493 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
19494 // the result is the size of the referenced type."
19495 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
19496 SrcTy = Ref->getPointeeType();
19497
19498 CharUnits Sizeof;
19499 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
19500 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
19501 : SizeOfType::SizeOf)) {
19502 return false;
19503 }
19504 return Success(Sizeof, E);
19505 }
19506 case UETT_OpenMPRequiredSimdAlign:
19507 assert(E->isArgumentType());
19508 return Success(
19509 Info.Ctx.toCharUnitsFromBits(
19510 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
19511 .getQuantity(),
19512 E);
19513 case UETT_VectorElements: {
19514 QualType Ty = E->getTypeOfArgument();
19515 // If the vector has a fixed size, we can determine the number of elements
19516 // at compile time.
19517 if (const auto *VT = Ty->getAs<VectorType>())
19518 return Success(VT->getNumElements(), E);
19519
19520 assert(Ty->isSizelessVectorType());
19521 if (Info.InConstantContext)
19522 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
19523 << E->getSourceRange();
19524
19525 return false;
19526 }
19527 case UETT_CountOf: {
19528 QualType Ty = E->getTypeOfArgument();
19529 assert(Ty->isArrayType());
19530
19531 // We don't need to worry about array element qualifiers, so getting the
19532 // unsafe array type is fine.
19533 if (const auto *CAT =
19534 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
19535 return Success(CAT->getSize(), E);
19536 }
19537
19538 assert(!Ty->isConstantSizeType());
19539
19540 // If it's a variable-length array type, we need to check whether it is a
19541 // multidimensional array. If so, we need to check the size expression of
19542 // the VLA to see if it's a constant size. If so, we can return that value.
19543 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
19544 assert(VAT);
19545 if (VAT->getElementType()->isArrayType()) {
19546 // Variable array size expression could be missing (e.g. int a[*][10]) In
19547 // that case, it can't be a constant expression.
19548 if (!VAT->getSizeExpr()) {
19549 Info.FFDiag(E->getBeginLoc());
19550 return false;
19551 }
19552
19553 std::optional<APSInt> Res =
19554 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
19555 if (Res) {
19556 // The resulting value always has type size_t, so we need to make the
19557 // returned APInt have the correct sign and bit-width.
19558 APInt Val{
19559 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
19560 Res->getZExtValue()};
19561 return Success(Val, E);
19562 }
19563 }
19564
19565 // Definitely a variable-length type, which is not an ICE.
19566 // FIXME: Better diagnostic.
19567 Info.FFDiag(E->getBeginLoc());
19568 return false;
19569 }
19570 }
19571
19572 llvm_unreachable("unknown expr/type trait");
19573}
19574
19575bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
19576 Info.Ctx.recordOffsetOfEvaluation(OOE);
19577 CharUnits Result;
19578 unsigned n = OOE->getNumComponents();
19579 if (n == 0)
19580 return Error(OOE);
19581 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
19582 for (unsigned i = 0; i != n; ++i) {
19583 OffsetOfNode ON = OOE->getComponent(i);
19584 switch (ON.getKind()) {
19585 case OffsetOfNode::Array: {
19586 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
19587 APSInt IdxResult;
19588 if (!EvaluateInteger(Idx, IdxResult, Info))
19589 return false;
19590 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
19591 if (!AT)
19592 return Error(OOE);
19593 CurrentType = AT->getElementType();
19594 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
19595 // Reject negative indices, indices too large to fit in int64_t,
19596 // and overflow in the offset computation.
19597 if (IdxResult.isNegative() || IdxResult.getActiveBits() > 63)
19598 return Error(OOE);
19599 int64_t IdxVal = IdxResult.getExtValue();
19600 int64_t ElemSize = ElementSize.getQuantity();
19601 if (IdxVal != 0 &&
19602 ElemSize > std::numeric_limits<int64_t>::max() / IdxVal)
19603 return Error(OOE, diag::note_constexpr_offsetof_overflow);
19604 int64_t Offset = IdxVal * ElemSize;
19605 if (Result.getQuantity() > std::numeric_limits<int64_t>::max() - Offset)
19606 return Error(OOE, diag::note_constexpr_offsetof_overflow);
19608 break;
19609 }
19610
19611 case OffsetOfNode::Field: {
19612 FieldDecl *MemberDecl = ON.getField();
19613 const auto *RD = CurrentType->getAsRecordDecl();
19614 if (!RD)
19615 return Error(OOE);
19616 if (RD->isInvalidDecl()) return false;
19617 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
19618 unsigned i = MemberDecl->getFieldIndex();
19619 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
19620 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
19621 CurrentType = MemberDecl->getType().getNonReferenceType();
19622 break;
19623 }
19624
19626 llvm_unreachable("dependent __builtin_offsetof");
19627
19628 case OffsetOfNode::Base: {
19629 CXXBaseSpecifier *BaseSpec = ON.getBase();
19630 if (BaseSpec->isVirtual())
19631 return Error(OOE);
19632
19633 // Find the layout of the class whose base we are looking into.
19634 const auto *RD = CurrentType->getAsCXXRecordDecl();
19635 if (!RD)
19636 return Error(OOE);
19637 if (RD->isInvalidDecl()) return false;
19638 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
19639
19640 // Find the base class itself.
19641 CurrentType = BaseSpec->getType();
19642 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
19643 if (!BaseRD)
19644 return Error(OOE);
19645
19646 // Add the offset to the base.
19647 Result += RL.getBaseClassOffset(BaseRD);
19648 break;
19649 }
19650 }
19651 }
19652 return Success(Result, OOE);
19653}
19654
19655bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19656 switch (E->getOpcode()) {
19657 default:
19658 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
19659 // See C99 6.6p3.
19660 return Error(E);
19661 case UO_Extension:
19662 // FIXME: Should extension allow i-c-e extension expressions in its scope?
19663 // If so, we could clear the diagnostic ID.
19664 return Visit(E->getSubExpr());
19665 case UO_Plus:
19666 // The result is just the value.
19667 return Visit(E->getSubExpr());
19668 case UO_Minus: {
19669 if (!Visit(E->getSubExpr()))
19670 return false;
19671 if (!Result.isInt()) return Error(E);
19672 const APSInt &Value = Result.getInt();
19673 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
19674 !E->getType().isWrapType()) {
19675 if (Info.checkingForUndefinedBehavior())
19676 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19677 diag::warn_integer_constant_overflow)
19678 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
19679 /*UpperCase=*/true, /*InsertSeparators=*/true)
19680 << E->getType() << E->getSourceRange();
19681
19682 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
19683 E->getType()))
19684 return false;
19685 }
19686 return Success(-Value, E);
19687 }
19688 case UO_Not: {
19689 if (!Visit(E->getSubExpr()))
19690 return false;
19691 if (!Result.isInt()) return Error(E);
19692 return Success(~Result.getInt(), E);
19693 }
19694 case UO_LNot: {
19695 bool bres;
19696 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
19697 return false;
19698 return Success(!bres, E);
19699 }
19700 }
19701}
19702
19703/// HandleCast - This is used to evaluate implicit or explicit casts where the
19704/// result type is integer.
19705bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
19706 const Expr *SubExpr = E->getSubExpr();
19707 QualType DestType = E->getType();
19708 QualType SrcType = SubExpr->getType();
19709
19710 switch (E->getCastKind()) {
19711 case CK_BaseToDerived:
19712 case CK_DerivedToBase:
19713 case CK_UncheckedDerivedToBase:
19714 case CK_Dynamic:
19715 case CK_ToUnion:
19716 case CK_ArrayToPointerDecay:
19717 case CK_FunctionToPointerDecay:
19718 case CK_NullToPointer:
19719 case CK_NullToMemberPointer:
19720 case CK_BaseToDerivedMemberPointer:
19721 case CK_DerivedToBaseMemberPointer:
19722 case CK_ReinterpretMemberPointer:
19723 case CK_ConstructorConversion:
19724 case CK_IntegralToPointer:
19725 case CK_ToVoid:
19726 case CK_VectorSplat:
19727 case CK_IntegralToFloating:
19728 case CK_FloatingCast:
19729 case CK_CPointerToObjCPointerCast:
19730 case CK_BlockPointerToObjCPointerCast:
19731 case CK_AnyPointerToBlockPointerCast:
19732 case CK_ObjCObjectLValueCast:
19733 case CK_FloatingRealToComplex:
19734 case CK_FloatingComplexToReal:
19735 case CK_FloatingComplexCast:
19736 case CK_FloatingComplexToIntegralComplex:
19737 case CK_IntegralRealToComplex:
19738 case CK_IntegralComplexCast:
19739 case CK_IntegralComplexToFloatingComplex:
19740 case CK_BuiltinFnToFnPtr:
19741 case CK_ZeroToOCLOpaqueType:
19742 case CK_NonAtomicToAtomic:
19743 case CK_AddressSpaceConversion:
19744 case CK_IntToOCLSampler:
19745 case CK_FloatingToFixedPoint:
19746 case CK_FixedPointToFloating:
19747 case CK_FixedPointCast:
19748 case CK_IntegralToFixedPoint:
19749 case CK_MatrixCast:
19750 case CK_HLSLAggregateSplatCast:
19751 llvm_unreachable("invalid cast kind for integral value");
19752
19753 case CK_BitCast:
19754 case CK_Dependent:
19755 case CK_LValueBitCast:
19756 case CK_ARCProduceObject:
19757 case CK_ARCConsumeObject:
19758 case CK_ARCReclaimReturnedObject:
19759 case CK_ARCExtendBlockObject:
19760 case CK_CopyAndAutoreleaseBlockObject:
19761 return Error(E);
19762
19763 case CK_UserDefinedConversion:
19764 case CK_LValueToRValue:
19765 case CK_AtomicToNonAtomic:
19766 case CK_NoOp:
19767 case CK_LValueToRValueBitCast:
19768 case CK_HLSLArrayRValue:
19769 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19770
19771 case CK_MemberPointerToBoolean:
19772 case CK_PointerToBoolean:
19773 case CK_IntegralToBoolean:
19774 case CK_FloatingToBoolean:
19775 case CK_BooleanToSignedIntegral:
19776 case CK_FloatingComplexToBoolean:
19777 case CK_IntegralComplexToBoolean: {
19778 bool BoolResult;
19779 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
19780 return false;
19781 uint64_t IntResult = BoolResult;
19782 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
19783 IntResult = (uint64_t)-1;
19784 return Success(IntResult, E);
19785 }
19786
19787 case CK_FixedPointToIntegral: {
19788 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
19789 if (!EvaluateFixedPoint(SubExpr, Src, Info))
19790 return false;
19791 bool Overflowed;
19792 llvm::APSInt Result = Src.convertToInt(
19793 Info.Ctx.getIntWidth(DestType),
19794 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
19795 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
19796 return false;
19797 return Success(Result, E);
19798 }
19799
19800 case CK_FixedPointToBoolean: {
19801 // Unsigned padding does not affect this.
19802 APValue Val;
19803 if (!Evaluate(Val, Info, SubExpr))
19804 return false;
19805 return Success(Val.getFixedPoint().getBoolValue(), E);
19806 }
19807
19808 case CK_IntegralCast: {
19809 if (!Visit(SubExpr))
19810 return false;
19811
19812 if (!Result.isInt()) {
19813 // Allow casts of address-of-label differences if they are no-ops
19814 // or narrowing, if the result is at least 32 bits wide.
19815 // (The narrowing case isn't actually guaranteed to
19816 // be constant-evaluatable except in some narrow cases which are hard
19817 // to detect here. We let it through on the assumption the user knows
19818 // what they are doing.)
19819 if (Result.isAddrLabelDiff()) {
19820 unsigned DestBits = Info.Ctx.getTypeSize(DestType);
19821 return DestBits >= 32 && DestBits <= Info.Ctx.getTypeSize(SrcType);
19822 }
19823 // Only allow casts of lvalues if they are lossless.
19824 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
19825 }
19826
19827 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
19828 const auto *ED = DestType->getAsEnumDecl();
19829 // Check that the value is within the range of the enumeration values.
19830 //
19831 // This corressponds to [expr.static.cast]p10 which says:
19832 // A value of integral or enumeration type can be explicitly converted
19833 // to a complete enumeration type ... If the enumeration type does not
19834 // have a fixed underlying type, the value is unchanged if the original
19835 // value is within the range of the enumeration values ([dcl.enum]), and
19836 // otherwise, the behavior is undefined.
19837 //
19838 // This was resolved as part of DR2338 which has CD5 status.
19839 if (!ED->isFixed()) {
19840 llvm::APInt Min;
19841 llvm::APInt Max;
19842
19843 ED->getValueRange(Max, Min);
19844 --Max;
19845
19846 if (ED->getNumNegativeBits() &&
19847 (Max.slt(Result.getInt().getSExtValue()) ||
19848 Min.sgt(Result.getInt().getSExtValue())))
19849 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
19850 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
19851 << Max.getSExtValue() << ED;
19852 else if (!ED->getNumNegativeBits() &&
19853 Max.ult(Result.getInt().getZExtValue()))
19854 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
19855 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
19856 << Max.getZExtValue() << ED;
19857 }
19858 }
19859
19860 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
19861 Result.getInt()), E);
19862 }
19863
19864 case CK_PointerToIntegral: {
19865 CCEDiag(E, diag::note_constexpr_invalid_cast)
19866 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
19867 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
19868
19869 LValue LV;
19870 if (!EvaluatePointer(SubExpr, LV, Info))
19871 return false;
19872
19873 if (LV.getLValueBase()) {
19874 // Only allow based lvalue casts if they are lossless.
19875 // FIXME: Allow a larger integer size than the pointer size, and allow
19876 // narrowing back down to pointer width in subsequent integral casts.
19877 // FIXME: Check integer type's active bits, not its type size.
19878 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
19879 return Error(E);
19880
19881 LV.Designator.setInvalid();
19882 LV.moveInto(Result);
19883 return true;
19884 }
19885
19886 APSInt AsInt;
19887 APValue V;
19888 LV.moveInto(V);
19889 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
19890 llvm_unreachable("Can't cast this!");
19891
19892 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
19893 }
19894
19895 case CK_IntegralComplexToReal: {
19896 ComplexValue C;
19897 if (!EvaluateComplex(SubExpr, C, Info))
19898 return false;
19899 return Success(C.getComplexIntReal(), E);
19900 }
19901
19902 case CK_FloatingToIntegral: {
19903 APFloat F(0.0);
19904 if (!EvaluateFloat(SubExpr, F, Info))
19905 return false;
19906
19907 APSInt Value;
19908 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
19909 return false;
19910 return Success(Value, E);
19911 }
19912 case CK_HLSLVectorTruncation: {
19913 APValue Val;
19914 if (!EvaluateVector(SubExpr, Val, Info))
19915 return Error(E);
19916 return Success(Val.getVectorElt(0), E);
19917 }
19918 case CK_HLSLMatrixTruncation: {
19919 APValue Val;
19920 if (!EvaluateMatrix(SubExpr, Val, Info))
19921 return Error(E);
19922 return Success(Val.getMatrixElt(0, 0), E);
19923 }
19924 case CK_HLSLElementwiseCast: {
19925 SmallVector<APValue> SrcVals;
19926 SmallVector<QualType> SrcTypes;
19927
19928 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
19929 return false;
19930
19931 // cast our single element
19932 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
19933 APValue ResultVal;
19934 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
19935 ResultVal))
19936 return false;
19937 return Success(ResultVal, E);
19938 }
19939 }
19940
19941 llvm_unreachable("unknown cast resulting in integral value");
19942}
19943
19944bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
19945 if (E->getSubExpr()->getType()->isAnyComplexType()) {
19946 ComplexValue LV;
19947 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
19948 return false;
19949 if (!LV.isComplexInt())
19950 return Error(E);
19951 return Success(LV.getComplexIntReal(), E);
19952 }
19953
19954 return Visit(E->getSubExpr());
19955}
19956
19957bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
19958 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
19959 ComplexValue LV;
19960 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
19961 return false;
19962 if (!LV.isComplexInt())
19963 return Error(E);
19964 return Success(LV.getComplexIntImag(), E);
19965 }
19966
19967 VisitIgnoredValue(E->getSubExpr());
19968 return Success(0, E);
19969}
19970
19971bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
19972 return Success(E->getPackLength(), E);
19973}
19974
19975bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
19976 return Success(E->getValue(), E);
19977}
19978
19979bool IntExprEvaluator::VisitConceptSpecializationExpr(
19980 const ConceptSpecializationExpr *E) {
19981 return Success(E->isSatisfied(), E);
19982}
19983
19984bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
19985 return Success(E->isSatisfied(), E);
19986}
19987
19988bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19989 switch (E->getOpcode()) {
19990 default:
19991 // Invalid unary operators
19992 return Error(E);
19993 case UO_Plus:
19994 // The result is just the value.
19995 return Visit(E->getSubExpr());
19996 case UO_Minus: {
19997 if (!Visit(E->getSubExpr())) return false;
19998 if (!Result.isFixedPoint())
19999 return Error(E);
20000 bool Overflowed;
20001 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
20002 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
20003 return false;
20004 return Success(Negated, E);
20005 }
20006 case UO_LNot: {
20007 bool bres;
20008 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
20009 return false;
20010 return Success(!bres, E);
20011 }
20012 }
20013}
20014
20015bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
20016 const Expr *SubExpr = E->getSubExpr();
20017 QualType DestType = E->getType();
20018 assert(DestType->isFixedPointType() &&
20019 "Expected destination type to be a fixed point type");
20020 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
20021
20022 switch (E->getCastKind()) {
20023 case CK_FixedPointCast: {
20024 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
20025 if (!EvaluateFixedPoint(SubExpr, Src, Info))
20026 return false;
20027 bool Overflowed;
20028 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
20029 if (Overflowed) {
20030 if (Info.checkingForUndefinedBehavior())
20031 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20032 diag::warn_fixedpoint_constant_overflow)
20033 << Result.toString() << E->getType();
20034 if (!HandleOverflow(Info, E, Result, E->getType()))
20035 return false;
20036 }
20037 return Success(Result, E);
20038 }
20039 case CK_IntegralToFixedPoint: {
20040 APSInt Src;
20041 if (!EvaluateInteger(SubExpr, Src, Info))
20042 return false;
20043
20044 bool Overflowed;
20045 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
20046 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
20047
20048 if (Overflowed) {
20049 if (Info.checkingForUndefinedBehavior())
20050 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20051 diag::warn_fixedpoint_constant_overflow)
20052 << IntResult.toString() << E->getType();
20053 if (!HandleOverflow(Info, E, IntResult, E->getType()))
20054 return false;
20055 }
20056
20057 return Success(IntResult, E);
20058 }
20059 case CK_FloatingToFixedPoint: {
20060 APFloat Src(0.0);
20061 if (!EvaluateFloat(SubExpr, Src, Info))
20062 return false;
20063
20064 bool Overflowed;
20065 APFixedPoint Result = APFixedPoint::getFromFloatValue(
20066 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
20067
20068 if (Overflowed) {
20069 if (Info.checkingForUndefinedBehavior())
20070 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20071 diag::warn_fixedpoint_constant_overflow)
20072 << Result.toString() << E->getType();
20073 if (!HandleOverflow(Info, E, Result, E->getType()))
20074 return false;
20075 }
20076
20077 return Success(Result, E);
20078 }
20079 case CK_NoOp:
20080 case CK_LValueToRValue:
20081 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20082 default:
20083 return Error(E);
20084 }
20085}
20086
20087bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20088 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20089 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20090
20091 const Expr *LHS = E->getLHS();
20092 const Expr *RHS = E->getRHS();
20093 FixedPointSemantics ResultFXSema =
20094 Info.Ctx.getFixedPointSemantics(E->getType());
20095
20096 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
20097 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
20098 return false;
20099 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
20100 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
20101 return false;
20102
20103 bool OpOverflow = false, ConversionOverflow = false;
20104 APFixedPoint Result(LHSFX.getSemantics());
20105 switch (E->getOpcode()) {
20106 case BO_Add: {
20107 Result = LHSFX.add(RHSFX, &OpOverflow)
20108 .convert(ResultFXSema, &ConversionOverflow);
20109 break;
20110 }
20111 case BO_Sub: {
20112 Result = LHSFX.sub(RHSFX, &OpOverflow)
20113 .convert(ResultFXSema, &ConversionOverflow);
20114 break;
20115 }
20116 case BO_Mul: {
20117 Result = LHSFX.mul(RHSFX, &OpOverflow)
20118 .convert(ResultFXSema, &ConversionOverflow);
20119 break;
20120 }
20121 case BO_Div: {
20122 if (RHSFX.getValue() == 0) {
20123 Info.FFDiag(E, diag::note_expr_divide_by_zero);
20124 return false;
20125 }
20126 Result = LHSFX.div(RHSFX, &OpOverflow)
20127 .convert(ResultFXSema, &ConversionOverflow);
20128 break;
20129 }
20130 case BO_Shl:
20131 case BO_Shr: {
20132 FixedPointSemantics LHSSema = LHSFX.getSemantics();
20133 llvm::APSInt RHSVal = RHSFX.getValue();
20134
20135 unsigned ShiftBW =
20136 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
20137 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
20138 // Embedded-C 4.1.6.2.2:
20139 // The right operand must be nonnegative and less than the total number
20140 // of (nonpadding) bits of the fixed-point operand ...
20141 if (RHSVal.isNegative())
20142 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
20143 else if (Amt != RHSVal)
20144 Info.CCEDiag(E, diag::note_constexpr_large_shift)
20145 << RHSVal << E->getType() << ShiftBW;
20146
20147 if (E->getOpcode() == BO_Shl)
20148 Result = LHSFX.shl(Amt, &OpOverflow);
20149 else
20150 Result = LHSFX.shr(Amt, &OpOverflow);
20151 break;
20152 }
20153 default:
20154 return false;
20155 }
20156 if (OpOverflow || ConversionOverflow) {
20157 if (Info.checkingForUndefinedBehavior())
20158 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20159 diag::warn_fixedpoint_constant_overflow)
20160 << Result.toString() << E->getType();
20161 if (!HandleOverflow(Info, E, Result, E->getType()))
20162 return false;
20163 }
20164 return Success(Result, E);
20165}
20166
20167//===----------------------------------------------------------------------===//
20168// Float Evaluation
20169//===----------------------------------------------------------------------===//
20170
20171namespace {
20172class FloatExprEvaluator
20173 : public ExprEvaluatorBase<FloatExprEvaluator> {
20174 APFloat &Result;
20175public:
20176 FloatExprEvaluator(EvalInfo &info, APFloat &result)
20177 : ExprEvaluatorBaseTy(info), Result(result) {}
20178
20179 bool Success(const APValue &V, const Expr *e) {
20180 Result = V.getFloat();
20181 return true;
20182 }
20183
20184 bool ZeroInitialization(const Expr *E) {
20185 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
20186 return true;
20187 }
20188
20189 bool VisitCallExpr(const CallExpr *E);
20190
20191 bool VisitUnaryOperator(const UnaryOperator *E);
20192 bool VisitBinaryOperator(const BinaryOperator *E);
20193 bool VisitFloatingLiteral(const FloatingLiteral *E);
20194 bool VisitCastExpr(const CastExpr *E);
20195
20196 bool VisitUnaryReal(const UnaryOperator *E);
20197 bool VisitUnaryImag(const UnaryOperator *E);
20198
20199 // FIXME: Missing: array subscript of vector, member of vector
20200};
20201} // end anonymous namespace
20202
20203static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
20204 assert(!E->isValueDependent());
20205 assert(E->isPRValue() && E->getType()->isRealFloatingType());
20206 return FloatExprEvaluator(Info, Result).Visit(E);
20207}
20208
20209static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
20210 QualType ResultTy,
20211 const Expr *Arg,
20212 bool SNaN,
20213 llvm::APFloat &Result) {
20214 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
20215 if (!S) return false;
20216
20217 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
20218
20219 llvm::APInt fill;
20220
20221 // Treat empty strings as if they were zero.
20222 if (S->getString().empty())
20223 fill = llvm::APInt(32, 0);
20224 else if (S->getString().getAsInteger(0, fill))
20225 return false;
20226
20227 if (Context.getTargetInfo().isNan2008()) {
20228 if (SNaN)
20229 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
20230 else
20231 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
20232 } else {
20233 // Prior to IEEE 754-2008, architectures were allowed to choose whether
20234 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
20235 // a different encoding to what became a standard in 2008, and for pre-
20236 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
20237 // sNaN. This is now known as "legacy NaN" encoding.
20238 if (SNaN)
20239 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
20240 else
20241 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
20242 }
20243
20244 return true;
20245}
20246
20247bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
20248 if (!IsConstantEvaluatedBuiltinCall(E))
20249 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20250
20251 unsigned BuiltinOp = ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E);
20252
20253 switch (BuiltinOp) {
20254 default:
20255 return false;
20256
20257 case Builtin::BI__builtin_huge_val:
20258 case Builtin::BI__builtin_huge_valf:
20259 case Builtin::BI__builtin_huge_vall:
20260 case Builtin::BI__builtin_huge_valf16:
20261 case Builtin::BI__builtin_huge_valf128:
20262 case Builtin::BI__builtin_inf:
20263 case Builtin::BI__builtin_inff:
20264 case Builtin::BI__builtin_infl:
20265 case Builtin::BI__builtin_inff16:
20266 case Builtin::BI__builtin_inff128: {
20267 const llvm::fltSemantics &Sem =
20268 Info.Ctx.getFloatTypeSemantics(E->getType());
20269 Result = llvm::APFloat::getInf(Sem);
20270 return true;
20271 }
20272
20273 case Builtin::BI__builtin_nans:
20274 case Builtin::BI__builtin_nansf:
20275 case Builtin::BI__builtin_nansl:
20276 case Builtin::BI__builtin_nansf16:
20277 case Builtin::BI__builtin_nansf128:
20278 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
20279 true, Result))
20280 return Error(E);
20281 return true;
20282
20283 case Builtin::BI__builtin_nan:
20284 case Builtin::BI__builtin_nanf:
20285 case Builtin::BI__builtin_nanl:
20286 case Builtin::BI__builtin_nanf16:
20287 case Builtin::BI__builtin_nanf128:
20288 // If this is __builtin_nan() turn this into a nan, otherwise we
20289 // can't constant fold it.
20290 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
20291 false, Result))
20292 return Error(E);
20293 return true;
20294
20295 case Builtin::BI__builtin_elementwise_abs:
20296 case Builtin::BI__builtin_fabs:
20297 case Builtin::BI__builtin_fabsf:
20298 case Builtin::BI__builtin_fabsl:
20299 case Builtin::BI__builtin_fabsf128:
20300 // The C standard says "fabs raises no floating-point exceptions,
20301 // even if x is a signaling NaN. The returned value is independent of
20302 // the current rounding direction mode." Therefore constant folding can
20303 // proceed without regard to the floating point settings.
20304 // Reference, WG14 N2478 F.10.4.3
20305 if (!EvaluateFloat(E->getArg(0), Result, Info))
20306 return false;
20307
20308 if (Result.isNegative())
20309 Result.changeSign();
20310 return true;
20311
20312 case Builtin::BI__arithmetic_fence:
20313 return EvaluateFloat(E->getArg(0), Result, Info);
20314
20315 // FIXME: Builtin::BI__builtin_powi
20316 // FIXME: Builtin::BI__builtin_powif
20317 // FIXME: Builtin::BI__builtin_powil
20318
20319 case Builtin::BI__builtin_copysign:
20320 case Builtin::BI__builtin_copysignf:
20321 case Builtin::BI__builtin_copysignl:
20322 case Builtin::BI__builtin_copysignf128: {
20323 APFloat RHS(0.);
20324 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20325 !EvaluateFloat(E->getArg(1), RHS, Info))
20326 return false;
20327 Result.copySign(RHS);
20328 return true;
20329 }
20330
20331 case Builtin::BI__builtin_fmax:
20332 case Builtin::BI__builtin_fmaxf:
20333 case Builtin::BI__builtin_fmaxl:
20334 case Builtin::BI__builtin_fmaxf16:
20335 case Builtin::BI__builtin_fmaxf128: {
20336 APFloat RHS(0.);
20337 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20338 !EvaluateFloat(E->getArg(1), RHS, Info))
20339 return false;
20340 Result = maxnum(Result, RHS);
20341 return true;
20342 }
20343
20344 case Builtin::BI__builtin_fmin:
20345 case Builtin::BI__builtin_fminf:
20346 case Builtin::BI__builtin_fminl:
20347 case Builtin::BI__builtin_fminf16:
20348 case Builtin::BI__builtin_fminf128: {
20349 APFloat RHS(0.);
20350 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20351 !EvaluateFloat(E->getArg(1), RHS, Info))
20352 return false;
20353 Result = minnum(Result, RHS);
20354 return true;
20355 }
20356
20357 case Builtin::BI__builtin_fmaximum_num:
20358 case Builtin::BI__builtin_fmaximum_numf:
20359 case Builtin::BI__builtin_fmaximum_numl:
20360 case Builtin::BI__builtin_fmaximum_numf16:
20361 case Builtin::BI__builtin_fmaximum_numf128: {
20362 APFloat RHS(0.);
20363 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20364 !EvaluateFloat(E->getArg(1), RHS, Info))
20365 return false;
20366 Result = maximumnum(Result, RHS);
20367 return true;
20368 }
20369
20370 case Builtin::BI__builtin_fminimum_num:
20371 case Builtin::BI__builtin_fminimum_numf:
20372 case Builtin::BI__builtin_fminimum_numl:
20373 case Builtin::BI__builtin_fminimum_numf16:
20374 case Builtin::BI__builtin_fminimum_numf128: {
20375 APFloat RHS(0.);
20376 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20377 !EvaluateFloat(E->getArg(1), RHS, Info))
20378 return false;
20379 Result = minimumnum(Result, RHS);
20380 return true;
20381 }
20382
20383 case Builtin::BI__builtin_elementwise_fma: {
20384 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
20385 !E->getArg(2)->isPRValue()) {
20386 return false;
20387 }
20388 APFloat SourceY(0.), SourceZ(0.);
20389 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20390 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
20391 !EvaluateFloat(E->getArg(2), SourceZ, Info))
20392 return false;
20393 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
20394 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
20395 return true;
20396 }
20397
20398 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
20399 APValue Vec;
20400 APSInt IdxAPS;
20401 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
20402 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
20403 return false;
20404 unsigned N = Vec.getVectorLength();
20405 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
20406 return Success(Vec.getVectorElt(Idx), E);
20407 }
20408 }
20409}
20410
20411bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
20412 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20413 ComplexValue CV;
20414 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
20415 return false;
20416 Result = CV.FloatReal;
20417 return true;
20418 }
20419
20420 return Visit(E->getSubExpr());
20421}
20422
20423bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
20424 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20425 ComplexValue CV;
20426 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
20427 return false;
20428 Result = CV.FloatImag;
20429 return true;
20430 }
20431
20432 VisitIgnoredValue(E->getSubExpr());
20433 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
20434 Result = llvm::APFloat::getZero(Sem);
20435 return true;
20436}
20437
20438bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20439 switch (E->getOpcode()) {
20440 default: return Error(E);
20441 case UO_Plus:
20442 return EvaluateFloat(E->getSubExpr(), Result, Info);
20443 case UO_Minus:
20444 // In C standard, WG14 N2478 F.3 p4
20445 // "the unary - raises no floating point exceptions,
20446 // even if the operand is signalling."
20447 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
20448 return false;
20449 Result.changeSign();
20450 return true;
20451 }
20452}
20453
20454bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20455 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20456 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20457
20458 APFloat RHS(0.0);
20459 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
20460 if (!LHSOK && !Info.noteFailure())
20461 return false;
20462 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
20463 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
20464}
20465
20466bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
20467 Result = E->getValue();
20468 return true;
20469}
20470
20471bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
20472 const Expr* SubExpr = E->getSubExpr();
20473
20474 switch (E->getCastKind()) {
20475 default:
20476 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20477
20478 case CK_HLSLAggregateSplatCast:
20479 llvm_unreachable("invalid cast kind for floating value");
20480
20481 case CK_IntegralToFloating: {
20482 APSInt IntResult;
20483 const FPOptions FPO = E->getFPFeaturesInEffect(
20484 Info.Ctx.getLangOpts());
20485 return EvaluateInteger(SubExpr, IntResult, Info) &&
20486 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
20487 IntResult, E->getType(), Result);
20488 }
20489
20490 case CK_FixedPointToFloating: {
20491 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
20492 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
20493 return false;
20494 Result =
20495 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
20496 return true;
20497 }
20498
20499 case CK_FloatingCast: {
20500 if (!Visit(SubExpr))
20501 return false;
20502 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
20503 Result);
20504 }
20505
20506 case CK_FloatingComplexToReal: {
20507 ComplexValue V;
20508 if (!EvaluateComplex(SubExpr, V, Info))
20509 return false;
20510 Result = V.getComplexFloatReal();
20511 return true;
20512 }
20513 case CK_HLSLVectorTruncation: {
20514 APValue Val;
20515 if (!EvaluateVector(SubExpr, Val, Info))
20516 return Error(E);
20517 return Success(Val.getVectorElt(0), E);
20518 }
20519 case CK_HLSLMatrixTruncation: {
20520 APValue Val;
20521 if (!EvaluateMatrix(SubExpr, Val, Info))
20522 return Error(E);
20523 return Success(Val.getMatrixElt(0, 0), E);
20524 }
20525 case CK_HLSLElementwiseCast: {
20526 SmallVector<APValue> SrcVals;
20527 SmallVector<QualType> SrcTypes;
20528
20529 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
20530 SrcTypes))
20531 return false;
20532 APValue Val;
20533
20534 // cast our single element
20535 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
20536 APValue ResultVal;
20537 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
20538 ResultVal))
20539 return false;
20540 return Success(ResultVal, E);
20541 }
20542 }
20543}
20544
20545//===----------------------------------------------------------------------===//
20546// Complex Evaluation (for float and integer)
20547//===----------------------------------------------------------------------===//
20548
20549namespace {
20550class ComplexExprEvaluator
20551 : public ExprEvaluatorBase<ComplexExprEvaluator> {
20552 ComplexValue &Result;
20553
20554public:
20555 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
20556 : ExprEvaluatorBaseTy(info), Result(Result) {}
20557
20558 bool Success(const APValue &V, const Expr *e) {
20559 Result.setFrom(V);
20560 return true;
20561 }
20562
20563 bool ZeroInitialization(const Expr *E);
20564
20565 //===--------------------------------------------------------------------===//
20566 // Visitor Methods
20567 //===--------------------------------------------------------------------===//
20568
20569 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
20570 bool VisitCastExpr(const CastExpr *E);
20571 bool VisitBinaryOperator(const BinaryOperator *E);
20572 bool VisitUnaryOperator(const UnaryOperator *E);
20573 bool VisitInitListExpr(const InitListExpr *E);
20574 bool VisitCallExpr(const CallExpr *E);
20575};
20576} // end anonymous namespace
20577
20578static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
20579 EvalInfo &Info) {
20580 assert(!E->isValueDependent());
20581 assert(E->isPRValue() && E->getType()->isAnyComplexType());
20582 return ComplexExprEvaluator(Info, Result).Visit(E);
20583}
20584
20585bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
20586 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
20587 if (ElemTy->isRealFloatingType()) {
20588 Result.makeComplexFloat();
20589 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
20590 Result.FloatReal = Zero;
20591 Result.FloatImag = Zero;
20592 } else {
20593 Result.makeComplexInt();
20594 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
20595 Result.IntReal = Zero;
20596 Result.IntImag = Zero;
20597 }
20598 return true;
20599}
20600
20601bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
20602 const Expr* SubExpr = E->getSubExpr();
20603
20604 if (SubExpr->getType()->isRealFloatingType()) {
20605 Result.makeComplexFloat();
20606 APFloat &Imag = Result.FloatImag;
20607 if (!EvaluateFloat(SubExpr, Imag, Info))
20608 return false;
20609
20610 Result.FloatReal = APFloat(Imag.getSemantics());
20611 return true;
20612 } else {
20613 assert(SubExpr->getType()->isIntegerType() &&
20614 "Unexpected imaginary literal.");
20615
20616 Result.makeComplexInt();
20617 APSInt &Imag = Result.IntImag;
20618 if (!EvaluateInteger(SubExpr, Imag, Info))
20619 return false;
20620
20621 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
20622 return true;
20623 }
20624}
20625
20626bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
20627
20628 switch (E->getCastKind()) {
20629 case CK_BitCast:
20630 case CK_BaseToDerived:
20631 case CK_DerivedToBase:
20632 case CK_UncheckedDerivedToBase:
20633 case CK_Dynamic:
20634 case CK_ToUnion:
20635 case CK_ArrayToPointerDecay:
20636 case CK_FunctionToPointerDecay:
20637 case CK_NullToPointer:
20638 case CK_NullToMemberPointer:
20639 case CK_BaseToDerivedMemberPointer:
20640 case CK_DerivedToBaseMemberPointer:
20641 case CK_MemberPointerToBoolean:
20642 case CK_ReinterpretMemberPointer:
20643 case CK_ConstructorConversion:
20644 case CK_IntegralToPointer:
20645 case CK_PointerToIntegral:
20646 case CK_PointerToBoolean:
20647 case CK_ToVoid:
20648 case CK_VectorSplat:
20649 case CK_IntegralCast:
20650 case CK_BooleanToSignedIntegral:
20651 case CK_IntegralToBoolean:
20652 case CK_IntegralToFloating:
20653 case CK_FloatingToIntegral:
20654 case CK_FloatingToBoolean:
20655 case CK_FloatingCast:
20656 case CK_CPointerToObjCPointerCast:
20657 case CK_BlockPointerToObjCPointerCast:
20658 case CK_AnyPointerToBlockPointerCast:
20659 case CK_ObjCObjectLValueCast:
20660 case CK_FloatingComplexToReal:
20661 case CK_FloatingComplexToBoolean:
20662 case CK_IntegralComplexToReal:
20663 case CK_IntegralComplexToBoolean:
20664 case CK_ARCProduceObject:
20665 case CK_ARCConsumeObject:
20666 case CK_ARCReclaimReturnedObject:
20667 case CK_ARCExtendBlockObject:
20668 case CK_CopyAndAutoreleaseBlockObject:
20669 case CK_BuiltinFnToFnPtr:
20670 case CK_ZeroToOCLOpaqueType:
20671 case CK_NonAtomicToAtomic:
20672 case CK_AddressSpaceConversion:
20673 case CK_IntToOCLSampler:
20674 case CK_FloatingToFixedPoint:
20675 case CK_FixedPointToFloating:
20676 case CK_FixedPointCast:
20677 case CK_FixedPointToBoolean:
20678 case CK_FixedPointToIntegral:
20679 case CK_IntegralToFixedPoint:
20680 case CK_MatrixCast:
20681 case CK_HLSLVectorTruncation:
20682 case CK_HLSLMatrixTruncation:
20683 case CK_HLSLElementwiseCast:
20684 case CK_HLSLAggregateSplatCast:
20685 llvm_unreachable("invalid cast kind for complex value");
20686
20687 case CK_LValueToRValue:
20688 case CK_AtomicToNonAtomic:
20689 case CK_NoOp:
20690 case CK_LValueToRValueBitCast:
20691 case CK_HLSLArrayRValue:
20692 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20693
20694 case CK_Dependent:
20695 case CK_LValueBitCast:
20696 case CK_UserDefinedConversion:
20697 return Error(E);
20698
20699 case CK_FloatingRealToComplex: {
20700 APFloat &Real = Result.FloatReal;
20701 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
20702 return false;
20703
20704 Result.makeComplexFloat();
20705 Result.FloatImag = APFloat(Real.getSemantics());
20706 return true;
20707 }
20708
20709 case CK_FloatingComplexCast: {
20710 if (!Visit(E->getSubExpr()))
20711 return false;
20712
20713 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20714 QualType From
20715 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20716
20717 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
20718 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
20719 }
20720
20721 case CK_FloatingComplexToIntegralComplex: {
20722 if (!Visit(E->getSubExpr()))
20723 return false;
20724
20725 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20726 QualType From
20727 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20728 Result.makeComplexInt();
20729 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
20730 To, Result.IntReal) &&
20731 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
20732 To, Result.IntImag);
20733 }
20734
20735 case CK_IntegralRealToComplex: {
20736 APSInt &Real = Result.IntReal;
20737 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
20738 return false;
20739
20740 Result.makeComplexInt();
20741 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
20742 return true;
20743 }
20744
20745 case CK_IntegralComplexCast: {
20746 if (!Visit(E->getSubExpr()))
20747 return false;
20748
20749 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20750 QualType From
20751 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20752
20753 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
20754 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
20755 return true;
20756 }
20757
20758 case CK_IntegralComplexToFloatingComplex: {
20759 if (!Visit(E->getSubExpr()))
20760 return false;
20761
20762 const FPOptions FPO = E->getFPFeaturesInEffect(
20763 Info.Ctx.getLangOpts());
20764 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20765 QualType From
20766 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20767 Result.makeComplexFloat();
20768 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
20769 To, Result.FloatReal) &&
20770 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
20771 To, Result.FloatImag);
20772 }
20773 }
20774
20775 llvm_unreachable("unknown cast resulting in complex value");
20776}
20777
20779 // Lookup Table for Multiplicative Inverse in GF(2^8)
20780 const uint8_t GFInv[256] = {
20781 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0,
20782 0xb0, 0xe1, 0xe5, 0xc7, 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f,
20783 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2, 0x3a, 0x6e, 0x5a, 0xf1,
20784 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,
20785 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f,
20786 0x77, 0xbb, 0x59, 0x19, 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69,
20787 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09, 0xed, 0x5c, 0x05, 0xca,
20788 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,
20789 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf,
20790 0x33, 0x93, 0x21, 0x3b, 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c,
20791 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82, 0x83, 0x7e, 0x7f, 0x80,
20792 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,
20793 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88,
20794 0xf9, 0xdc, 0x89, 0x9a, 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48,
20795 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62, 0x0c, 0xe0, 0x1f, 0xef,
20796 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,
20797 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04,
20798 0x1b, 0xfc, 0xac, 0xe6, 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea,
20799 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b, 0xb1, 0x0d, 0xd6, 0xeb,
20800 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,
20801 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0,
20802 0xcd, 0x1a, 0x41, 0x1c};
20803
20804 return GFInv[Byte];
20805}
20806
20807uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm,
20808 bool Inverse) {
20809 unsigned NumBitsInByte = 8;
20810 // Computing the affine transformation
20811 uint8_t RetByte = 0;
20812 for (uint32_t BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
20813 uint8_t AByte =
20814 AQword.lshr((7 - static_cast<int32_t>(BitIdx)) * NumBitsInByte)
20815 .getLoBits(8)
20816 .getZExtValue();
20817 uint8_t Product;
20818 if (Inverse) {
20819 Product = AByte & GFNIMultiplicativeInverse(XByte);
20820 } else {
20821 Product = AByte & XByte;
20822 }
20823 uint8_t Parity = 0;
20824
20825 // Dot product in GF(2) uses XOR instead of addition
20826 for (unsigned PBitIdx = 0; PBitIdx != NumBitsInByte; ++PBitIdx) {
20827 Parity = Parity ^ ((Product >> PBitIdx) & 0x1);
20828 }
20829
20830 uint8_t Temp = Imm[BitIdx] ? 1 : 0;
20831 RetByte |= (Temp ^ Parity) << BitIdx;
20832 }
20833 return RetByte;
20834}
20835
20837 // Multiplying two polynomials of degree 7
20838 // Polynomial of degree 7
20839 // x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
20840 uint16_t TWord = 0;
20841 unsigned NumBitsInByte = 8;
20842 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
20843 if ((BByte >> BitIdx) & 0x1) {
20844 TWord = TWord ^ (AByte << BitIdx);
20845 }
20846 }
20847
20848 // When multiplying two polynomials of degree 7
20849 // results in a polynomial of degree 14
20850 // so the result has to be reduced to 7
20851 // Reduction polynomial is x^8 + x^4 + x^3 + x + 1 i.e. 0x11B
20852 for (int32_t BitIdx = 14; BitIdx > 7; --BitIdx) {
20853 if ((TWord >> BitIdx) & 0x1) {
20854 TWord = TWord ^ (0x11B << (BitIdx - 8));
20855 }
20856 }
20857 return (TWord & 0xFF);
20858}
20859
20860void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
20861 APFloat &ResR, APFloat &ResI) {
20862 // This is an implementation of complex multiplication according to the
20863 // constraints laid out in C11 Annex G. The implementation uses the
20864 // following naming scheme:
20865 // (a + ib) * (c + id)
20866
20867 APFloat AC = A * C;
20868 APFloat BD = B * D;
20869 APFloat AD = A * D;
20870 APFloat BC = B * C;
20871 ResR = AC - BD;
20872 ResI = AD + BC;
20873 if (ResR.isNaN() && ResI.isNaN()) {
20874 bool Recalc = false;
20875 if (A.isInfinity() || B.isInfinity()) {
20876 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
20877 A);
20878 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
20879 B);
20880 if (C.isNaN())
20881 C = APFloat::copySign(APFloat(C.getSemantics()), C);
20882 if (D.isNaN())
20883 D = APFloat::copySign(APFloat(D.getSemantics()), D);
20884 Recalc = true;
20885 }
20886 if (C.isInfinity() || D.isInfinity()) {
20887 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
20888 C);
20889 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
20890 D);
20891 if (A.isNaN())
20892 A = APFloat::copySign(APFloat(A.getSemantics()), A);
20893 if (B.isNaN())
20894 B = APFloat::copySign(APFloat(B.getSemantics()), B);
20895 Recalc = true;
20896 }
20897 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
20898 BC.isInfinity())) {
20899 if (A.isNaN())
20900 A = APFloat::copySign(APFloat(A.getSemantics()), A);
20901 if (B.isNaN())
20902 B = APFloat::copySign(APFloat(B.getSemantics()), B);
20903 if (C.isNaN())
20904 C = APFloat::copySign(APFloat(C.getSemantics()), C);
20905 if (D.isNaN())
20906 D = APFloat::copySign(APFloat(D.getSemantics()), D);
20907 Recalc = true;
20908 }
20909 if (Recalc) {
20910 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
20911 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
20912 }
20913 }
20914}
20915
20916void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
20917 APFloat &ResR, APFloat &ResI) {
20918 // This is an implementation of complex division according to the
20919 // constraints laid out in C11 Annex G. The implementation uses the
20920 // following naming scheme:
20921 // (a + ib) / (c + id)
20922
20923 int DenomLogB = 0;
20924 APFloat MaxCD = maxnum(abs(C), abs(D));
20925 if (MaxCD.isFinite()) {
20926 DenomLogB = ilogb(MaxCD);
20927 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
20928 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
20929 }
20930 APFloat Denom = C * C + D * D;
20931 ResR =
20932 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
20933 ResI =
20934 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
20935 if (ResR.isNaN() && ResI.isNaN()) {
20936 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
20937 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
20938 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
20939 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
20940 D.isFinite()) {
20941 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
20942 A);
20943 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
20944 B);
20945 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
20946 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
20947 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
20948 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
20949 C);
20950 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
20951 D);
20952 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
20953 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
20954 }
20955 }
20956}
20957
20959 // Normalize shift amount to [0, BitWidth) range to match runtime behavior
20960 APSInt NormAmt = Amount;
20961 unsigned BitWidth = Value.getBitWidth();
20962 unsigned AmtBitWidth = NormAmt.getBitWidth();
20963 if (BitWidth == 1) {
20964 // Rotating a 1-bit value is always a no-op
20965 NormAmt = APSInt(APInt(AmtBitWidth, 0), NormAmt.isUnsigned());
20966 } else if (BitWidth == 2) {
20967 // For 2-bit values: rotation amount is 0 or 1 based on
20968 // whether the amount is even or odd. We can't use srem here because
20969 // the divisor (2) would be misinterpreted as -2 in 2-bit signed arithmetic.
20970 NormAmt =
20971 APSInt(APInt(AmtBitWidth, NormAmt[0] ? 1 : 0), NormAmt.isUnsigned());
20972 } else {
20973 APInt Divisor;
20974 if (AmtBitWidth > BitWidth) {
20975 Divisor = llvm::APInt(AmtBitWidth, BitWidth);
20976 } else {
20977 Divisor = llvm::APInt(BitWidth, BitWidth);
20978 if (AmtBitWidth < BitWidth) {
20979 NormAmt = NormAmt.extend(BitWidth);
20980 }
20981 }
20982
20983 // Normalize to [0, BitWidth)
20984 if (NormAmt.isSigned()) {
20985 NormAmt = APSInt(NormAmt.srem(Divisor), /*isUnsigned=*/false);
20986 if (NormAmt.isNegative()) {
20987 APSInt SignedDivisor(Divisor, /*isUnsigned=*/false);
20988 NormAmt += SignedDivisor;
20989 }
20990 } else {
20991 NormAmt = APSInt(NormAmt.urem(Divisor), /*isUnsigned=*/true);
20992 }
20993 }
20994
20995 return NormAmt;
20996}
20997
20998bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20999 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
21000 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
21001
21002 // Track whether the LHS or RHS is real at the type system level. When this is
21003 // the case we can simplify our evaluation strategy.
21004 bool LHSReal = false, RHSReal = false;
21005
21006 bool LHSOK;
21007 if (E->getLHS()->getType()->isRealFloatingType()) {
21008 LHSReal = true;
21009 APFloat &Real = Result.FloatReal;
21010 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
21011 if (LHSOK) {
21012 Result.makeComplexFloat();
21013 Result.FloatImag = APFloat(Real.getSemantics());
21014 }
21015 } else {
21016 LHSOK = Visit(E->getLHS());
21017 }
21018 if (!LHSOK && !Info.noteFailure())
21019 return false;
21020
21021 ComplexValue RHS;
21022 if (E->getRHS()->getType()->isRealFloatingType()) {
21023 RHSReal = true;
21024 APFloat &Real = RHS.FloatReal;
21025 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
21026 return false;
21027 RHS.makeComplexFloat();
21028 RHS.FloatImag = APFloat(Real.getSemantics());
21029 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
21030 return false;
21031
21032 assert(!(LHSReal && RHSReal) &&
21033 "Cannot have both operands of a complex operation be real.");
21034 switch (E->getOpcode()) {
21035 default: return Error(E);
21036 case BO_Add:
21037 if (Result.isComplexFloat()) {
21038 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
21039 APFloat::rmNearestTiesToEven);
21040 if (LHSReal)
21041 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
21042 else if (!RHSReal)
21043 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
21044 APFloat::rmNearestTiesToEven);
21045 } else {
21046 Result.getComplexIntReal() += RHS.getComplexIntReal();
21047 Result.getComplexIntImag() += RHS.getComplexIntImag();
21048 }
21049 break;
21050 case BO_Sub:
21051 if (Result.isComplexFloat()) {
21052 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
21053 APFloat::rmNearestTiesToEven);
21054 if (LHSReal) {
21055 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
21056 Result.getComplexFloatImag().changeSign();
21057 } else if (!RHSReal) {
21058 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
21059 APFloat::rmNearestTiesToEven);
21060 }
21061 } else {
21062 Result.getComplexIntReal() -= RHS.getComplexIntReal();
21063 Result.getComplexIntImag() -= RHS.getComplexIntImag();
21064 }
21065 break;
21066 case BO_Mul:
21067 if (Result.isComplexFloat()) {
21068 // This is an implementation of complex multiplication according to the
21069 // constraints laid out in C11 Annex G. The implementation uses the
21070 // following naming scheme:
21071 // (a + ib) * (c + id)
21072 ComplexValue LHS = Result;
21073 APFloat &A = LHS.getComplexFloatReal();
21074 APFloat &B = LHS.getComplexFloatImag();
21075 APFloat &C = RHS.getComplexFloatReal();
21076 APFloat &D = RHS.getComplexFloatImag();
21077 APFloat &ResR = Result.getComplexFloatReal();
21078 APFloat &ResI = Result.getComplexFloatImag();
21079 if (LHSReal) {
21080 assert(!RHSReal && "Cannot have two real operands for a complex op!");
21081 ResR = A;
21082 ResI = A;
21083 // ResR = A * C;
21084 // ResI = A * D;
21085 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
21086 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
21087 return false;
21088 } else if (RHSReal) {
21089 // ResR = C * A;
21090 // ResI = C * B;
21091 ResR = C;
21092 ResI = C;
21093 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
21094 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
21095 return false;
21096 } else {
21097 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
21098 }
21099 } else {
21100 ComplexValue LHS = Result;
21101 Result.getComplexIntReal() =
21102 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
21103 LHS.getComplexIntImag() * RHS.getComplexIntImag());
21104 Result.getComplexIntImag() =
21105 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
21106 LHS.getComplexIntImag() * RHS.getComplexIntReal());
21107 }
21108 break;
21109 case BO_Div:
21110 if (Result.isComplexFloat()) {
21111 // This is an implementation of complex division according to the
21112 // constraints laid out in C11 Annex G. The implementation uses the
21113 // following naming scheme:
21114 // (a + ib) / (c + id)
21115 ComplexValue LHS = Result;
21116 APFloat &A = LHS.getComplexFloatReal();
21117 APFloat &B = LHS.getComplexFloatImag();
21118 APFloat &C = RHS.getComplexFloatReal();
21119 APFloat &D = RHS.getComplexFloatImag();
21120 APFloat &ResR = Result.getComplexFloatReal();
21121 APFloat &ResI = Result.getComplexFloatImag();
21122 if (RHSReal) {
21123 ResR = A;
21124 ResI = B;
21125 // ResR = A / C;
21126 // ResI = B / C;
21127 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
21128 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
21129 return false;
21130 } else {
21131 if (LHSReal) {
21132 // No real optimizations we can do here, stub out with zero.
21133 B = APFloat::getZero(A.getSemantics());
21134 }
21135 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
21136 }
21137 } else {
21138 ComplexValue LHS = Result;
21139 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
21140 RHS.getComplexIntImag() * RHS.getComplexIntImag();
21141 if (Den.isZero())
21142 return Error(E, diag::note_expr_divide_by_zero);
21143
21144 Result.getComplexIntReal() =
21145 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
21146 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
21147 Result.getComplexIntImag() =
21148 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
21149 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
21150 }
21151 break;
21152 }
21153
21154 return true;
21155}
21156
21157bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
21158 // Get the operand value into 'Result'.
21159 if (!Visit(E->getSubExpr()))
21160 return false;
21161
21162 switch (E->getOpcode()) {
21163 default:
21164 return Error(E);
21165 case UO_Extension:
21166 return true;
21167 case UO_Plus:
21168 // The result is always just the subexpr.
21169 return true;
21170 case UO_Minus:
21171 if (Result.isComplexFloat()) {
21172 Result.getComplexFloatReal().changeSign();
21173 Result.getComplexFloatImag().changeSign();
21174 }
21175 else {
21176 Result.getComplexIntReal() = -Result.getComplexIntReal();
21177 Result.getComplexIntImag() = -Result.getComplexIntImag();
21178 }
21179 return true;
21180 case UO_Not:
21181 if (Result.isComplexFloat())
21182 Result.getComplexFloatImag().changeSign();
21183 else
21184 Result.getComplexIntImag() = -Result.getComplexIntImag();
21185 return true;
21186 }
21187}
21188
21189bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
21190 if (E->getNumInits() == 2) {
21191 if (E->getType()->isComplexType()) {
21192 Result.makeComplexFloat();
21193 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
21194 return false;
21195 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
21196 return false;
21197 } else {
21198 Result.makeComplexInt();
21199 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
21200 return false;
21201 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
21202 return false;
21203 }
21204 return true;
21205 }
21206 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
21207}
21208
21209bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
21210 if (!IsConstantEvaluatedBuiltinCall(E))
21211 return ExprEvaluatorBaseTy::VisitCallExpr(E);
21212
21213 switch (E->getBuiltinCallee()) {
21214 case Builtin::BI__builtin_complex:
21215 Result.makeComplexFloat();
21216 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
21217 return false;
21218 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
21219 return false;
21220 return true;
21221
21222 default:
21223 return false;
21224 }
21225}
21226
21227//===----------------------------------------------------------------------===//
21228// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
21229// implicit conversion.
21230//===----------------------------------------------------------------------===//
21231
21232namespace {
21233class AtomicExprEvaluator :
21234 public ExprEvaluatorBase<AtomicExprEvaluator> {
21235 const LValue *This;
21236 APValue &Result;
21237public:
21238 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
21239 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
21240
21241 bool Success(const APValue &V, const Expr *E) {
21242 Result = V;
21243 return true;
21244 }
21245
21246 bool ZeroInitialization(const Expr *E) {
21247 ImplicitValueInitExpr VIE(
21248 E->getType()->castAs<AtomicType>()->getValueType());
21249 // For atomic-qualified class (and array) types in C++, initialize the
21250 // _Atomic-wrapped subobject directly, in-place.
21251 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
21252 : Evaluate(Result, Info, &VIE);
21253 }
21254
21255 bool VisitCastExpr(const CastExpr *E) {
21256 switch (E->getCastKind()) {
21257 default:
21258 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21259 case CK_NullToPointer:
21260 VisitIgnoredValue(E->getSubExpr());
21261 return ZeroInitialization(E);
21262 case CK_NonAtomicToAtomic:
21263 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
21264 : Evaluate(Result, Info, E->getSubExpr());
21265 }
21266 }
21267};
21268} // end anonymous namespace
21269
21270static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
21271 EvalInfo &Info) {
21272 assert(!E->isValueDependent());
21273 assert(E->isPRValue() && E->getType()->isAtomicType());
21274 return AtomicExprEvaluator(Info, This, Result).Visit(E);
21275}
21276
21277//===----------------------------------------------------------------------===//
21278// Void expression evaluation, primarily for a cast to void on the LHS of a
21279// comma operator
21280//===----------------------------------------------------------------------===//
21281
21282namespace {
21283class VoidExprEvaluator
21284 : public ExprEvaluatorBase<VoidExprEvaluator> {
21285public:
21286 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
21287
21288 bool Success(const APValue &V, const Expr *e) { return true; }
21289
21290 bool ZeroInitialization(const Expr *E) { return true; }
21291
21292 bool VisitCastExpr(const CastExpr *E) {
21293 switch (E->getCastKind()) {
21294 default:
21295 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21296 case CK_ToVoid:
21297 VisitIgnoredValue(E->getSubExpr());
21298 return true;
21299 }
21300 }
21301
21302 bool VisitCallExpr(const CallExpr *E) {
21303 if (!IsConstantEvaluatedBuiltinCall(E))
21304 return ExprEvaluatorBaseTy::VisitCallExpr(E);
21305
21306 switch (E->getBuiltinCallee()) {
21307 case Builtin::BI__assume:
21308 case Builtin::BI__builtin_assume:
21309 // The argument is not evaluated!
21310 return true;
21311
21312 case Builtin::BI__builtin_operator_delete:
21313 return HandleOperatorDeleteCall(Info, E);
21314
21315 default:
21316 return false;
21317 }
21318 }
21319
21320 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
21321};
21322} // end anonymous namespace
21323
21324bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
21325 // We cannot speculatively evaluate a delete expression.
21326 if (Info.SpeculativeEvaluationDepth)
21327 return false;
21328
21329 FunctionDecl *OperatorDelete = E->getOperatorDelete();
21330 if (!OperatorDelete
21331 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
21332 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
21333 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
21334 return false;
21335 }
21336
21337 const Expr *Arg = E->getArgument();
21338
21339 LValue Pointer;
21340 if (!EvaluatePointer(Arg, Pointer, Info))
21341 return false;
21342 if (Pointer.Designator.Invalid)
21343 return false;
21344
21345 // Deleting a null pointer has no effect.
21346 if (Pointer.isNullPointer()) {
21347 // This is the only case where we need to produce an extension warning:
21348 // the only other way we can succeed is if we find a dynamic allocation,
21349 // and we will have warned when we allocated it in that case.
21350 if (!Info.getLangOpts().CPlusPlus20)
21351 Info.CCEDiag(E, diag::note_constexpr_new);
21352 return true;
21353 }
21354
21355 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
21356 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
21357 if (!Alloc)
21358 return false;
21359 QualType AllocType = Pointer.Base.getDynamicAllocType();
21360
21361 // For the non-array case, the designator must be empty if the static type
21362 // does not have a virtual destructor.
21363 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
21365 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
21366 << Arg->getType()->getPointeeType() << AllocType;
21367 return false;
21368 }
21369
21370 // For a class type with a virtual destructor, the selected operator delete
21371 // is the one looked up when building the destructor.
21372 if (!E->isArrayForm() && !E->isGlobalDelete()) {
21373 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
21374 if (VirtualDelete &&
21375 !VirtualDelete
21376 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
21377 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
21378 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
21379 return false;
21380 }
21381 }
21382
21383 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
21384 (*Alloc)->Value, AllocType))
21385 return false;
21386
21387 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
21388 // The element was already erased. This means the destructor call also
21389 // deleted the object.
21390 // FIXME: This probably results in undefined behavior before we get this
21391 // far, and should be diagnosed elsewhere first.
21392 Info.FFDiag(E, diag::note_constexpr_double_delete);
21393 return false;
21394 }
21395
21396 return true;
21397}
21398
21399static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
21400 assert(!E->isValueDependent());
21401 assert(E->isPRValue() && E->getType()->isVoidType());
21402 return VoidExprEvaluator(Info).Visit(E);
21403}
21404
21405//===----------------------------------------------------------------------===//
21406// Top level Expr::EvaluateAsRValue method.
21407//===----------------------------------------------------------------------===//
21408
21409static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
21410 assert(!E->isValueDependent());
21411 // In C, function designators are not lvalues, but we evaluate them as if they
21412 // are.
21413 QualType T = E->getType();
21414 if (E->isGLValue() || T->isFunctionType()) {
21415 LValue LV;
21416 if (!EvaluateLValue(E, LV, Info))
21417 return false;
21418 LV.moveInto(Result);
21419 } else if (T->isVectorType()) {
21420 if (!EvaluateVector(E, Result, Info))
21421 return false;
21422 } else if (T->isConstantMatrixType()) {
21423 if (!EvaluateMatrix(E, Result, Info))
21424 return false;
21425 } else if (T->isIntegralOrEnumerationType()) {
21426 if (!IntExprEvaluator(Info, Result).Visit(E))
21427 return false;
21428 } else if (T->hasPointerRepresentation()) {
21429 LValue LV;
21430 if (!EvaluatePointer(E, LV, Info))
21431 return false;
21432 LV.moveInto(Result);
21433 } else if (T->isRealFloatingType()) {
21434 llvm::APFloat F(0.0);
21435 if (!EvaluateFloat(E, F, Info))
21436 return false;
21437 Result = APValue(F);
21438 } else if (T->isAnyComplexType()) {
21439 ComplexValue C;
21440 if (!EvaluateComplex(E, C, Info))
21441 return false;
21442 C.moveInto(Result);
21443 } else if (T->isFixedPointType()) {
21444 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
21445 } else if (T->isMemberPointerType()) {
21446 MemberPtr P;
21447 if (!EvaluateMemberPointer(E, P, Info))
21448 return false;
21449 P.moveInto(Result);
21450 return true;
21451 } else if (T->isArrayType()) {
21452 LValue LV;
21453 APValue &Value =
21454 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
21455 if (!EvaluateArray(E, LV, Value, Info))
21456 return false;
21457 Result = Value;
21458 } else if (T->isRecordType()) {
21459 LValue LV;
21460 APValue &Value =
21461 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
21462 if (!EvaluateRecord(E, LV, Value, Info))
21463 return false;
21464 Result = Value;
21465 } else if (T->isVoidType()) {
21466 if (!Info.getLangOpts().CPlusPlus11)
21467 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
21468 << E->getType();
21469 if (!EvaluateVoid(E, Info))
21470 return false;
21471 } else if (T->isAtomicType()) {
21473 if (Unqual->isArrayType() || Unqual->isRecordType()) {
21474 LValue LV;
21475 APValue &Value = Info.CurrentCall->createTemporary(
21476 E, Unqual, ScopeKind::FullExpression, LV);
21477 if (!EvaluateAtomic(E, &LV, Value, Info))
21478 return false;
21479 Result = Value;
21480 } else {
21481 if (!EvaluateAtomic(E, nullptr, Result, Info))
21482 return false;
21483 }
21484 } else if (Info.getLangOpts().CPlusPlus11) {
21485 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
21486 return false;
21487 } else {
21488 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
21489 return false;
21490 }
21491
21492 return true;
21493}
21494
21495/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
21496/// cases, the in-place evaluation is essential, since later initializers for
21497/// an object can indirectly refer to subobjects which were initialized earlier.
21498static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
21499 const Expr *E, bool AllowNonLiteralTypes) {
21500 assert(!E->isValueDependent());
21501
21502 // Normally expressions passed to EvaluateInPlace have a type, but not when
21503 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
21504 // replaced with a CXXConstructExpr. This can happen in LLDB.
21505 if (E->getType().isNull())
21506 return false;
21507
21508 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
21509 return false;
21510
21511 if (E->isPRValue()) {
21512 // Evaluate arrays and record types in-place, so that later initializers can
21513 // refer to earlier-initialized members of the object.
21514 QualType T = E->getType();
21515 if (T->isArrayType())
21516 return EvaluateArray(E, This, Result, Info);
21517 else if (T->isRecordType())
21518 return EvaluateRecord(E, This, Result, Info);
21519 else if (T->isAtomicType()) {
21521 if (Unqual->isArrayType() || Unqual->isRecordType())
21522 return EvaluateAtomic(E, &This, Result, Info);
21523 }
21524 }
21525
21526 // For any other type, in-place evaluation is unimportant.
21527 return Evaluate(Result, Info, E);
21528}
21529
21530/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
21531/// lvalue-to-rvalue cast if it is an lvalue.
21532static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
21533 assert(!E->isValueDependent());
21534
21535 if (E->getType().isNull())
21536 return false;
21537
21538 if (!CheckLiteralType(Info, E))
21539 return false;
21540
21541 if (Info.EnableNewConstInterp) {
21542 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
21543 return false;
21544 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
21545 ConstantExprKind::Normal);
21546 }
21547
21548 if (!::Evaluate(Result, Info, E))
21549 return false;
21550
21551 // Implicit lvalue-to-rvalue cast.
21552 if (E->isGLValue()) {
21553 LValue LV;
21554 LV.setFrom(Info.Ctx, Result);
21555 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
21556 return false;
21557 }
21558
21559 // Check this core constant expression is a constant expression.
21560 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
21561 ConstantExprKind::Normal) &&
21562 CheckMemoryLeaks(Info);
21563}
21564
21565static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
21566 const ASTContext &Ctx, bool &IsConst) {
21567 // Fast-path evaluations of integer literals, since we sometimes see files
21568 // containing vast quantities of these.
21569 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
21570 Result =
21571 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
21572 IsConst = true;
21573 return true;
21574 }
21575
21576 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
21577 Result = APValue(APSInt(APInt(1, L->getValue())));
21578 IsConst = true;
21579 return true;
21580 }
21581
21582 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
21583 Result = APValue(FL->getValue());
21584 IsConst = true;
21585 return true;
21586 }
21587
21588 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
21589 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
21590 IsConst = true;
21591 return true;
21592 }
21593
21594 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
21595 if (CE->hasAPValueResult()) {
21596 APValue APV = CE->getAPValueResult();
21597 if (!APV.isLValue()) {
21598 Result = std::move(APV);
21599 IsConst = true;
21600 return true;
21601 }
21602 }
21603
21604 // The SubExpr is usually just an IntegerLiteral.
21605 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
21606 }
21607
21608 // This case should be rare, but we need to check it before we check on
21609 // the type below.
21610 if (Exp->getType().isNull()) {
21611 IsConst = false;
21612 return true;
21613 }
21614
21615 return false;
21616}
21617
21620 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
21621 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
21622}
21623
21625 const ASTContext &Ctx, EvalInfo &Info) {
21626 assert(!E->isValueDependent());
21627 bool IsConst;
21628 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
21629 return IsConst;
21630
21631 return EvaluateAsRValue(Info, E, Result.Val);
21632}
21633
21635 const ASTContext &Ctx,
21636 Expr::SideEffectsKind AllowSideEffects,
21637 EvalInfo &Info) {
21638 assert(!E->isValueDependent());
21640 return false;
21641
21642 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
21643 !ExprResult.Val.isInt() ||
21644 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21645 return false;
21646
21647 return true;
21648}
21649
21651 const ASTContext &Ctx,
21652 Expr::SideEffectsKind AllowSideEffects,
21653 EvalInfo &Info) {
21654 assert(!E->isValueDependent());
21655 if (!E->getType()->isFixedPointType())
21656 return false;
21657
21658 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
21659 return false;
21660
21661 if (!ExprResult.Val.isFixedPoint() ||
21662 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21663 return false;
21664
21665 return true;
21666}
21667
21668/// EvaluateAsRValue - Return true if this is a constant which we can fold using
21669/// any crazy technique (that has nothing to do with language standards) that
21670/// we want to. If this function returns true, it returns the folded constant
21671/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
21672/// will be applied to the result.
21674 bool InConstantContext) const {
21675 assert(!isValueDependent() &&
21676 "Expression evaluator can't be called on a dependent expression.");
21677 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
21678 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21679 Info.InConstantContext = InConstantContext;
21680 return ::EvaluateAsRValue(this, Result, Ctx, Info);
21681}
21682
21684 bool InConstantContext) const {
21685 assert(!isValueDependent() &&
21686 "Expression evaluator can't be called on a dependent expression.");
21687 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
21688 EvalResult Scratch;
21689 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
21690 HandleConversionToBool(Scratch.Val, Result);
21691}
21692
21694 SideEffectsKind AllowSideEffects,
21695 bool InConstantContext) const {
21696 assert(!isValueDependent() &&
21697 "Expression evaluator can't be called on a dependent expression.");
21698 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
21699 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21700 Info.InConstantContext = InConstantContext;
21701 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
21702}
21703
21705 SideEffectsKind AllowSideEffects,
21706 bool InConstantContext) const {
21707 assert(!isValueDependent() &&
21708 "Expression evaluator can't be called on a dependent expression.");
21709 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
21710 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21711 Info.InConstantContext = InConstantContext;
21712 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
21713}
21714
21715bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
21716 SideEffectsKind AllowSideEffects,
21717 bool InConstantContext) const {
21718 assert(!isValueDependent() &&
21719 "Expression evaluator can't be called on a dependent expression.");
21720
21721 if (!getType()->isRealFloatingType())
21722 return false;
21723
21724 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
21726 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
21727 !ExprResult.Val.isFloat() ||
21728 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21729 return false;
21730
21731 Result = ExprResult.Val.getFloat();
21732 return true;
21733}
21734
21736 bool InConstantContext) const {
21737 assert(!isValueDependent() &&
21738 "Expression evaluator can't be called on a dependent expression.");
21739
21740 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
21741 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
21742 Info.InConstantContext = InConstantContext;
21743 LValue LV;
21744 CheckedTemporaries CheckedTemps;
21745
21746 if (Info.EnableNewConstInterp) {
21747 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
21748 ConstantExprKind::Normal))
21749 return false;
21750
21751 LV.setFrom(Ctx, Result.Val);
21753 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
21754 ConstantExprKind::Normal, CheckedTemps);
21755 }
21756
21757 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
21758 Result.HasSideEffects ||
21761 ConstantExprKind::Normal, CheckedTemps))
21762 return false;
21763
21764 LV.moveInto(Result.Val);
21765 return true;
21766}
21767
21769 APValue DestroyedValue, QualType Type,
21770 SourceLocation Loc, Expr::EvalStatus &EStatus,
21771 bool IsConstantDestruction) {
21772 EvalInfo Info(Ctx, EStatus,
21773 IsConstantDestruction ? EvaluationMode::ConstantExpression
21775 Info.setEvaluatingDecl(Base, DestroyedValue,
21776 EvalInfo::EvaluatingDeclKind::Dtor);
21777 Info.InConstantContext = IsConstantDestruction;
21778
21779 LValue LVal;
21780 LVal.set(Base);
21781
21782 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
21783 EStatus.HasSideEffects)
21784 return false;
21785
21786 if (!Info.discardCleanups())
21787 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21788
21789 return true;
21790}
21791
21793 ConstantExprKind Kind) const {
21794 assert(!isValueDependent() &&
21795 "Expression evaluator can't be called on a dependent expression.");
21796 bool IsConst;
21797 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
21798 Result.Val.hasValue())
21799 return true;
21800
21801 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
21803 EvalInfo Info(Ctx, Result, EM);
21804 Info.InConstantContext = true;
21805
21806 if (Info.EnableNewConstInterp) {
21807 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
21808 return false;
21809 return CheckConstantExpression(Info, getExprLoc(),
21810 getStorageType(Ctx, this), Result.Val, Kind);
21811 }
21812
21813 // The type of the object we're initializing is 'const T' for a class NTTP.
21814 QualType T = getType();
21815 if (Kind == ConstantExprKind::ClassTemplateArgument)
21816 T.addConst();
21817
21818 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
21819 // represent the result of the evaluation. CheckConstantExpression ensures
21820 // this doesn't escape.
21821 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
21822 APValue::LValueBase Base(&BaseMTE);
21823 Info.setEvaluatingDecl(Base, Result.Val);
21824
21825 LValue LVal;
21826 LVal.set(Base);
21827 // C++23 [intro.execution]/p5
21828 // A full-expression is [...] a constant-expression
21829 // So we need to make sure temporary objects are destroyed after having
21830 // evaluating the expression (per C++23 [class.temporary]/p4).
21831 FullExpressionRAII Scope(Info);
21832 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
21833 Result.HasSideEffects || !Scope.destroy())
21834 return false;
21835
21836 if (!Info.discardCleanups())
21837 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21838
21839 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
21840 Result.Val, Kind))
21841 return false;
21842 if (!CheckMemoryLeaks(Info))
21843 return false;
21844
21845 // If this is a class template argument, it's required to have constant
21846 // destruction too.
21847 if (Kind == ConstantExprKind::ClassTemplateArgument &&
21849 true) ||
21850 Result.HasSideEffects)) {
21851 // FIXME: Prefix a note to indicate that the problem is lack of constant
21852 // destruction.
21853 return false;
21854 }
21855
21856 return true;
21857}
21858
21860 Expr::EvalResult &EStatus,
21861 bool IsConstantInitialization) const {
21862 assert(!isValueDependent() &&
21863 "Expression evaluator can't be called on a dependent expression.");
21864 assert(VD && "Need a valid VarDecl");
21865
21866 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
21867 std::string Name;
21868 llvm::raw_string_ostream OS(Name);
21869 VD->printQualifiedName(OS);
21870 return Name;
21871 });
21872
21873 EvalInfo Info(Ctx, EStatus,
21874 (IsConstantInitialization &&
21875 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
21878 Info.setEvaluatingDecl(VD, EStatus.Val);
21879 Info.InConstantContext = IsConstantInitialization;
21880
21881 SourceLocation DeclLoc = VD->getLocation();
21882 QualType DeclTy = VD->getType();
21883
21884 if (Info.EnableNewConstInterp) {
21885 auto &InterpCtx = Ctx.getInterpContext();
21886 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, EStatus.Val))
21887 return false;
21888
21889 return CheckConstantExpression(Info, DeclLoc, DeclTy, EStatus.Val,
21890 ConstantExprKind::Normal);
21891 } else {
21892 LValue LVal;
21893 LVal.set(VD);
21894
21895 {
21896 // C++23 [intro.execution]/p5
21897 // A full-expression is ... an init-declarator ([dcl.decl]) or a
21898 // mem-initializer.
21899 // So we need to make sure temporary objects are destroyed after having
21900 // evaluated the expression (per C++23 [class.temporary]/p4).
21901 //
21902 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
21903 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
21904 // outermost FullExpr, such as ExprWithCleanups.
21905 FullExpressionRAII Scope(Info);
21906 if (!EvaluateInPlace(EStatus.Val, Info, LVal, this,
21907 /*AllowNonLiteralTypes=*/true) ||
21908 EStatus.HasSideEffects)
21909 return false;
21910 }
21911
21912 // At this point, any lifetime-extended temporaries are completely
21913 // initialized.
21914 Info.performLifetimeExtension();
21915
21916 if (!Info.discardCleanups())
21917 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21918 }
21919
21920 return CheckConstantExpression(Info, DeclLoc, DeclTy, EStatus.Val,
21921 ConstantExprKind::Normal) &&
21922 CheckMemoryLeaks(Info);
21923}
21924
21927 // This function is only meaningful for records and arrays of records.
21928 QualType VarTy = getType();
21929 if (VarTy->isArrayType()) {
21930 QualType ElemTy = getASTContext().getBaseElementType(VarTy);
21931 if (!ElemTy->isRecordType()) {
21932 ensureEvaluatedStmt()->HasConstantDestruction = true;
21933 return true;
21934 }
21935 } else if (!VarTy->isRecordType()) {
21936 ensureEvaluatedStmt()->HasConstantDestruction = true;
21937 return true;
21938 }
21939
21940 Expr::EvalStatus EStatus;
21941 EStatus.Diag = &Notes;
21942
21943 // Only treat the destruction as constant destruction if we formally have
21944 // constant initialization (or are usable in a constant expression).
21945 bool IsConstantDestruction = hasConstantInitialization();
21946 ASTContext &Ctx = getASTContext();
21947
21948 // Make a copy of the value for the destructor to mutate, if we know it.
21949 // Otherwise, treat the value as default-initialized; if the destructor works
21950 // anyway, then the destruction is constant (and must be essentially empty).
21951 APValue DestroyedValue;
21952 if (getEvaluatedValue())
21953 DestroyedValue = *getEvaluatedValue();
21954 else if (!handleDefaultInitValue(VarTy, DestroyedValue))
21955 return false;
21956
21957 if (Ctx.getLangOpts().EnableNewConstInterp) {
21958 EvalInfo Info(Ctx, EStatus,
21959 IsConstantDestruction ? EvaluationMode::ConstantExpression
21961 Info.InConstantContext = IsConstantDestruction;
21962 if (!Ctx.getInterpContext().evaluateDestruction(Info, this,
21963 std::move(DestroyedValue)))
21964 return false;
21965 ensureEvaluatedStmt()->HasConstantDestruction = true;
21966 return true;
21967 }
21968
21969 if (!EvaluateDestruction(Ctx, this, std::move(DestroyedValue), VarTy,
21970 getLocation(), EStatus, IsConstantDestruction) ||
21971 EStatus.HasSideEffects)
21972 return false;
21973
21974 ensureEvaluatedStmt()->HasConstantDestruction = true;
21975 return true;
21976}
21977
21978/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
21979/// constant folded, but discard the result.
21981 assert(!isValueDependent() &&
21982 "Expression evaluator can't be called on a dependent expression.");
21983
21985 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
21987}
21988
21989APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
21990 assert(!isValueDependent() &&
21991 "Expression evaluator can't be called on a dependent expression.");
21992
21993 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
21994 EvalResult EVResult;
21995 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
21996 Info.InConstantContext = true;
21997
21998 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
21999 (void)Result;
22000 assert(Result && "Could not evaluate expression");
22001 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22002
22003 return EVResult.Val.getInt();
22004}
22005
22008 assert(!isValueDependent() &&
22009 "Expression evaluator can't be called on a dependent expression.");
22010
22011 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
22012 EvalResult EVResult;
22013 EVResult.Diag = Diag;
22014 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
22015 Info.InConstantContext = true;
22016 Info.CheckingForUndefinedBehavior = true;
22017
22018 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
22019 (void)Result;
22020 assert(Result && "Could not evaluate expression");
22021 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22022
22023 return EVResult.Val.getInt();
22024}
22025
22027 assert(!isValueDependent() &&
22028 "Expression evaluator can't be called on a dependent expression.");
22029
22030 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
22031 bool IsConst;
22032 EvalResult EVResult;
22033 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
22034 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
22035 Info.CheckingForUndefinedBehavior = true;
22036 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
22037 }
22038}
22039
22041 assert(Val.isLValue());
22042 return IsGlobalLValue(Val.getLValueBase());
22043}
22044
22045/// isIntegerConstantExpr - this recursive routine will test if an expression is
22046/// an integer constant expression.
22047
22048/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
22049/// comma, etc
22050
22051// CheckICE - This function does the fundamental ICE checking: the returned
22052// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
22053//
22054// Note that to reduce code duplication, this helper does no evaluation
22055// itself; the caller checks whether the expression is evaluatable, and
22056// in the rare cases where CheckICE actually cares about the evaluated
22057// value, it calls into Evaluate.
22058
22059namespace {
22060
22061enum ICEKind {
22062 /// This expression is an ICE.
22063 IK_ICE,
22064 /// This expression is not an ICE, but if it isn't evaluated, it's
22065 /// a legal subexpression for an ICE. This return value is used to handle
22066 /// the comma operator in C99 mode, and non-constant subexpressions.
22067 IK_ICEIfUnevaluated,
22068 /// This expression is not an ICE, and is not a legal subexpression for one.
22069 IK_NotICE
22070};
22071
22072struct ICEDiag {
22073 ICEKind Kind;
22074 SourceLocation Loc;
22075
22076 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
22077};
22078
22079}
22080
22081static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
22082
22083static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
22084
22085static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
22086 Expr::EvalResult EVResult;
22087 Expr::EvalStatus Status;
22088 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22089
22090 Info.InConstantContext = true;
22091 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
22092 !EVResult.Val.isInt())
22093 return ICEDiag(IK_NotICE, E->getBeginLoc());
22094
22095 return NoDiag();
22096}
22097
22098static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
22099 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
22101 return ICEDiag(IK_NotICE, E->getBeginLoc());
22102
22103 switch (E->getStmtClass()) {
22104#define ABSTRACT_STMT(Node)
22105#define STMT(Node, Base) case Expr::Node##Class:
22106#define EXPR(Node, Base)
22107#include "clang/AST/StmtNodes.inc"
22108 case Expr::PredefinedExprClass:
22109 case Expr::FloatingLiteralClass:
22110 case Expr::ImaginaryLiteralClass:
22111 case Expr::StringLiteralClass:
22112 case Expr::ArraySubscriptExprClass:
22113 case Expr::MatrixSingleSubscriptExprClass:
22114 case Expr::MatrixSubscriptExprClass:
22115 case Expr::ArraySectionExprClass:
22116 case Expr::OMPArrayShapingExprClass:
22117 case Expr::OMPIteratorExprClass:
22118 case Expr::CompoundAssignOperatorClass:
22119 case Expr::CompoundLiteralExprClass:
22120 case Expr::ExtVectorElementExprClass:
22121 case Expr::MatrixElementExprClass:
22122 case Expr::DesignatedInitExprClass:
22123 case Expr::ArrayInitLoopExprClass:
22124 case Expr::ArrayInitIndexExprClass:
22125 case Expr::NoInitExprClass:
22126 case Expr::DesignatedInitUpdateExprClass:
22127 case Expr::ImplicitValueInitExprClass:
22128 case Expr::ParenListExprClass:
22129 case Expr::VAArgExprClass:
22130 case Expr::AddrLabelExprClass:
22131 case Expr::StmtExprClass:
22132 case Expr::CXXMemberCallExprClass:
22133 case Expr::CUDAKernelCallExprClass:
22134 case Expr::CXXAddrspaceCastExprClass:
22135 case Expr::CXXDynamicCastExprClass:
22136 case Expr::CXXTypeidExprClass:
22137 case Expr::CXXUuidofExprClass:
22138 case Expr::MSPropertyRefExprClass:
22139 case Expr::MSPropertySubscriptExprClass:
22140 case Expr::CXXNullPtrLiteralExprClass:
22141 case Expr::UserDefinedLiteralClass:
22142 case Expr::CXXThisExprClass:
22143 case Expr::CXXThrowExprClass:
22144 case Expr::CXXNewExprClass:
22145 case Expr::CXXDeleteExprClass:
22146 case Expr::CXXPseudoDestructorExprClass:
22147 case Expr::UnresolvedLookupExprClass:
22148 case Expr::RecoveryExprClass:
22149 case Expr::DependentScopeDeclRefExprClass:
22150 case Expr::CXXConstructExprClass:
22151 case Expr::CXXInheritedCtorInitExprClass:
22152 case Expr::CXXStdInitializerListExprClass:
22153 case Expr::CXXBindTemporaryExprClass:
22154 case Expr::ExprWithCleanupsClass:
22155 case Expr::CXXTemporaryObjectExprClass:
22156 case Expr::CXXUnresolvedConstructExprClass:
22157 case Expr::CXXDependentScopeMemberExprClass:
22158 case Expr::UnresolvedMemberExprClass:
22159 case Expr::ObjCStringLiteralClass:
22160 case Expr::ObjCBoxedExprClass:
22161 case Expr::ObjCArrayLiteralClass:
22162 case Expr::ObjCDictionaryLiteralClass:
22163 case Expr::ObjCEncodeExprClass:
22164 case Expr::ObjCMessageExprClass:
22165 case Expr::ObjCSelectorExprClass:
22166 case Expr::ObjCProtocolExprClass:
22167 case Expr::ObjCIvarRefExprClass:
22168 case Expr::ObjCPropertyRefExprClass:
22169 case Expr::ObjCSubscriptRefExprClass:
22170 case Expr::ObjCIsaExprClass:
22171 case Expr::ObjCAvailabilityCheckExprClass:
22172 case Expr::ShuffleVectorExprClass:
22173 case Expr::ConvertVectorExprClass:
22174 case Expr::BlockExprClass:
22175 case Expr::NoStmtClass:
22176 case Expr::OpaqueValueExprClass:
22177 case Expr::PackExpansionExprClass:
22178 case Expr::SubstNonTypeTemplateParmPackExprClass:
22179 case Expr::FunctionParmPackExprClass:
22180 case Expr::AsTypeExprClass:
22181 case Expr::ObjCIndirectCopyRestoreExprClass:
22182 case Expr::MaterializeTemporaryExprClass:
22183 case Expr::PseudoObjectExprClass:
22184 case Expr::AtomicExprClass:
22185 case Expr::LambdaExprClass:
22186 case Expr::CXXFoldExprClass:
22187 case Expr::CoawaitExprClass:
22188 case Expr::DependentCoawaitExprClass:
22189 case Expr::CoyieldExprClass:
22190 case Expr::SYCLUniqueStableNameExprClass:
22191 case Expr::CXXParenListInitExprClass:
22192 case Expr::HLSLOutArgExprClass:
22193 case Expr::CXXExpansionSelectExprClass:
22194 return ICEDiag(IK_NotICE, E->getBeginLoc());
22195
22196 case Expr::MemberExprClass: {
22197 if (Ctx.getLangOpts().C23) {
22198 const Expr *ME = E->IgnoreParenImpCasts();
22199 while (const auto *M = dyn_cast<MemberExpr>(ME)) {
22200 if (M->isArrow())
22201 return ICEDiag(IK_NotICE, E->getBeginLoc());
22202 ME = M->getBase()->IgnoreParenImpCasts();
22203 }
22204 const auto *DRE = dyn_cast<DeclRefExpr>(ME);
22205 if (DRE) {
22206 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
22207 VD && VD->isConstexpr())
22208 return CheckEvalInICE(E, Ctx);
22209 }
22210 }
22211 return ICEDiag(IK_NotICE, E->getBeginLoc());
22212 }
22213
22214 case Expr::InitListExprClass: {
22215 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
22216 // form "T x = { a };" is equivalent to "T x = a;".
22217 // Unless we're initializing a reference, T is a scalar as it is known to be
22218 // of integral or enumeration type.
22219 if (E->isPRValue())
22220 if (cast<InitListExpr>(E)->getNumInits() == 1)
22221 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
22222 return ICEDiag(IK_NotICE, E->getBeginLoc());
22223 }
22224
22225 case Expr::SizeOfPackExprClass:
22226 case Expr::GNUNullExprClass:
22227 case Expr::SourceLocExprClass:
22228 case Expr::EmbedExprClass:
22229 case Expr::OpenACCAsteriskSizeExprClass:
22230 return NoDiag();
22231
22232 case Expr::PackIndexingExprClass:
22233 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
22234
22235 case Expr::SubstNonTypeTemplateParmExprClass:
22236 return
22237 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
22238
22239 case Expr::ConstantExprClass:
22240 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
22241
22242 case Expr::ParenExprClass:
22243 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
22244 case Expr::GenericSelectionExprClass:
22245 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
22246 case Expr::IntegerLiteralClass:
22247 case Expr::FixedPointLiteralClass:
22248 case Expr::CharacterLiteralClass:
22249 case Expr::ObjCBoolLiteralExprClass:
22250 case Expr::CXXBoolLiteralExprClass:
22251 case Expr::CXXScalarValueInitExprClass:
22252 case Expr::TypeTraitExprClass:
22253 case Expr::ConceptSpecializationExprClass:
22254 case Expr::RequiresExprClass:
22255 case Expr::ArrayTypeTraitExprClass:
22256 case Expr::ExpressionTraitExprClass:
22257 case Expr::CXXNoexceptExprClass:
22258 case Expr::CXXReflectExprClass:
22259 return NoDiag();
22260 case Expr::CallExprClass:
22261 case Expr::CXXOperatorCallExprClass: {
22262 // C99 6.6/3 allows function calls within unevaluated subexpressions of
22263 // constant expressions, but they can never be ICEs because an ICE cannot
22264 // contain an operand of (pointer to) function type.
22265 const CallExpr *CE = cast<CallExpr>(E);
22266 if (CE->getBuiltinCallee())
22267 return CheckEvalInICE(E, Ctx);
22268 return ICEDiag(IK_NotICE, E->getBeginLoc());
22269 }
22270 case Expr::CXXRewrittenBinaryOperatorClass:
22271 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
22272 Ctx);
22273 case Expr::DeclRefExprClass: {
22274 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
22275 if (isa<EnumConstantDecl>(D))
22276 return NoDiag();
22277
22278 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
22279 // integer variables in constant expressions:
22280 //
22281 // C++ 7.1.5.1p2
22282 // A variable of non-volatile const-qualified integral or enumeration
22283 // type initialized by an ICE can be used in ICEs.
22284 //
22285 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
22286 // that mode, use of reference variables should not be allowed.
22287 const VarDecl *VD = dyn_cast<VarDecl>(D);
22288 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
22289 !VD->getType()->isReferenceType())
22290 return NoDiag();
22291
22292 return ICEDiag(IK_NotICE, E->getBeginLoc());
22293 }
22294 case Expr::UnaryOperatorClass: {
22295 const UnaryOperator *Exp = cast<UnaryOperator>(E);
22296 switch (Exp->getOpcode()) {
22297 case UO_PostInc:
22298 case UO_PostDec:
22299 case UO_PreInc:
22300 case UO_PreDec:
22301 case UO_AddrOf:
22302 case UO_Deref:
22303 case UO_Coawait:
22304 // C99 6.6/3 allows increment and decrement within unevaluated
22305 // subexpressions of constant expressions, but they can never be ICEs
22306 // because an ICE cannot contain an lvalue operand.
22307 return ICEDiag(IK_NotICE, E->getBeginLoc());
22308 case UO_Extension:
22309 case UO_LNot:
22310 case UO_Plus:
22311 case UO_Minus:
22312 case UO_Not:
22313 case UO_Real:
22314 case UO_Imag:
22315 return CheckICE(Exp->getSubExpr(), Ctx);
22316 }
22317 llvm_unreachable("invalid unary operator class");
22318 }
22319 case Expr::OffsetOfExprClass: {
22320 // Note that per C99, offsetof must be an ICE. And AFAIK, using
22321 // EvaluateAsRValue matches the proposed gcc behavior for cases like
22322 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
22323 // compliance: we should warn earlier for offsetof expressions with
22324 // array subscripts that aren't ICEs, and if the array subscripts
22325 // are ICEs, the value of the offsetof must be an integer constant.
22326 return CheckEvalInICE(E, Ctx);
22327 }
22328 case Expr::UnaryExprOrTypeTraitExprClass: {
22330 if ((Exp->getKind() == UETT_SizeOf) &&
22332 return ICEDiag(IK_NotICE, E->getBeginLoc());
22333 if (Exp->getKind() == UETT_CountOf) {
22334 QualType ArgTy = Exp->getTypeOfArgument();
22335 if (ArgTy->isVariableArrayType()) {
22336 // We need to look whether the array is multidimensional. If it is,
22337 // then we want to check the size expression manually to see whether
22338 // it is an ICE or not.
22339 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
22340 if (VAT->getElementType()->isArrayType())
22341 // Variable array size expression could be missing (e.g. int a[*][10])
22342 // In that case, it can't be a constant expression.
22343 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
22344 : ICEDiag(IK_NotICE, E->getBeginLoc());
22345
22346 // Otherwise, this is a regular VLA, which is definitely not an ICE.
22347 return ICEDiag(IK_NotICE, E->getBeginLoc());
22348 }
22349 }
22350 return NoDiag();
22351 }
22352 case Expr::BinaryOperatorClass: {
22353 const BinaryOperator *Exp = cast<BinaryOperator>(E);
22354 switch (Exp->getOpcode()) {
22355 case BO_PtrMemD:
22356 case BO_PtrMemI:
22357 case BO_Assign:
22358 case BO_MulAssign:
22359 case BO_DivAssign:
22360 case BO_RemAssign:
22361 case BO_AddAssign:
22362 case BO_SubAssign:
22363 case BO_ShlAssign:
22364 case BO_ShrAssign:
22365 case BO_AndAssign:
22366 case BO_XorAssign:
22367 case BO_OrAssign:
22368 // C99 6.6/3 allows assignments within unevaluated subexpressions of
22369 // constant expressions, but they can never be ICEs because an ICE cannot
22370 // contain an lvalue operand.
22371 return ICEDiag(IK_NotICE, E->getBeginLoc());
22372
22373 case BO_Mul:
22374 case BO_Div:
22375 case BO_Rem:
22376 case BO_Add:
22377 case BO_Sub:
22378 case BO_Shl:
22379 case BO_Shr:
22380 case BO_LT:
22381 case BO_GT:
22382 case BO_LE:
22383 case BO_GE:
22384 case BO_EQ:
22385 case BO_NE:
22386 case BO_And:
22387 case BO_Xor:
22388 case BO_Or:
22389 case BO_Comma:
22390 case BO_Cmp: {
22391 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
22392 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
22393 if (Exp->getOpcode() == BO_Div ||
22394 Exp->getOpcode() == BO_Rem) {
22395 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
22396 // we don't evaluate one.
22397 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
22398 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
22399 if (REval == 0)
22400 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22401 if (REval.isSigned() && REval.isAllOnes()) {
22402 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
22403 if (LEval.isMinSignedValue())
22404 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22405 }
22406 }
22407 }
22408 if (Exp->getOpcode() == BO_Comma) {
22409 if (Ctx.getLangOpts().C99) {
22410 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
22411 // if it isn't evaluated.
22412 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
22413 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22414 } else {
22415 // In both C89 and C++, commas in ICEs are illegal.
22416 return ICEDiag(IK_NotICE, E->getBeginLoc());
22417 }
22418 }
22419 return Worst(LHSResult, RHSResult);
22420 }
22421 case BO_LAnd:
22422 case BO_LOr: {
22423 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
22424 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
22425 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
22426 // Rare case where the RHS has a comma "side-effect"; we need
22427 // to actually check the condition to see whether the side
22428 // with the comma is evaluated.
22429 if ((Exp->getOpcode() == BO_LAnd) !=
22430 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
22431 return RHSResult;
22432 return NoDiag();
22433 }
22434
22435 return Worst(LHSResult, RHSResult);
22436 }
22437 }
22438 llvm_unreachable("invalid binary operator kind");
22439 }
22440 case Expr::ImplicitCastExprClass:
22441 case Expr::CStyleCastExprClass:
22442 case Expr::CXXFunctionalCastExprClass:
22443 case Expr::CXXStaticCastExprClass:
22444 case Expr::CXXReinterpretCastExprClass:
22445 case Expr::CXXConstCastExprClass:
22446 case Expr::ObjCBridgedCastExprClass: {
22447 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
22448 if (isa<ExplicitCastExpr>(E)) {
22449 if (const FloatingLiteral *FL
22450 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
22451 unsigned DestWidth = Ctx.getIntWidth(E->getType());
22452 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
22453 APSInt IgnoredVal(DestWidth, !DestSigned);
22454 bool Ignored;
22455 // If the value does not fit in the destination type, the behavior is
22456 // undefined, so we are not required to treat it as a constant
22457 // expression.
22458 if (FL->getValue().convertToInteger(IgnoredVal,
22459 llvm::APFloat::rmTowardZero,
22460 &Ignored) & APFloat::opInvalidOp)
22461 return ICEDiag(IK_NotICE, E->getBeginLoc());
22462 return NoDiag();
22463 }
22464 }
22465 switch (cast<CastExpr>(E)->getCastKind()) {
22466 case CK_LValueToRValue:
22467 case CK_AtomicToNonAtomic:
22468 case CK_NonAtomicToAtomic:
22469 case CK_NoOp:
22470 case CK_IntegralToBoolean:
22471 case CK_IntegralCast:
22472 return CheckICE(SubExpr, Ctx);
22473 default:
22474 return ICEDiag(IK_NotICE, E->getBeginLoc());
22475 }
22476 }
22477 case Expr::BinaryConditionalOperatorClass: {
22479 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
22480 if (CommonResult.Kind == IK_NotICE) return CommonResult;
22481 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
22482 if (FalseResult.Kind == IK_NotICE) return FalseResult;
22483 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
22484 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
22485 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
22486 return FalseResult;
22487 }
22488 case Expr::ConditionalOperatorClass: {
22490 // If the condition (ignoring parens) is a __builtin_constant_p call,
22491 // then only the true side is actually considered in an integer constant
22492 // expression, and it is fully evaluated. This is an important GNU
22493 // extension. See GCC PR38377 for discussion.
22494 if (const CallExpr *CallCE
22495 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
22496 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
22497 return CheckEvalInICE(E, Ctx);
22498 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
22499 if (CondResult.Kind == IK_NotICE)
22500 return CondResult;
22501
22502 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
22503 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
22504
22505 if (TrueResult.Kind == IK_NotICE)
22506 return TrueResult;
22507 if (FalseResult.Kind == IK_NotICE)
22508 return FalseResult;
22509 if (CondResult.Kind == IK_ICEIfUnevaluated)
22510 return CondResult;
22511 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
22512 return NoDiag();
22513 // Rare case where the diagnostics depend on which side is evaluated
22514 // Note that if we get here, CondResult is 0, and at least one of
22515 // TrueResult and FalseResult is non-zero.
22516 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
22517 return FalseResult;
22518 return TrueResult;
22519 }
22520 case Expr::CXXDefaultArgExprClass:
22521 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
22522 case Expr::CXXDefaultInitExprClass:
22523 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
22524 case Expr::ChooseExprClass: {
22525 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
22526 }
22527 case Expr::BuiltinBitCastExprClass: {
22528 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
22529 return ICEDiag(IK_NotICE, E->getBeginLoc());
22530 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
22531 }
22532 }
22533
22534 llvm_unreachable("Invalid StmtClass!");
22535}
22536
22537/// Evaluate an expression as a C++11 integral constant expression.
22539 const Expr *E,
22540 llvm::APSInt *Value) {
22542 return false;
22543
22545 if (!E->isCXX11ConstantExpr(Ctx, &Result))
22546 return false;
22547
22548 if (!Result.isInt())
22549 return false;
22550
22551 if (Value) *Value = Result.getInt();
22552 return true;
22553}
22554
22556 assert(!isValueDependent() &&
22557 "Expression evaluator can't be called on a dependent expression.");
22558
22559 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
22560
22561 if (Ctx.getLangOpts().CPlusPlus11)
22562 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
22563
22564 ICEDiag D = CheckICE(this, Ctx);
22565 if (D.Kind != IK_ICE)
22566 return false;
22567 return true;
22568}
22569
22570std::optional<llvm::APSInt>
22572 if (isValueDependent()) {
22573 // Expression evaluator can't succeed on a dependent expression.
22574 return std::nullopt;
22575 }
22576
22577 if (Ctx.getLangOpts().CPlusPlus11) {
22578 APSInt Value;
22580 return Value;
22581 return std::nullopt;
22582 }
22583
22584 if (!isIntegerConstantExpr(Ctx))
22585 return std::nullopt;
22586
22587 // The only possible side-effects here are due to UB discovered in the
22588 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
22589 // required to treat the expression as an ICE, so we produce the folded
22590 // value.
22592 Expr::EvalStatus Status;
22593 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
22594 Info.InConstantContext = true;
22595
22596 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
22597 llvm_unreachable("ICE cannot be evaluated!");
22598
22599 return ExprResult.Val.getInt();
22600}
22601
22603 assert(!isValueDependent() &&
22604 "Expression evaluator can't be called on a dependent expression.");
22605
22606 return CheckICE(this, Ctx).Kind == IK_ICE;
22607}
22608
22610 assert(!isValueDependent() &&
22611 "Expression evaluator can't be called on a dependent expression.");
22612
22613 // We support this checking in C++98 mode in order to diagnose compatibility
22614 // issues.
22615 assert(Ctx.getLangOpts().CPlusPlus);
22616
22617 bool IsConst;
22618 APValue Scratch;
22619 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
22620 if (Result)
22621 *Result = std::move(Scratch);
22622 return true;
22623 }
22624
22625 // Build evaluation settings.
22626 Expr::EvalStatus Status;
22627 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22628
22629 bool IsConstExpr =
22630 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
22631 // NOTE: We don't produce a diagnostic for this, but the callers that
22632 // call us on arbitrary full-expressions should generally not care.
22633 Info.discardCleanups() && !Status.HasSideEffects;
22634
22635 return IsConstExpr && !Status.DiagEmitted;
22636}
22637
22639 const FunctionDecl *Callee,
22641 const Expr *This) const {
22642 assert(!isValueDependent() &&
22643 "Expression evaluator can't be called on a dependent expression.");
22644
22645 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
22646 std::string Name;
22647 llvm::raw_string_ostream OS(Name);
22648 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
22649 /*Qualified=*/true);
22650 return Name;
22651 });
22652
22653 Expr::EvalStatus Status;
22654 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
22655 Info.InConstantContext = true;
22656
22657 if (Info.EnableNewConstInterp) {
22658 if (std::optional<bool> BoolResult =
22659 Info.Ctx.getInterpContext().evaluateWithSubstitution(
22660 Info, Callee, Args, This, this)) {
22661 Value = APValue(APSInt(APInt(1, static_cast<uint64_t>(*BoolResult))));
22662 return true;
22663 }
22664 return false;
22665 }
22666
22667 LValue ThisVal;
22668 const LValue *ThisPtr = nullptr;
22669 if (This) {
22670#ifndef NDEBUG
22671 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
22672 assert(MD && "Don't provide `this` for non-methods.");
22673 assert(MD->isImplicitObjectMemberFunction() &&
22674 "Don't provide `this` for methods without an implicit object.");
22675#endif
22676 if (!This->isValueDependent() &&
22677 EvaluateObjectArgument(Info, This, ThisVal) &&
22678 !Info.EvalStatus.HasSideEffects)
22679 ThisPtr = &ThisVal;
22680
22681 // Ignore any side-effects from a failed evaluation. This is safe because
22682 // they can't interfere with any other argument evaluation.
22683 Info.EvalStatus.HasSideEffects = false;
22684 }
22685
22686 CallRef Call = Info.CurrentCall->createCall(Callee);
22687 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
22688 I != E; ++I) {
22689 unsigned Idx = I - Args.begin();
22690 if (Idx >= Callee->getNumParams())
22691 break;
22692 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
22693 if ((*I)->isValueDependent() ||
22694 !EvaluateCallArg(PVD, *I, Call, Info) ||
22695 Info.EvalStatus.HasSideEffects) {
22696 // If evaluation fails, throw away the argument entirely.
22697 if (APValue *Slot = Info.getParamSlot(Call, PVD))
22698 *Slot = APValue();
22699 }
22700
22701 // Ignore any side-effects from a failed evaluation. This is safe because
22702 // they can't interfere with any other argument evaluation.
22703 Info.EvalStatus.HasSideEffects = false;
22704 }
22705
22706 // Parameter cleanups happen in the caller and are not part of this
22707 // evaluation.
22708 Info.discardCleanups();
22709 Info.EvalStatus.HasSideEffects = false;
22710
22711 // Build fake call to Callee.
22712 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
22713 Call);
22714 // FIXME: Missing ExprWithCleanups in enable_if conditions?
22715 FullExpressionRAII Scope(Info);
22716 return Evaluate(Value, Info, this) && Scope.destroy() &&
22717 !Info.EvalStatus.HasSideEffects;
22718}
22719
22722 PartialDiagnosticAt> &Diags) {
22723 // FIXME: It would be useful to check constexpr function templates, but at the
22724 // moment the constant expression evaluator cannot cope with the non-rigorous
22725 // ASTs which we build for dependent expressions.
22726 if (FD->isDependentContext())
22727 return true;
22728
22729 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
22730 std::string Name;
22731 llvm::raw_string_ostream OS(Name);
22733 /*Qualified=*/true);
22734 return Name;
22735 });
22736
22737 Expr::EvalStatus Status;
22738 Status.Diag = &Diags;
22739
22740 EvalInfo Info(FD->getASTContext(), Status,
22742 Info.InConstantContext = true;
22743 Info.CheckingPotentialConstantExpression = true;
22744
22745 // The constexpr VM attempts to compile all methods to bytecode here.
22746 if (Info.EnableNewConstInterp) {
22747 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
22748 return Diags.empty();
22749 }
22750
22751 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
22752 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
22753
22754 // Fabricate an arbitrary expression on the stack and pretend that it
22755 // is a temporary being used as the 'this' pointer.
22756 LValue This;
22757 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
22758 : Info.Ctx.IntTy);
22759 This.set({&VIE, Info.CurrentCall->Index});
22760
22762
22763 APValue Scratch;
22764 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
22765 // Evaluate the call as a constant initializer, to allow the construction
22766 // of objects of non-literal types.
22767 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
22768 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
22769 } else {
22770 SourceLocation Loc = FD->getLocation();
22772 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
22773 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
22774 /*ResultSlot=*/nullptr);
22775 }
22776
22777 return Diags.empty();
22778}
22779
22781 const FunctionDecl *FD,
22783 PartialDiagnosticAt> &Diags) {
22784 assert(!E->isValueDependent() &&
22785 "Expression evaluator can't be called on a dependent expression.");
22786
22787 Expr::EvalStatus Status;
22788 Status.Diag = &Diags;
22789
22790 EvalInfo Info(FD->getASTContext(), Status,
22792 Info.InConstantContext = true;
22793 Info.CheckingPotentialConstantExpression = true;
22794
22795 if (Info.EnableNewConstInterp) {
22796 Info.Ctx.getInterpContext().isPotentialConstantExprUnevaluated(Info, E, FD);
22797 return Diags.empty();
22798 }
22799
22800 // Fabricate a call stack frame to give the arguments a plausible cover story.
22801 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
22802 /*CallExpr=*/nullptr, CallRef());
22803
22804 APValue ResultScratch;
22805 Evaluate(ResultScratch, Info, E);
22806 return Diags.empty();
22807}
22808
22809std::optional<uint64_t> Expr::tryEvaluateObjectSize(const ASTContext &Ctx,
22810 unsigned Type) const {
22811 if (!getType()->isPointerType())
22812 return std::nullopt;
22813
22814 Expr::EvalStatus Status;
22815 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22816 if (Info.EnableNewConstInterp)
22817 return Info.Ctx.getInterpContext().tryEvaluateObjectSize(Info, this, Type);
22818 return tryEvaluateBuiltinObjectSize(this, Type, Info);
22819}
22820
22821static std::optional<uint64_t>
22822EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
22823 std::string *StringResult) {
22824 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
22825 return std::nullopt;
22826
22827 LValue String;
22828
22829 if (!EvaluatePointer(E, String, Info))
22830 return std::nullopt;
22831
22832 QualType CharTy = E->getType()->getPointeeType();
22833
22834 // Fast path: if it's a string literal, search the string value.
22835 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
22836 String.getLValueBase().dyn_cast<const Expr *>())) {
22837 StringRef Str = S->getBytes();
22838 int64_t Off = String.Offset.getQuantity();
22839 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
22840 S->getCharByteWidth() == 1 &&
22841 // FIXME: Add fast-path for wchar_t too.
22842 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
22843 Str = Str.substr(Off);
22844
22845 StringRef::size_type Pos = Str.find(0);
22846 if (Pos != StringRef::npos)
22847 Str = Str.substr(0, Pos);
22848
22849 if (StringResult)
22850 *StringResult = Str;
22851 return Str.size();
22852 }
22853
22854 // Fall through to slow path.
22855 }
22856
22857 // Slow path: scan the bytes of the string looking for the terminating 0.
22858 for (uint64_t Strlen = 0; /**/; ++Strlen) {
22859 APValue Char;
22860 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
22861 !Char.isInt())
22862 return std::nullopt;
22863 if (!Char.getInt())
22864 return Strlen;
22865 else if (StringResult)
22866 StringResult->push_back(Char.getInt().getExtValue());
22867 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
22868 return std::nullopt;
22869 }
22870}
22871
22872std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
22873 Expr::EvalStatus Status;
22874 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22875 std::string StringResult;
22876
22877 if (Info.EnableNewConstInterp) {
22878 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
22879 return std::nullopt;
22880 return StringResult;
22881 }
22882
22883 if (EvaluateBuiltinStrLen(this, Info, &StringResult))
22884 return StringResult;
22885 return std::nullopt;
22886}
22887
22888template <typename T>
22890 const Expr *SizeExpression,
22891 const Expr *PtrExpression,
22892 ASTContext &Ctx,
22893 Expr::EvalResult &Status) {
22894 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22895 Info.InConstantContext = true;
22896
22897 if (Info.EnableNewConstInterp)
22898 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
22899 PtrExpression, Result);
22900
22901 LValue String;
22902 FullExpressionRAII Scope(Info);
22903 APSInt SizeValue;
22904 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
22905 return false;
22906
22907 uint64_t Size = SizeValue.getZExtValue();
22908
22909 // FIXME: better protect against invalid or excessive sizes
22910 if constexpr (std::is_same_v<APValue, T>)
22911 Result = APValue(APValue::UninitArray{}, Size, Size);
22912 else {
22913 if (Size < Result.max_size())
22914 Result.reserve(Size);
22915 }
22916 if (!::EvaluatePointer(PtrExpression, String, Info))
22917 return false;
22918
22919 QualType CharTy = PtrExpression->getType()->getPointeeType();
22920 for (uint64_t I = 0; I < Size; ++I) {
22921 APValue Char;
22922 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
22923 Char))
22924 return false;
22925
22926 if constexpr (std::is_same_v<APValue, T>) {
22927 Result.getArrayInitializedElt(I) = std::move(Char);
22928 } else {
22929 APSInt C = Char.getInt();
22930
22931 assert(C.getBitWidth() <= 8 &&
22932 "string element not representable in char");
22933
22934 Result.push_back(static_cast<char>(C.getExtValue()));
22935 }
22936
22937 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
22938 return false;
22939 }
22940
22941 return Scope.destroy() && CheckMemoryLeaks(Info);
22942}
22943
22945 const Expr *SizeExpression,
22946 const Expr *PtrExpression, ASTContext &Ctx,
22947 EvalResult &Status) const {
22948 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
22949 PtrExpression, Ctx, Status);
22950}
22951
22953 const Expr *SizeExpression,
22954 const Expr *PtrExpression, ASTContext &Ctx,
22955 EvalResult &Status) const {
22956 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
22957 PtrExpression, Ctx, Status);
22958}
22959
22960std::optional<uint64_t> Expr::tryEvaluateStrLen(const ASTContext &Ctx) const {
22961 Expr::EvalStatus Status;
22962 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
22963
22964 if (Info.EnableNewConstInterp)
22965 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this);
22966 return EvaluateBuiltinStrLen(this, Info);
22967}
22968
22969namespace {
22970struct IsWithinLifetimeHandler {
22971 EvalInfo &Info;
22972 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
22973 using result_type = std::optional<bool>;
22974 std::optional<bool> failed() { return std::nullopt; }
22975 template <typename T>
22976 std::optional<bool> found(T &Subobj, QualType SubobjType,
22978 return true;
22979 }
22980 template <typename T>
22981 std::optional<bool> found(T &Subobj, QualType SubobjType) {
22982 return true;
22983 }
22984};
22985
22986std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
22987 const CallExpr *E) {
22988 EvalInfo &Info = IEE.Info;
22989 // Sometimes this is called during some sorts of constant folding / early
22990 // evaluation. These are meant for non-constant expressions and are not
22991 // necessary since this consteval builtin will never be evaluated at runtime.
22992 // Just fail to evaluate when not in a constant context.
22993 if (!Info.InConstantContext)
22994 return std::nullopt;
22995 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
22996 const Expr *Arg = E->getArg(0);
22997 if (Arg->isValueDependent())
22998 return std::nullopt;
22999 LValue Val;
23000 if (!EvaluatePointer(Arg, Val, Info))
23001 return std::nullopt;
23002
23003 if (Val.allowConstexprUnknown())
23004 return true;
23005
23006 auto Error = [&](int Diag) {
23007 bool CalledFromStd = false;
23008 const auto *Callee = Info.CurrentCall->getCallee();
23009 if (Callee && Callee->isInStdNamespace()) {
23010 const IdentifierInfo *Identifier = Callee->getIdentifier();
23011 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
23012 }
23013 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
23014 : E->getExprLoc(),
23015 diag::err_invalid_is_within_lifetime)
23016 << (CalledFromStd ? "std::is_within_lifetime"
23017 : "__builtin_is_within_lifetime")
23018 << Diag;
23019 return std::nullopt;
23020 };
23021 // C++2c [meta.const.eval]p4:
23022 // During the evaluation of an expression E as a core constant expression, a
23023 // call to this function is ill-formed unless p points to an object that is
23024 // usable in constant expressions or whose complete object's lifetime began
23025 // within E.
23026
23027 // Make sure it points to an object
23028 // nullptr does not point to an object
23029 if (Val.isNullPointer() || Val.getLValueBase().isNull())
23030 return Error(0);
23031 QualType T = Val.getLValueBase().getType();
23032 assert(!T->isFunctionType() &&
23033 "Pointers to functions should have been typed as function pointers "
23034 "which would have been rejected earlier");
23035 assert(T->isObjectType());
23036 // Hypothetical array element is not an object
23037 if (Val.getLValueDesignator().isOnePastTheEnd())
23038 return Error(1);
23039 assert(Val.getLValueDesignator().isValidSubobject() &&
23040 "Unchecked case for valid subobject");
23041 // All other ill-formed values should have failed EvaluatePointer, so the
23042 // object should be a pointer to an object that is usable in a constant
23043 // expression or whose complete lifetime began within the expression
23044 CompleteObject CO =
23045 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
23046 // The lifetime hasn't begun yet if we are still evaluating the
23047 // initializer ([basic.life]p(1.2))
23048 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
23049 return Error(2);
23050
23051 if (!CO)
23052 return false;
23053 IsWithinLifetimeHandler handler{Info};
23054 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
23055}
23056} // 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:25
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.
unsigned ConvertBuiltinIDToX86BuiltinID(const ASTContext &Ctx, unsigned BuiltinOp)
Convert a builtin ID to the canonical x86 builtin ID the constant evaluators dispatch on in their x86...
static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E, APFloat OrigVal, APValue &Result)
static ICEDiag Worst(ICEDiag A, ICEDiag B)
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, const VarDecl *VD, CallStackFrame *Frame, unsigned Version, APValue *&Result)
Try to evaluate the initializer for a variable declaration.
static bool handleDefaultInitValue(QualType T, APValue &Result)
Get the value to use for a default-initialized object of type T.
static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, uint64_t Size, uint64_t Idx)
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base)
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const LValue &LVal, ConstantExprKind Kind, CheckedTemporaries &CheckedTemps)
Check that this reference or pointer core constant expression is a valid value for an address or refe...
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, const APSInt &LHS, const APSInt &RHS, unsigned BitWidth, Operation Op, APSInt &Result)
Perform the given integer operation, which is known to need at most BitWidth bits,...
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info)
Evaluate an expression of record type as a temporary.
static bool EvaluateArray(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, APValue &Value, const FieldDecl *FD)
static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E, QualType ElemType, APValue const &VecVal1, APValue const &VecVal2, unsigned EltNum, APValue &Result)
static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static const ValueDecl * HandleMemberPointerAccess(EvalInfo &Info, QualType LVType, LValue &LV, const Expr *RHS, bool IncludeMember=true)
HandleMemberPointerAccess - Evaluate a member access operation and build an lvalue referring to the r...
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, LValue &Result)
HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on the provided lvalue,...
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info)
static bool IsOpaqueConstantCall(const CallExpr *E)
Should this call expression be treated as forming an opaque constant?
static bool CheckMemberPointerConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Member pointers are constant expressions unless they point to a non-virtual dllimport member function...
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal, APValue &RVal, bool WantObjectRepresentation=false)
Perform an lvalue-to-rvalue conversion on the given glvalue.
static bool handleElementwiseCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &SrcTypes, SmallVectorImpl< QualType > &DestTypes, SmallVectorImpl< APValue > &Results)
static bool refersToCompleteObject(const LValue &LVal)
Tests to see if the LValue has a user-specified designator (that isn't necessarily valid)....
static bool AreElementsOfSameArray(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B)
Determine whether the given subobject designators refer to elements of the same array object.
static bool EvaluateDecompositionDeclInit(EvalInfo &Info, const DecompositionDecl *DD)
static bool IsWeakLValue(const LValue &Value)
static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, APValue &Result, const CXXConstructExpr *CCE, QualType AllocType)
static bool EvaluateRecord(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, APValue &Val)
Perform an assignment of Val to LVal. Takes ownership of Val.
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, const RecordDecl *TruncatedType, unsigned TruncatedElements)
Cast an lvalue referring to a base subobject to a derived class, by truncating the lvalue's path to t...
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E)
Evaluate an expression to see if it had side-effects, and discard its result.
static bool constructAggregate(EvalInfo &Info, const FPOptions FPO, const Expr *E, APValue &Result, QualType ResultType, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &ElTypes)
static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T, const LValue &LV, CharUnits &Size)
If we're evaluating the object size of an instance of a struct that contains a flexible array member,...
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, QualType Type, LValue &Result)
static bool evalShuffleGeneric(EvalInfo &Info, const CallExpr *Call, APValue &Out, llvm::function_ref< std::pair< unsigned, int >(unsigned, unsigned)> GetSourceIndex)
static QualType getSubobjectType(QualType ObjType, QualType SubobjType, bool IsMutable=false)
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate an integer or fixed point expression into an APResult.
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
static const CXXRecordDecl * getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength)
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, const CXXRecordDecl *DerivedRD, const CXXRecordDecl *BaseRD)
Cast an lvalue referring to a derived class to a known base subobject.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
static bool HandleConversionToBool(const APValue &Val, bool &Result)
static void expandVector(APValue &Vec, unsigned NumElements)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
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 std::optional< uint64_t > tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, bool IsDynamic=false)
Tries to evaluate the __builtin_object_size for E. If successful, returns true and stores the 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.
Result
Implement __builtin_bit_cast and related operations.
static bool isModification(AccessKinds AK)
Definition Interp.cpp:147
#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
llvm::json::Object Object
llvm::json::Array Array
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:1001
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:626
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition APValue.cpp:468
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:1016
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1084
APValue & getUnionValue()
Definition APValue.h:683
CharUnits & getLValueOffset()
Definition APValue.cpp:1011
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:703
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:1077
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:974
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:223
SourceManager & getSourceManager()
Definition ASTContext.h:869
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.
Builtin::Context & BuiltinInfo
Definition ASTContext.h:810
const LangOptions & getLangOpts() const
Definition ASTContext.h:965
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:928
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:861
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
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:927
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:4579
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5995
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6000
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2756
uint64_t getValue() const
Definition ExprCXX.h:3048
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
QualType getElementType() const
Definition TypeBase.h:3798
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8246
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:4459
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4513
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4497
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4494
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4177
Expr * getLHS() const
Definition Expr.h:4094
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4138
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4144
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4191
SourceLocation getExprLoc() const
Definition Expr.h:4085
Expr * getRHS() const
Definition Expr.h:4096
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4130
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4121
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4180
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4257
Opcode getOpcode() const
Definition Expr.h:4089
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4141
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4835
const BlockDecl * getBlockDecl() const
Definition Expr.h:6696
bool isAuxBuiltinID(unsigned ID) const
Return true if the builtin ID belongs exclusively to the AuxTarget, and false if it belongs to both p...
Definition Builtins.h:443
unsigned getAuxBuiltinID(unsigned ID) const
Return real builtin ID (i.e.
Definition Builtins.h:449
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
const Expr * getSubExpr() const
Definition ExprCXX.h:1519
bool getValue() const
Definition ExprCXX.h:744
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1621
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1654
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3047
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition DeclCXX.h:2716
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1112
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2669
bool isArrayForm() const
Definition ExprCXX.h:2656
bool isGlobalDelete() const
Definition ExprCXX.h:2655
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:136
DeclStmt * getBeginStmt()
Definition StmtCXX.h:164
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:170
DeclStmt * getEndStmt()
Definition StmtCXX.h:167
DeclStmt * getRangeStmt()
Definition StmtCXX.h:163
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1792
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
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:2717
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:2724
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2868
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
bool isInstance() const
Definition DeclCXX.h:2172
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2749
bool isStatic() const
Definition DeclCXX.cpp:2415
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2728
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2893
bool isArray() const
Definition ExprCXX.h:2468
QualType getAllocatedType() const
Definition ExprCXX.h:2438
std::optional< Expr * > getArraySize()
This might return std::nullopt even if isArray() returns true, since there might not be an array size...
Definition ExprCXX.h:2473
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2507
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2498
SourceRange getSourceRange() const
Definition ExprCXX.h:2614
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2463
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2537
bool getValue() const
Definition ExprCXX.h:4332
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
Definition DeclCXX.h:1238
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:1377
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:1102
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1191
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2127
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:308
bool isImplicit() const
Definition ExprCXX.h:1181
bool isTypeOperand() const
Definition ExprCXX.h:888
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:166
Expr * getExprOperand() const
Definition ExprCXX.h:899
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:134
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1118
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
SourceLocation getBeginLoc() const
Definition Expr.h:3283
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
Definition Expr.cpp:3601
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1598
Expr * getCallee()
Definition Expr.h:3096
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3140
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3242
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3143
Decl * getCalleeDecl()
Definition Expr.h:3126
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1609
CaseStmt - Represent a case statement.
Definition Stmt.h:1930
Expr * getLHS()
Definition Stmt.h:2013
Expr * getRHS()
Definition Stmt.h:2025
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3682
path_iterator path_begin()
Definition Expr.h:3752
unsigned path_size() const
Definition Expr.h:3751
CastKind getCastKind() const
Definition Expr.h:3726
const FieldDecl * getTargetUnionField() const
Definition Expr.h:3776
path_iterator path_end()
Definition Expr.h:3753
const CXXBaseSpecifier *const * path_const_iterator
Definition Expr.h:3749
bool path_empty() const
Definition Expr.h:3750
Expr * getSubExpr()
Definition Expr.h:3732
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition Expr.h:3796
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:1635
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4890
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:3339
QualType getElementType() const
Definition TypeBase.h:3349
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4306
QualType getComputationLHSType() const
Definition Expr.h:4340
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3611
bool hasStaticStorage() const
Definition Expr.h:3656
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
Definition Expr.cpp:5703
bool isFileScope() const
Definition Expr.h:3643
const Expr * getInitializer() const
Definition Expr.h:3639
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1750
bool body_empty() const
Definition Stmt.h:1794
Stmt *const * const_body_iterator
Definition Stmt.h:1822
body_iterator body_end()
Definition Stmt.h:1815
body_range body()
Definition Stmt.h:1813
body_iterator body_begin()
Definition Stmt.h:1814
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
ConditionalOperator - The ?
Definition Expr.h:4397
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4429
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4420
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4424
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3887
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:251
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:291
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:3913
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3894
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3920
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3880
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3900
APValue getAPValueResult() const
Definition Expr.cpp:419
bool hasAPValueResult() const
Definition Expr.h:1163
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4451
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:4802
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4815
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:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2259
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:1276
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1480
ValueDecl * getDecl()
Definition Expr.h:1344
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1641
decl_range decls()
Definition Stmt.h:1689
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:453
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
A decomposition declaration.
Definition DeclCXX.h:4270
auto flat_bindings() const
Definition DeclCXX.h:4315
InitListExpr * getUpdater() const
Definition Expr.h:5948
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2842
Stmt * getBody()
Definition Stmt.h:2867
Expr * getCond()
Definition Stmt.h:2860
Symbolic representation of a dynamic allocation.
Definition APValue.h:65
static unsigned getMaxIndex()
Definition APValue.h:85
const Expr * getBase() const
Definition Expr.h:6593
ChildElementIter< false > begin()
Definition Expr.h:5247
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3934
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3961
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:85
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:677
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:681
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition Expr.h:679
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:3104
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:3999
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
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:3095
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 EvaluateAsInitializer(const ASTContext &Ctx, const VarDecl *VD, EvalResult &Result, bool IsConstantInitializer) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
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:3697
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:3262
Expr()=delete
ConstantExprKind
Definition Expr.h:755
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:283
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...
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:4446
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4559
bool isFPConstrained() const
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3204
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3307
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4750
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3289
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3440
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3451
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:105
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1581
llvm::APFloat getValue() const
Definition Expr.h:1672
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2898
Stmt * getInit()
Definition Stmt.h:2913
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2942
Expr * getInc()
Definition Stmt.h:2941
Expr * getCond()
Definition Stmt.h:2940
const Expr * getSubExpr() const
Definition Expr.h:1068
Represents a function declaration or definition.
Definition Decl.h:2029
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2837
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3257
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4183
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4171
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3843
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2413
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4307
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2506
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:3404
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2421
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:3102
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:6480
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:2269
Stmt * getThen()
Definition Stmt.h:2358
Stmt * getInit()
Definition Stmt.h:2419
bool isNonNegatedConsteval() const
Definition Stmt.h:2454
Expr * getCond()
Definition Stmt.h:2346
Stmt * getElse()
Definition Stmt.h:2367
bool isConsteval() const
Definition Stmt.h:2449
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
const Expr * getSubExpr() const
Definition Expr.h:1749
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6069
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3511
ArrayRef< NamedDecl * > chain() const
Definition Decl.h:3532
Describes an C or C++ initializer list.
Definition Expr.h:5314
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2471
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2457
unsigned getNumInits() const
Definition Expr.h:5347
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5417
const Expr * getInit(unsigned Init) const
Definition Expr.h:5369
ArrayRef< Expr * > inits() const
Definition Expr.h:5367
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2110
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2098
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1407
@ 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...
bool isCompatibleWith(ClangABI Version) const
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4920
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4945
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4937
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:4953
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
Expr * getBase() const
Definition Expr.h:3447
bool isArrow() const
Definition Expr.h:3554
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition Decl.cpp:1688
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:68
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2592
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2580
TypeSourceInfo * getTypeSourceInfo() const
Definition Expr.h:2573
unsigned getNumComponents() const
Definition Expr.h:2588
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2485
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition Expr.h:2491
@ Array
An index into an array.
Definition Expr.h:2432
@ Identifier
A field in a dependent type, known only by its name.
Definition Expr.h:2436
@ Field
A field.
Definition Expr.h:2434
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition Expr.h:2439
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2481
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition Expr.h:2501
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1184
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1234
Expr * getSelectedExpr() const
Definition ExprCXX.h:4639
const Expr * getSubExpr() const
Definition Expr.h:2205
Represents a parameter to a function.
Definition Decl.h:1819
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1879
bool isExplicitObjectParameter() const
Definition Decl.h:1907
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
StringLiteral * getFunctionName()
Definition Expr.h:2055
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6864
ArrayRef< Expr * > semantics()
Definition Expr.h:6888
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2970
QualType withConst() const
Definition TypeBase.h:1174
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1171
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:8447
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:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
void removeLocalVolatile()
Definition TypeBase.h:8563
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1179
void removeLocalConst()
Definition TypeBase.h:8555
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1719
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1560
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8493
bool isWrapType() const
Returns true if it is a OverflowBehaviorType of Wrap kind.
Definition Type.cpp:3060
Represents a struct/union/class.
Definition Decl.h:4369
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
Definition Decl.h:4585
field_iterator field_end() const
Definition Decl.h:4575
field_range fields() const
Definition Decl.h:4572
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4569
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4421
bool field_empty() const
Definition Decl.h:4580
field_iterator field_begin() const
Definition Decl.cpp:5273
bool isSatisfied() const
Whether or not the requires clause is satisfied.
SourceLocation getLocation() const
Definition Expr.h:2161
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:593
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:4649
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4701
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4682
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4688
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4515
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2289
bool isIntType() const
Definition Expr.h:5056
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:4618
Stmt - This represents one statement.
Definition Stmt.h:86
@ NoStmtClass
Definition Stmt.h:89
StmtClass getStmtClass() const
Definition Stmt.h:1503
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:1805
unsigned getLength() const
Definition Expr.h:1915
StringRef getBytes() const
Allow access to clients that need the byte representation, such as ASTWriterStmt::VisitStringLiteral(...
Definition Expr.h:1881
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1888
StringRef getString() const
Definition Expr.h:1873
unsigned getCharByteWidth() const
Definition Expr.h:1916
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1903
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2519
Expr * getCond()
Definition Stmt.h:2582
Stmt * getBody()
Definition Stmt.h:2594
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2599
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2650
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4897
bool isUnion() const
Definition Decl.h:3972
Exposes information about the current target.
Definition TargetInfo.h:227
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
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:8429
bool getBoolValue() const
Definition ExprCXX.h:2951
const APValue & getAPValue() const
Definition ExprCXX.h:2956
bool isStoredAsBoolean() const
Definition ExprCXX.h:2947
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
bool isFunctionReferenceType() const
Definition TypeBase.h:8758
bool isMFloat8Type() const
Definition TypeBase.h:9075
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2293
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:455
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3117
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2270
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:761
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9353
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2359
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2177
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:8787
bool isNothrowT() const
Definition Type.cpp:3301
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:749
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2521
bool isArrayType() const
Definition TypeBase.h:8783
bool isFunctionPointerType() const
Definition TypeBase.h:8751
bool isCountAttributedType() const
Definition Type.cpp:778
bool isConstantMatrixType() const
Definition TypeBase.h:8851
bool isPointerType() const
Definition TypeBase.h:8684
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
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:1958
bool isVariableArrayType() const
Definition TypeBase.h:8795
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2705
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9172
bool isExtVectorBoolType() const
Definition TypeBase.h:8831
bool isMemberDataPointerType() const
Definition TypeBase.h:8776
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9019
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8819
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9110
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isAtomicType() const
Definition TypeBase.h:8876
bool isComplexIntegerType() const
Definition Type.cpp:767
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9330
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2570
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:2531
bool isFunctionType() const
Definition TypeBase.h:8680
bool isVectorType() const
Definition TypeBase.h:8823
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2409
bool isFloatingType() const
Definition Type.cpp:2393
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:2336
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2992
bool isAnyPointerType() const
Definition TypeBase.h:8692
TypeClass getTypeClass() const
Definition TypeBase.h:2445
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isNullPtrType() const
Definition TypeBase.h:9087
bool isRecordType() const
Definition TypeBase.h:8811
bool isUnionType() const
Definition Type.cpp:755
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2667
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition TypeBase.h:9221
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2631
QualType getArgumentType() const
Definition Expr.h:2674
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2710
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2700
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2663
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
SourceLocation getExprLoc() const
Definition Expr.h:2374
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
static bool isIncrementOp(Opcode Op)
Definition Expr.h:2332
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2304
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:5579
QualType getType() const
Definition Value.cpp:238
bool hasValue() const
Definition Value.h:135
Represents a variable declaration or definition.
Definition Decl.h:932
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1593
bool hasInit() const
Definition Decl.cpp:2377
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition Decl.cpp:2618
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1602
const APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or nullptr if the value is not yet...
Definition Decl.cpp:2610
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2838
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2630
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2345
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:2465
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2536
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:1214
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1183
const Expr * getInit() const
Definition Decl.h:1391
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2554
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1190
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2354
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1274
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:2507
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1381
Expr * getSizeExpr() const
Definition TypeBase.h:4044
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
QualType getElementType() const
Definition TypeBase.h:4253
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2707
Expr * getCond()
Definition Stmt.h:2759
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2771
bool evaluateDestruction(State &Parent, const VarDecl *VD, APValue Value)
Evaluates the destruction of a variable.
Definition Context.cpp:164
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 Sub(InterpState &S, CodePtr OpPC)
Definition Interp.h:435
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1510
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:57
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3150
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:3854
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
AccessKind
This enum distinguishes between different ways to access (read or write) a variable.
ASTEdit note(RangeSelector Anchor, TextGenerator Note)
Generates a single, no-op edit with the associated note anchored at the start location of the specifi...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
const Expr * findStructFieldAccess(const Expr *E, const Expr **OutArrayIndex=nullptr, QualType *OutArrayElementTy=nullptr)
Walk E through parens, implicit casts, unary &/*, array subscripts and comma operators to find the he...
Definition Expr.cpp:5768
bool hasSpecificAttr(const Container &container)
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:351
@ Success
Annotation was successful.
Definition Parser.h:65
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1048
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:218
@ AS_public
Definition Specifiers.h:125
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition ASTLambda.h:45
@ TSCS_unspecified
Definition Specifiers.h:237
Expr * Cond
};
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
CheckSubobjectKind
The order of this enum is important for diagnostics.
Definition State.h:44
@ CSK_ArrayToPointer
Definition State.h:48
@ CSK_Derived
Definition State.h:46
@ CSK_Base
Definition State.h:45
@ CSK_Real
Definition State.h:50
@ CSK_ArrayIndex
Definition State.h:49
@ CSK_Imag
Definition State.h:51
@ CSK_VectorElement
Definition State.h:52
@ CSK_Field
Definition State.h:47
@ SD_Static
Static storage duration.
Definition Specifiers.h:344
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:341
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition State.h:28
@ AK_TypeId
Definition State.h:36
@ AK_Construct
Definition State.h:37
@ AK_Increment
Definition State.h:32
@ AK_DynamicCast
Definition State.h:35
@ AK_Read
Definition State.h:29
@ AK_Assign
Definition State.h:31
@ AK_IsWithinLifetime
Definition State.h:39
@ AK_MemberCall
Definition State.h:34
@ AK_ReadObjectRepresentation
Definition State.h:30
@ AK_Dereference
Definition State.h:40
@ AK_Destroy
Definition State.h:38
@ AK_Decrement
Definition State.h:33
@ Off
Never emit colors regardless of the output stream.
@ Type
The name was classified as a type.
Definition Sema.h:564
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
EvaluationMode
Definition State.h:55
@ ConstantFold
Fold the expression to a constant.
Definition State.h:69
@ ConstantExpressionUnevaluated
Evaluate as a constant expression.
Definition State.h:65
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:58
@ IgnoreSideEffects
Evaluate in any way we know how.
Definition State.h:73
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ 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:5981
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1774
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
unsigned long uint64_t
long int64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
hash_code hash_value(const clang::dependencies::ModuleID &ID)
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 int32_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 uint16_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#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:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
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:640
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
unsigned SuppressLambdaBody
Whether to suppress printing the body of a lambda.
DenseMapInfo< APValue::LValueBase > Base
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