clang 24.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 static unsigned countNonVirtualBases(const CXXRecordDecl *RD) {
119 return llvm::count_if(RD->bases(), [](auto &B) { return !B.isVirtual(); });
120 }
121
122 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
123 /// This will look through a single cast.
124 ///
125 /// Returns null if we couldn't unwrap a function with alloc_size.
126 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
127 if (!E->getType()->isPointerType())
128 return nullptr;
129
130 E = E->IgnoreParens();
131 // If we're doing a variable assignment from e.g. malloc(N), there will
132 // probably be a cast of some kind. In exotic cases, we might also see a
133 // top-level ExprWithCleanups. Ignore them either way.
134 if (const auto *FE = dyn_cast<FullExpr>(E))
135 E = FE->getSubExpr()->IgnoreParens();
136
137 if (const auto *Cast = dyn_cast<CastExpr>(E))
138 E = Cast->getSubExpr()->IgnoreParens();
139
140 if (const auto *CE = dyn_cast<CallExpr>(E))
141 return CE->getCalleeAllocSizeAttr() ? CE : nullptr;
142 return nullptr;
143 }
144
145 /// Determines whether or not the given Base contains a call to a function
146 /// with the alloc_size attribute.
147 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
148 const auto *E = Base.dyn_cast<const Expr *>();
149 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
150 }
151
152 /// Determines whether the given kind of constant expression is only ever
153 /// used for name mangling. If so, it's permitted to reference things that we
154 /// can't generate code for (in particular, dllimported functions).
155 static bool isForManglingOnly(ConstantExprKind Kind) {
156 switch (Kind) {
157 case ConstantExprKind::Normal:
158 case ConstantExprKind::ClassTemplateArgument:
159 case ConstantExprKind::ImmediateInvocation:
160 // Note that non-type template arguments of class type are emitted as
161 // template parameter objects.
162 return false;
163
164 case ConstantExprKind::NonClassTemplateArgument:
165 return true;
166 }
167 llvm_unreachable("unknown ConstantExprKind");
168 }
169
170 static bool isTemplateArgument(ConstantExprKind Kind) {
171 switch (Kind) {
172 case ConstantExprKind::Normal:
173 case ConstantExprKind::ImmediateInvocation:
174 return false;
175
176 case ConstantExprKind::ClassTemplateArgument:
177 case ConstantExprKind::NonClassTemplateArgument:
178 return true;
179 }
180 llvm_unreachable("unknown ConstantExprKind");
181 }
182
183 /// The bound to claim that an array of unknown bound has.
184 /// The value in MostDerivedArraySize is undefined in this case. So, set it
185 /// to an arbitrary value that's likely to loudly break things if it's used.
186 static const uint64_t AssumedSizeForUnsizedArray =
187 std::numeric_limits<uint64_t>::max() / 2;
188
189 /// Determines if an LValue with the given LValueBase will have an unsized
190 /// array in its designator.
191 /// Find the path length and type of the most-derived subobject in the given
192 /// path, and find the size of the containing array, if any.
193 static unsigned
194 findMostDerivedSubobject(const ASTContext &Ctx, APValue::LValueBase Base,
196 uint64_t &ArraySize, QualType &Type, bool &IsArray,
197 bool &FirstEntryIsUnsizedArray) {
198 // This only accepts LValueBases from APValues, and APValues don't support
199 // arrays that lack size info.
200 assert(!isBaseAnAllocSizeCall(Base) &&
201 "Unsized arrays shouldn't appear here");
202 unsigned MostDerivedLength = 0;
203 // The type of Base is a reference type if the base is a constexpr-unknown
204 // variable. In that case, look through the reference type.
205 Type = getType(Base).getNonReferenceType();
206
207 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
208 if (Type->isArrayType()) {
209 const ArrayType *AT = Ctx.getAsArrayType(Type);
210 Type = AT->getElementType();
211 MostDerivedLength = I + 1;
212 IsArray = true;
213
214 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
215 ArraySize = CAT->getZExtSize();
216 } else {
217 assert(I == 0 && "unexpected unsized array designator");
218 FirstEntryIsUnsizedArray = true;
219 ArraySize = AssumedSizeForUnsizedArray;
220 }
221 } else if (Type->isAnyComplexType()) {
222 const ComplexType *CT = Type->castAs<ComplexType>();
223 Type = CT->getElementType();
224 ArraySize = 2;
225 MostDerivedLength = I + 1;
226 IsArray = true;
227 } else if (const auto *VT = Type->getAs<VectorType>()) {
228 Type = VT->getElementType();
229 ArraySize = VT->getNumElements();
230 MostDerivedLength = I + 1;
231 IsArray = true;
232 } else if (const FieldDecl *FD = getAsField(Path[I])) {
233 Type = FD->getType();
234 ArraySize = 0;
235 MostDerivedLength = I + 1;
236 IsArray = false;
237 } else {
238 // Path[I] describes a base class.
239 ArraySize = 0;
240 IsArray = false;
241 }
242 }
243 return MostDerivedLength;
244 }
245
246 /// A path from a glvalue to a subobject of that glvalue.
247 struct SubobjectDesignator {
248 /// True if the subobject was named in a manner not supported by C++11. Such
249 /// lvalues can still be folded, but they are not core constant expressions
250 /// and we cannot perform lvalue-to-rvalue conversions on them.
251 LLVM_PREFERRED_TYPE(bool)
252 unsigned Invalid : 1;
253
254 /// Is this a pointer one past the end of an object?
255 LLVM_PREFERRED_TYPE(bool)
256 unsigned IsOnePastTheEnd : 1;
257
258 /// Indicator of whether the first entry is an unsized array.
259 LLVM_PREFERRED_TYPE(bool)
260 unsigned FirstEntryIsAnUnsizedArray : 1;
261
262 /// Indicator of whether the most-derived object is an array element.
263 LLVM_PREFERRED_TYPE(bool)
264 unsigned MostDerivedIsArrayElement : 1;
265
266 /// The length of the path to the most-derived object of which this is a
267 /// subobject.
268 unsigned MostDerivedPathLength : 28;
269
270 /// The size of the array of which the most-derived object is an element.
271 /// This will always be 0 if the most-derived object is not an array
272 /// element. 0 is not an indicator of whether or not the most-derived object
273 /// is an array, however, because 0-length arrays are allowed.
274 ///
275 /// If the current array is an unsized array, the value of this is
276 /// undefined.
277 uint64_t MostDerivedArraySize;
278 /// The type of the most derived object referred to by this address.
279 QualType MostDerivedType;
280
281 typedef APValue::LValuePathEntry PathEntry;
282
283 /// The entries on the path from the glvalue to the designated subobject.
285
286 SubobjectDesignator() : Invalid(true) {}
287
288 explicit SubobjectDesignator(QualType T)
289 : Invalid(false), IsOnePastTheEnd(false),
290 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
291 MostDerivedPathLength(0), MostDerivedArraySize(0),
292 MostDerivedType(T.isNull() ? QualType() : T.getNonReferenceType()) {}
293
294 SubobjectDesignator(const ASTContext &Ctx, const APValue &V)
295 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
296 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
297 MostDerivedPathLength(0), MostDerivedArraySize(0) {
298 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
299 if (!Invalid) {
300 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
301 llvm::append_range(Entries, V.getLValuePath());
302 if (V.getLValueBase()) {
303 bool IsArray = false;
304 bool FirstIsUnsizedArray = false;
305 MostDerivedPathLength = findMostDerivedSubobject(
306 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
307 MostDerivedType, IsArray, FirstIsUnsizedArray);
308 MostDerivedIsArrayElement = IsArray;
309 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
310 }
311 }
312 }
313
314 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
315 unsigned NewLength) {
316 if (Invalid)
317 return;
318
319 assert(Base && "cannot truncate path for null pointer");
320 assert(NewLength <= Entries.size() && "not a truncation");
321
322 if (NewLength == Entries.size())
323 return;
324 Entries.resize(NewLength);
325
326 bool IsArray = false;
327 bool FirstIsUnsizedArray = false;
328 MostDerivedPathLength = findMostDerivedSubobject(
329 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
330 FirstIsUnsizedArray);
331 MostDerivedIsArrayElement = IsArray;
332 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
333 }
334
335 void setInvalid() {
336 Invalid = true;
337 Entries.clear();
338 }
339
340 /// Determine whether the most derived subobject is an array without a
341 /// known bound.
342 bool isMostDerivedAnUnsizedArray() const {
343 assert(!Invalid && "Calling this makes no sense on invalid designators");
344 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
345 }
346
347 /// Determine what the most derived array's size is. Results in an assertion
348 /// failure if the most derived array lacks a size.
349 uint64_t getMostDerivedArraySize() const {
350 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
351 return MostDerivedArraySize;
352 }
353
354 /// Determine whether this is a one-past-the-end pointer.
355 bool isOnePastTheEnd() const {
356 assert(!Invalid);
357 if (IsOnePastTheEnd)
358 return true;
359 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
360 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
361 MostDerivedArraySize)
362 return true;
363 return false;
364 }
365
366 /// Get the range of valid index adjustments in the form
367 /// {maximum value that can be subtracted from this pointer,
368 /// maximum value that can be added to this pointer}
369 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
370 if (Invalid || isMostDerivedAnUnsizedArray())
371 return {0, 0};
372
373 // [expr.add]p4: For the purposes of these operators, a pointer to a
374 // nonarray object behaves the same as a pointer to the first element of
375 // an array of length one with the type of the object as its element type.
376 bool IsArray = MostDerivedPathLength == Entries.size() &&
377 MostDerivedIsArrayElement;
378 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
379 : (uint64_t)IsOnePastTheEnd;
380 uint64_t ArraySize =
381 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
382 return {ArrayIndex, ArraySize - ArrayIndex};
383 }
384
385 /// Check that this refers to a valid subobject.
386 bool isValidSubobject() const {
387 if (Invalid)
388 return false;
389 return !isOnePastTheEnd();
390 }
391 /// Check that this refers to a valid subobject, and if not, produce a
392 /// relevant diagnostic and set the designator as invalid.
393 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
394
395 /// Get the type of the designated object.
396 QualType getType(ASTContext &Ctx) const {
397 assert(!Invalid && "invalid designator has no subobject type");
398 return MostDerivedPathLength == Entries.size()
399 ? MostDerivedType
400 : Ctx.getCanonicalTagType(getAsBaseClass(Entries.back()));
401 }
402
403 /// Update this designator to refer to the first element within this array.
404 void addArrayUnchecked(const ConstantArrayType *CAT) {
405 Entries.push_back(PathEntry::ArrayIndex(0));
406
407 // This is a most-derived object.
408 MostDerivedType = CAT->getElementType();
409 MostDerivedIsArrayElement = true;
410 MostDerivedArraySize = CAT->getZExtSize();
411 MostDerivedPathLength = Entries.size();
412 }
413 /// Update this designator to refer to the first element within the array of
414 /// elements of type T. This is an array of unknown size.
415 void addUnsizedArrayUnchecked(QualType ElemTy) {
416 Entries.push_back(PathEntry::ArrayIndex(0));
417
418 MostDerivedType = ElemTy;
419 MostDerivedIsArrayElement = true;
420 // The value in MostDerivedArraySize is undefined in this case. So, set it
421 // to an arbitrary value that's likely to loudly break things if it's
422 // used.
423 MostDerivedArraySize = AssumedSizeForUnsizedArray;
424 MostDerivedPathLength = Entries.size();
425 }
426 /// Update this designator to refer to the given base or member of this
427 /// object.
428 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
429 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
430
431 // If this isn't a base class, it's a new most-derived object.
432 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
433 MostDerivedType = FD->getType();
434 MostDerivedIsArrayElement = false;
435 MostDerivedArraySize = 0;
436 MostDerivedPathLength = Entries.size();
437 }
438 }
439 /// Update this designator to refer to the given complex component.
440 void addComplexUnchecked(QualType EltTy, bool Imag) {
441 Entries.push_back(PathEntry::ArrayIndex(Imag));
442
443 // This is technically a most-derived object, though in practice this
444 // is unlikely to matter.
445 MostDerivedType = EltTy;
446 MostDerivedIsArrayElement = true;
447 MostDerivedArraySize = 2;
448 MostDerivedPathLength = Entries.size();
449 }
450
451 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
452 uint64_t Idx) {
453 Entries.push_back(PathEntry::ArrayIndex(Idx));
454 MostDerivedType = EltTy;
455 MostDerivedPathLength = Entries.size();
456 MostDerivedArraySize = 0;
457 MostDerivedIsArrayElement = false;
458 }
459
460 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
461 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
462 const APSInt &N);
463 /// Add N to the address of this subobject.
464 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N, const LValue &LV);
465 };
466
467 /// A scope at the end of which an object can need to be destroyed.
468 enum class ScopeKind {
469 Block,
470 FullExpression,
471 Call
472 };
473
474 /// A reference to a particular call and its arguments.
475 struct CallRef {
476 CallRef() : OrigCallee(), CallIndex(0), Version() {}
477 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
478 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
479
480 explicit operator bool() const { return OrigCallee; }
481
482 /// Get the parameter that the caller initialized, corresponding to the
483 /// given parameter in the callee.
484 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
485 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
486 : PVD;
487 }
488
489 /// The callee at the point where the arguments were evaluated. This might
490 /// be different from the actual callee (a different redeclaration, or a
491 /// virtual override), but this function's parameters are the ones that
492 /// appear in the parameter map.
493 const FunctionDecl *OrigCallee;
494 /// The call index of the frame that holds the argument values.
495 unsigned CallIndex;
496 /// The version of the parameters corresponding to this call.
497 unsigned Version;
498 };
499
500 /// A stack frame in the constexpr call stack.
501 class CallStackFrame : public interp::Frame {
502 public:
503 EvalInfo &Info;
504
505 /// Parent - The caller of this stack frame.
506 CallStackFrame *Caller;
507
508 /// Callee - The function which was called.
509 const FunctionDecl *Callee;
510
511 /// This - The binding for the this pointer in this call, if any.
512 const LValue *This;
513
514 /// CallExpr - The syntactical structure of member function calls
515 const Expr *CallExpr;
516
517 /// Information on how to find the arguments to this call. Our arguments
518 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
519 /// key and this value as the version.
520 CallRef Arguments;
521
522 /// Source location information about the default argument or default
523 /// initializer expression we're evaluating, if any.
524 CurrentSourceLocExprScope CurSourceLocExprScope;
525
526 // Note that we intentionally use std::map here so that references to
527 // values are stable.
528 typedef std::pair<const void *, unsigned> MapKeyTy;
529 typedef std::map<MapKeyTy, APValue> MapTy;
530 /// Temporaries - Temporary lvalues materialized within this stack frame.
531 MapTy Temporaries;
532
533 /// CallRange - The source range of the call expression for this call.
534 SourceRange CallRange;
535
536 /// Index - The call index of this call.
537 unsigned Index;
538
539 /// The stack of integers for tracking version numbers for temporaries.
540 SmallVector<unsigned, 2> TempVersionStack = {1};
541 unsigned CurTempVersion = TempVersionStack.back();
542
543 unsigned getTempVersion() const { return TempVersionStack.back(); }
544
545 void pushTempVersion() {
546 TempVersionStack.push_back(++CurTempVersion);
547 }
548
549 void popTempVersion() {
550 TempVersionStack.pop_back();
551 }
552
553 CallRef createCall(const FunctionDecl *Callee) {
554 return {Callee, Index, ++CurTempVersion};
555 }
556
557 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
558 // on the overall stack usage of deeply-recursing constexpr evaluations.
559 // (We should cache this map rather than recomputing it repeatedly.)
560 // But let's try this and see how it goes; we can look into caching the map
561 // as a later change.
562
563 /// LambdaCaptureFields - Mapping from captured variables/this to
564 /// corresponding data members in the closure class.
565 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
566 FieldDecl *LambdaThisCaptureField = nullptr;
567
568 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
569 const FunctionDecl *Callee, const LValue *This,
570 const Expr *CallExpr, CallRef Arguments);
571 ~CallStackFrame();
572
573 // Return the temporary for Key whose version number is Version.
574 APValue *getTemporary(const void *Key, unsigned Version) {
575 MapKeyTy KV(Key, Version);
576 auto LB = Temporaries.lower_bound(KV);
577 if (LB != Temporaries.end() && LB->first == KV)
578 return &LB->second;
579 return nullptr;
580 }
581
582 // Return the current temporary for Key in the map.
583 APValue *getCurrentTemporary(const void *Key) {
584 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
585 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
586 return &std::prev(UB)->second;
587 return nullptr;
588 }
589
590 // Return the version number of the current temporary for Key.
591 unsigned getCurrentTemporaryVersion(const void *Key) const {
592 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
593 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
594 return std::prev(UB)->first.second;
595 return 0;
596 }
597
598 /// Allocate storage for an object of type T in this stack frame.
599 /// Populates LV with a handle to the created object. Key identifies
600 /// the temporary within the stack frame, and must not be reused without
601 /// bumping the temporary version number.
602 template<typename KeyT>
603 APValue &createTemporary(const KeyT *Key, QualType T,
604 ScopeKind Scope, LValue &LV);
605
606 /// Allocate storage for a parameter of a function call made in this frame.
607 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
608
609 void describe(llvm::raw_ostream &OS) const override;
610
611 Frame *getCaller() const override { return Caller; }
612 SourceRange getCallRange() const override { return CallRange; }
613 const FunctionDecl *getCallee() const override { return Callee; }
614
615 bool isStdFunction() const {
616 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
617 if (DC->isStdNamespace())
618 return true;
619 return false;
620 }
621
622 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
623 /// permitted. See MSConstexprDocs for description of permitted contexts.
624 bool CanEvalMSConstexpr = false;
625
626 private:
627 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
628 ScopeKind Scope);
629 };
630
631 /// Temporarily override 'this'.
632 class ThisOverrideRAII {
633 public:
634 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
635 : Frame(Frame), OldThis(Frame.This) {
636 if (Enable)
637 Frame.This = NewThis;
638 }
639 ~ThisOverrideRAII() {
640 Frame.This = OldThis;
641 }
642 private:
643 CallStackFrame &Frame;
644 const LValue *OldThis;
645 };
646
647 // A shorthand time trace scope struct, prints source range, for example
648 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
649 class ExprTimeTraceScope {
650 public:
651 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
652 : TimeScope(Name, [E, &Ctx] {
654 }) {}
655
656 private:
657 llvm::TimeTraceScope TimeScope;
658 };
659
660 /// RAII object used to change the current ability of
661 /// [[msvc::constexpr]] evaulation.
662 struct MSConstexprContextRAII {
663 CallStackFrame &Frame;
664 bool OldValue;
665 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
666 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
667 Frame.CanEvalMSConstexpr = Value;
668 }
669
670 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
671 };
672}
673
674static bool HandleDestruction(EvalInfo &Info, const Expr *E,
675 const LValue &This, QualType ThisType);
676static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
678 QualType T);
679
680namespace {
681 /// A cleanup, and a flag indicating whether it is lifetime-extended.
682 class Cleanup {
683 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
684 APValue::LValueBase Base;
685 QualType T;
686
687 public:
688 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
689 ScopeKind Scope)
690 : Value(Val, Scope), Base(Base), T(T) {}
691
692 /// Determine whether this cleanup should be performed at the end of the
693 /// given kind of scope.
694 bool isDestroyedAtEndOf(ScopeKind K) const {
695 return (int)Value.getInt() >= (int)K;
696 }
697 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
698 if (RunDestructors) {
699 SourceLocation Loc;
700 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
701 Loc = VD->getLocation();
702 else if (const Expr *E = Base.dyn_cast<const Expr*>())
703 Loc = E->getExprLoc();
704 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
705 }
706 *Value.getPointer() = APValue();
707 return true;
708 }
709
710 bool hasSideEffect() {
711 return T.isDestructedType();
712 }
713 };
714
715 /// A reference to an object whose construction we are currently evaluating.
716 struct ObjectUnderConstruction {
717 APValue::LValueBase Base;
718 ArrayRef<APValue::LValuePathEntry> Path;
719 friend bool operator==(const ObjectUnderConstruction &LHS,
720 const ObjectUnderConstruction &RHS) {
721 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
722 }
723 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
724 return llvm::hash_combine(Obj.Base, Obj.Path);
725 }
726 };
727 enum class ConstructionPhase {
728 None,
729 Bases,
730 AfterBases,
731 AfterFields,
732 Destroying,
733 DestroyingBases
734 };
735}
736
737namespace llvm {
738template<> struct DenseMapInfo<ObjectUnderConstruction> {
739 using Base = DenseMapInfo<APValue::LValueBase>;
740 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
741 return hash_value(Object);
742 }
743 static bool isEqual(const ObjectUnderConstruction &LHS,
744 const ObjectUnderConstruction &RHS) {
745 return LHS == RHS;
746 }
747};
748}
749
750namespace {
751 /// A dynamically-allocated heap object.
752 struct DynAlloc {
753 /// The value of this heap-allocated object.
754 APValue Value;
755 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
756 /// or a CallExpr (the latter is for direct calls to operator new inside
757 /// std::allocator<T>::allocate).
758 const Expr *AllocExpr = nullptr;
759
760 enum Kind {
761 New,
762 ArrayNew,
763 StdAllocator
764 };
765
766 /// Get the kind of the allocation. This must match between allocation
767 /// and deallocation.
768 Kind getKind() const {
769 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
770 return NE->isArray() ? ArrayNew : New;
771 assert(isa<CallExpr>(AllocExpr));
772 return StdAllocator;
773 }
774 };
775
776 struct DynAllocOrder {
777 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
778 return L.getIndex() < R.getIndex();
779 }
780 };
781
782 /// EvalInfo - This is a private struct used by the evaluator to capture
783 /// information about a subexpression as it is folded. It retains information
784 /// about the AST context, but also maintains information about the folded
785 /// expression.
786 ///
787 /// If an expression could be evaluated, it is still possible it is not a C
788 /// "integer constant expression" or constant expression. If not, this struct
789 /// captures information about how and why not.
790 ///
791 /// One bit of information passed *into* the request for constant folding
792 /// indicates whether the subexpression is "evaluated" or not according to C
793 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
794 /// evaluate the expression regardless of what the RHS is, but C only allows
795 /// certain things in certain situations.
796 class EvalInfo final : public interp::State {
797 public:
798 /// CurrentCall - The top of the constexpr call stack.
799 CallStackFrame *CurrentCall;
800
801 /// CallStackDepth - The number of calls in the call stack right now.
802 unsigned CallStackDepth;
803
804 /// NextCallIndex - The next call index to assign.
805 unsigned NextCallIndex;
806
807 /// StepsLeft - The remaining number of evaluation steps we're permitted
808 /// to perform. This is essentially a limit for the number of statements
809 /// we will evaluate.
810 unsigned StepsLeft;
811
812 /// Enable the experimental new constant interpreter. If an expression is
813 /// not supported by the interpreter, an error is triggered.
814 bool EnableNewConstInterp;
815
816 /// BottomFrame - The frame in which evaluation started. This must be
817 /// initialized after CurrentCall and CallStackDepth.
818 CallStackFrame BottomFrame;
819
820 /// A stack of values whose lifetimes end at the end of some surrounding
821 /// evaluation frame.
822 llvm::SmallVector<Cleanup, 16> CleanupStack;
823
824 /// EvaluatingDecl - This is the declaration whose initializer is being
825 /// evaluated, if any.
826 APValue::LValueBase EvaluatingDecl;
827
828 enum class EvaluatingDeclKind {
829 None,
830 /// We're evaluating the construction of EvaluatingDecl.
831 Ctor,
832 /// We're evaluating the destruction of EvaluatingDecl.
833 Dtor,
834 };
835 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
836
837 /// EvaluatingDeclValue - This is the value being constructed for the
838 /// declaration whose initializer is being evaluated, if any.
839 APValue *EvaluatingDeclValue;
840
841 /// Stack of loops and 'switch' statements which we're currently
842 /// breaking/continuing; null entries are used to mark unlabeled
843 /// break/continue.
844 SmallVector<const Stmt *> BreakContinueStack;
845
846 /// Set of objects that are currently being constructed.
847 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
848 ObjectsUnderConstruction;
849
850 /// Current heap allocations, along with the location where each was
851 /// allocated. We use std::map here because we need stable addresses
852 /// for the stored APValues.
853 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
854
855 /// The number of heap allocations performed so far in this evaluation.
856 unsigned NumHeapAllocs = 0;
857
858 struct EvaluatingConstructorRAII {
859 EvalInfo &EI;
860 ObjectUnderConstruction Object;
861 bool DidInsert;
862 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
863 bool HasBases)
864 : EI(EI), Object(Object) {
865 DidInsert =
866 EI.ObjectsUnderConstruction
867 .insert({Object, HasBases ? ConstructionPhase::Bases
868 : ConstructionPhase::AfterBases})
869 .second;
870 }
871 void finishedConstructingBases() {
872 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
873 }
874 void finishedConstructingFields() {
875 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
876 }
877 ~EvaluatingConstructorRAII() {
878 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
879 }
880 };
881
882 struct EvaluatingDestructorRAII {
883 EvalInfo &EI;
884 ObjectUnderConstruction Object;
885 bool DidInsert;
886 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
887 : EI(EI), Object(Object) {
888 DidInsert = EI.ObjectsUnderConstruction
889 .insert({Object, ConstructionPhase::Destroying})
890 .second;
891 }
892 void startedDestroyingBases() {
893 EI.ObjectsUnderConstruction[Object] =
894 ConstructionPhase::DestroyingBases;
895 }
896 ~EvaluatingDestructorRAII() {
897 if (DidInsert)
898 EI.ObjectsUnderConstruction.erase(Object);
899 }
900 };
901
902 ConstructionPhase
903 isEvaluatingCtorDtor(APValue::LValueBase Base,
904 ArrayRef<APValue::LValuePathEntry> Path) {
905 return ObjectsUnderConstruction.lookup({Base, Path});
906 }
907
908 /// If we're currently speculatively evaluating, the outermost call stack
909 /// depth at which we can mutate state, otherwise 0.
910 unsigned SpeculativeEvaluationDepth = 0;
911
912 /// The current array initialization index, if we're performing array
913 /// initialization.
914 uint64_t ArrayInitIndex = -1;
915
916 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
917 : State(const_cast<ASTContext &>(C), S), CurrentCall(nullptr),
918 CallStackDepth(0), NextCallIndex(1),
919 StepsLeft(C.getLangOpts().ConstexprStepLimit),
920 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
921 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
922 /*This=*/nullptr,
923 /*CallExpr=*/nullptr, CallRef()),
924 EvaluatingDecl((const ValueDecl *)nullptr),
925 EvaluatingDeclValue(nullptr) {
926 EvalMode = Mode;
927 }
928
929 ~EvalInfo() {
930 discardCleanups();
931 }
932
933 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
934 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
935 EvaluatingDecl = Base;
936 IsEvaluatingDecl = EDK;
937 EvaluatingDeclValue = &Value;
938 }
939
940 bool CheckCallLimit(SourceLocation Loc) {
941 // Don't perform any constexpr calls (other than the call we're checking)
942 // when checking a potential constant expression.
943 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
944 return false;
945 if (NextCallIndex == 0) {
946 // NextCallIndex has wrapped around.
947 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
948 return false;
949 }
950 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
951 return true;
952 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
953 << getLangOpts().ConstexprCallDepth;
954 return false;
955 }
956
957 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
958 uint64_t ElemCount, bool Diag) {
959 // FIXME: GH63562
960 // APValue stores array extents as unsigned,
961 // so anything that is greater that unsigned would overflow when
962 // constructing the array, we catch this here.
963 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
964 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
965 if (Diag)
966 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
967 return false;
968 }
969
970 // FIXME: GH63562
971 // Arrays allocate an APValue per element.
972 // We use the number of constexpr steps as a proxy for the maximum size
973 // of arrays to avoid exhausting the system resources, as initialization
974 // of each element is likely to take some number of steps anyway.
975 uint64_t Limit = getLangOpts().ConstexprStepLimit;
976 if (Limit != 0 && ElemCount > Limit) {
977 if (Diag) {
978 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits, 1)
979 << ElemCount << Limit;
980 Note(Loc, diag::note_constexpr_steps);
981 }
982 return false;
983 }
984 return true;
985 }
986
987 std::pair<CallStackFrame *, unsigned>
988 getCallFrameAndDepth(unsigned CallIndex) {
989 assert(CallIndex && "no call index in getCallFrameAndDepth");
990 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
991 // be null in this loop.
992 unsigned Depth = CallStackDepth;
993 CallStackFrame *Frame = CurrentCall;
994 while (Frame->Index > CallIndex) {
995 Frame = Frame->Caller;
996 --Depth;
997 }
998 if (Frame->Index == CallIndex)
999 return {Frame, Depth};
1000 return {nullptr, 0};
1001 }
1002
1003 bool nextStep(const Stmt *S) {
1004 if (getLangOpts().ConstexprStepLimit == 0)
1005 return true;
1006
1007 if (!StepsLeft) {
1008 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded, 1)
1009 << getLangOpts().ConstexprStepLimit;
1010 Note(S->getBeginLoc(), diag::note_constexpr_steps);
1011 return false;
1012 }
1013 --StepsLeft;
1014 return true;
1015 }
1016
1017 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1018
1019 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1020 std::optional<DynAlloc *> Result;
1021 auto It = HeapAllocs.find(DA);
1022 if (It != HeapAllocs.end())
1023 Result = &It->second;
1024 return Result;
1025 }
1026
1027 /// Get the allocated storage for the given parameter of the given call.
1028 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1029 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1030 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1031 : nullptr;
1032 }
1033
1034 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1035 struct StdAllocatorCaller {
1036 unsigned FrameIndex;
1037 QualType ElemType;
1038 const Expr *Call;
1039 explicit operator bool() const { return FrameIndex != 0; };
1040 };
1041
1042 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1043 for (const CallStackFrame *Call = CurrentCall; Call->Caller != nullptr;
1044 Call = Call->Caller) {
1045 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1046 if (!MD)
1047 continue;
1048 const IdentifierInfo *FnII = MD->getIdentifier();
1049 if (!FnII || !FnII->isStr(FnName))
1050 continue;
1051
1052 const auto *CTSD =
1053 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1054 if (!CTSD)
1055 continue;
1056
1057 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1058 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1059 if (CTSD->isInStdNamespace() && ClassII &&
1060 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1061 TAL[0].getKind() == TemplateArgument::Type)
1062 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1063 }
1064
1065 return {};
1066 }
1067
1068 void performLifetimeExtension() {
1069 // Disable the cleanups for lifetime-extended temporaries.
1070 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1071 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1072 });
1073 }
1074
1075 /// Throw away any remaining cleanups at the end of evaluation. If any
1076 /// cleanups would have had a side-effect, note that as an unmodeled
1077 /// side-effect and return false. Otherwise, return true.
1078 bool discardCleanups() {
1079 for (Cleanup &C : CleanupStack) {
1080 if (C.hasSideEffect() && !noteSideEffect()) {
1081 CleanupStack.clear();
1082 return false;
1083 }
1084 }
1085 CleanupStack.clear();
1086 return true;
1087 }
1088
1089 private:
1090 const interp::Frame *getCurrentFrame() override { return CurrentCall; }
1091
1092 unsigned getCallStackDepth() override { return CallStackDepth; }
1093 bool stepsLeft() const override { return StepsLeft > 0; }
1094
1095 public:
1096 /// Notes that we failed to evaluate an expression that other expressions
1097 /// directly depend on, and determine if we should keep evaluating. This
1098 /// should only be called if we actually intend to keep evaluating.
1099 ///
1100 /// Call noteSideEffect() instead if we may be able to ignore the value that
1101 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1102 ///
1103 /// (Foo(), 1) // use noteSideEffect
1104 /// (Foo() || true) // use noteSideEffect
1105 /// Foo() + 1 // use noteFailure
1106 [[nodiscard]] bool noteFailure() {
1107 // Failure when evaluating some expression often means there is some
1108 // subexpression whose evaluation was skipped. Therefore, (because we
1109 // don't track whether we skipped an expression when unwinding after an
1110 // evaluation failure) every evaluation failure that bubbles up from a
1111 // subexpression implies that a side-effect has potentially happened. We
1112 // skip setting the HasSideEffects flag to true until we decide to
1113 // continue evaluating after that point, which happens here.
1114 bool KeepGoing = keepEvaluatingAfterFailure();
1115 EvalStatus.HasSideEffects |= KeepGoing;
1116 return KeepGoing;
1117 }
1118
1119 class ArrayInitLoopIndex {
1120 EvalInfo &Info;
1121 uint64_t OuterIndex;
1122
1123 public:
1124 ArrayInitLoopIndex(EvalInfo &Info)
1125 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1126 Info.ArrayInitIndex = 0;
1127 }
1128 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1129
1130 operator uint64_t&() { return Info.ArrayInitIndex; }
1131 };
1132 };
1133
1134 /// Object used to treat all foldable expressions as constant expressions.
1135 struct FoldConstant {
1136 EvalInfo &Info;
1137 bool Enabled;
1138 bool HadNoPriorDiags;
1139 EvaluationMode OldMode;
1140
1141 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1142 : Info(Info),
1143 Enabled(Enabled),
1144 HadNoPriorDiags(Info.EvalStatus.Diag &&
1145 Info.EvalStatus.Diag->empty() &&
1146 !Info.EvalStatus.HasSideEffects),
1147 OldMode(Info.EvalMode) {
1148 if (Enabled)
1149 Info.EvalMode = EvaluationMode::ConstantFold;
1150 }
1151 void keepDiagnostics() { Enabled = false; }
1152 ~FoldConstant() {
1153 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1154 !Info.EvalStatus.HasSideEffects) {
1155 Info.EvalStatus.Diag->clear();
1156 Info.EvalStatus.DiagEmitted = false;
1157 }
1158 Info.EvalMode = OldMode;
1159 }
1160 };
1161
1162 /// RAII object used to set the current evaluation mode to ignore
1163 /// side-effects.
1164 struct IgnoreSideEffectsRAII {
1165 EvalInfo &Info;
1166 EvaluationMode OldMode;
1167 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1168 : Info(Info), OldMode(Info.EvalMode) {
1169 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1170 }
1171
1172 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1173 };
1174
1175 /// RAII object used to optionally suppress diagnostics and side-effects from
1176 /// a speculative evaluation.
1177 class SpeculativeEvaluationRAII {
1178 EvalInfo *Info = nullptr;
1179 Expr::EvalStatus OldStatus;
1180 unsigned OldSpeculativeEvaluationDepth = 0;
1181
1182 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1183 Info = Other.Info;
1184 OldStatus = Other.OldStatus;
1185 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1186 Other.Info = nullptr;
1187 }
1188
1189 void maybeRestoreState() {
1190 if (!Info)
1191 return;
1192
1193 Info->EvalStatus = OldStatus;
1194 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1195 }
1196
1197 public:
1198 SpeculativeEvaluationRAII() = default;
1199
1200 SpeculativeEvaluationRAII(
1201 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1202 : Info(&Info), OldStatus(Info.EvalStatus),
1203 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1204 Info.EvalStatus.Diag = NewDiag;
1205 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1206 }
1207
1208 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1209 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1210 moveFromAndCancel(std::move(Other));
1211 }
1212
1213 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1214 maybeRestoreState();
1215 moveFromAndCancel(std::move(Other));
1216 return *this;
1217 }
1218
1219 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1220 };
1221
1222 /// RAII object wrapping a full-expression or block scope, and handling
1223 /// the ending of the lifetime of temporaries created within it.
1224 template<ScopeKind Kind>
1225 class ScopeRAII {
1226 EvalInfo &Info;
1227 unsigned OldStackSize;
1228 public:
1229 ScopeRAII(EvalInfo &Info)
1230 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1231 // Push a new temporary version. This is needed to distinguish between
1232 // temporaries created in different iterations of a loop.
1233 Info.CurrentCall->pushTempVersion();
1234 }
1235 bool destroy(bool RunDestructors = true) {
1236 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1237 OldStackSize = std::numeric_limits<unsigned>::max();
1238 return OK;
1239 }
1240 ~ScopeRAII() {
1241 if (OldStackSize != std::numeric_limits<unsigned>::max())
1242 destroy(false);
1243 // Body moved to a static method to encourage the compiler to inline away
1244 // instances of this class.
1245 Info.CurrentCall->popTempVersion();
1246 }
1247 private:
1248 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1249 unsigned OldStackSize) {
1250 assert(OldStackSize <= Info.CleanupStack.size() &&
1251 "running cleanups out of order?");
1252
1253 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1254 // for a full-expression scope.
1255 bool Success = true;
1256 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1257 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1258 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1259 Success = false;
1260 break;
1261 }
1262 }
1263 }
1264
1265 // Compact any retained cleanups.
1266 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1267 if (Kind != ScopeKind::Block)
1268 NewEnd =
1269 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1270 return C.isDestroyedAtEndOf(Kind);
1271 });
1272 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1273 return Success;
1274 }
1275 };
1276 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1277 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1278 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1279}
1280
1281bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1282 CheckSubobjectKind CSK) {
1283 if (Invalid)
1284 return false;
1285 if (isOnePastTheEnd()) {
1286 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1287 << CSK;
1288 setInvalid();
1289 return false;
1290 }
1291 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1292 // must actually be at least one array element; even a VLA cannot have a
1293 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1294 return true;
1295}
1296
1297void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1298 const Expr *E) {
1299 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1300 // Do not set the designator as invalid: we can represent this situation,
1301 // and correct handling of __builtin_object_size requires us to do so.
1302}
1303
1304void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1305 const Expr *E,
1306 const APSInt &N) {
1307 // If we're complaining, we must be able to statically determine the size of
1308 // the most derived array.
1309 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1310 Info.CCEDiag(E, diag::note_constexpr_array_index)
1311 << N << /*array*/ 0
1312 << static_cast<unsigned>(getMostDerivedArraySize());
1313 else
1314 Info.CCEDiag(E, diag::note_constexpr_array_index)
1315 << N << /*non-array*/ 1;
1316 setInvalid();
1317}
1318
1319CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1320 const FunctionDecl *Callee, const LValue *This,
1321 const Expr *CallExpr, CallRef Call)
1322 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1323 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1324 Index(Info.NextCallIndex++) {
1325 Info.CurrentCall = this;
1326 ++Info.CallStackDepth;
1327}
1328
1329CallStackFrame::~CallStackFrame() {
1330 assert(Info.CurrentCall == this && "calls retired out of order");
1331 --Info.CallStackDepth;
1332 Info.CurrentCall = Caller;
1333}
1334
1335static bool isRead(AccessKinds AK) {
1336 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1337 AK == AK_IsWithinLifetime || AK == AK_Dereference;
1338}
1339
1341 switch (AK) {
1342 case AK_Read:
1344 case AK_MemberCall:
1345 case AK_DynamicCast:
1346 case AK_TypeId:
1348 case AK_Dereference:
1349 return false;
1350 case AK_Assign:
1351 case AK_Increment:
1352 case AK_Decrement:
1353 case AK_Construct:
1354 case AK_Destroy:
1355 return true;
1356 }
1357 llvm_unreachable("unknown access kind");
1358}
1359
1360static bool isAnyAccess(AccessKinds AK) {
1361 return isRead(AK) || isModification(AK);
1362}
1363
1364/// Is this an access per the C++ definition?
1366 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1367 AK != AK_IsWithinLifetime && AK != AK_Dereference;
1368}
1369
1370/// Is this kind of access valid on an indeterminate object value?
1372 switch (AK) {
1373 case AK_Read:
1374 case AK_Increment:
1375 case AK_Decrement:
1376 case AK_Dereference:
1377 // These need the object's value.
1378 return false;
1379
1382 case AK_Assign:
1383 case AK_Construct:
1384 case AK_Destroy:
1385 // Construction and destruction don't need the value.
1386 return true;
1387
1388 case AK_MemberCall:
1389 case AK_DynamicCast:
1390 case AK_TypeId:
1391 // These aren't really meaningful on scalars.
1392 return true;
1393 }
1394 llvm_unreachable("unknown access kind");
1395}
1396
1397namespace {
1398 struct ComplexValue {
1399 private:
1400 bool IsInt;
1401
1402 public:
1403 APSInt IntReal, IntImag;
1404 APFloat FloatReal, FloatImag;
1405
1406 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1407
1408 void makeComplexFloat() { IsInt = false; }
1409 bool isComplexFloat() const { return !IsInt; }
1410 APFloat &getComplexFloatReal() { return FloatReal; }
1411 APFloat &getComplexFloatImag() { return FloatImag; }
1412
1413 void makeComplexInt() { IsInt = true; }
1414 bool isComplexInt() const { return IsInt; }
1415 APSInt &getComplexIntReal() { return IntReal; }
1416 APSInt &getComplexIntImag() { return IntImag; }
1417
1418 void moveInto(APValue &v) const {
1419 if (isComplexFloat())
1420 v = APValue(FloatReal, FloatImag);
1421 else
1422 v = APValue(IntReal, IntImag);
1423 }
1424 void setFrom(const APValue &v) {
1425 assert(v.isComplexFloat() || v.isComplexInt());
1426 if (v.isComplexFloat()) {
1427 makeComplexFloat();
1428 FloatReal = v.getComplexFloatReal();
1429 FloatImag = v.getComplexFloatImag();
1430 } else {
1431 makeComplexInt();
1432 IntReal = v.getComplexIntReal();
1433 IntImag = v.getComplexIntImag();
1434 }
1435 }
1436 };
1437
1438 struct LValue {
1439 APValue::LValueBase Base;
1440 CharUnits Offset;
1441 SubobjectDesignator Designator;
1442 bool IsNullPtr : 1;
1443 bool InvalidBase : 1;
1444 // P2280R4 track if we have an unknown reference or pointer.
1445 bool AllowConstexprUnknown = false;
1446
1447 const APValue::LValueBase getLValueBase() const { return Base; }
1448 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1449 CharUnits &getLValueOffset() { return Offset; }
1450 const CharUnits &getLValueOffset() const { return Offset; }
1451 SubobjectDesignator &getLValueDesignator() { return Designator; }
1452 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1453 bool isNullPointer() const { return IsNullPtr;}
1454
1455 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1456 unsigned getLValueVersion() const { return Base.getVersion(); }
1457
1458 bool pointsToCompleteClass(const CXXRecordDecl *D) const {
1459 if (Designator.Entries.empty())
1460 return true;
1461
1462 return Designator.MostDerivedType->getAsCXXRecordDecl() == D;
1463 }
1464
1465 void moveInto(APValue &V) const {
1466 if (Designator.Invalid)
1467 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1468 else {
1469 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1470 V = APValue(Base, Offset, Designator.Entries,
1471 Designator.IsOnePastTheEnd, IsNullPtr);
1472 }
1473 if (AllowConstexprUnknown)
1474 V.setConstexprUnknown();
1475 }
1476 void setFrom(const ASTContext &Ctx, const APValue &V) {
1477 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1478 Base = V.getLValueBase();
1479 Offset = V.getLValueOffset();
1480 InvalidBase = false;
1481 Designator = SubobjectDesignator(Ctx, V);
1482 IsNullPtr = V.isNullPointer();
1483 AllowConstexprUnknown = V.allowConstexprUnknown();
1484 }
1485
1486 void set(APValue::LValueBase B, bool BInvalid = false) {
1487#ifndef NDEBUG
1488 // We only allow a few types of invalid bases. Enforce that here.
1489 if (BInvalid) {
1490 const auto *E = B.get<const Expr *>();
1491 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1492 "Unexpected type of invalid base");
1493 }
1494#endif
1495
1496 Base = B;
1497 Offset = CharUnits::fromQuantity(0);
1498 InvalidBase = BInvalid;
1499 Designator = SubobjectDesignator(getType(B));
1500 IsNullPtr = false;
1501 AllowConstexprUnknown = false;
1502 }
1503
1504 void setNull(ASTContext &Ctx, QualType PointerTy) {
1505 Base = (const ValueDecl *)nullptr;
1506 Offset =
1508 InvalidBase = false;
1509 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1510 IsNullPtr = true;
1511 AllowConstexprUnknown = false;
1512 }
1513
1514 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1515 set(B, true);
1516 }
1517
1518 std::string toString(ASTContext &Ctx, QualType T) const {
1519 APValue Printable;
1520 moveInto(Printable);
1521 return Printable.getAsString(Ctx, T);
1522 }
1523
1524 private:
1525 // Check that this LValue is not based on a null pointer. If it is, produce
1526 // a diagnostic and mark the designator as invalid.
1527 template <typename GenDiagType>
1528 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1529 if (Designator.Invalid)
1530 return false;
1531 if (IsNullPtr) {
1532 GenDiag();
1533 Designator.setInvalid();
1534 return false;
1535 }
1536 return true;
1537 }
1538
1539 public:
1540 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1541 CheckSubobjectKind CSK) {
1542 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1543 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1544 });
1545 }
1546
1547 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1548 AccessKinds AK) {
1549 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1550 if (AK == AccessKinds::AK_Dereference)
1551 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1552 else
1553 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1554 });
1555 }
1556
1557 // Check this LValue refers to an object. If not, set the designator to be
1558 // invalid and emit a diagnostic.
1559 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1560 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1561 Designator.checkSubobject(Info, E, CSK);
1562 }
1563
1564 void addDecl(EvalInfo &Info, const Expr *E,
1565 const Decl *D, bool Virtual = false) {
1566 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1567 Designator.addDeclUnchecked(D, Virtual);
1568 }
1569 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1570 if (!Designator.Entries.empty()) {
1571 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1572 Designator.setInvalid();
1573 return;
1574 }
1575 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1576 assert(!Base || getType(Base).getNonReferenceType()->isPointerType() ||
1577 getType(Base).getNonReferenceType()->isArrayType());
1578 Designator.FirstEntryIsAnUnsizedArray = true;
1579 Designator.addUnsizedArrayUnchecked(ElemTy);
1580 }
1581 }
1582 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1583 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1584 Designator.addArrayUnchecked(CAT);
1585 }
1586 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1587 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1588 Designator.addComplexUnchecked(EltTy, Imag);
1589 }
1590 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1591 uint64_t Size, uint64_t Idx) {
1592 if (checkSubobject(Info, E, CSK_VectorElement))
1593 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1594 }
1595 void clearIsNullPointer() {
1596 IsNullPtr = false;
1597 }
1598 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1599 const APSInt &Index, CharUnits ElementSize) {
1600 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1601 // but we're not required to diagnose it and it's valid in C++.)
1602 if (!Index)
1603 return;
1604
1605 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1606 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1607 // offsets.
1608 uint64_t Offset64 = Offset.getQuantity();
1609 uint64_t ElemSize64 = ElementSize.getQuantity();
1610 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1611 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1612
1613 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1614 Designator.adjustIndex(Info, E, Index, *this);
1615 clearIsNullPointer();
1616 }
1617 void adjustOffset(CharUnits N) {
1618 Offset += N;
1619 if (N.getQuantity())
1620 clearIsNullPointer();
1621 }
1622 };
1623
1624 struct MemberPtr {
1625 MemberPtr() {}
1626 explicit MemberPtr(const ValueDecl *Decl)
1627 : DeclAndIsDerivedMember(Decl, false) {}
1628
1629 /// The member or (direct or indirect) field referred to by this member
1630 /// pointer, or 0 if this is a null member pointer.
1631 const ValueDecl *getDecl() const {
1632 return DeclAndIsDerivedMember.getPointer();
1633 }
1634 /// Is this actually a member of some type derived from the relevant class?
1635 bool isDerivedMember() const {
1636 return DeclAndIsDerivedMember.getInt();
1637 }
1638 /// Get the class which the declaration actually lives in.
1639 const CXXRecordDecl *getContainingRecord() const {
1640 return cast<CXXRecordDecl>(
1641 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1642 }
1643
1644 void moveInto(APValue &V) const {
1645 V = APValue(getDecl(), isDerivedMember(), Path);
1646 }
1647 void setFrom(const APValue &V) {
1648 assert(V.isMemberPointer());
1649 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1650 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1651 Path.clear();
1652 llvm::append_range(Path, V.getMemberPointerPath());
1653 }
1654
1655 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1656 /// whether the member is a member of some class derived from the class type
1657 /// of the member pointer.
1658 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1659 /// Path - The path of base/derived classes from the member declaration's
1660 /// class (exclusive) to the class type of the member pointer (inclusive).
1661 SmallVector<const CXXRecordDecl*, 4> Path;
1662
1663 /// Perform a cast towards the class of the Decl (either up or down the
1664 /// hierarchy).
1665 bool castBack(const CXXRecordDecl *Class) {
1666 assert(!Path.empty());
1667 const CXXRecordDecl *Expected;
1668 if (Path.size() >= 2)
1669 Expected = Path[Path.size() - 2];
1670 else
1671 Expected = getContainingRecord();
1672 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1673 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1674 // if B does not contain the original member and is not a base or
1675 // derived class of the class containing the original member, the result
1676 // of the cast is undefined.
1677 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1678 // (D::*). We consider that to be a language defect.
1679 return false;
1680 }
1681 Path.pop_back();
1682 return true;
1683 }
1684 /// Perform a base-to-derived member pointer cast.
1685 bool castToDerived(const CXXRecordDecl *Derived) {
1686 if (!getDecl())
1687 return true;
1688 if (!isDerivedMember()) {
1689 Path.push_back(Derived);
1690 return true;
1691 }
1692 if (!castBack(Derived))
1693 return false;
1694 if (Path.empty())
1695 DeclAndIsDerivedMember.setInt(false);
1696 return true;
1697 }
1698 /// Perform a derived-to-base member pointer cast.
1699 bool castToBase(const CXXRecordDecl *Base) {
1700 if (!getDecl())
1701 return true;
1702 if (Path.empty())
1703 DeclAndIsDerivedMember.setInt(true);
1704 if (isDerivedMember()) {
1705 Path.push_back(Base);
1706 return true;
1707 }
1708 return castBack(Base);
1709 }
1710 };
1711
1712 /// Compare two member pointers, which are assumed to be of the same type.
1713 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1714 if (!LHS.getDecl() || !RHS.getDecl())
1715 return !LHS.getDecl() && !RHS.getDecl();
1716 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1717 return false;
1718 return LHS.Path == RHS.Path;
1719 }
1720}
1721
1722void SubobjectDesignator::adjustIndex(EvalInfo &Info, const Expr *E, APSInt N,
1723 const LValue &LV) {
1724 if (Invalid || !N)
1725 return;
1726 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1727 if (isMostDerivedAnUnsizedArray()) {
1728 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1729 // Can't verify -- trust that the user is doing the right thing (or if
1730 // not, trust that the caller will catch the bad behavior).
1731 // FIXME: Should we reject if this overflows, at least?
1732 Entries.back() =
1733 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1734 return;
1735 }
1736
1737 // [expr.add]p4: For the purposes of these operators, a pointer to a
1738 // nonarray object behaves the same as a pointer to the first element of
1739 // an array of length one with the type of the object as its element type.
1740 bool IsArray =
1741 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1742 uint64_t ArrayIndex =
1743 IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd;
1744 uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1;
1745
1746 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1747 if (!Info.checkingPotentialConstantExpression() ||
1748 !LV.AllowConstexprUnknown) {
1749 // Calculate the actual index in a wide enough type, so we can include
1750 // it in the note.
1751 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1752 (llvm::APInt &)N += ArrayIndex;
1753 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
1754 diagnosePointerArithmetic(Info, E, N);
1755 }
1756 setInvalid();
1757 return;
1758 }
1759
1760 ArrayIndex += TruncatedN;
1761 assert(ArrayIndex <= ArraySize &&
1762 "bounds check succeeded for out-of-bounds index");
1763
1764 if (IsArray)
1765 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1766 else
1767 IsOnePastTheEnd = (ArrayIndex != 0);
1768}
1769
1770static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1771static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1772 const LValue &This, const Expr *E,
1773 bool AllowNonLiteralTypes = false);
1774static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1775 bool InvalidBaseOK = false);
1776static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1777 bool InvalidBaseOK = false);
1778static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1779 EvalInfo &Info);
1780static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1781static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1782static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1783 EvalInfo &Info);
1784static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1785static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1786static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info);
1787static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1788 EvalInfo &Info);
1789static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1790static std::optional<uint64_t>
1791EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
1792 std::string *StringResult = nullptr);
1793
1794/// Evaluate an integer or fixed point expression into an APResult.
1795static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1796 EvalInfo &Info);
1797
1798/// Evaluate only a fixed point expression into an APResult.
1799static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1800 EvalInfo &Info);
1801
1802//===----------------------------------------------------------------------===//
1803// Misc utilities
1804//===----------------------------------------------------------------------===//
1805
1806/// Negate an APSInt in place, converting it to a signed form if necessary, and
1807/// preserving its value (by extending by up to one bit as needed).
1808static void negateAsSigned(APSInt &Int) {
1809 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1810 Int = Int.extend(Int.getBitWidth() + 1);
1811 Int.setIsSigned(true);
1812 }
1813 Int = -Int;
1814}
1815
1816template<typename KeyT>
1817APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1818 ScopeKind Scope, LValue &LV) {
1819 unsigned Version = getTempVersion();
1820 APValue::LValueBase Base(Key, Index, Version);
1821 LV.set(Base);
1822 return createLocal(Base, Key, T, Scope);
1823}
1824
1825/// Allocate storage for a parameter of a function call made in this frame.
1826APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1827 LValue &LV) {
1828 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1829 APValue::LValueBase Base(PVD, Index, Args.Version);
1830 LV.set(Base);
1831 // We always destroy parameters at the end of the call, even if we'd allow
1832 // them to live to the end of the full-expression at runtime, in order to
1833 // give portable results and match other compilers.
1834 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1835}
1836
1837APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1838 QualType T, ScopeKind Scope) {
1839 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1840 unsigned Version = Base.getVersion();
1841 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1842 assert(Result.isAbsent() && "local created multiple times");
1843
1844 // If we're creating a local immediately in the operand of a speculative
1845 // evaluation, don't register a cleanup to be run outside the speculative
1846 // evaluation context, since we won't actually be able to initialize this
1847 // object.
1848 if (Index <= Info.SpeculativeEvaluationDepth) {
1849 if (T.isDestructedType())
1850 Info.noteSideEffect();
1851 } else {
1852 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1853 }
1854 return Result;
1855}
1856
1857APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1858 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1859 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1860 return nullptr;
1861 }
1862
1863 DynamicAllocLValue DA(NumHeapAllocs++);
1865 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1866 std::forward_as_tuple(DA), std::tuple<>());
1867 assert(Result.second && "reused a heap alloc index?");
1868 Result.first->second.AllocExpr = E;
1869 return &Result.first->second.Value;
1870}
1871
1872/// Produce a string describing the given constexpr call.
1873void CallStackFrame::describe(raw_ostream &Out) const {
1874 bool IsMemberCall = false;
1875 bool ExplicitInstanceParam = false;
1876 clang::PrintingPolicy PrintingPolicy = Info.Ctx.getPrintingPolicy();
1877 PrintingPolicy.SuppressLambdaBody = true;
1878
1879 if (const auto *MD = dyn_cast<CXXMethodDecl>(Callee)) {
1880 IsMemberCall = !isa<CXXConstructorDecl>(MD) && !MD->isStatic();
1881 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
1882 }
1883
1884 if (!IsMemberCall)
1885 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1886 /*Qualified=*/false);
1887
1888 if (This && IsMemberCall) {
1889 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1890 const Expr *Object = MCE->getImplicitObjectArgument();
1891 Object->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1892 /*Indentation=*/0);
1893 if (Object->getType()->isPointerType())
1894 Out << "->";
1895 else
1896 Out << ".";
1897 } else if (const auto *OCE =
1898 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1899 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr, PrintingPolicy,
1900 /*Indentation=*/0);
1901 Out << ".";
1902 } else {
1903 APValue Val;
1904 This->moveInto(Val);
1905 Val.printPretty(
1906 Out, Info.Ctx,
1907 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1908 Out << ".";
1909 }
1910 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1911 /*Qualified=*/false);
1912 }
1913
1914 Out << '(';
1915
1916 llvm::ListSeparator Comma;
1917 for (const ParmVarDecl *Param :
1918 Callee->parameters().slice(ExplicitInstanceParam)) {
1919 Out << Comma;
1920 const APValue *V = Info.getParamSlot(Arguments, Param);
1921 if (V)
1922 V->printPretty(Out, Info.Ctx, Param->getType());
1923 else
1924 Out << "<...>";
1925 }
1926
1927 Out << ')';
1928}
1929
1930/// Evaluate an expression to see if it had side-effects, and discard its
1931/// result.
1932/// \return \c true if the caller should keep evaluating.
1933static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1934 assert(!E->isValueDependent());
1935 APValue Scratch;
1936 if (!Evaluate(Scratch, Info, E))
1937 // We don't need the value, but we might have skipped a side effect here.
1938 return Info.noteSideEffect();
1939 return true;
1940}
1941
1942/// Should this call expression be treated as forming an opaque constant?
1943static bool IsOpaqueConstantCall(const CallExpr *E) {
1944 unsigned Builtin = E->getBuiltinCallee();
1945 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1946 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1947 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
1948 Builtin == Builtin::BI__builtin_function_start);
1949}
1950
1951static bool IsOpaqueConstantCall(const LValue &LVal) {
1952 const auto *BaseExpr =
1953 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
1954 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
1955}
1956
1958 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1959 // constant expression of pointer type that evaluates to...
1960
1961 // ... a null pointer value, or a prvalue core constant expression of type
1962 // std::nullptr_t.
1963 if (!B)
1964 return true;
1965
1966 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1967 // ... the address of an object with static storage duration,
1968 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1969 return VD->hasGlobalStorage();
1971 return true;
1972 // ... the address of a function,
1973 // ... the address of a GUID [MS extension],
1974 // ... the address of an unnamed global constant
1976 }
1977
1978 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1979 return true;
1980
1981 const Expr *E = B.get<const Expr*>();
1982 switch (E->getStmtClass()) {
1983 default:
1984 return false;
1985 case Expr::CompoundLiteralExprClass: {
1987 return CLE->isFileScope() && CLE->isLValue();
1988 }
1989 case Expr::MaterializeTemporaryExprClass:
1990 // A materialized temporary might have been lifetime-extended to static
1991 // storage duration.
1992 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1993 // A string literal has static storage duration.
1994 case Expr::StringLiteralClass:
1995 case Expr::PredefinedExprClass:
1996 case Expr::ObjCStringLiteralClass:
1997 case Expr::ObjCEncodeExprClass:
1998 return true;
1999 case Expr::ObjCBoxedExprClass:
2000 case Expr::ObjCArrayLiteralClass:
2001 case Expr::ObjCDictionaryLiteralClass:
2002 return cast<ObjCObjectLiteral>(E)->isExpressibleAsConstantInitializer();
2003 case Expr::CallExprClass:
2005 // For GCC compatibility, &&label has static storage duration.
2006 case Expr::AddrLabelExprClass:
2007 return true;
2008 // A Block literal expression may be used as the initialization value for
2009 // Block variables at global or local static scope.
2010 case Expr::BlockExprClass:
2011 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2012 // The APValue generated from a __builtin_source_location will be emitted as a
2013 // literal.
2014 case Expr::SourceLocExprClass:
2015 return true;
2016 case Expr::ImplicitValueInitExprClass:
2017 // FIXME:
2018 // We can never form an lvalue with an implicit value initialization as its
2019 // base through expression evaluation, so these only appear in one case: the
2020 // implicit variable declaration we invent when checking whether a constexpr
2021 // constructor can produce a constant expression. We must assume that such
2022 // an expression might be a global lvalue.
2023 return true;
2024 }
2025}
2026
2027static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2028 return LVal.Base.dyn_cast<const ValueDecl*>();
2029}
2030
2031// Information about an LValueBase that is some kind of string.
2034 StringRef Bytes;
2036};
2037
2038// Gets the lvalue base of LVal as a string.
2039static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2040 LValueBaseString &AsString) {
2041 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2042 if (!BaseExpr)
2043 return false;
2044
2045 // For ObjCEncodeExpr, we need to compute and store the string.
2046 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2047 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2048 AsString.ObjCEncodeStorage);
2049 AsString.Bytes = AsString.ObjCEncodeStorage;
2050 AsString.CharWidth = 1;
2051 return true;
2052 }
2053
2054 // Otherwise, we have a StringLiteral.
2055 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2056 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2057 Lit = PE->getFunctionName();
2058
2059 if (!Lit)
2060 return false;
2061
2062 AsString.Bytes = Lit->getBytes();
2063 AsString.CharWidth = Lit->getCharByteWidth();
2064 return true;
2065}
2066
2067// Determine whether two string literals potentially overlap. This will be the
2068// case if they agree on the values of all the bytes on the overlapping region
2069// between them.
2070//
2071// The overlapping region is the portion of the two string literals that must
2072// overlap in memory if the pointers actually point to the same address at
2073// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2074// the overlapping region is "cdef\0", which in this case does agree, so the
2075// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2076// "bazbar" + 3, the overlapping region contains all of both strings, so they
2077// are not potentially overlapping, even though they agree from the given
2078// addresses onwards.
2079//
2080// See open core issue CWG2765 which is discussing the desired rule here.
2081static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2082 const LValue &LHS,
2083 const LValue &RHS) {
2084 LValueBaseString LHSString, RHSString;
2085 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2086 !GetLValueBaseAsString(Info, RHS, RHSString))
2087 return false;
2088
2089 // This is the byte offset to the location of the first character of LHS
2090 // within RHS. We don't need to look at the characters of one string that
2091 // would appear before the start of the other string if they were merged.
2092 CharUnits Offset = RHS.Offset - LHS.Offset;
2093 if (Offset.isNegative()) {
2094 if (LHSString.Bytes.size() < (size_t)-Offset.getQuantity())
2095 return false;
2096 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2097 } else {
2098 if (RHSString.Bytes.size() < (size_t)Offset.getQuantity())
2099 return false;
2100 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2101 }
2102
2103 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2104 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2105 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2106 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2107
2108 // The null terminator isn't included in the string data, so check for it
2109 // manually. If the longer string doesn't have a null terminator where the
2110 // shorter string ends, they aren't potentially overlapping.
2111 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2112 if (Shorter.size() + NullByte >= Longer.size())
2113 break;
2114 if (Longer[Shorter.size() + NullByte])
2115 return false;
2116 }
2117
2118 // Otherwise, they're potentially overlapping if and only if the overlapping
2119 // region is the same.
2120 return Shorter == Longer.take_front(Shorter.size());
2121}
2122
2123static bool IsWeakLValue(const LValue &Value) {
2125 return Decl && Decl->isWeak();
2126}
2127
2128static bool isZeroSized(const LValue &Value) {
2130 if (isa_and_nonnull<VarDecl>(Decl)) {
2131 QualType Ty = Decl->getType();
2132 if (Ty->isArrayType())
2133 return Ty->isIncompleteType() ||
2134 Decl->getASTContext().getTypeSize(Ty) == 0;
2135 }
2136 return false;
2137}
2138
2139static bool HasSameBase(const LValue &A, const LValue &B) {
2140 if (!A.getLValueBase())
2141 return !B.getLValueBase();
2142 if (!B.getLValueBase())
2143 return false;
2144
2145 if (A.getLValueBase().getOpaqueValue() !=
2146 B.getLValueBase().getOpaqueValue())
2147 return false;
2148
2149 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2150 A.getLValueVersion() == B.getLValueVersion();
2151}
2152
2153static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2154 assert(Base && "no location for a null lvalue");
2155 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2156
2157 // For a parameter, find the corresponding call stack frame (if it still
2158 // exists), and point at the parameter of the function definition we actually
2159 // invoked.
2160 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2161 unsigned Idx = PVD->getFunctionScopeIndex();
2162 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2163 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2164 F->Arguments.Version == Base.getVersion() && F->Callee &&
2165 Idx < F->Callee->getNumParams()) {
2166 VD = F->Callee->getParamDecl(Idx);
2167 break;
2168 }
2169 }
2170 }
2171
2172 if (VD)
2173 Info.Note(VD->getLocation(), diag::note_declared_at);
2174 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2175 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2176 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2177 // FIXME: Produce a note for dangling pointers too.
2178 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2179 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2180 diag::note_constexpr_dynamic_alloc_here);
2181 }
2182
2183 // We have no information to show for a typeid(T) object.
2184}
2185
2190
2191/// Materialized temporaries that we've already checked to determine if they're
2192/// initializsed by a constant expression.
2195
2197 EvalInfo &Info, SourceLocation DiagLoc,
2198 QualType Type, const APValue &Value,
2199 ConstantExprKind Kind,
2200 const FieldDecl *SubobjectDecl,
2201 CheckedTemporaries &CheckedTemps,
2202 bool IsCompleteClass = true);
2203
2204/// Check that this reference or pointer core constant expression is a valid
2205/// value for an address or reference constant expression. Return true if we
2206/// can fold this expression, whether or not it's a constant expression.
2207static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2208 QualType Type, const LValue &LVal,
2209 ConstantExprKind Kind,
2210 CheckedTemporaries &CheckedTemps) {
2211 bool IsReferenceType = Type->isReferenceType();
2212
2213 APValue::LValueBase Base = LVal.getLValueBase();
2214 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2215
2216 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2217 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2218
2219 // Additional restrictions apply in a template argument. We only enforce the
2220 // C++20 restrictions here; additional syntactic and semantic restrictions
2221 // are applied elsewhere.
2222 if (isTemplateArgument(Kind)) {
2223 int InvalidBaseKind = -1;
2224 StringRef Ident;
2225 if (Base.is<TypeInfoLValue>())
2226 InvalidBaseKind = 0;
2227 else if (isa_and_nonnull<StringLiteral>(BaseE))
2228 InvalidBaseKind = 1;
2229 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2230 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2231 InvalidBaseKind = 2;
2232 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2233 InvalidBaseKind = 3;
2234 Ident = PE->getIdentKindName();
2235 }
2236
2237 if (InvalidBaseKind != -1) {
2238 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2239 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2240 << Ident;
2241 return false;
2242 }
2243 }
2244
2245 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2246 FD && FD->isImmediateFunction()) {
2247 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2248 << !Type->isAnyPointerType();
2249 Info.Note(FD->getLocation(), diag::note_declared_at);
2250 return false;
2251 }
2252
2253 // Check that the object is a global. Note that the fake 'this' object we
2254 // manufacture when checking potential constant expressions is conservatively
2255 // assumed to be global here.
2256 if (!IsGlobalLValue(Base)) {
2257 if (Info.getLangOpts().CPlusPlus11) {
2258 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2259 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2260 << BaseVD;
2261 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2262 if (VarD && VarD->isConstexpr()) {
2263 // Non-static local constexpr variables have unintuitive semantics:
2264 // constexpr int a = 1;
2265 // constexpr const int *p = &a;
2266 // ... is invalid because the address of 'a' is not constant. Suggest
2267 // adding a 'static' in this case.
2268 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2269 << VarD
2270 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2271 } else {
2272 NoteLValueLocation(Info, Base);
2273 }
2274 } else {
2275 Info.FFDiag(Loc);
2276 }
2277 // Don't allow references to temporaries to escape.
2278 return false;
2279 }
2280 assert((Info.checkingPotentialConstantExpression() ||
2281 LVal.getLValueCallIndex() == 0) &&
2282 "have call index for global lvalue");
2283
2284 if (LVal.allowConstexprUnknown()) {
2285 if (BaseVD) {
2286 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2287 NoteLValueLocation(Info, Base);
2288 } else {
2289 Info.FFDiag(Loc);
2290 }
2291 return false;
2292 }
2293
2294 if (Base.is<DynamicAllocLValue>()) {
2295 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2296 << IsReferenceType << !Designator.Entries.empty();
2297 NoteLValueLocation(Info, Base);
2298 return false;
2299 }
2300
2301 if (BaseVD) {
2302 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2303 // Check if this is a thread-local variable.
2304 if (Var->getTLSKind())
2305 // FIXME: Diagnostic!
2306 return false;
2307
2308 // A dllimport variable never acts like a constant, unless we're
2309 // evaluating a value for use only in name mangling, and unless it's a
2310 // static local. For the latter case, we'd still need to evaluate the
2311 // constant expression in case we're inside a (inlined) function.
2312 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>() &&
2313 !Var->isStaticLocal())
2314 return false;
2315
2316 // In CUDA/HIP device compilation, only device side variables have
2317 // constant addresses.
2318 if (Info.getLangOpts().CUDA && Info.getLangOpts().CUDAIsDevice &&
2319 Info.Ctx.CUDAConstantEvalCtx.NoWrongSidedVars) {
2320 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2321 !Var->hasAttr<CUDAConstantAttr>() &&
2322 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2323 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2324 Var->hasAttr<HIPManagedAttr>())
2325 return false;
2326 }
2327 }
2328 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2329 // __declspec(dllimport) must be handled very carefully:
2330 // We must never initialize an expression with the thunk in C++.
2331 // Doing otherwise would allow the same id-expression to yield
2332 // different addresses for the same function in different translation
2333 // units. However, this means that we must dynamically initialize the
2334 // expression with the contents of the import address table at runtime.
2335 //
2336 // The C language has no notion of ODR; furthermore, it has no notion of
2337 // dynamic initialization. This means that we are permitted to
2338 // perform initialization with the address of the thunk.
2339 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2340 FD->hasAttr<DLLImportAttr>())
2341 // FIXME: Diagnostic!
2342 return false;
2343 }
2344 } else if (const auto *MTE =
2345 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2346 if (CheckedTemps.insert(MTE).second) {
2347 QualType TempType = getType(Base);
2348 if (TempType.isDestructedType()) {
2349 Info.FFDiag(MTE->getExprLoc(),
2350 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2351 << TempType;
2352 return false;
2353 }
2354
2355 APValue *V = MTE->getOrCreateValue(false);
2356 assert(V && "evasluation result refers to uninitialised temporary");
2358 Info, MTE->getExprLoc(), TempType, *V, Kind,
2359 /*SubobjectDecl=*/nullptr, CheckedTemps))
2360 return false;
2361 }
2362 }
2363
2364 // Allow address constant expressions to be past-the-end pointers. This is
2365 // an extension: the standard requires them to point to an object.
2366 if (!IsReferenceType)
2367 return true;
2368
2369 // A reference constant expression must refer to an object.
2370 if (!Base) {
2371 // FIXME: diagnostic
2372 Info.CCEDiag(Loc);
2373 return true;
2374 }
2375
2376 // Does this refer one past the end of some object?
2377 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2378 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2379 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2380 NoteLValueLocation(Info, Base);
2381 }
2382
2383 return true;
2384}
2385
2386/// Member pointers are constant expressions unless they point to a
2387/// non-virtual dllimport member function.
2388static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2389 SourceLocation Loc,
2390 QualType Type,
2391 const APValue &Value,
2392 ConstantExprKind Kind) {
2393 const ValueDecl *Member = Value.getMemberPointerDecl();
2394 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2395 if (!FD)
2396 return true;
2397 if (FD->isImmediateFunction()) {
2398 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2399 Info.Note(FD->getLocation(), diag::note_declared_at);
2400 return false;
2401 }
2402 return isForManglingOnly(Kind) || FD->isVirtual() ||
2403 !FD->hasAttr<DLLImportAttr>();
2404}
2405
2406/// Check that this core constant expression is of literal type, and if not,
2407/// produce an appropriate diagnostic.
2408static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2409 const LValue *This = nullptr) {
2410 // The restriction to literal types does not exist in C++23 anymore.
2411 if (Info.getLangOpts().CPlusPlus23)
2412 return true;
2413
2414 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2415 return true;
2416
2417 // C++1y: A constant initializer for an object o [...] may also invoke
2418 // constexpr constructors for o and its subobjects even if those objects
2419 // are of non-literal class types.
2420 //
2421 // C++11 missed this detail for aggregates, so classes like this:
2422 // struct foo_t { union { int i; volatile int j; } u; };
2423 // are not (obviously) initializable like so:
2424 // __attribute__((__require_constant_initialization__))
2425 // static const foo_t x = {{0}};
2426 // because "i" is a subobject with non-literal initialization (due to the
2427 // volatile member of the union). See:
2428 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2429 // Therefore, we use the C++1y behavior.
2430 if (This && Info.EvaluatingDecl == This->getLValueBase())
2431 return true;
2432
2433 // Prvalue constant expressions must be of literal types.
2434 if (Info.getLangOpts().CPlusPlus11)
2435 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2436 << E->getType();
2437 else
2438 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2439 return false;
2440}
2441
2443 EvalInfo &Info, SourceLocation DiagLoc,
2444 QualType Type, const APValue &Value,
2445 ConstantExprKind Kind,
2446 const FieldDecl *SubobjectDecl,
2447 CheckedTemporaries &CheckedTemps,
2448 bool IsCompleteClass) {
2449 if (!Value.hasValue()) {
2450 if (SubobjectDecl) {
2451 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2452 << /*(name)*/ 1 << SubobjectDecl;
2453 Info.Note(SubobjectDecl->getLocation(),
2454 diag::note_constexpr_subobject_declared_here);
2455 } else {
2456 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2457 << /*of type*/ 0 << Type;
2458 }
2459 return false;
2460 }
2461
2462 // We allow _Atomic(T) to be initialized from anything that T can be
2463 // initialized from.
2464 if (const AtomicType *AT = Type->getAs<AtomicType>())
2465 Type = AT->getValueType();
2466
2467 // Core issue 1454: For a literal constant expression of array or class type,
2468 // each subobject of its value shall have been initialized by a constant
2469 // expression.
2470 if (Value.isArray()) {
2472 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2473 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2474 Value.getArrayInitializedElt(I), Kind,
2475 SubobjectDecl, CheckedTemps))
2476 return false;
2477 }
2478 if (!Value.hasArrayFiller())
2479 return true;
2480 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2481 Value.getArrayFiller(), Kind, SubobjectDecl,
2482 CheckedTemps);
2483 }
2484 if (Value.isUnion() && Value.getUnionField()) {
2485 return CheckEvaluationResult(
2486 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2487 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2488 }
2489 if (Value.isStruct()) {
2490 auto *RD = Type->castAsRecordDecl();
2491 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2492 unsigned BaseIndex = 0;
2493 for (const CXXBaseSpecifier &BS : CD->bases()) {
2494 if (BS.isVirtual())
2495 continue;
2496 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2497 if (!BaseValue.hasValue()) {
2498 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2499 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2500 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2501 return false;
2502 }
2503 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2504 Kind, /*SubobjectDecl=*/nullptr,
2505 CheckedTemps, /*IsCompleteClass=*/false))
2506 return false;
2507 ++BaseIndex;
2508 }
2509 }
2510 for (const auto *I : RD->fields()) {
2511 if (I->isUnnamedBitField())
2512 continue;
2513
2514 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2515 Value.getStructField(I->getFieldIndex()), Kind,
2516 I, CheckedTemps))
2517 return false;
2518 }
2519
2520 if (IsCompleteClass) {
2521 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2522 unsigned BaseIndex = 0;
2523 for (const CXXBaseSpecifier &BS : CD->vbases()) {
2524 assert(BS.isVirtual());
2525 const APValue &BaseValue = Value.getStructVirtualBase(BaseIndex);
2526 if (!BaseValue.hasValue()) {
2527 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2528 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2529 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2530 return false;
2531 }
2532 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2533 BaseValue, Kind, /*SubobjectDecl=*/nullptr,
2534 CheckedTemps, /*IsCompleteClass=*/false))
2535 return false;
2536 ++BaseIndex;
2537 }
2538 }
2539 }
2540 }
2541
2542 if (Value.isLValue() &&
2544 LValue LVal;
2545 LVal.setFrom(Info.Ctx, Value);
2546 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2547 CheckedTemps);
2548 }
2549
2550 if (Value.isMemberPointer() &&
2552 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2553
2554 // Everything else is fine.
2555 return true;
2556}
2557
2558/// Check that this core constant expression value is a valid value for a
2559/// constant expression. If not, report an appropriate diagnostic. Does not
2560/// check that the expression is of literal type.
2561static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2562 QualType Type, const APValue &Value,
2563 ConstantExprKind Kind) {
2564 // Nothing to check for a constant expression of type 'cv void'.
2565 if (Type->isVoidType())
2566 return true;
2567
2568 CheckedTemporaries CheckedTemps;
2570 Info, DiagLoc, Type, Value, Kind,
2571 /*SubobjectDecl=*/nullptr, CheckedTemps);
2572}
2573
2574/// Check that this evaluated value is fully-initialized and can be loaded by
2575/// an lvalue-to-rvalue conversion.
2576static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2577 QualType Type, const APValue &Value) {
2578 CheckedTemporaries CheckedTemps;
2579 return CheckEvaluationResult(
2581 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2582}
2583
2584/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2585/// "the allocated storage is deallocated within the evaluation".
2586static bool CheckMemoryLeaks(EvalInfo &Info) {
2587 if (!Info.HeapAllocs.empty()) {
2588 // We can still fold to a constant despite a compile-time memory leak,
2589 // so long as the heap allocation isn't referenced in the result (we check
2590 // that in CheckConstantExpression).
2591 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2592 diag::note_constexpr_memory_leak)
2593 << unsigned(Info.HeapAllocs.size() - 1);
2594 }
2595 return true;
2596}
2597
2598static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2599 // A null base expression indicates a null pointer. These are always
2600 // evaluatable, and they are false unless the offset is zero.
2601 if (!Value.getLValueBase()) {
2602 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2603 Result = !Value.getLValueOffset().isZero();
2604 return true;
2605 }
2606
2607 // We have a non-null base. These are generally known to be true, but if it's
2608 // a weak declaration it can be null at runtime.
2609 Result = true;
2610 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2611 return !Decl || !Decl->isWeak();
2612}
2613
2614static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2615 // TODO: This function should produce notes if it fails.
2616 switch (Val.getKind()) {
2617 case APValue::None:
2619 return false;
2620 case APValue::Int:
2621 Result = Val.getInt().getBoolValue();
2622 return true;
2624 Result = Val.getFixedPoint().getBoolValue();
2625 return true;
2626 case APValue::Float:
2627 Result = !Val.getFloat().isZero();
2628 return true;
2630 Result = Val.getComplexIntReal().getBoolValue() ||
2631 Val.getComplexIntImag().getBoolValue();
2632 return true;
2634 Result = !Val.getComplexFloatReal().isZero() ||
2635 !Val.getComplexFloatImag().isZero();
2636 return true;
2637 case APValue::LValue:
2638 return EvalPointerValueAsBool(Val, Result);
2640 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2641 return false;
2642 }
2644 return true;
2645 case APValue::Vector:
2646 case APValue::Matrix:
2647 case APValue::Array:
2648 case APValue::Struct:
2649 case APValue::Union:
2651 return false;
2652 }
2653
2654 llvm_unreachable("unknown APValue kind");
2655}
2656
2657static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2658 EvalInfo &Info) {
2659 assert(!E->isValueDependent());
2660 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2661 APValue Val;
2662 if (!Evaluate(Val, Info, E))
2663 return false;
2664 return HandleConversionToBool(Val, Result);
2665}
2666
2667template<typename T>
2668static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2669 const T &SrcValue, QualType DestType) {
2670 Info.CCEDiag(E, diag::note_constexpr_overflow) << SrcValue << DestType;
2671 if (const auto *OBT = DestType->getAs<OverflowBehaviorType>();
2672 OBT && OBT->isTrapKind()) {
2673 return false;
2674 }
2675 return Info.noteUndefinedBehavior();
2676}
2677
2678static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2679 QualType SrcType, const APFloat &Value,
2680 QualType DestType, APSInt &Result) {
2681 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2682 // Determine whether we are converting to unsigned or signed.
2683 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2684
2685 Result = APSInt(DestWidth, !DestSigned);
2686 bool ignored;
2687 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2688 & APFloat::opInvalidOp)
2689 return HandleOverflow(Info, E, Value, DestType);
2690 return true;
2691}
2692
2693/// Get rounding mode to use in evaluation of the specified expression.
2694///
2695/// If rounding mode is unknown at compile time, still try to evaluate the
2696/// expression. If the result is exact, it does not depend on rounding mode.
2697/// So return "tonearest" mode instead of "dynamic".
2698static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2699 llvm::RoundingMode RM =
2700 E->getFPFeaturesInEffect(Info.getLangOpts()).getRoundingMode();
2701 if (RM == llvm::RoundingMode::Dynamic)
2702 RM = llvm::RoundingMode::NearestTiesToEven;
2703 return RM;
2704}
2705
2706/// Check if the given evaluation result is allowed for constant evaluation.
2707static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2708 APFloat::opStatus St) {
2709 // In a constant context, assume that any dynamic rounding mode or FP
2710 // exception state matches the default floating-point environment.
2711 if (Info.InConstantContext)
2712 return true;
2713
2714 FPOptions FPO = E->getFPFeaturesInEffect(Info.getLangOpts());
2715 if ((St & APFloat::opInexact) &&
2716 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2717 // Inexact result means that it depends on rounding mode. If the requested
2718 // mode is dynamic, the evaluation cannot be made in compile time.
2719 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2720 return false;
2721 }
2722
2723 if ((St != APFloat::opOK) &&
2724 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2726 FPO.getAllowFEnvAccess())) {
2727 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2728 return false;
2729 }
2730
2731 if ((St & APFloat::opStatus::opInvalidOp) &&
2733 // There is no usefully definable result.
2734 Info.FFDiag(E);
2735 return false;
2736 }
2737
2738 // FIXME: if:
2739 // - evaluation triggered other FP exception, and
2740 // - exception mode is not "ignore", and
2741 // - the expression being evaluated is not a part of global variable
2742 // initializer,
2743 // the evaluation probably need to be rejected.
2744 return true;
2745}
2746
2747static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2748 QualType SrcType, QualType DestType,
2749 APFloat &Result) {
2750 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2752 "HandleFloatToFloatCast has been checked with only CastExpr, "
2753 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2754 "the new expression or address the root cause of this usage.");
2755 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2756 APFloat::opStatus St;
2757 APFloat Value = Result;
2758 bool ignored;
2759 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2760 return checkFloatingPointResult(Info, E, St);
2761}
2762
2763static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2764 QualType DestType, QualType SrcType,
2765 const APSInt &Value) {
2766 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2767 // Figure out if this is a truncate, extend or noop cast.
2768 // If the input is signed, do a sign extend, noop, or truncate.
2769 APSInt Result = Value.extOrTrunc(DestWidth);
2770 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2771 if (DestType->isBooleanType())
2772 Result = Value.getBoolValue();
2773 return Result;
2774}
2775
2776static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2777 const FPOptions FPO,
2778 QualType SrcType, const APSInt &Value,
2779 QualType DestType, APFloat &Result) {
2780 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2781 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2782 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2783 return checkFloatingPointResult(Info, E, St);
2784}
2785
2786static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2787 APValue &Value, const FieldDecl *FD) {
2788 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2789
2790 if (!Value.isInt()) {
2791 // Trying to store a pointer-cast-to-integer into a bitfield.
2792 // FIXME: In this case, we should provide the diagnostic for casting
2793 // a pointer to an integer.
2794 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2795 Info.FFDiag(E);
2796 return false;
2797 }
2798
2799 APSInt &Int = Value.getInt();
2800 unsigned OldBitWidth = Int.getBitWidth();
2801 unsigned NewBitWidth = FD->getBitWidthValue();
2802 if (NewBitWidth < OldBitWidth)
2803 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2804 return true;
2805}
2806
2807/// Perform the given integer operation, which is known to need at most BitWidth
2808/// bits, and check for overflow in the original type (if that type was not an
2809/// unsigned type).
2810template<typename Operation>
2811static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2812 const APSInt &LHS, const APSInt &RHS,
2813 unsigned BitWidth, Operation Op,
2814 APSInt &Result) {
2815 if (LHS.isUnsigned()) {
2816 Result = Op(LHS, RHS);
2817 return true;
2818 }
2819
2820 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2821 Result = Value.trunc(LHS.getBitWidth());
2822 if (Result.extend(BitWidth) != Value && !E->getType().isWrapType()) {
2823 if (Info.checkingForUndefinedBehavior())
2824 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2825 diag::warn_integer_constant_overflow)
2826 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2827 /*UpperCase=*/true, /*InsertSeparators=*/true)
2828 << E->getType() << E->getSourceRange();
2829 return HandleOverflow(Info, E, Value, E->getType());
2830 }
2831 return true;
2832}
2833
2834/// Perform the given binary integer operation.
2835static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2836 const APSInt &LHS, BinaryOperatorKind Opcode,
2837 APSInt RHS, APSInt &Result) {
2838 bool HandleOverflowResult = true;
2839 switch (Opcode) {
2840 default:
2841 Info.FFDiag(E);
2842 return false;
2843 case BO_Mul:
2844 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2845 std::multiplies<APSInt>(), Result);
2846 case BO_Add:
2847 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2848 std::plus<APSInt>(), Result);
2849 case BO_Sub:
2850 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2851 std::minus<APSInt>(), Result);
2852 case BO_And: Result = LHS & RHS; return true;
2853 case BO_Xor: Result = LHS ^ RHS; return true;
2854 case BO_Or: Result = LHS | RHS; return true;
2855 case BO_Div:
2856 case BO_Rem:
2857 if (RHS == 0) {
2858 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2859 << E->getRHS()->getSourceRange();
2860 return false;
2861 }
2862 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2863 // this operation and gives the two's complement result.
2864 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2865 LHS.isMinSignedValue())
2866 HandleOverflowResult = HandleOverflow(
2867 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2868 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2869 return HandleOverflowResult;
2870 case BO_Shl: {
2871 if (Info.getLangOpts().OpenCL)
2872 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2873 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2874 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2875 RHS.isUnsigned());
2876 else if (RHS.isSigned() && RHS.isNegative()) {
2877 // During constant-folding, a negative shift is an opposite shift. Such
2878 // a shift is not a constant expression.
2879 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2880 if (!Info.noteUndefinedBehavior())
2881 return false;
2882 RHS = -RHS;
2883 goto shift_right;
2884 }
2885 shift_left:
2886 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2887 // the shifted type.
2888 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2889 if (SA != RHS) {
2890 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2891 << RHS << E->getType() << LHS.getBitWidth();
2892 if (!Info.noteUndefinedBehavior())
2893 return false;
2894 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2895 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2896 // operand, and must not overflow the corresponding unsigned type.
2897 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2898 // E1 x 2^E2 module 2^N.
2899 if (LHS.isNegative()) {
2900 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2901 if (!Info.noteUndefinedBehavior())
2902 return false;
2903 } else if (LHS.countl_zero() < SA) {
2904 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2905 if (!Info.noteUndefinedBehavior())
2906 return false;
2907 }
2908 }
2909 Result = LHS << SA;
2910 return true;
2911 }
2912 case BO_Shr: {
2913 if (Info.getLangOpts().OpenCL)
2914 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2915 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2916 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2917 RHS.isUnsigned());
2918 else if (RHS.isSigned() && RHS.isNegative()) {
2919 // During constant-folding, a negative shift is an opposite shift. Such a
2920 // shift is not a constant expression.
2921 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2922 if (!Info.noteUndefinedBehavior())
2923 return false;
2924 RHS = -RHS;
2925 goto shift_left;
2926 }
2927 shift_right:
2928 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2929 // shifted type.
2930 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2931 if (SA != RHS) {
2932 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2933 << RHS << E->getType() << LHS.getBitWidth();
2934 if (!Info.noteUndefinedBehavior())
2935 return false;
2936 }
2937
2938 Result = LHS >> SA;
2939 return true;
2940 }
2941
2942 case BO_LT: Result = LHS < RHS; return true;
2943 case BO_GT: Result = LHS > RHS; return true;
2944 case BO_LE: Result = LHS <= RHS; return true;
2945 case BO_GE: Result = LHS >= RHS; return true;
2946 case BO_EQ: Result = LHS == RHS; return true;
2947 case BO_NE: Result = LHS != RHS; return true;
2948 case BO_Cmp:
2949 llvm_unreachable("BO_Cmp should be handled elsewhere");
2950 }
2951}
2952
2953/// Perform the given binary floating-point operation, in-place, on LHS.
2954static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2955 APFloat &LHS, BinaryOperatorKind Opcode,
2956 const APFloat &RHS) {
2957 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2958 APFloat::opStatus St;
2959 switch (Opcode) {
2960 default:
2961 Info.FFDiag(E);
2962 return false;
2963 case BO_Mul:
2964 St = LHS.multiply(RHS, RM);
2965 break;
2966 case BO_Add:
2967 St = LHS.add(RHS, RM);
2968 break;
2969 case BO_Sub:
2970 St = LHS.subtract(RHS, RM);
2971 break;
2972 case BO_Div:
2973 // [expr.mul]p4:
2974 // If the second operand of / or % is zero the behavior is undefined.
2975 if (RHS.isZero())
2976 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2977 St = LHS.divide(RHS, RM);
2978 break;
2979 }
2980
2981 // [expr.pre]p4:
2982 // If during the evaluation of an expression, the result is not
2983 // mathematically defined [...], the behavior is undefined.
2984 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2985 if (LHS.isNaN()) {
2986 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2987 return Info.noteUndefinedBehavior();
2988 }
2989
2990 return checkFloatingPointResult(Info, E, St);
2991}
2992
2993static bool handleLogicalOpForVector(const APInt &LHSValue,
2994 BinaryOperatorKind Opcode,
2995 const APInt &RHSValue, APInt &Result) {
2996 bool LHS = (LHSValue != 0);
2997 bool RHS = (RHSValue != 0);
2998
2999 if (Opcode == BO_LAnd)
3000 Result = LHS && RHS;
3001 else
3002 Result = LHS || RHS;
3003 return true;
3004}
3005static bool handleLogicalOpForVector(const APFloat &LHSValue,
3006 BinaryOperatorKind Opcode,
3007 const APFloat &RHSValue, APInt &Result) {
3008 bool LHS = !LHSValue.isZero();
3009 bool RHS = !RHSValue.isZero();
3010
3011 if (Opcode == BO_LAnd)
3012 Result = LHS && RHS;
3013 else
3014 Result = LHS || RHS;
3015 return true;
3016}
3017
3018static bool handleLogicalOpForVector(const APValue &LHSValue,
3019 BinaryOperatorKind Opcode,
3020 const APValue &RHSValue, APInt &Result) {
3021 // The result is always an int type, however operands match the first.
3022 if (LHSValue.getKind() == APValue::Int)
3023 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3024 RHSValue.getInt(), Result);
3025 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3026 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3027 RHSValue.getFloat(), Result);
3028}
3029
3030template <typename APTy>
3031static bool
3033 const APTy &RHSValue, APInt &Result) {
3034 switch (Opcode) {
3035 default:
3036 llvm_unreachable("unsupported binary operator");
3037 case BO_EQ:
3038 Result = (LHSValue == RHSValue);
3039 break;
3040 case BO_NE:
3041 Result = (LHSValue != RHSValue);
3042 break;
3043 case BO_LT:
3044 Result = (LHSValue < RHSValue);
3045 break;
3046 case BO_GT:
3047 Result = (LHSValue > RHSValue);
3048 break;
3049 case BO_LE:
3050 Result = (LHSValue <= RHSValue);
3051 break;
3052 case BO_GE:
3053 Result = (LHSValue >= RHSValue);
3054 break;
3055 }
3056
3057 // The boolean operations on these vector types use an instruction that
3058 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3059 // to -1 to make sure that we produce the correct value.
3060 Result.negate();
3061
3062 return true;
3063}
3064
3065static bool handleCompareOpForVector(const APValue &LHSValue,
3066 BinaryOperatorKind Opcode,
3067 const APValue &RHSValue, APInt &Result) {
3068 // The result is always an int type, however operands match the first.
3069 if (LHSValue.getKind() == APValue::Int)
3070 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3071 RHSValue.getInt(), Result);
3072 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3073 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3074 RHSValue.getFloat(), Result);
3075}
3076
3077// Perform binary operations for vector types, in place on the LHS.
3078static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3079 BinaryOperatorKind Opcode,
3080 APValue &LHSValue,
3081 const APValue &RHSValue) {
3082 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3083 "Operation not supported on vector types");
3084
3085 const auto *VT = E->getType()->castAs<VectorType>();
3086 unsigned NumElements = VT->getNumElements();
3087 QualType EltTy = VT->getElementType();
3088
3089 // In the cases (typically C as I've observed) where we aren't evaluating
3090 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3091 // just give up.
3092 if (!LHSValue.isVector()) {
3093 assert(LHSValue.isLValue() &&
3094 "A vector result that isn't a vector OR uncalculated LValue");
3095 Info.FFDiag(E);
3096 return false;
3097 }
3098
3099 assert(LHSValue.getVectorLength() == NumElements &&
3100 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3101
3102 SmallVector<APValue, 4> ResultElements;
3103
3104 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3105 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3106 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3107
3108 if (EltTy->isIntegerType()) {
3109 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3110 EltTy->isUnsignedIntegerType()};
3111 bool Success = true;
3112
3113 if (BinaryOperator::isLogicalOp(Opcode))
3114 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3115 else if (BinaryOperator::isComparisonOp(Opcode))
3116 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3117 else
3118 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3119 RHSElt.getInt(), EltResult);
3120
3121 if (!Success) {
3122 Info.FFDiag(E);
3123 return false;
3124 }
3125 ResultElements.emplace_back(EltResult);
3126
3127 } else if (EltTy->isFloatingType()) {
3128 assert(LHSElt.getKind() == APValue::Float &&
3129 RHSElt.getKind() == APValue::Float &&
3130 "Mismatched LHS/RHS/Result Type");
3131 APFloat LHSFloat = LHSElt.getFloat();
3132
3133 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3134 RHSElt.getFloat())) {
3135 Info.FFDiag(E);
3136 return false;
3137 }
3138
3139 ResultElements.emplace_back(LHSFloat);
3140 }
3141 }
3142
3143 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3144 return true;
3145}
3146
3147/// Cast an lvalue referring to a base subobject to a derived class, by
3148/// truncating the lvalue's path to the given length.
3149static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3150 const RecordDecl *TruncatedType,
3151 unsigned TruncatedElements) {
3152 SubobjectDesignator &D = Result.Designator;
3153
3154 // Check we actually point to a derived class object.
3155 if (TruncatedElements == D.Entries.size())
3156 return true;
3157 assert(TruncatedElements >= D.MostDerivedPathLength &&
3158 "not casting to a derived class");
3159 if (!Result.checkSubobject(Info, E, CSK_Derived))
3160 return false;
3161
3162 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3163 const RecordDecl *RD = TruncatedType;
3164 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3165 if (RD->isInvalidDecl()) return false;
3166 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3167 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3168 if (isVirtualBaseClass(D.Entries[I]))
3169 Result.Offset -= Layout.getVBaseClassOffset(Base);
3170 else
3171 Result.Offset -= Layout.getBaseClassOffset(Base);
3172 RD = Base;
3173 }
3174 D.Entries.resize(TruncatedElements);
3175 return true;
3176}
3177
3178static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3179 const CXXRecordDecl *Derived,
3180 const CXXRecordDecl *Base,
3181 const ASTRecordLayout *RL = nullptr) {
3182 if (!RL) {
3183 if (Derived->isInvalidDecl()) return false;
3184 RL = &Info.Ctx.getASTRecordLayout(Derived);
3185 }
3186
3187 Obj.addDecl(Info, E, Base, /*Virtual=*/false);
3188 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3189 return true;
3190}
3191
3192static bool HandleLValueDirectVirtualBase(EvalInfo &Info, const Expr *E,
3193 LValue &Obj,
3194 const CXXRecordDecl *Derived,
3195 const CXXRecordDecl *Base,
3196 const ASTRecordLayout *RL = nullptr) {
3197 if (!RL) {
3198 if (Derived->isInvalidDecl())
3199 return false;
3200 RL = &Info.Ctx.getASTRecordLayout(Derived);
3201 }
3202
3203 Obj.addDecl(Info, E, Base, /*Virtual=*/true);
3204 Obj.getLValueOffset() += RL->getVBaseClassOffset(Base);
3205 return true;
3206}
3207
3208static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3209 const CXXRecordDecl *DerivedDecl,
3210 const CXXBaseSpecifier *Base) {
3211 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3212
3213 if (!Base->isVirtual())
3214 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3215
3216 SubobjectDesignator &D = Obj.Designator;
3217 if (D.Invalid)
3218 return false;
3219
3220 // Extract most-derived object and corresponding type.
3221 // FIXME: After implementing P2280R4 it became possible to get references
3222 // here. We do MostDerivedType->getAsCXXRecordDecl() in several other
3223 // locations and if we see crashes in those locations in the future
3224 // it may make more sense to move this fix into Lvalue::set.
3225 DerivedDecl = D.MostDerivedType.getNonReferenceType()->getAsCXXRecordDecl();
3226 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3227 return false;
3228
3229 // Find the virtual base class.
3230 if (DerivedDecl->isInvalidDecl()) return false;
3231 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3232 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3233 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3234 return true;
3235}
3236
3237static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3238 QualType Type, LValue &Result) {
3239 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3240 PathE = E->path_end();
3241 PathI != PathE; ++PathI) {
3243 *PathI))
3244 return false;
3245 Type = (*PathI)->getType();
3246 }
3247 return true;
3248}
3249
3250/// Cast an lvalue referring to a derived class to a known base subobject.
3251static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3252 const CXXRecordDecl *DerivedRD,
3253 const CXXRecordDecl *BaseRD) {
3254 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3255 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3256 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3257 llvm_unreachable("Class must be derived from the passed in base class!");
3258
3259 for (CXXBasePathElement &Elem : Paths.front())
3260 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3261 return false;
3262 return true;
3263}
3264
3265/// Update LVal to refer to the given field, which must be a member of the type
3266/// currently described by LVal.
3267static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3268 const FieldDecl *FD,
3269 const ASTRecordLayout *RL = nullptr) {
3270 if (!RL) {
3271 const RecordDecl *RD = FD->getParent();
3272 if (RD->isInvalidDecl())
3273 return false;
3274 // There are some cases where the base is not yet complete but we haven't
3275 // disagnosed (such as in a template instantation of an attribute that
3276 // references the expression, ala enable_if). These aren't necessarily
3277 // constant expressions so we return 'false', but they might be, so we don't
3278 // diagnose.
3279 if (!RD->isCompleteDefinition())
3280 return false;
3281 RL = &Info.Ctx.getASTRecordLayout(RD);
3282 }
3283
3284 unsigned I = FD->getFieldIndex();
3285 LVal.addDecl(Info, E, FD);
3286 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3287 return true;
3288}
3289
3290/// Update LVal to refer to the given indirect field.
3291static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3292 LValue &LVal,
3293 const IndirectFieldDecl *IFD) {
3294 for (const auto *C : IFD->chain())
3295 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3296 return false;
3297 return true;
3298}
3299
3304
3305/// Get the size of the given type in char units.
3306static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3308 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3309 // extension.
3310 if (Type->isVoidType() || Type->isFunctionType()) {
3311 Size = CharUnits::One();
3312 return true;
3313 }
3314
3315 if (Type->isDependentType()) {
3316 Info.FFDiag(Loc);
3317 return false;
3318 }
3319
3320 if (!Type->isConstantSizeType()) {
3321 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3322 // FIXME: Better diagnostic.
3323 Info.FFDiag(Loc);
3324 return false;
3325 }
3326
3327 if (SOT == SizeOfType::SizeOf)
3328 Size = Info.Ctx.getTypeSizeInChars(Type);
3329 else
3330 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3331 return true;
3332}
3333
3334/// Update a pointer value to model pointer arithmetic.
3335/// \param Info - Information about the ongoing evaluation.
3336/// \param E - The expression being evaluated, for diagnostic purposes.
3337/// \param LVal - The pointer value to be updated.
3338/// \param EltTy - The pointee type represented by LVal.
3339/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3340static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3341 LValue &LVal, QualType EltTy,
3342 APSInt Adjustment) {
3343 CharUnits SizeOfPointee;
3344 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3345 return false;
3346
3347 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3348 return true;
3349}
3350
3351static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3352 LValue &LVal, QualType EltTy,
3353 int64_t Adjustment) {
3354 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3355 APSInt::get(Adjustment));
3356}
3357
3358/// Update an lvalue to refer to a component of a complex number.
3359/// \param Info - Information about the ongoing evaluation.
3360/// \param LVal - The lvalue to be updated.
3361/// \param EltTy - The complex number's component type.
3362/// \param Imag - False for the real component, true for the imaginary.
3363static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3364 LValue &LVal, QualType EltTy,
3365 bool Imag) {
3366 if (Imag) {
3367 CharUnits SizeOfComponent;
3368 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3369 return false;
3370 LVal.Offset += SizeOfComponent;
3371 }
3372 LVal.addComplex(Info, E, EltTy, Imag);
3373 return true;
3374}
3375
3376static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3377 LValue &LVal, QualType EltTy,
3378 uint64_t Size, uint64_t Idx) {
3379 if (Idx) {
3380 CharUnits SizeOfElement;
3381 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3382 return false;
3383 LVal.Offset += SizeOfElement * Idx;
3384 }
3385 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3386 return true;
3387}
3388
3389/// Try to evaluate the initializer for a variable declaration.
3390///
3391/// \param Info Information about the ongoing evaluation.
3392/// \param E An expression to be used when printing diagnostics.
3393/// \param VD The variable whose initializer should be obtained.
3394/// \param Version The version of the variable within the frame.
3395/// \param Frame The frame in which the variable was created. Must be null
3396/// if this variable is not local to the evaluation.
3397/// \param Result Filled in with a pointer to the value of the variable.
3398static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3399 const VarDecl *VD, CallStackFrame *Frame,
3400 unsigned Version, APValue *&Result) {
3401 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3402 // and pointers.
3403 bool AllowConstexprUnknown =
3404 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3405
3406 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3407
3408 auto CheckUninitReference = [&](bool IsLocalVariable) {
3409 if (!Result || (!Result->hasValue() && VD->getType()->isReferenceType())) {
3410 // C++23 [expr.const]p8
3411 // ... For such an object that is not usable in constant expressions, the
3412 // dynamic type of the object is constexpr-unknown. For such a reference
3413 // that is not usable in constant expressions, the reference is treated
3414 // as binding to an unspecified object of the referenced type whose
3415 // lifetime and that of all subobjects includes the entire constant
3416 // evaluation and whose dynamic type is constexpr-unknown.
3417 //
3418 // Variables that are part of the current evaluation are not
3419 // constexpr-unknown.
3420 if (!AllowConstexprUnknown || IsLocalVariable) {
3421 if (!Info.checkingPotentialConstantExpression())
3422 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3423 return false;
3424 }
3425 Result = nullptr;
3426 }
3427 return true;
3428 };
3429
3430 // If this is a local variable, dig out its value.
3431 if (Frame) {
3432 Result = Frame->getTemporary(VD, Version);
3433 if (Result)
3434 return CheckUninitReference(/*IsLocalVariable=*/true);
3435
3436 if (!isa<ParmVarDecl>(VD)) {
3437 // Assume variables referenced within a lambda's call operator that were
3438 // not declared within the call operator are captures and during checking
3439 // of a potential constant expression, assume they are unknown constant
3440 // expressions.
3441 assert(isLambdaCallOperator(Frame->Callee) &&
3442 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3443 "missing value for local variable");
3444 if (Info.checkingPotentialConstantExpression())
3445 return false;
3446
3447 llvm_unreachable(
3448 "A variable in a frame should either be a local or a parameter");
3449 }
3450 }
3451
3452 // If we're currently evaluating the initializer of this declaration, use that
3453 // in-flight value.
3454 if (Info.EvaluatingDecl == Base) {
3455 Result = Info.EvaluatingDeclValue;
3456 return CheckUninitReference(/*IsLocalVariable=*/false);
3457 }
3458
3459 // P2280R4 struck the restriction that variable of reference type lifetime
3460 // should begin within the evaluation of E
3461 // Used to be C++20 [expr.const]p5.12.2:
3462 // ... its lifetime began within the evaluation of E;
3463 if (isa<ParmVarDecl>(VD)) {
3464 if (AllowConstexprUnknown) {
3465 Result = nullptr;
3466 return true;
3467 }
3468
3469 // Assume parameters of a potential constant expression are usable in
3470 // constant expressions.
3471 if (!Info.checkingPotentialConstantExpression() ||
3472 !Info.CurrentCall->Callee ||
3473 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3474 if (Info.getLangOpts().CPlusPlus11) {
3475 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3476 << VD;
3477 NoteLValueLocation(Info, Base);
3478 } else {
3479 Info.FFDiag(E);
3480 }
3481 }
3482 return false;
3483 }
3484
3485 if (E->isValueDependent())
3486 return false;
3487
3488 // Dig out the initializer, and use the declaration which it's attached to.
3489 // FIXME: We should eventually check whether the variable has a reachable
3490 // initializing declaration.
3491 const Expr *Init = VD->getAnyInitializer(VD);
3492 // P2280R4 struck the restriction that variable of reference type should have
3493 // a preceding initialization.
3494 // Used to be C++20 [expr.const]p5.12:
3495 // ... reference has a preceding initialization and either ...
3496 if (!Init && !AllowConstexprUnknown) {
3497 // Don't diagnose during potential constant expression checking; an
3498 // initializer might be added later.
3499 if (!Info.checkingPotentialConstantExpression()) {
3500 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3501 << VD;
3502 NoteLValueLocation(Info, Base);
3503 }
3504 return false;
3505 }
3506
3507 // P2280R4 struck the initialization requirement for variables of reference
3508 // type so we can no longer assume we have an Init.
3509 // Used to be C++20 [expr.const]p5.12:
3510 // ... reference has a preceding initialization and either ...
3511 if (Init && Init->isValueDependent()) {
3512 // The DeclRefExpr is not value-dependent, but the variable it refers to
3513 // has a value-dependent initializer. This should only happen in
3514 // constant-folding cases, where the variable is not actually of a suitable
3515 // type for use in a constant expression (otherwise the DeclRefExpr would
3516 // have been value-dependent too), so diagnose that.
3517 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3518 if (!Info.checkingPotentialConstantExpression()) {
3519 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3520 ? diag::note_constexpr_ltor_non_constexpr
3521 : diag::note_constexpr_ltor_non_integral, 1)
3522 << VD << VD->getType();
3523 NoteLValueLocation(Info, Base);
3524 }
3525 return false;
3526 }
3527
3528 // Check that we can fold the initializer. In C++, we will have already done
3529 // this in the cases where it matters for conformance.
3530 // P2280R4 struck the initialization requirement for variables of reference
3531 // type so we can no longer assume we have an Init.
3532 // Used to be C++20 [expr.const]p5.12:
3533 // ... reference has a preceding initialization and either ...
3534 if (Init && !VD->evaluateValue() && !AllowConstexprUnknown) {
3535 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3536 NoteLValueLocation(Info, Base);
3537 return false;
3538 }
3539
3540 // Check that the variable is actually usable in constant expressions. For a
3541 // const integral variable or a reference, we might have a non-constant
3542 // initializer that we can nonetheless evaluate the initializer for. Such
3543 // variables are not usable in constant expressions. In C++98, the
3544 // initializer also syntactically needs to be an ICE.
3545 //
3546 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3547 // expressions here; doing so would regress diagnostics for things like
3548 // reading from a volatile constexpr variable.
3549 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3550 VD->mightBeUsableInConstantExpressions(Info.Ctx) &&
3551 !AllowConstexprUnknown) ||
3552 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3553 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3554 if (Init) {
3555 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3556 NoteLValueLocation(Info, Base);
3557 } else {
3558 Info.CCEDiag(E);
3559 }
3560 }
3561
3562 // Never use the initializer of a weak variable, not even for constant
3563 // folding. We can't be sure that this is the definition that will be used.
3564 if (VD->isWeak()) {
3565 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3566 NoteLValueLocation(Info, Base);
3567 return false;
3568 }
3569
3570 Result = const_cast<APValue *>(VD->getEvaluatedValue());
3571
3572 if (!Result && !AllowConstexprUnknown)
3573 return false;
3574
3575 return CheckUninitReference(/*IsLocalVariable=*/false);
3576}
3577
3578/// Get the base index of the given base class within an APValue representing
3579/// the given derived class.
3580static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3581 const CXXRecordDecl *Base) {
3582 Base = Base->getCanonicalDecl();
3583 unsigned Index = 0;
3584 for (const CXXBaseSpecifier &B : Derived->bases()) {
3585 if (B.isVirtual())
3586 continue;
3588 return Index;
3589 ++Index;
3590 }
3591
3592 for (const CXXBaseSpecifier &B : Derived->vbases()) {
3594 return Index;
3595 ++Index;
3596 }
3597
3598 llvm_unreachable("base class missing from derived class's bases list");
3599}
3600
3601/// Extract the value of a character from a string literal.
3602static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3603 uint64_t Index) {
3604 assert(!isa<SourceLocExpr>(Lit) &&
3605 "SourceLocExpr should have already been converted to a StringLiteral");
3606
3607 // FIXME: Support MakeStringConstant
3608 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3609 std::string Str;
3610 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3611 assert(Index <= Str.size() && "Index too large");
3612 return APSInt::getUnsigned(Str.c_str()[Index]);
3613 }
3614
3615 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3616 Lit = PE->getFunctionName();
3617 const StringLiteral *S = cast<StringLiteral>(Lit);
3618 const ConstantArrayType *CAT =
3619 Info.Ctx.getAsConstantArrayType(S->getType());
3620 assert(CAT && "string literal isn't an array");
3621 QualType CharType = CAT->getElementType();
3622 assert(CharType->isIntegerType() && "unexpected character type");
3623 APSInt Value(Info.Ctx.getTypeSize(CharType),
3624 CharType->isUnsignedIntegerType());
3625 if (Index < S->getLength())
3626 Value = S->getCodeUnit(Index);
3627 return Value;
3628}
3629
3630// Expand a string literal into an array of characters.
3631//
3632// FIXME: This is inefficient; we should probably introduce something similar
3633// to the LLVM ConstantDataArray to make this cheaper.
3634static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3635 APValue &Result,
3636 QualType AllocType = QualType()) {
3637 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3638 AllocType.isNull() ? S->getType() : AllocType);
3639 assert(CAT && "string literal isn't an array");
3640 QualType CharType = CAT->getElementType();
3641 assert(CharType->isIntegerType() && "unexpected character type");
3642
3643 unsigned Elts = CAT->getZExtSize();
3645 std::min(S->getLength(), Elts), Elts);
3646 APSInt Value(Info.Ctx.getTypeSize(CharType),
3647 CharType->isUnsignedIntegerType());
3648 if (Result.hasArrayFiller())
3649 Result.getArrayFiller() = APValue(Value);
3650 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3651 Value = S->getCodeUnit(I);
3652 Result.getArrayInitializedElt(I) = APValue(Value);
3653 }
3654}
3655
3656// Expand an array so that it has more than Index filled elements.
3657static void expandArray(APValue &Array, unsigned Index) {
3658 unsigned Size = Array.getArraySize();
3659 assert(Index < Size);
3660
3661 // Always at least double the number of elements for which we store a value.
3662 unsigned OldElts = Array.getArrayInitializedElts();
3663 unsigned NewElts = std::max(Index+1, OldElts * 2);
3664 NewElts = std::min(Size, std::max(NewElts, 8u));
3665
3666 // Copy the data across.
3667 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3668 for (unsigned I = 0; I != OldElts; ++I)
3669 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3670 for (unsigned I = OldElts; I != NewElts; ++I)
3671 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3672 if (NewValue.hasArrayFiller())
3673 NewValue.getArrayFiller() = Array.getArrayFiller();
3674 Array.swap(NewValue);
3675}
3676
3677// Expand an indeterminate vector to materialize all elements.
3678static void expandVector(APValue &Vec, unsigned NumElements) {
3679 assert(Vec.isIndeterminate());
3681 Vec = APValue(Elts.data(), Elts.size());
3682}
3683
3684/// Determine whether a type would actually be read by an lvalue-to-rvalue
3685/// conversion. If it's of class type, we may assume that the copy operation
3686/// is trivial. Note that this is never true for a union type with fields
3687/// (because the copy always "reads" the active member) and always true for
3688/// a non-class type.
3689static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3691 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3692 return !RD || isReadByLvalueToRvalueConversion(RD);
3693}
3695 // FIXME: A trivial copy of a union copies the object representation, even if
3696 // the union is empty.
3697 if (RD->isUnion())
3698 return !RD->field_empty();
3699 if (RD->isEmpty())
3700 return false;
3701
3702 for (auto *Field : RD->fields())
3703 if (!Field->isUnnamedBitField() &&
3704 isReadByLvalueToRvalueConversion(Field->getType()))
3705 return true;
3706
3707 for (auto &BaseSpec : RD->bases())
3708 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3709 return true;
3710
3711 return false;
3712}
3713
3714/// Diagnose an attempt to read from any unreadable field within the specified
3715/// type, which might be a class type.
3716static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3717 QualType T) {
3718 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3719 if (!RD)
3720 return false;
3721
3722 if (!RD->hasMutableFields())
3723 return false;
3724
3725 for (auto *Field : RD->fields()) {
3726 // If we're actually going to read this field in some way, then it can't
3727 // be mutable. If we're in a union, then assigning to a mutable field
3728 // (even an empty one) can change the active member, so that's not OK.
3729 // FIXME: Add core issue number for the union case.
3730 if (Field->isMutable() &&
3731 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3732 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3733 Info.Note(Field->getLocation(), diag::note_declared_at);
3734 return true;
3735 }
3736
3737 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3738 return true;
3739 }
3740
3741 for (auto &BaseSpec : RD->bases())
3742 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3743 return true;
3744
3745 // All mutable fields were empty, and thus not actually read.
3746 return false;
3747}
3748
3749static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3751 bool MutableSubobject = false) {
3752 // A temporary or transient heap allocation we created.
3753 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3754 return true;
3755
3756 switch (Info.IsEvaluatingDecl) {
3757 case EvalInfo::EvaluatingDeclKind::None:
3758 return false;
3759
3760 case EvalInfo::EvaluatingDeclKind::Ctor:
3761 // The variable whose initializer we're evaluating.
3762 if (Info.EvaluatingDecl == Base)
3763 return true;
3764
3765 // A temporary lifetime-extended by the variable whose initializer we're
3766 // evaluating.
3767 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3768 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3769 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3770 return false;
3771
3772 case EvalInfo::EvaluatingDeclKind::Dtor:
3773 // C++2a [expr.const]p6:
3774 // [during constant destruction] the lifetime of a and its non-mutable
3775 // subobjects (but not its mutable subobjects) [are] considered to start
3776 // within e.
3777 if (MutableSubobject || Base != Info.EvaluatingDecl)
3778 return false;
3779 // FIXME: We can meaningfully extend this to cover non-const objects, but
3780 // we will need special handling: we should be able to access only
3781 // subobjects of such objects that are themselves declared const.
3783 return T.isConstQualified() || T->isReferenceType();
3784 }
3785
3786 llvm_unreachable("unknown evaluating decl kind");
3787}
3788
3789static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3790 SourceLocation CallLoc = {}) {
3791 return Info.CheckArraySize(
3792 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3793 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3794 /*Diag=*/true);
3795}
3796
3797static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E,
3798 QualType SourceTy, QualType DestTy,
3799 APValue const &Original, APValue &Result) {
3800 // boolean must be checked before integer
3801 // since IsIntegerType() is true for bool
3802 if (SourceTy->isBooleanType()) {
3803 if (DestTy->isBooleanType()) {
3804 Result = Original;
3805 return true;
3806 }
3807 if (DestTy->isIntegerType() || DestTy->isRealFloatingType()) {
3808 bool BoolResult;
3809 if (!HandleConversionToBool(Original, BoolResult))
3810 return false;
3811 uint64_t IntResult = BoolResult;
3812 QualType IntType = DestTy->isIntegerType()
3813 ? DestTy
3814 : Info.Ctx.getIntTypeForBitwidth(64, false);
3815 Result = APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3816 }
3817 if (DestTy->isRealFloatingType()) {
3818 APValue Result2 = APValue(APFloat(0.0));
3819 if (!HandleIntToFloatCast(Info, E, FPO,
3820 Info.Ctx.getIntTypeForBitwidth(64, false),
3821 Result.getInt(), DestTy, Result2.getFloat()))
3822 return false;
3823 Result = std::move(Result2);
3824 }
3825 return true;
3826 }
3827 if (SourceTy->isIntegerType()) {
3828 if (DestTy->isRealFloatingType()) {
3829 Result = APValue(APFloat(0.0));
3830 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
3831 DestTy, Result.getFloat());
3832 }
3833 if (DestTy->isBooleanType()) {
3834 bool BoolResult;
3835 if (!HandleConversionToBool(Original, BoolResult))
3836 return false;
3837 uint64_t IntResult = BoolResult;
3838 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3839 return true;
3840 }
3841 if (DestTy->isIntegerType()) {
3842 Result = APValue(
3843 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
3844 return true;
3845 }
3846 } else if (SourceTy->isRealFloatingType()) {
3847 if (DestTy->isRealFloatingType()) {
3848 Result = Original;
3849 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
3850 Result.getFloat());
3851 }
3852 if (DestTy->isBooleanType()) {
3853 bool BoolResult;
3854 if (!HandleConversionToBool(Original, BoolResult))
3855 return false;
3856 uint64_t IntResult = BoolResult;
3857 Result = APValue(Info.Ctx.MakeIntValue(IntResult, DestTy));
3858 return true;
3859 }
3860 if (DestTy->isIntegerType()) {
3861 Result = APValue(APSInt());
3862 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
3863 DestTy, Result.getInt());
3864 }
3865 }
3866
3867 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3868 return false;
3869}
3870
3871// do the heavy lifting for casting to aggregate types
3872// because we have to deal with bitfields specially
3873static bool constructAggregate(EvalInfo &Info, const FPOptions FPO,
3874 const Expr *E, APValue &Result,
3875 QualType ResultType,
3876 SmallVectorImpl<APValue> &Elements,
3877 SmallVectorImpl<QualType> &ElTypes) {
3878
3880 {&Result, ResultType, 0}};
3881
3882 unsigned ElI = 0;
3883 while (!WorkList.empty() && ElI < Elements.size()) {
3884 auto [Res, Type, BitWidth] = WorkList.pop_back_val();
3885
3886 if (Type->isRealFloatingType()) {
3887 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3888 *Res))
3889 return false;
3890 ElI++;
3891 continue;
3892 }
3893 if (Type->isIntegerType()) {
3894 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], Type, Elements[ElI],
3895 *Res))
3896 return false;
3897 if (BitWidth > 0) {
3898 if (!Res->isInt())
3899 return false;
3900 APSInt &Int = Res->getInt();
3901 unsigned OldBitWidth = Int.getBitWidth();
3902 unsigned NewBitWidth = BitWidth;
3903 if (NewBitWidth < OldBitWidth)
3904 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
3905 }
3906 ElI++;
3907 continue;
3908 }
3909 if (Type->isVectorType()) {
3910 QualType ElTy = Type->castAs<VectorType>()->getElementType();
3911 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
3912 SmallVector<APValue> Vals(NumEl);
3913 for (unsigned I = 0; I < NumEl; ++I) {
3914 if (!handleScalarCast(Info, FPO, E, ElTypes[ElI], ElTy, Elements[ElI],
3915 Vals[I]))
3916 return false;
3917 ElI++;
3918 }
3919 *Res = APValue(Vals.data(), NumEl);
3920 continue;
3921 }
3922 if (Type->isConstantArrayType()) {
3923 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
3924 ->getElementType();
3925 uint64_t Size =
3926 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
3927 *Res = APValue(APValue::UninitArray(), Size, Size);
3928 for (int64_t I = Size - 1; I > -1; --I)
3929 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
3930 continue;
3931 }
3932 if (Type->isRecordType()) {
3933 const RecordDecl *RD = Type->getAsRecordDecl();
3934
3935 unsigned NumBases = 0;
3936 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3937 NumBases = CXXRD->getNumBases();
3938
3939 *Res = APValue(APValue::UninitStruct(), NumBases, RD->getNumFields());
3940
3942 // we need to traverse backwards
3943 // Visit the base classes.
3944 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3945 if (CXXRD->getNumBases() > 0) {
3946 assert(CXXRD->getNumBases() == 1);
3947 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
3948 ReverseList.emplace_back(&Res->getStructBase(0), BS.getType(), 0u);
3949 }
3950 }
3951
3952 // Visit the fields.
3953 for (FieldDecl *FD : RD->fields()) {
3954 unsigned FDBW = 0;
3955 if (FD->isUnnamedBitField())
3956 continue;
3957 if (FD->isBitField()) {
3958 FDBW = FD->getBitWidthValue();
3959 }
3960
3961 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
3962 FD->getType(), FDBW);
3963 }
3964
3965 std::reverse(ReverseList.begin(), ReverseList.end());
3966 llvm::append_range(WorkList, ReverseList);
3967 continue;
3968 }
3969 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3970 return false;
3971 }
3972 return true;
3973}
3974
3975static bool handleElementwiseCast(EvalInfo &Info, const Expr *E,
3976 const FPOptions FPO,
3977 SmallVectorImpl<APValue> &Elements,
3978 SmallVectorImpl<QualType> &SrcTypes,
3979 SmallVectorImpl<QualType> &DestTypes,
3980 SmallVectorImpl<APValue> &Results) {
3981
3982 assert((Elements.size() == SrcTypes.size()) &&
3983 (Elements.size() == DestTypes.size()));
3984
3985 for (unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
3986 APValue Original = Elements[I];
3987 QualType SourceTy = SrcTypes[I];
3988 QualType DestTy = DestTypes[I];
3989
3990 if (!handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
3991 return false;
3992 }
3993 return true;
3994}
3995
3996static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy) {
3997
3998 SmallVector<QualType> WorkList = {BaseTy};
3999
4000 unsigned Size = 0;
4001 while (!WorkList.empty()) {
4002 QualType Type = WorkList.pop_back_val();
4004 Type->isBooleanType()) {
4005 ++Size;
4006 continue;
4007 }
4008 if (Type->isVectorType()) {
4009 unsigned NumEl = Type->castAs<VectorType>()->getNumElements();
4010 Size += NumEl;
4011 continue;
4012 }
4013 if (Type->isConstantMatrixType()) {
4014 unsigned NumEl =
4015 Type->castAs<ConstantMatrixType>()->getNumElementsFlattened();
4016 Size += NumEl;
4017 continue;
4018 }
4019 if (Type->isConstantArrayType()) {
4020 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4021 ->getElementType();
4022 uint64_t ArrSize =
4023 cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))->getZExtSize();
4024 for (uint64_t I = 0; I < ArrSize; ++I) {
4025 WorkList.push_back(ElTy);
4026 }
4027 continue;
4028 }
4029 if (Type->isRecordType()) {
4030 const RecordDecl *RD = Type->getAsRecordDecl();
4031
4032 // Visit the base classes.
4033 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4034 if (CXXRD->getNumBases() > 0) {
4035 assert(CXXRD->getNumBases() == 1);
4036 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4037 WorkList.push_back(BS.getType());
4038 }
4039 }
4040
4041 // visit the fields.
4042 for (FieldDecl *FD : RD->fields()) {
4043 if (FD->isUnnamedBitField())
4044 continue;
4045 WorkList.push_back(FD->getType());
4046 }
4047 continue;
4048 }
4049 }
4050 return Size;
4051}
4052
4053static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal,
4054 QualType &SrcTy) {
4055 SrcTy = E->getType();
4056
4057 if (!Evaluate(SrcVal, Info, E))
4058 return false;
4059
4060 assert((SrcVal.isFloat() || SrcVal.isInt() ||
4061 (SrcVal.isVector() && SrcVal.getVectorLength() == 1)) &&
4062 "Not a valid HLSLAggregateSplatCast.");
4063
4064 if (SrcVal.isVector()) {
4065 assert(SrcTy->isVectorType() && "Type mismatch.");
4066 SrcTy = SrcTy->castAs<VectorType>()->getElementType();
4067 SrcVal = SrcVal.getVectorElt(0);
4068 }
4069 if (SrcVal.isMatrix()) {
4070 assert(SrcTy->isConstantMatrixType() && "Type mismatch.");
4071 SrcTy = SrcTy->castAs<ConstantMatrixType>()->getElementType();
4072 SrcVal = SrcVal.getMatrixElt(0, 0);
4073 }
4074 return true;
4075}
4076
4077static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value,
4078 QualType BaseTy, SmallVectorImpl<APValue> &Elements,
4079 SmallVectorImpl<QualType> &Types, unsigned Size) {
4080
4081 SmallVector<std::pair<APValue, QualType>> WorkList = {{Value, BaseTy}};
4082 unsigned Populated = 0;
4083 while (!WorkList.empty() && Populated < Size) {
4084 auto [Work, Type] = WorkList.pop_back_val();
4085
4086 if (Work.isFloat() || Work.isInt()) {
4087 Elements.push_back(Work);
4088 Types.push_back(Type);
4089 Populated++;
4090 continue;
4091 }
4092 if (Work.isVector()) {
4093 assert(Type->isVectorType() && "Type mismatch.");
4094 QualType ElTy = Type->castAs<VectorType>()->getElementType();
4095 for (unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4096 I++) {
4097 Elements.push_back(Work.getVectorElt(I));
4098 Types.push_back(ElTy);
4099 Populated++;
4100 }
4101 continue;
4102 }
4103 if (Work.isMatrix()) {
4104 assert(Type->isConstantMatrixType() && "Type mismatch.");
4105 const auto *MT = Type->castAs<ConstantMatrixType>();
4106 QualType ElTy = MT->getElementType();
4107 // Matrix elements are flattened in row-major order.
4108 for (unsigned Row = 0; Row < Work.getMatrixNumRows() && Populated < Size;
4109 Row++) {
4110 for (unsigned Col = 0;
4111 Col < Work.getMatrixNumColumns() && Populated < Size; Col++) {
4112 Elements.push_back(Work.getMatrixElt(Row, Col));
4113 Types.push_back(ElTy);
4114 Populated++;
4115 }
4116 }
4117 continue;
4118 }
4119 if (Work.isArray()) {
4120 assert(Type->isConstantArrayType() && "Type mismatch.");
4121 QualType ElTy = cast<ConstantArrayType>(Info.Ctx.getAsArrayType(Type))
4122 ->getElementType();
4123 for (int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4124 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4125 }
4126 continue;
4127 }
4128
4129 if (Work.isStruct()) {
4130 assert(Type->isRecordType() && "Type mismatch.");
4131
4132 const RecordDecl *RD = Type->getAsRecordDecl();
4133
4135 // Visit the fields.
4136 for (FieldDecl *FD : RD->fields()) {
4137 if (FD->isUnnamedBitField())
4138 continue;
4139 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4140 FD->getType());
4141 }
4142
4143 std::reverse(ReverseList.begin(), ReverseList.end());
4144 llvm::append_range(WorkList, ReverseList);
4145
4146 // Visit the base classes.
4147 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4148 if (CXXRD->getNumBases() > 0) {
4149 assert(CXXRD->getNumBases() == 1);
4150 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[0];
4151 const APValue &Base = Work.getStructBase(0);
4152
4153 // Can happen in error cases.
4154 if (!Base.isStruct())
4155 return false;
4156
4157 WorkList.emplace_back(Base, BS.getType());
4158 }
4159 }
4160 continue;
4161 }
4162 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4163 return false;
4164 }
4165 return true;
4166}
4167
4168namespace {
4169/// A handle to a complete object (an object that is not a subobject of
4170/// another object).
4171struct CompleteObject {
4172 /// The identity of the object.
4173 APValue::LValueBase Base;
4174 /// The value of the complete object.
4175 APValue *Value;
4176 /// The type of the complete object.
4177 QualType Type;
4178
4179 CompleteObject() : Value(nullptr) {}
4180 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
4181 : Base(Base), Value(Value), Type(Type) {}
4182
4183 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
4184 // If this isn't a "real" access (eg, if it's just accessing the type
4185 // info), allow it. We assume the type doesn't change dynamically for
4186 // subobjects of constexpr objects (even though we'd hit UB here if it
4187 // did). FIXME: Is this right?
4188 if (!isAnyAccess(AK))
4189 return true;
4190
4191 // In C++14 onwards, it is permitted to read a mutable member whose
4192 // lifetime began within the evaluation.
4193 // FIXME: Should we also allow this in C++11?
4194 if (!Info.getLangOpts().CPlusPlus14 &&
4195 AK != AccessKinds::AK_IsWithinLifetime)
4196 return false;
4197 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
4198 }
4199
4200 explicit operator bool() const { return !Type.isNull(); }
4201};
4202} // end anonymous namespace
4203
4204static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
4205 bool IsMutable = false) {
4206 // C++ [basic.type.qualifier]p1:
4207 // - A const object is an object of type const T or a non-mutable subobject
4208 // of a const object.
4209 if (ObjType.isConstQualified() && !IsMutable)
4210 SubobjType.addConst();
4211 // - A volatile object is an object of type const T or a subobject of a
4212 // volatile object.
4213 if (ObjType.isVolatileQualified())
4214 SubobjType.addVolatile();
4215 return SubobjType;
4216}
4217
4218/// Find the designated sub-object of an rvalue.
4219template <typename SubobjectHandler>
4220static typename SubobjectHandler::result_type
4221findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
4222 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4223 if (Sub.Invalid)
4224 // A diagnostic will have already been produced.
4225 return handler.failed();
4226 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4227 if (Info.getLangOpts().CPlusPlus11)
4228 Info.FFDiag(E, Sub.isOnePastTheEnd()
4229 ? diag::note_constexpr_access_past_end
4230 : diag::note_constexpr_access_unsized_array)
4231 << handler.AccessKind;
4232 else
4233 Info.FFDiag(E);
4234 return handler.failed();
4235 }
4236
4237 APValue *O = Obj.Value;
4238 QualType ObjType = Obj.Type;
4239 const FieldDecl *LastField = nullptr;
4240 const FieldDecl *VolatileField = nullptr;
4241
4242 // Walk the designator's path to find the subobject.
4243 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
4244 // Reading an indeterminate value is undefined, but assigning over one is OK.
4245 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
4246 (O->isIndeterminate() &&
4247 !isValidIndeterminateAccess(handler.AccessKind))) {
4248 // Object has ended lifetime.
4249 // If I is non-zero, some subobject (member or array element) of a
4250 // complete object has ended its lifetime, so this is valid for
4251 // IsWithinLifetime, resulting in false.
4252 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
4253 return false;
4254 if (!Info.checkingPotentialConstantExpression()) {
4255 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4256 << handler.AccessKind << O->isIndeterminate()
4257 << E->getSourceRange();
4258 NoteLValueLocation(Info, Obj.Base);
4259 }
4260 return handler.failed();
4261 }
4262
4263 // C++ [class.ctor]p5, C++ [class.dtor]p5:
4264 // const and volatile semantics are not applied on an object under
4265 // {con,de}struction.
4266 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
4267 ObjType->isRecordType() &&
4268 Info.isEvaluatingCtorDtor(
4269 Obj.Base, ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
4270 ConstructionPhase::None) {
4271 ObjType = Info.Ctx.getCanonicalType(ObjType);
4272 ObjType.removeLocalConst();
4273 ObjType.removeLocalVolatile();
4274 }
4275
4276 // If this is our last pass, check that the final object type is OK.
4277 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
4278 // Accesses to volatile objects are prohibited.
4279 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
4280 if (Info.getLangOpts().CPlusPlus) {
4281 int DiagKind;
4282 SourceLocation Loc;
4283 const NamedDecl *Decl = nullptr;
4284 if (VolatileField) {
4285 DiagKind = 2;
4286 Loc = VolatileField->getLocation();
4287 Decl = VolatileField;
4288 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
4289 DiagKind = 1;
4290 Loc = VD->getLocation();
4291 Decl = VD;
4292 } else {
4293 DiagKind = 0;
4294 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
4295 Loc = E->getExprLoc();
4296 }
4297 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
4298 << handler.AccessKind << DiagKind << Decl;
4299 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4300 } else {
4301 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4302 }
4303 return handler.failed();
4304 }
4305
4306 // If we are reading an object of class type, there may still be more
4307 // things we need to check: if there are any mutable subobjects, we
4308 // cannot perform this read. (This only happens when performing a trivial
4309 // copy or assignment.)
4310 if (ObjType->isRecordType() &&
4311 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4312 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
4313 return handler.failed();
4314 }
4315
4316 if (I == N) {
4317 if (!handler.found(*O, ObjType, Obj.Base))
4318 return false;
4319
4320 // If we modified a bit-field, truncate it to the right width.
4321 if (isModification(handler.AccessKind) &&
4322 LastField && LastField->isBitField() &&
4323 !truncateBitfieldValue(Info, E, *O, LastField))
4324 return false;
4325
4326 return true;
4327 }
4328
4329 LastField = nullptr;
4330
4331 // The value of an atomic object is represented like a value of the
4332 // underlying type, so look through the _Atomic wrapper.
4333 if (const AtomicType *AT = ObjType->getAs<AtomicType>())
4334 ObjType = Info.Ctx.getQualifiedType(AT->getValueType(),
4335 ObjType.getQualifiers());
4336
4337 if (ObjType->isArrayType()) {
4338 // Next subobject is an array element.
4339 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
4341 "vla in literal type?");
4342 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4343 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4344 CAT && CAT->getSize().ule(Index)) {
4345 // Note, it should not be possible to form a pointer with a valid
4346 // designator which points more than one past the end of the array.
4347 if (Info.getLangOpts().CPlusPlus11)
4348 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4349 << handler.AccessKind;
4350 else
4351 Info.FFDiag(E);
4352 return handler.failed();
4353 }
4354
4355 ObjType = AT->getElementType();
4356
4357 if (O->getArrayInitializedElts() > Index)
4358 O = &O->getArrayInitializedElt(Index);
4359 else if (!isRead(handler.AccessKind)) {
4360 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4361 CAT && !CheckArraySize(Info, CAT, E->getExprLoc()))
4362 return handler.failed();
4363
4364 expandArray(*O, Index);
4365 O = &O->getArrayInitializedElt(Index);
4366 } else
4367 O = &O->getArrayFiller();
4368 } else if (ObjType->isAnyComplexType()) {
4369 // Next subobject is a complex number.
4370 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4371 if (Index > 1) {
4372 if (Info.getLangOpts().CPlusPlus11)
4373 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4374 << handler.AccessKind;
4375 else
4376 Info.FFDiag(E);
4377 return handler.failed();
4378 }
4379
4380 ObjType = getSubobjectType(
4381 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4382
4383 assert(I == N - 1 && "extracting subobject of scalar?");
4384 if (O->isComplexInt()) {
4385 return handler.found(Index ? O->getComplexIntImag()
4386 : O->getComplexIntReal(), ObjType);
4387 } else {
4388 assert(O->isComplexFloat());
4389 return handler.found(Index ? O->getComplexFloatImag()
4390 : O->getComplexFloatReal(), ObjType);
4391 }
4392 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4393 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4394 unsigned NumElements = VT->getNumElements();
4395 if (Index == NumElements) {
4396 if (Info.getLangOpts().CPlusPlus11)
4397 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4398 << handler.AccessKind;
4399 else
4400 Info.FFDiag(E);
4401 return handler.failed();
4402 }
4403
4404 if (Index > NumElements) {
4405 Info.CCEDiag(E, diag::note_constexpr_array_index)
4406 << Index << /*array*/ 0 << NumElements;
4407 return handler.failed();
4408 }
4409
4410 ObjType = VT->getElementType();
4411 assert(I == N - 1 && "extracting subobject of scalar?");
4412
4413 if (O->isIndeterminate()) {
4414 if (isRead(handler.AccessKind)) {
4415 Info.FFDiag(E);
4416 return handler.failed();
4417 }
4418 expandVector(*O, NumElements);
4419 }
4420 assert(O->isVector() && "unexpected object during vector element access");
4421 return handler.found(O->getVectorElt(Index), ObjType, Obj.Base);
4422 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4423 if (Field->isMutable() &&
4424 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4425 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4426 << handler.AccessKind << Field;
4427 Info.Note(Field->getLocation(), diag::note_declared_at);
4428 return handler.failed();
4429 }
4430
4431 // Next subobject is a class, struct or union field.
4432 RecordDecl *RD = ObjType->castAsCanonical<RecordType>()->getDecl();
4433 if (RD->isUnion()) {
4434 const FieldDecl *UnionField = O->getUnionField();
4435 if (!UnionField ||
4436 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4437 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4438 // Placement new onto an inactive union member makes it active.
4439 O->setUnion(Field, APValue());
4440 } else {
4441 // Pointer to/into inactive union member: Not within lifetime
4442 if (handler.AccessKind == AK_IsWithinLifetime)
4443 return false;
4444 // FIXME: If O->getUnionValue() is absent, report that there's no
4445 // active union member rather than reporting the prior active union
4446 // member. We'll need to fix nullptr_t to not use APValue() as its
4447 // representation first.
4448 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4449 << handler.AccessKind << Field << !UnionField << UnionField;
4450 return handler.failed();
4451 }
4452 }
4453 O = &O->getUnionValue();
4454 } else
4455 O = &O->getStructField(Field->getFieldIndex());
4456
4457 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4458 LastField = Field;
4459 if (Field->getType().isVolatileQualified())
4460 VolatileField = Field;
4461 } else {
4462 // Next subobject is a base class.
4463 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4464 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4465
4466 unsigned BaseIndex = getBaseIndex(Derived, Base);
4467 unsigned NumNonVirtualBases = O->getStructNumBases();
4468 if (BaseIndex >= NumNonVirtualBases) {
4469 O = &O->getStructVirtualBase(BaseIndex - NumNonVirtualBases);
4470 } else
4471 O = &O->getStructBase(BaseIndex);
4472
4473 ObjType = getSubobjectType(ObjType, Info.Ctx.getCanonicalTagType(Base));
4474 }
4475 }
4476}
4477
4478namespace {
4479struct ExtractSubobjectHandler {
4480 EvalInfo &Info;
4481 const Expr *E;
4482 APValue &Result;
4483 const AccessKinds AccessKind;
4484
4485 typedef bool result_type;
4486 bool failed() { return false; }
4487 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4488 Result = Subobj;
4489 if (AccessKind == AK_ReadObjectRepresentation)
4490 return true;
4491 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4492 }
4493 bool found(APSInt &Value, QualType SubobjType) {
4494 Result = APValue(Value);
4495 return true;
4496 }
4497 bool found(APFloat &Value, QualType SubobjType) {
4498 Result = APValue(Value);
4499 return true;
4500 }
4501};
4502} // end anonymous namespace
4503
4504/// Extract the designated sub-object of an rvalue.
4505static bool extractSubobject(EvalInfo &Info, const Expr *E,
4506 const CompleteObject &Obj,
4507 const SubobjectDesignator &Sub, APValue &Result,
4508 AccessKinds AK = AK_Read) {
4509 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4510 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4511 return findSubobject(Info, E, Obj, Sub, Handler);
4512}
4513
4514namespace {
4515struct ModifySubobjectHandler {
4516 EvalInfo &Info;
4517 APValue &NewVal;
4518 const Expr *E;
4519
4520 typedef bool result_type;
4521 static const AccessKinds AccessKind = AK_Assign;
4522
4523 bool checkConst(QualType QT) {
4524 // Assigning to a const object has undefined behavior.
4525 if (QT.isConstQualified()) {
4526 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4527 return false;
4528 }
4529 return true;
4530 }
4531
4532 bool failed() { return false; }
4533 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4534 if (!checkConst(SubobjType))
4535 return false;
4536 // We've been given ownership of NewVal, so just swap it in.
4537 Subobj.swap(NewVal);
4538 return true;
4539 }
4540 bool found(APSInt &Value, QualType SubobjType) {
4541 if (!checkConst(SubobjType))
4542 return false;
4543 if (!NewVal.isInt()) {
4544 // Maybe trying to write a cast pointer value into a complex?
4545 Info.FFDiag(E);
4546 return false;
4547 }
4548 Value = NewVal.getInt();
4549 return true;
4550 }
4551 bool found(APFloat &Value, QualType SubobjType) {
4552 if (!checkConst(SubobjType))
4553 return false;
4554 Value = NewVal.getFloat();
4555 return true;
4556 }
4557};
4558} // end anonymous namespace
4559
4560const AccessKinds ModifySubobjectHandler::AccessKind;
4561
4562/// Update the designated sub-object of an rvalue to the given value.
4563static bool modifySubobject(EvalInfo &Info, const Expr *E,
4564 const CompleteObject &Obj,
4565 const SubobjectDesignator &Sub,
4566 APValue &NewVal) {
4567 ModifySubobjectHandler Handler = { Info, NewVal, E };
4568 return findSubobject(Info, E, Obj, Sub, Handler);
4569}
4570
4571/// Find the position where two subobject designators diverge, or equivalently
4572/// the length of the common initial subsequence.
4573static unsigned FindDesignatorMismatch(QualType ObjType,
4574 const SubobjectDesignator &A,
4575 const SubobjectDesignator &B,
4576 bool &WasArrayIndex) {
4577 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4578 for (/**/; I != N; ++I) {
4579 if (!ObjType.isNull() &&
4580 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4581 // Next subobject is an array element.
4582 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4583 WasArrayIndex = true;
4584 return I;
4585 }
4586 if (ObjType->isAnyComplexType())
4587 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4588 else
4589 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4590 } else {
4591 if (A.Entries[I].getAsBaseOrMember() !=
4592 B.Entries[I].getAsBaseOrMember()) {
4593 WasArrayIndex = false;
4594 return I;
4595 }
4596 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4597 // Next subobject is a field.
4598 ObjType = FD->getType();
4599 else
4600 // Next subobject is a base class.
4601 ObjType = QualType();
4602 }
4603 }
4604 WasArrayIndex = false;
4605 return I;
4606}
4607
4608/// Determine whether the given subobject designators refer to elements of the
4609/// same array object.
4611 const SubobjectDesignator &A,
4612 const SubobjectDesignator &B) {
4613 if (A.Entries.size() != B.Entries.size())
4614 return false;
4615
4616 bool IsArray = A.MostDerivedIsArrayElement;
4617 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4618 // A is a subobject of the array element.
4619 return false;
4620
4621 // If A (and B) designates an array element, the last entry will be the array
4622 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4623 // of length 1' case, and the entire path must match.
4624 bool WasArrayIndex;
4625 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4626 return CommonLength >= A.Entries.size() - IsArray;
4627}
4628
4629/// Find the complete object to which an LValue refers.
4630static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4631 AccessKinds AK, const LValue &LVal,
4632 QualType LValType) {
4633 if (LVal.InvalidBase) {
4634 Info.FFDiag(E);
4635 return CompleteObject();
4636 }
4637
4638 if (!LVal.Base) {
4640 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4641 else
4642 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4643 return CompleteObject();
4644 }
4645
4646 CallStackFrame *Frame = nullptr;
4647 unsigned Depth = 0;
4648 if (LVal.getLValueCallIndex()) {
4649 std::tie(Frame, Depth) =
4650 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4651 if (!Frame) {
4652 Info.FFDiag(E, diag::note_constexpr_access_uninit, 1)
4653 << AK << /*Indeterminate=*/false << E->getSourceRange();
4654 NoteLValueLocation(Info, LVal.Base);
4655 return CompleteObject();
4656 }
4657 }
4658
4659 bool IsAccess = isAnyAccess(AK);
4660
4661 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4662 // is not a constant expression (even if the object is non-volatile). We also
4663 // apply this rule to C++98, in order to conform to the expected 'volatile'
4664 // semantics.
4665 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4666 if (Info.getLangOpts().CPlusPlus)
4667 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4668 << AK << LValType;
4669 else
4670 Info.FFDiag(E);
4671 return CompleteObject();
4672 }
4673
4674 // Compute value storage location and type of base object.
4675 APValue *BaseVal = nullptr;
4676 QualType BaseType = getType(LVal.Base);
4677
4678 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4679 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4680 // This is the object whose initializer we're evaluating, so its lifetime
4681 // started in the current evaluation.
4682 BaseVal = Info.EvaluatingDeclValue;
4683 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4684 // Allow reading from a GUID declaration.
4685 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4686 if (isModification(AK)) {
4687 // All the remaining cases do not permit modification of the object.
4688 Info.FFDiag(E, diag::note_constexpr_modify_global);
4689 return CompleteObject();
4690 }
4691 APValue &V = GD->getAsAPValue();
4692 if (V.isAbsent()) {
4693 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4694 << GD->getType();
4695 return CompleteObject();
4696 }
4697 return CompleteObject(LVal.Base, &V, GD->getType());
4698 }
4699
4700 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4701 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4702 if (isModification(AK)) {
4703 Info.FFDiag(E, diag::note_constexpr_modify_global);
4704 return CompleteObject();
4705 }
4706 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4707 GCD->getType());
4708 }
4709
4710 // Allow reading from template parameter objects.
4711 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4712 if (isModification(AK)) {
4713 Info.FFDiag(E, diag::note_constexpr_modify_global);
4714 return CompleteObject();
4715 }
4716 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4717 TPO->getType());
4718 }
4719
4720 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4721 // In C++11, constexpr, non-volatile variables initialized with constant
4722 // expressions are constant expressions too. Inside constexpr functions,
4723 // parameters are constant expressions even if they're non-const.
4724 // In C++1y, objects local to a constant expression (those with a Frame) are
4725 // both readable and writable inside constant expressions.
4726 // In C, such things can also be folded, although they are not ICEs.
4727 const VarDecl *VD = dyn_cast<VarDecl>(D);
4728 if (VD) {
4729 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4730 VD = VDef;
4731 }
4732 if (!VD || VD->isInvalidDecl()) {
4733 Info.FFDiag(E);
4734 return CompleteObject();
4735 }
4736
4737 bool IsConstant = BaseType.isConstant(Info.Ctx);
4738 bool ConstexprVar = false;
4739 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4740 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4741 ConstexprVar = VD->isConstexpr();
4742
4743 // Unless we're looking at a local variable or argument in a constexpr call,
4744 // the variable we're reading must be const (unless we are binding to a
4745 // reference).
4746 if (AK != clang::AK_Dereference && !Frame) {
4747 if (IsAccess && isa<ParmVarDecl>(VD)) {
4748 // Access of a parameter that's not associated with a frame isn't going
4749 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4750 // suitable diagnostic.
4751 } else if (Info.getLangOpts().CPlusPlus14 &&
4752 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4753 // OK, we can read and modify an object if we're in the process of
4754 // evaluating its initializer, because its lifetime began in this
4755 // evaluation.
4756 } else if (isModification(AK)) {
4757 // All the remaining cases do not permit modification of the object.
4758 Info.FFDiag(E, diag::note_constexpr_modify_global);
4759 return CompleteObject();
4760 } else if (VD->isConstexpr()) {
4761 // OK, we can read this variable.
4762 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4763 Info.FFDiag(E);
4764 return CompleteObject();
4765 } else if (BaseType->isIntegralOrEnumerationType()) {
4766 if (!IsConstant) {
4767 if (!IsAccess)
4768 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4769 if (Info.getLangOpts().CPlusPlus) {
4770 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4771 Info.Note(VD->getLocation(), diag::note_declared_at);
4772 } else {
4773 Info.FFDiag(E);
4774 }
4775 return CompleteObject();
4776 }
4777 } else if (!IsAccess) {
4778 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4779 } else if ((IsConstant || BaseType->isReferenceType()) &&
4780 Info.checkingPotentialConstantExpression() &&
4781 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4782 // This variable might end up being constexpr. Don't diagnose it yet.
4783 } else if (IsConstant) {
4784 // Keep evaluating to see what we can do. In particular, we support
4785 // folding of const floating-point types, in order to make static const
4786 // data members of such types (supported as an extension) more useful.
4787 if (Info.getLangOpts().CPlusPlus) {
4788 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4789 ? diag::note_constexpr_ltor_non_constexpr
4790 : diag::note_constexpr_ltor_non_integral, 1)
4791 << VD << BaseType;
4792 Info.Note(VD->getLocation(), diag::note_declared_at);
4793 } else {
4794 Info.CCEDiag(E);
4795 }
4796 } else {
4797 // Never allow reading a non-const value.
4798 if (Info.getLangOpts().CPlusPlus) {
4799 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4800 ? diag::note_constexpr_ltor_non_constexpr
4801 : diag::note_constexpr_ltor_non_integral, 1)
4802 << VD << BaseType;
4803 Info.Note(VD->getLocation(), diag::note_declared_at);
4804 } else {
4805 Info.FFDiag(E);
4806 }
4807 return CompleteObject();
4808 }
4809 }
4810
4811 // When binding to a reference, the variable does not need to be constexpr
4812 // or have constant initalization.
4813 if (AK != clang::AK_Dereference &&
4814 !evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(),
4815 BaseVal))
4816 return CompleteObject();
4817 // If evaluateVarDeclInit sees a constexpr-unknown variable, it returns
4818 // a null BaseVal. Any constexpr-unknown variable seen here is an error:
4819 // we can't access a constexpr-unknown object.
4820 if (AK != clang::AK_Dereference && !BaseVal) {
4821 if (!Info.checkingPotentialConstantExpression()) {
4822 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4823 << AK << VD;
4824 Info.Note(VD->getLocation(), diag::note_declared_at);
4825 }
4826 return CompleteObject();
4827 }
4828 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4829 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4830 if (!Alloc) {
4831 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4832 return CompleteObject();
4833 }
4834 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4835 LVal.Base.getDynamicAllocType());
4836 }
4837 // When binding to a reference, the variable does not need to be
4838 // within its lifetime.
4839 else if (AK != clang::AK_Dereference) {
4840 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4841
4842 if (!Frame) {
4843 if (const MaterializeTemporaryExpr *MTE =
4844 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4845 assert(MTE->getStorageDuration() == SD_Static &&
4846 "should have a frame for a non-global materialized temporary");
4847
4848 // C++20 [expr.const]p4: [DR2126]
4849 // An object or reference is usable in constant expressions if it is
4850 // - a temporary object of non-volatile const-qualified literal type
4851 // whose lifetime is extended to that of a variable that is usable
4852 // in constant expressions
4853 //
4854 // C++20 [expr.const]p5:
4855 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4856 // - a non-volatile glvalue that refers to an object that is usable
4857 // in constant expressions, or
4858 // - a non-volatile glvalue of literal type that refers to a
4859 // non-volatile object whose lifetime began within the evaluation
4860 // of E;
4861 //
4862 // C++11 misses the 'began within the evaluation of e' check and
4863 // instead allows all temporaries, including things like:
4864 // int &&r = 1;
4865 // int x = ++r;
4866 // constexpr int k = r;
4867 // Therefore we use the C++14-onwards rules in C++11 too.
4868 //
4869 // Note that temporaries whose lifetimes began while evaluating a
4870 // variable's constructor are not usable while evaluating the
4871 // corresponding destructor, not even if they're of const-qualified
4872 // types.
4873 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4874 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4875 if (!IsAccess)
4876 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4877 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4878 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4879 return CompleteObject();
4880 }
4881
4882 BaseVal = MTE->getOrCreateValue(false);
4883 assert(BaseVal && "got reference to unevaluated temporary");
4884 } else if (const CompoundLiteralExpr *CLE =
4885 dyn_cast_or_null<CompoundLiteralExpr>(Base)) {
4886 // According to GCC info page:
4887 //
4888 // 6.28 Compound Literals
4889 //
4890 // As an optimization, G++ sometimes gives array compound literals
4891 // longer lifetimes: when the array either appears outside a function or
4892 // has a const-qualified type. If foo and its initializer had elements
4893 // of type char *const rather than char *, or if foo were a global
4894 // variable, the array would have static storage duration. But it is
4895 // probably safest just to avoid the use of array compound literals in
4896 // C++ code.
4897 //
4898 // Obey that rule by checking constness for converted array types.
4899 if (QualType CLETy = CLE->getType(); CLETy->isArrayType() &&
4900 !LValType->isArrayType() &&
4901 !CLETy.isConstant(Info.Ctx)) {
4902 Info.FFDiag(E);
4903 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4904 return CompleteObject();
4905 }
4906
4907 BaseVal = &CLE->getStaticValue();
4908 } else {
4909 if (!IsAccess)
4910 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4911 APValue Val;
4912 LVal.moveInto(Val);
4913 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4914 << AK
4915 << Val.getAsString(Info.Ctx,
4916 Info.Ctx.getLValueReferenceType(LValType));
4917 NoteLValueLocation(Info, LVal.Base);
4918 return CompleteObject();
4919 }
4920 } else if (AK != clang::AK_Dereference) {
4921 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4922 assert(BaseVal && "missing value for temporary");
4923 }
4924 }
4925
4926 // In C++14, we can't safely access any mutable state when we might be
4927 // evaluating after an unmodeled side effect. Parameters are modeled as state
4928 // in the caller, but aren't visible once the call returns, so they can be
4929 // modified in a speculatively-evaluated call.
4930 //
4931 // FIXME: Not all local state is mutable. Allow local constant subobjects
4932 // to be read here (but take care with 'mutable' fields).
4933 unsigned VisibleDepth = Depth;
4934 if (llvm::isa_and_nonnull<ParmVarDecl>(
4935 LVal.Base.dyn_cast<const ValueDecl *>()))
4936 ++VisibleDepth;
4937 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4938 Info.EvalStatus.HasSideEffects) ||
4939 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4940 return CompleteObject();
4941
4942 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4943}
4944
4945/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4946/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4947/// glvalue referred to by an entity of reference type.
4948///
4949/// \param Info - Information about the ongoing evaluation.
4950/// \param Conv - The expression for which we are performing the conversion.
4951/// Used for diagnostics.
4952/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4953/// case of a non-class type).
4954/// \param LVal - The glvalue on which we are attempting to perform this action.
4955/// \param RVal - The produced value will be placed here.
4956/// \param WantObjectRepresentation - If true, we're looking for the object
4957/// representation rather than the value, and in particular,
4958/// there is no requirement that the result be fully initialized.
4959static bool
4961 const LValue &LVal, APValue &RVal,
4962 bool WantObjectRepresentation = false) {
4963 if (LVal.Designator.Invalid)
4964 return false;
4965
4966 // Check for special cases where there is no existing APValue to look at.
4967 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4968
4969 AccessKinds AK =
4970 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4971
4972 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4974 // Special-case character extraction so we don't have to construct an
4975 // APValue for the whole string.
4976 assert(LVal.Designator.Entries.size() <= 1 &&
4977 "Can only read characters from string literals");
4978 if (LVal.Designator.Entries.empty()) {
4979 // Fail for now for LValue to RValue conversion of an array.
4980 // (This shouldn't show up in C/C++, but it could be triggered by a
4981 // weird EvaluateAsRValue call from a tool.)
4982 Info.FFDiag(Conv);
4983 return false;
4984 }
4985 if (LVal.Designator.isOnePastTheEnd()) {
4986 if (Info.getLangOpts().CPlusPlus11)
4987 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4988 else
4989 Info.FFDiag(Conv);
4990 return false;
4991 }
4992 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4993 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4994 return true;
4995 }
4996 }
4997
4998 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4999 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
5000}
5001
5002static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E,
5003 QualType DestTy,
5004 SmallVectorImpl<APValue> &SrcVals,
5005 SmallVectorImpl<QualType> &SrcTypes) {
5006 APValue Val;
5007 if (!Evaluate(Val, Info, E))
5008 return false;
5009
5010 // must be dealing with a record
5011 if (Val.isLValue()) {
5012 LValue LVal;
5013 LVal.setFrom(Info.Ctx, Val);
5014 if (!handleLValueToRValueConversion(Info, E, E->getType(), LVal, Val))
5015 return false;
5016 }
5017
5018 unsigned NEls = elementwiseSize(Info, DestTy);
5019 // flatten the source
5020 if (!flattenAPValue(Info, E, Val, E->getType(), SrcVals, SrcTypes, NEls))
5021 return false;
5022
5023 return true;
5024}
5025
5026/// Perform an assignment of Val to LVal. Takes ownership of Val.
5027static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
5028 QualType LValType, APValue &Val) {
5029 if (LVal.Designator.Invalid)
5030 return false;
5031
5032 if (!Info.getLangOpts().CPlusPlus14) {
5033 Info.FFDiag(E);
5034 return false;
5035 }
5036
5037 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5038 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
5039}
5040
5041namespace {
5042struct CompoundAssignSubobjectHandler {
5043 EvalInfo &Info;
5044 const CompoundAssignOperator *E;
5045 QualType PromotedLHSType;
5047 const APValue &RHS;
5048
5049 static const AccessKinds AccessKind = AK_Assign;
5050
5051 typedef bool result_type;
5052
5053 bool checkConst(QualType QT) {
5054 // Assigning to a const object has undefined behavior.
5055 if (QT.isConstQualified()) {
5056 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5057 return false;
5058 }
5059 return true;
5060 }
5061
5062 bool failed() { return false; }
5063 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
5064 switch (Subobj.getKind()) {
5065 case APValue::Int:
5066 return found(Subobj.getInt(), SubobjType);
5067 case APValue::Float:
5068 return found(Subobj.getFloat(), SubobjType);
5071 // FIXME: Implement complex compound assignment.
5072 Info.FFDiag(E);
5073 return false;
5074 case APValue::LValue:
5075 return foundPointer(Subobj, SubobjType);
5076 case APValue::Vector:
5077 return foundVector(Subobj, SubobjType);
5079 Info.FFDiag(E, diag::note_constexpr_access_uninit)
5080 << /*read of=*/0 << /*uninitialized object=*/1
5081 << E->getLHS()->getSourceRange();
5082 NoteLValueLocation(Info, Base);
5083 return false;
5084 default:
5085 // FIXME: can this happen?
5086 Info.FFDiag(E);
5087 return false;
5088 }
5089 }
5090
5091 bool foundVector(APValue &Value, QualType SubobjType) {
5092 if (!checkConst(SubobjType))
5093 return false;
5094
5095 if (!SubobjType->isVectorType()) {
5096 Info.FFDiag(E);
5097 return false;
5098 }
5099 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
5100 }
5101
5102 bool found(APSInt &Value, QualType SubobjType) {
5103 if (!checkConst(SubobjType))
5104 return false;
5105
5106 if (!SubobjType->isIntegerType()) {
5107 // We don't support compound assignment on integer-cast-to-pointer
5108 // values.
5109 Info.FFDiag(E);
5110 return false;
5111 }
5112
5113 if (RHS.isInt()) {
5114 APSInt LHS =
5115 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
5116 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
5117 return false;
5118 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
5119 return true;
5120 } else if (RHS.isFloat()) {
5121 const FPOptions FPO = E->getFPFeaturesInEffect(
5122 Info.Ctx.getLangOpts());
5123 APFloat FValue(0.0);
5124 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
5125 PromotedLHSType, FValue) &&
5126 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
5127 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
5128 Value);
5129 }
5130
5131 Info.FFDiag(E);
5132 return false;
5133 }
5134 bool found(APFloat &Value, QualType SubobjType) {
5135 return checkConst(SubobjType) &&
5136 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
5137 Value) &&
5138 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
5139 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
5140 }
5141 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5142 if (!checkConst(SubobjType))
5143 return false;
5144
5145 QualType PointeeType;
5146 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5147 PointeeType = PT->getPointeeType();
5148
5149 if (PointeeType.isNull() || !RHS.isInt() ||
5150 (Opcode != BO_Add && Opcode != BO_Sub)) {
5151 Info.FFDiag(E);
5152 return false;
5153 }
5154
5155 APSInt Offset = RHS.getInt();
5156 if (Opcode == BO_Sub)
5157 negateAsSigned(Offset);
5158
5159 LValue LVal;
5160 LVal.setFrom(Info.Ctx, Subobj);
5161 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
5162 return false;
5163 LVal.moveInto(Subobj);
5164 return true;
5165 }
5166};
5167} // end anonymous namespace
5168
5169const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5170
5171/// Perform a compound assignment of LVal <op>= RVal.
5172static bool handleCompoundAssignment(EvalInfo &Info,
5173 const CompoundAssignOperator *E,
5174 const LValue &LVal, QualType LValType,
5175 QualType PromotedLValType,
5176 BinaryOperatorKind Opcode,
5177 const APValue &RVal) {
5178 if (LVal.Designator.Invalid)
5179 return false;
5180
5181 if (!Info.getLangOpts().CPlusPlus14) {
5182 Info.FFDiag(E);
5183 return false;
5184 }
5185
5186 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
5187 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5188 RVal };
5189 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5190}
5191
5192namespace {
5193struct IncDecSubobjectHandler {
5194 EvalInfo &Info;
5195 const UnaryOperator *E;
5197 APValue *Old;
5198
5199 typedef bool result_type;
5200
5201 bool checkConst(QualType QT) {
5202 // Assigning to a const object has undefined behavior.
5203 if (QT.isConstQualified()) {
5204 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5205 return false;
5206 }
5207 return true;
5208 }
5209
5210 bool failed() { return false; }
5211 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
5212 // Stash the old value. Also clear Old, so we don't clobber it later
5213 // if we're post-incrementing a complex.
5214 if (Old) {
5215 *Old = Subobj;
5216 Old = nullptr;
5217 }
5218
5219 switch (Subobj.getKind()) {
5220 case APValue::Int:
5221 return found(Subobj.getInt(), SubobjType);
5222 case APValue::Float:
5223 return found(Subobj.getFloat(), SubobjType);
5225 return found(Subobj.getComplexIntReal(),
5226 SubobjType->castAs<ComplexType>()->getElementType()
5227 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5229 return found(Subobj.getComplexFloatReal(),
5230 SubobjType->castAs<ComplexType>()->getElementType()
5231 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
5232 case APValue::LValue:
5233 return foundPointer(Subobj, SubobjType);
5234 default:
5235 // FIXME: can this happen?
5236 Info.FFDiag(E);
5237 return false;
5238 }
5239 }
5240 bool found(APSInt &Value, QualType SubobjType) {
5241 if (!checkConst(SubobjType))
5242 return false;
5243
5244 if (!SubobjType->isIntegerType()) {
5245 // We don't support increment / decrement on integer-cast-to-pointer
5246 // values.
5247 Info.FFDiag(E);
5248 return false;
5249 }
5250
5251 if (Old) *Old = APValue(Value);
5252
5253 // bool arithmetic promotes to int, and the conversion back to bool
5254 // doesn't reduce mod 2^n, so special-case it.
5255 if (SubobjType->isBooleanType()) {
5256 if (AccessKind == AK_Increment)
5257 Value = 1;
5258 else
5259 Value = !Value;
5260 return true;
5261 }
5262
5263 bool WasNegative = Value.isNegative();
5264 if (AccessKind == AK_Increment) {
5265 ++Value;
5266
5267 if (!WasNegative && Value.isNegative() && E->canOverflow() &&
5268 !SubobjType.isWrapType()) {
5269 APSInt ActualValue(Value, /*IsUnsigned*/true);
5270 return HandleOverflow(Info, E, ActualValue, SubobjType);
5271 }
5272 } else {
5273 --Value;
5274
5275 if (WasNegative && !Value.isNegative() && E->canOverflow() &&
5276 !SubobjType.isWrapType()) {
5277 unsigned BitWidth = Value.getBitWidth();
5278 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
5279 ActualValue.setBit(BitWidth);
5280 return HandleOverflow(Info, E, ActualValue, SubobjType);
5281 }
5282 }
5283 return true;
5284 }
5285 bool found(APFloat &Value, QualType SubobjType) {
5286 if (!checkConst(SubobjType))
5287 return false;
5288
5289 if (Old) *Old = APValue(Value);
5290
5291 APFloat One(Value.getSemantics(), 1);
5292 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
5293 APFloat::opStatus St;
5294 if (AccessKind == AK_Increment)
5295 St = Value.add(One, RM);
5296 else
5297 St = Value.subtract(One, RM);
5298 return checkFloatingPointResult(Info, E, St);
5299 }
5300 bool foundPointer(APValue &Subobj, QualType SubobjType) {
5301 if (!checkConst(SubobjType))
5302 return false;
5303
5304 QualType PointeeType;
5305 if (const PointerType *PT = SubobjType->getAs<PointerType>())
5306 PointeeType = PT->getPointeeType();
5307 else {
5308 Info.FFDiag(E);
5309 return false;
5310 }
5311
5312 LValue LVal;
5313 LVal.setFrom(Info.Ctx, Subobj);
5314 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
5315 AccessKind == AK_Increment ? 1 : -1))
5316 return false;
5317 LVal.moveInto(Subobj);
5318 return true;
5319 }
5320};
5321} // end anonymous namespace
5322
5323/// Perform an increment or decrement on LVal.
5324static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
5325 QualType LValType, bool IsIncrement, APValue *Old) {
5326 if (LVal.Designator.Invalid)
5327 return false;
5328
5329 if (!Info.getLangOpts().CPlusPlus14) {
5330 Info.FFDiag(E);
5331 return false;
5332 }
5333
5334 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
5335 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
5336 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
5337 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
5338}
5339
5340/// Build an lvalue for the object argument of a member function call.
5341static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
5342 LValue &This) {
5343 if (Object->getType()->isPointerType() && Object->isPRValue())
5344 return EvaluatePointer(Object, This, Info);
5345
5346 if (Object->isGLValue())
5347 return EvaluateLValue(Object, This, Info);
5348
5349 if (Object->getType()->isLiteralType(Info.Ctx))
5350 return EvaluateTemporary(Object, This, Info);
5351
5352 if (Object->getType()->isRecordType() && Object->isPRValue())
5353 return EvaluateTemporary(Object, This, Info);
5354
5355 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
5356 return false;
5357}
5358
5359/// HandleMemberPointerAccess - Evaluate a member access operation and build an
5360/// lvalue referring to the result.
5361///
5362/// \param Info - Information about the ongoing evaluation.
5363/// \param LV - An lvalue referring to the base of the member pointer.
5364/// \param RHS - The member pointer expression.
5365/// \param IncludeMember - Specifies whether the member itself is included in
5366/// the resulting LValue subobject designator. This is not possible when
5367/// creating a bound member function.
5368/// \return The field or method declaration to which the member pointer refers,
5369/// or 0 if evaluation fails.
5370static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5371 QualType LVType,
5372 LValue &LV,
5373 const Expr *RHS,
5374 bool IncludeMember = true) {
5375 MemberPtr MemPtr;
5376 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
5377 return nullptr;
5378
5379 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
5380 // member value, the behavior is undefined.
5381 if (!MemPtr.getDecl()) {
5382 // FIXME: Specific diagnostic.
5383 Info.FFDiag(RHS);
5384 return nullptr;
5385 }
5386
5387 if (MemPtr.isDerivedMember()) {
5388 // This is a member of some derived class. Truncate LV appropriately.
5389 // The end of the derived-to-base path for the base object must match the
5390 // derived-to-base path for the member pointer.
5391 // C++23 [expr.mptr.oper]p4:
5392 // If the result of E1 is an object [...] whose most derived object does
5393 // not contain the member to which E2 refers, the behavior is undefined.
5394 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5395 LV.Designator.Entries.size()) {
5396 Info.FFDiag(RHS);
5397 return nullptr;
5398 }
5399 unsigned PathLengthToMember =
5400 LV.Designator.Entries.size() - MemPtr.Path.size();
5401 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5402 const CXXRecordDecl *LVDecl = getAsBaseClass(
5403 LV.Designator.Entries[PathLengthToMember + I]);
5404 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5405 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5406 Info.FFDiag(RHS);
5407 return nullptr;
5408 }
5409 }
5410 // MemPtr.Path only contains the base classes of the class directly
5411 // containing the member E2. It is still necessary to check that the class
5412 // directly containing the member E2 lies on the derived-to-base path of E1
5413 // to avoid incorrectly permitting member pointer access into a sibling
5414 // class of the class containing the member E2. If this class would
5415 // correspond to the most-derived class of E1, it either isn't contained in
5416 // LV.Designator.Entries or the corresponding entry refers to an array
5417 // element instead. Therefore get the most derived class directly in this
5418 // case. Otherwise the previous entry should correpond to this class.
5419 const CXXRecordDecl *LastLVDecl =
5420 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5421 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5422 : LV.Designator.MostDerivedType->getAsCXXRecordDecl();
5423 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5424 if (LastLVDecl->getCanonicalDecl() != LastMPDecl->getCanonicalDecl()) {
5425 Info.FFDiag(RHS);
5426 return nullptr;
5427 }
5428
5429 // Truncate the lvalue to the appropriate derived class.
5430 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5431 PathLengthToMember))
5432 return nullptr;
5433 } else if (!MemPtr.Path.empty()) {
5434 // Extend the LValue path with the member pointer's path.
5435 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5436 MemPtr.Path.size() + IncludeMember);
5437
5438 // Walk down to the appropriate base class.
5439 if (const PointerType *PT = LVType->getAs<PointerType>())
5440 LVType = PT->getPointeeType();
5441 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5442 assert(RD && "member pointer access on non-class-type expression");
5443 // The first class in the path is that of the lvalue.
5444 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5445 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5446 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5447 return nullptr;
5448 RD = Base;
5449 }
5450 // Finally cast to the class containing the member.
5451 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5452 MemPtr.getContainingRecord()))
5453 return nullptr;
5454 }
5455
5456 // Add the member. Note that we cannot build bound member functions here.
5457 if (IncludeMember) {
5458 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5459 if (!HandleLValueMember(Info, RHS, LV, FD))
5460 return nullptr;
5461 } else if (const IndirectFieldDecl *IFD =
5462 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5463 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5464 return nullptr;
5465 } else {
5466 llvm_unreachable("can't construct reference to bound member function");
5467 }
5468 }
5469
5470 return MemPtr.getDecl();
5471}
5472
5473static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5474 const BinaryOperator *BO,
5475 LValue &LV,
5476 bool IncludeMember = true) {
5477 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5478
5479 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5480 if (Info.noteFailure()) {
5481 MemberPtr MemPtr;
5482 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5483 }
5484 return nullptr;
5485 }
5486
5487 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5488 BO->getRHS(), IncludeMember);
5489}
5490
5491/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5492/// the provided lvalue, which currently refers to the base object.
5493static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5494 LValue &Result) {
5495 SubobjectDesignator &D = Result.Designator;
5496 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5497 return false;
5498
5499 QualType TargetQT = E->getType();
5500 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5501 TargetQT = PT->getPointeeType();
5502
5503 auto InvalidCast = [&]() {
5504 if (!Info.checkingPotentialConstantExpression() ||
5505 !Result.AllowConstexprUnknown) {
5506 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5507 << D.MostDerivedType << TargetQT;
5508 }
5509 return false;
5510 };
5511
5512 // Check this cast lands within the final derived-to-base subobject path.
5513 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size())
5514 return InvalidCast();
5515
5516 // Check the type of the final cast. We don't need to check the path,
5517 // since a cast can only be formed if the path is unique.
5518 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5519 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5520 const CXXRecordDecl *FinalType;
5521 if (NewEntriesSize == D.MostDerivedPathLength)
5522 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5523 else
5524 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5525 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
5526 return InvalidCast();
5527
5528 // Truncate the lvalue to the appropriate derived class.
5529 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5530}
5531
5532/// Get the value to use for a default-initialized object of type T.
5533/// Return false if it encounters something invalid.
5535 bool IsCompleteClass = true) {
5536 bool Success = true;
5537
5538 // If there is already a value present don't overwrite it.
5539 if (!Result.isAbsent())
5540 return true;
5541
5542 if (auto *RD = T->getAsCXXRecordDecl()) {
5543 if (RD->isInvalidDecl()) {
5544 Result = APValue();
5545 return false;
5546 }
5547 if (RD->isUnion()) {
5548 Result = APValue((const FieldDecl *)nullptr);
5549 return true;
5550 }
5551
5552 // bases() includes directly specified virtual bases as well.
5553 unsigned NonVirtualBases = countNonVirtualBases(RD);
5554 Result =
5555 APValue(APValue::UninitStruct(), NonVirtualBases, RD->getNumFields(),
5556 IsCompleteClass ? RD->getNumVBases() : 0);
5557
5558 unsigned Index = 0;
5559 for (const CXXBaseSpecifier &B : RD->bases()) {
5560 if (B.isVirtual())
5561 continue;
5563 B.getType(), Result.getStructBase(Index), /*IsCompleteClass=*/false);
5564 ++Index;
5565 }
5566
5567 for (const auto *I : RD->fields()) {
5568 if (I->isUnnamedBitField())
5569 continue;
5571 I->getType(), Result.getStructField(I->getFieldIndex()));
5572 }
5573
5574 if (IsCompleteClass) {
5575 Index = 0;
5576
5577 for (const auto &B : RD->vbases()) {
5579 Result.getStructVirtualBase(Index),
5580 /*IsCompleteClass=*/false);
5581 ++Index;
5582 }
5583 } else {
5584 // Virtual bases should only exist at the top level of an APValue.
5585 assert(Result.getStructNumVirtualBases() == 0);
5586 }
5587
5588 return Success;
5589 }
5590
5591 if (auto *AT =
5592 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5593 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5594 if (Result.hasArrayFiller())
5595 Success &=
5596 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5597 return Success;
5598 }
5599
5601 return true;
5602}
5603
5604namespace {
5605enum EvalStmtResult {
5606 /// Evaluation failed.
5607 ESR_Failed,
5608 /// Hit a 'return' statement.
5609 ESR_Returned,
5610 /// Evaluation succeeded.
5611 ESR_Succeeded,
5612 /// Hit a 'continue' statement.
5613 ESR_Continue,
5614 /// Hit a 'break' statement.
5615 ESR_Break,
5616 /// Still scanning for 'case' or 'default' statement.
5617 ESR_CaseNotFound
5618};
5619}
5620/// Evaluates the initializer of a reference.
5621static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info,
5622 const ValueDecl *D,
5623 const Expr *Init, LValue &Result,
5624 APValue &Val) {
5625 assert(Init->isGLValue() && D->getType()->isReferenceType());
5626 // A reference is an lvalue.
5627 if (!EvaluateLValue(Init, Result, Info))
5628 return false;
5629 // [C++26][decl.ref]
5630 // The object designated by such a glvalue can be outside its lifetime
5631 // Because a null pointer value or a pointer past the end of an object
5632 // does not point to an object, a reference in a well-defined program cannot
5633 // refer to such things;
5634 if (!Result.Designator.Invalid && Result.Designator.isOnePastTheEnd()) {
5635 Info.FFDiag(Init, diag::note_constexpr_access_past_end) << AK_Dereference;
5636 return false;
5637 }
5638
5639 // Save the result.
5640 Result.moveInto(Val);
5641 return true;
5642}
5643
5644static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5645 if (VD->isInvalidDecl())
5646 return false;
5647 // We don't need to evaluate the initializer for a static local.
5648 if (!VD->hasLocalStorage())
5649 return true;
5650
5651 LValue Result;
5652 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5653 ScopeKind::Block, Result);
5654
5655 const Expr *InitE = VD->getInit();
5656 if (!InitE) {
5657 if (VD->getType()->isDependentType())
5658 return Info.noteSideEffect();
5659 return handleDefaultInitValue(VD->getType(), Val);
5660 }
5661 if (InitE->isValueDependent())
5662 return false;
5663
5664 // For references to objects, check they do not designate a one-past-the-end
5665 // object.
5666 if (VD->getType()->isReferenceType()) {
5667 return EvaluateInitForDeclOfReferenceType(Info, VD, InitE, Result, Val);
5668 } else if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5669 // Wipe out any partially-computed value, to allow tracking that this
5670 // evaluation failed.
5671 Val = APValue();
5672 return false;
5673 }
5674
5675 return true;
5676}
5677
5678static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5679 const DecompositionDecl *DD);
5680
5681static bool EvaluateDecl(EvalInfo &Info, const Decl *D,
5682 bool EvaluateConditionDecl = false) {
5683 bool OK = true;
5684 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5685 OK &= EvaluateVarDecl(Info, VD);
5686
5687 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D);
5688 EvaluateConditionDecl && DD)
5689 OK &= EvaluateDecompositionDeclInit(Info, DD);
5690
5691 return OK;
5692}
5693
5694static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
5695 const DecompositionDecl *DD) {
5696 bool OK = true;
5697 for (auto *BD : DD->flat_bindings())
5698 if (auto *VD = BD->getHoldingVar())
5699 OK &= EvaluateDecl(Info, VD, /*EvaluateConditionDecl=*/true);
5700
5701 return OK;
5702}
5703
5704static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info,
5705 const VarDecl *VD) {
5706 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5707 if (!EvaluateDecompositionDeclInit(Info, DD))
5708 return false;
5709 }
5710 return true;
5711}
5712
5713static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5714 assert(E->isValueDependent());
5715 if (Info.noteSideEffect())
5716 return true;
5717 assert(E->containsErrors() && "valid value-dependent expression should never "
5718 "reach invalid code path.");
5719 return false;
5720}
5721
5722/// Evaluate a condition (either a variable declaration or an expression).
5723static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5724 const Expr *Cond, bool &Result) {
5725 if (Cond->isValueDependent())
5726 return false;
5727 FullExpressionRAII Scope(Info);
5728 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5729 return false;
5731 return false;
5732 if (!MaybeEvaluateDeferredVarDeclInit(Info, CondDecl))
5733 return false;
5734 return Scope.destroy();
5735}
5736
5737namespace {
5738/// A location where the result (returned value) of evaluating a
5739/// statement should be stored.
5740struct StmtResult {
5741 /// The APValue that should be filled in with the returned value.
5742 APValue &Value;
5743 /// The location containing the result, if any (used to support RVO).
5744 const LValue *Slot;
5745};
5746
5747struct TempVersionRAII {
5748 CallStackFrame &Frame;
5749
5750 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5751 Frame.pushTempVersion();
5752 }
5753
5754 ~TempVersionRAII() {
5755 Frame.popTempVersion();
5756 }
5757};
5758
5759}
5760
5761static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5762 const Stmt *S,
5763 const SwitchCase *SC = nullptr);
5764
5765/// Helper to implement named break/continue. Returns 'true' if the evaluation
5766/// result should be propagated up. Otherwise, it sets the evaluation result
5767/// to either Continue to continue the current loop, or Succeeded to break it.
5768static bool ShouldPropagateBreakContinue(EvalInfo &Info,
5769 const Stmt *LoopOrSwitch,
5771 EvalStmtResult &ESR) {
5772 bool IsSwitch = isa<SwitchStmt>(LoopOrSwitch);
5773
5774 // For loops, map Succeeded to Continue so we don't have to check for both.
5775 if (!IsSwitch && ESR == ESR_Succeeded) {
5776 ESR = ESR_Continue;
5777 return false;
5778 }
5779
5780 if (ESR != ESR_Break && ESR != ESR_Continue)
5781 return false;
5782
5783 // Are we breaking out of or continuing this statement?
5784 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5785 const Stmt *StackTop = Info.BreakContinueStack.back();
5786 if (CanBreakOrContinue && (StackTop == nullptr || StackTop == LoopOrSwitch)) {
5787 Info.BreakContinueStack.pop_back();
5788 if (ESR == ESR_Break)
5789 ESR = ESR_Succeeded;
5790 return false;
5791 }
5792
5793 // We're not. Propagate the result up.
5794 for (BlockScopeRAII *S : Scopes) {
5795 if (!S->destroy()) {
5796 ESR = ESR_Failed;
5797 break;
5798 }
5799 }
5800 return true;
5801}
5802
5803/// Evaluate the body of a loop, and translate the result as appropriate.
5804static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5805 const Stmt *Body,
5806 const SwitchCase *Case = nullptr) {
5807 BlockScopeRAII Scope(Info);
5808
5809 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5810 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5811 ESR = ESR_Failed;
5812
5813 return ESR;
5814}
5815
5816/// Evaluate a switch statement.
5817static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5818 const SwitchStmt *SS) {
5819 BlockScopeRAII Scope(Info);
5820
5821 // Evaluate the switch condition.
5822 APSInt Value;
5823 {
5824 if (const Stmt *Init = SS->getInit()) {
5825 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5826 if (ESR != ESR_Succeeded) {
5827 if (ESR != ESR_Failed && !Scope.destroy())
5828 ESR = ESR_Failed;
5829 return ESR;
5830 }
5831 }
5832
5833 FullExpressionRAII CondScope(Info);
5834 if (SS->getConditionVariable() &&
5835 !EvaluateDecl(Info, SS->getConditionVariable()))
5836 return ESR_Failed;
5837 if (SS->getCond()->isValueDependent()) {
5838 // We don't know what the value is, and which branch should jump to.
5839 EvaluateDependentExpr(SS->getCond(), Info);
5840 return ESR_Failed;
5841 }
5842 if (!EvaluateInteger(SS->getCond(), Value, Info))
5843 return ESR_Failed;
5844
5846 return ESR_Failed;
5847
5848 if (!CondScope.destroy())
5849 return ESR_Failed;
5850 }
5851
5852 // Find the switch case corresponding to the value of the condition.
5853 // FIXME: Cache this lookup.
5854 const SwitchCase *Found = nullptr;
5855 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5856 SC = SC->getNextSwitchCase()) {
5857 if (isa<DefaultStmt>(SC)) {
5858 Found = SC;
5859 continue;
5860 }
5861
5862 const CaseStmt *CS = cast<CaseStmt>(SC);
5863 const Expr *LHS = CS->getLHS();
5864 const Expr *RHS = CS->getRHS();
5865 if (LHS->isValueDependent() || (RHS && RHS->isValueDependent()))
5866 return ESR_Failed;
5867 APSInt LHSValue = LHS->EvaluateKnownConstInt(Info.Ctx);
5868 APSInt RHSValue = RHS ? RHS->EvaluateKnownConstInt(Info.Ctx) : LHSValue;
5869 if (LHSValue <= Value && Value <= RHSValue) {
5870 Found = SC;
5871 break;
5872 }
5873 }
5874
5875 if (!Found)
5876 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5877
5878 // Search the switch body for the switch case and evaluate it from there.
5879 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5880 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5881 return ESR_Failed;
5882 if (ShouldPropagateBreakContinue(Info, SS, /*Scopes=*/{}, ESR))
5883 return ESR;
5884
5885 switch (ESR) {
5886 case ESR_Break:
5887 llvm_unreachable("Should have been converted to Succeeded");
5888 case ESR_Succeeded:
5889 case ESR_Continue:
5890 case ESR_Failed:
5891 case ESR_Returned:
5892 return ESR;
5893 case ESR_CaseNotFound:
5894 // This can only happen if the switch case is nested within a statement
5895 // expression. We have no intention of supporting that.
5896 Info.FFDiag(Found->getBeginLoc(),
5897 diag::note_constexpr_stmt_expr_unsupported);
5898 return ESR_Failed;
5899 }
5900 llvm_unreachable("Invalid EvalStmtResult!");
5901}
5902
5903static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5904 // An expression E is a core constant expression unless the evaluation of E
5905 // would evaluate one of the following: [C++23] - a control flow that passes
5906 // through a declaration of a variable with static or thread storage duration
5907 // unless that variable is usable in constant expressions.
5908 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5909 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5910 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5911 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5912 return false;
5913 }
5914 return true;
5915}
5916
5917// Evaluate a statement.
5918static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5919 const Stmt *S, const SwitchCase *Case) {
5920 if (!Info.nextStep(S))
5921 return ESR_Failed;
5922
5923 // If we're hunting down a 'case' or 'default' label, recurse through
5924 // substatements until we hit the label.
5925 if (Case) {
5926 switch (S->getStmtClass()) {
5927 case Stmt::CompoundStmtClass:
5928 // FIXME: Precompute which substatement of a compound statement we
5929 // would jump to, and go straight there rather than performing a
5930 // linear scan each time.
5931 case Stmt::LabelStmtClass:
5932 case Stmt::AttributedStmtClass:
5933 case Stmt::DoStmtClass:
5934 break;
5935
5936 case Stmt::CaseStmtClass:
5937 case Stmt::DefaultStmtClass:
5938 if (Case == S)
5939 Case = nullptr;
5940 break;
5941
5942 case Stmt::IfStmtClass: {
5943 // FIXME: Precompute which side of an 'if' we would jump to, and go
5944 // straight there rather than scanning both sides.
5945 const IfStmt *IS = cast<IfStmt>(S);
5946
5947 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5948 // preceded by our switch label.
5949 BlockScopeRAII Scope(Info);
5950
5951 // Step into the init statement in case it brings an (uninitialized)
5952 // variable into scope.
5953 if (const Stmt *Init = IS->getInit()) {
5954 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5955 if (ESR != ESR_CaseNotFound) {
5956 assert(ESR != ESR_Succeeded);
5957 return ESR;
5958 }
5959 }
5960
5961 // Condition variable must be initialized if it exists.
5962 // FIXME: We can skip evaluating the body if there's a condition
5963 // variable, as there can't be any case labels within it.
5964 // (The same is true for 'for' statements.)
5965
5966 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5967 if (ESR == ESR_Failed)
5968 return ESR;
5969 if (ESR != ESR_CaseNotFound)
5970 return Scope.destroy() ? ESR : ESR_Failed;
5971 if (!IS->getElse())
5972 return ESR_CaseNotFound;
5973
5974 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5975 if (ESR == ESR_Failed)
5976 return ESR;
5977 if (ESR != ESR_CaseNotFound)
5978 return Scope.destroy() ? ESR : ESR_Failed;
5979 return ESR_CaseNotFound;
5980 }
5981
5982 case Stmt::WhileStmtClass: {
5983 EvalStmtResult ESR =
5984 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5985 if (ShouldPropagateBreakContinue(Info, S, /*Scopes=*/{}, ESR))
5986 return ESR;
5987 if (ESR != ESR_Continue)
5988 return ESR;
5989 break;
5990 }
5991
5992 case Stmt::ForStmtClass: {
5993 const ForStmt *FS = cast<ForStmt>(S);
5994 BlockScopeRAII Scope(Info);
5995
5996 // Step into the init statement in case it brings an (uninitialized)
5997 // variable into scope.
5998 if (const Stmt *Init = FS->getInit()) {
5999 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
6000 if (ESR != ESR_CaseNotFound) {
6001 assert(ESR != ESR_Succeeded);
6002 return ESR;
6003 }
6004 }
6005
6006 EvalStmtResult ESR =
6007 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
6008 if (ShouldPropagateBreakContinue(Info, FS, /*Scopes=*/{}, ESR))
6009 return ESR;
6010 if (ESR != ESR_Continue)
6011 return ESR;
6012 if (const auto *Inc = FS->getInc()) {
6013 if (Inc->isValueDependent()) {
6014 if (!EvaluateDependentExpr(Inc, Info))
6015 return ESR_Failed;
6016 } else {
6017 FullExpressionRAII IncScope(Info);
6018 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6019 return ESR_Failed;
6020 }
6021 }
6022 break;
6023 }
6024
6025 case Stmt::DeclStmtClass: {
6026 // Start the lifetime of any uninitialized variables we encounter. They
6027 // might be used by the selected branch of the switch.
6028 const DeclStmt *DS = cast<DeclStmt>(S);
6029 for (const auto *D : DS->decls()) {
6030 if (const auto *VD = dyn_cast<VarDecl>(D)) {
6031 if (!CheckLocalVariableDeclaration(Info, VD))
6032 return ESR_Failed;
6033 if (VD->hasLocalStorage() && !VD->getInit())
6034 if (!EvaluateVarDecl(Info, VD))
6035 return ESR_Failed;
6036 // FIXME: If the variable has initialization that can't be jumped
6037 // over, bail out of any immediately-surrounding compound-statement
6038 // too. There can't be any case labels here.
6039 }
6040 }
6041 return ESR_CaseNotFound;
6042 }
6043
6044 default:
6045 return ESR_CaseNotFound;
6046 }
6047 }
6048
6049 switch (S->getStmtClass()) {
6050 default:
6051 if (const Expr *E = dyn_cast<Expr>(S)) {
6052 if (E->isValueDependent()) {
6053 if (!EvaluateDependentExpr(E, Info))
6054 return ESR_Failed;
6055 } else {
6056 // Don't bother evaluating beyond an expression-statement which couldn't
6057 // be evaluated.
6058 // FIXME: Do we need the FullExpressionRAII object here?
6059 // VisitExprWithCleanups should create one when necessary.
6060 FullExpressionRAII Scope(Info);
6061 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
6062 return ESR_Failed;
6063 }
6064 return ESR_Succeeded;
6065 }
6066
6067 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
6068 return ESR_Failed;
6069
6070 case Stmt::NullStmtClass:
6071 return ESR_Succeeded;
6072
6073 case Stmt::DeclStmtClass: {
6074 const DeclStmt *DS = cast<DeclStmt>(S);
6075 for (const auto *D : DS->decls()) {
6076 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
6077 if (VD && !CheckLocalVariableDeclaration(Info, VD))
6078 return ESR_Failed;
6079
6080 if (const auto *ESD = dyn_cast<CXXExpansionStmtDecl>(D)) {
6081 assert(ESD->getInstantiations() && "not expanded?");
6082 return EvaluateStmt(Result, Info, ESD->getInstantiations(), Case);
6083 }
6084
6085 // Each declaration initialization is its own full-expression.
6086 FullExpressionRAII Scope(Info);
6087 if (!EvaluateDecl(Info, D, /*EvaluateConditionDecl=*/true) &&
6088 !Info.noteFailure())
6089 return ESR_Failed;
6090 if (!Scope.destroy())
6091 return ESR_Failed;
6092 }
6093 return ESR_Succeeded;
6094 }
6095
6096 case Stmt::ReturnStmtClass: {
6097 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
6098 FullExpressionRAII Scope(Info);
6099 if (RetExpr && RetExpr->isValueDependent()) {
6100 EvaluateDependentExpr(RetExpr, Info);
6101 // We know we returned, but we don't know what the value is.
6102 return ESR_Failed;
6103 }
6104 if (RetExpr &&
6105 !(Result.Slot
6106 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
6107 : Evaluate(Result.Value, Info, RetExpr)))
6108 return ESR_Failed;
6109 return Scope.destroy() ? ESR_Returned : ESR_Failed;
6110 }
6111
6112 case Stmt::CompoundStmtClass: {
6113 BlockScopeRAII Scope(Info);
6114
6115 const CompoundStmt *CS = cast<CompoundStmt>(S);
6116 for (const auto *BI : CS->body()) {
6117 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
6118 if (ESR == ESR_Succeeded)
6119 Case = nullptr;
6120 else if (ESR != ESR_CaseNotFound) {
6121 if (ESR != ESR_Failed && !Scope.destroy())
6122 return ESR_Failed;
6123 return ESR;
6124 }
6125 }
6126 if (Case)
6127 return ESR_CaseNotFound;
6128 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6129 }
6130
6131 case Stmt::IfStmtClass: {
6132 const IfStmt *IS = cast<IfStmt>(S);
6133
6134 // Evaluate the condition, as either a var decl or as an expression.
6135 BlockScopeRAII Scope(Info);
6136 if (const Stmt *Init = IS->getInit()) {
6137 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
6138 if (ESR != ESR_Succeeded) {
6139 if (ESR != ESR_Failed && !Scope.destroy())
6140 return ESR_Failed;
6141 return ESR;
6142 }
6143 }
6144 bool Cond;
6145 if (IS->isConsteval()) {
6147 // If we are not in a constant context, if consteval should not evaluate
6148 // to true.
6149 if (!Info.InConstantContext)
6150 Cond = !Cond;
6151 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
6152 Cond))
6153 return ESR_Failed;
6154
6155 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
6156 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
6157 if (ESR != ESR_Succeeded) {
6158 if (ESR != ESR_Failed && !Scope.destroy())
6159 return ESR_Failed;
6160 return ESR;
6161 }
6162 }
6163 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6164 }
6165
6166 case Stmt::WhileStmtClass: {
6167 const WhileStmt *WS = cast<WhileStmt>(S);
6168 while (true) {
6169 BlockScopeRAII Scope(Info);
6170 bool Continue;
6171 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
6172 Continue))
6173 return ESR_Failed;
6174 if (!Continue)
6175 break;
6176
6177 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
6178 if (ShouldPropagateBreakContinue(Info, WS, &Scope, ESR))
6179 return ESR;
6180
6181 if (ESR != ESR_Continue) {
6182 if (ESR != ESR_Failed && !Scope.destroy())
6183 return ESR_Failed;
6184 return ESR;
6185 }
6186 if (!Scope.destroy())
6187 return ESR_Failed;
6188 }
6189 return ESR_Succeeded;
6190 }
6191
6192 case Stmt::DoStmtClass: {
6193 const DoStmt *DS = cast<DoStmt>(S);
6194 bool Continue;
6195 do {
6196 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
6197 if (ShouldPropagateBreakContinue(Info, DS, /*Scopes=*/{}, ESR))
6198 return ESR;
6199 if (ESR != ESR_Continue)
6200 return ESR;
6201 Case = nullptr;
6202
6203 if (DS->getCond()->isValueDependent()) {
6204 EvaluateDependentExpr(DS->getCond(), Info);
6205 // Bailout as we don't know whether to keep going or terminate the loop.
6206 return ESR_Failed;
6207 }
6208 FullExpressionRAII CondScope(Info);
6209 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
6210 !CondScope.destroy())
6211 return ESR_Failed;
6212 } while (Continue);
6213 return ESR_Succeeded;
6214 }
6215
6216 case Stmt::ForStmtClass: {
6217 const ForStmt *FS = cast<ForStmt>(S);
6218 BlockScopeRAII ForScope(Info);
6219 if (FS->getInit()) {
6220 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6221 if (ESR != ESR_Succeeded) {
6222 if (ESR != ESR_Failed && !ForScope.destroy())
6223 return ESR_Failed;
6224 return ESR;
6225 }
6226 }
6227 while (true) {
6228 BlockScopeRAII IterScope(Info);
6229 bool Continue = true;
6230 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
6231 FS->getCond(), Continue))
6232 return ESR_Failed;
6233
6234 if (!Continue) {
6235 if (!IterScope.destroy())
6236 return ESR_Failed;
6237 break;
6238 }
6239
6240 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6241 if (ShouldPropagateBreakContinue(Info, FS, {&IterScope, &ForScope}, ESR))
6242 return ESR;
6243 if (ESR != ESR_Continue) {
6244 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6245 return ESR_Failed;
6246 return ESR;
6247 }
6248
6249 if (const auto *Inc = FS->getInc()) {
6250 if (Inc->isValueDependent()) {
6251 if (!EvaluateDependentExpr(Inc, Info))
6252 return ESR_Failed;
6253 } else {
6254 FullExpressionRAII IncScope(Info);
6255 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
6256 return ESR_Failed;
6257 }
6258 }
6259
6260 if (!IterScope.destroy())
6261 return ESR_Failed;
6262 }
6263 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6264 }
6265
6266 case Stmt::CXXForRangeStmtClass: {
6268 BlockScopeRAII Scope(Info);
6269
6270 // Evaluate the init-statement if present.
6271 if (FS->getInit()) {
6272 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
6273 if (ESR != ESR_Succeeded) {
6274 if (ESR != ESR_Failed && !Scope.destroy())
6275 return ESR_Failed;
6276 return ESR;
6277 }
6278 }
6279
6280 // Initialize the __range variable.
6281 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
6282 if (ESR != ESR_Succeeded) {
6283 if (ESR != ESR_Failed && !Scope.destroy())
6284 return ESR_Failed;
6285 return ESR;
6286 }
6287
6288 // In error-recovery cases it's possible to get here even if we failed to
6289 // synthesize the __begin and __end variables.
6290 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
6291 return ESR_Failed;
6292
6293 // Create the __begin and __end iterators.
6294 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
6295 if (ESR != ESR_Succeeded) {
6296 if (ESR != ESR_Failed && !Scope.destroy())
6297 return ESR_Failed;
6298 return ESR;
6299 }
6300 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
6301 if (ESR != ESR_Succeeded) {
6302 if (ESR != ESR_Failed && !Scope.destroy())
6303 return ESR_Failed;
6304 return ESR;
6305 }
6306
6307 while (true) {
6308 // Condition: __begin != __end.
6309 {
6310 if (FS->getCond()->isValueDependent()) {
6311 EvaluateDependentExpr(FS->getCond(), Info);
6312 // We don't know whether to keep going or terminate the loop.
6313 return ESR_Failed;
6314 }
6315 bool Continue = true;
6316 FullExpressionRAII CondExpr(Info);
6317 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
6318 return ESR_Failed;
6319 if (!Continue)
6320 break;
6321 }
6322
6323 // User's variable declaration, initialized by *__begin.
6324 BlockScopeRAII InnerScope(Info);
6325 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
6326 if (ESR != ESR_Succeeded) {
6327 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6328 return ESR_Failed;
6329 return ESR;
6330 }
6331
6332 // Loop body.
6333 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
6334 if (ShouldPropagateBreakContinue(Info, FS, {&InnerScope, &Scope}, ESR))
6335 return ESR;
6336 if (ESR != ESR_Continue) {
6337 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
6338 return ESR_Failed;
6339 return ESR;
6340 }
6341 if (FS->getInc()->isValueDependent()) {
6342 if (!EvaluateDependentExpr(FS->getInc(), Info))
6343 return ESR_Failed;
6344 } else {
6345 // Increment: ++__begin
6346 if (!EvaluateIgnoredValue(Info, FS->getInc()))
6347 return ESR_Failed;
6348 }
6349
6350 if (!InnerScope.destroy())
6351 return ESR_Failed;
6352 }
6353
6354 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6355 }
6356
6357 case Stmt::CXXExpansionStmtInstantiationClass: {
6358 BlockScopeRAII Scope(Info);
6359 const auto *Expansion = cast<CXXExpansionStmtInstantiation>(S);
6360 for (const Stmt *PreambleStmt : Expansion->getPreambleStmts()) {
6361 EvalStmtResult ESR = EvaluateStmt(Result, Info, PreambleStmt);
6362 if (ESR != ESR_Succeeded) {
6363 if (ESR != ESR_Failed && !Scope.destroy())
6364 return ESR_Failed;
6365 return ESR;
6366 }
6367 }
6368
6369 // No need to push an extra scope for these since they're already
6370 // CompoundStmts.
6371 EvalStmtResult ESR = ESR_Succeeded;
6372 for (const Stmt *Instantiation : Expansion->getInstantiations()) {
6373 ESR = EvaluateStmt(Result, Info, Instantiation);
6374 if (ESR == ESR_Failed ||
6375 ShouldPropagateBreakContinue(Info, Expansion, &Scope, ESR))
6376 return ESR;
6377 if (ESR != ESR_Continue) {
6378 // Succeeded here actually means we encountered a 'break'.
6379 assert(ESR == ESR_Succeeded || ESR == ESR_Returned);
6380 break;
6381 }
6382 }
6383
6384 // Map Continue back to Succeeded if we fell off the end of the loop.
6385 if (ESR == ESR_Continue)
6386 ESR = ESR_Succeeded;
6387
6388 return Scope.destroy() ? ESR : ESR_Failed;
6389 }
6390
6391 case Stmt::SwitchStmtClass:
6392 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
6393
6394 case Stmt::ContinueStmtClass:
6395 case Stmt::BreakStmtClass: {
6396 auto *B = cast<LoopControlStmt>(S);
6397 Info.BreakContinueStack.push_back(B->getNamedLoopOrSwitch());
6398 return isa<ContinueStmt>(S) ? ESR_Continue : ESR_Break;
6399 }
6400
6401 case Stmt::LabelStmtClass:
6402 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
6403
6404 case Stmt::AttributedStmtClass: {
6405 const auto *AS = cast<AttributedStmt>(S);
6406 const auto *SS = AS->getSubStmt();
6407 MSConstexprContextRAII ConstexprContext(
6408 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
6409 isa<ReturnStmt>(SS));
6410
6411 auto LO = Info.Ctx.getLangOpts();
6412 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6413 for (auto *Attr : AS->getAttrs()) {
6414 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
6415 if (!AA)
6416 continue;
6417
6418 auto *Assumption = AA->getAssumption();
6419 if (Assumption->isValueDependent())
6420 return ESR_Failed;
6421
6422 if (Assumption->HasSideEffects(Info.Ctx))
6423 continue;
6424
6425 bool Value;
6426 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
6427 return ESR_Failed;
6428 if (!Value) {
6429 Info.CCEDiag(Assumption->getExprLoc(),
6430 diag::note_constexpr_assumption_failed);
6431 return ESR_Failed;
6432 }
6433 }
6434 }
6435
6436 return EvaluateStmt(Result, Info, SS, Case);
6437 }
6438
6439 case Stmt::CaseStmtClass:
6440 case Stmt::DefaultStmtClass:
6441 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
6442 case Stmt::CXXTryStmtClass:
6443 // Evaluate try blocks by evaluating all sub statements.
6444 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
6445 }
6446}
6447
6448/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
6449/// default constructor. If so, we'll fold it whether or not it's marked as
6450/// constexpr. If it is marked as constexpr, we will never implicitly define it,
6451/// so we need special handling.
6452static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
6453 const CXXConstructorDecl *CD,
6454 bool IsValueInitialization) {
6455 if (!CD->isTrivial() || !CD->isDefaultConstructor())
6456 return false;
6457
6458 // Value-initialization does not call a trivial default constructor, so such a
6459 // call is a core constant expression whether or not the constructor is
6460 // constexpr.
6461 if (!CD->isConstexpr() && !IsValueInitialization) {
6462 if (Info.getLangOpts().CPlusPlus11) {
6463 // FIXME: If DiagDecl is an implicitly-declared special member function,
6464 // we should be much more explicit about why it's not constexpr.
6465 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6466 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
6467 Info.Note(CD->getLocation(), diag::note_declared_at);
6468 } else {
6469 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6470 }
6471 }
6472 return true;
6473}
6474
6475/// CheckConstexprFunction - Check that a function can be called in a constant
6476/// expression.
6477static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
6479 const FunctionDecl *Definition,
6480 const Stmt *Body) {
6481 // Potential constant expressions can contain calls to declared, but not yet
6482 // defined, constexpr functions.
6483 if (Info.checkingPotentialConstantExpression() && !Definition &&
6484 Declaration->isConstexpr())
6485 return false;
6486
6487 // Bail out if the function declaration itself is invalid. We will
6488 // have produced a relevant diagnostic while parsing it, so just
6489 // note the problematic sub-expression.
6490 if (Declaration->isInvalidDecl()) {
6491 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6492 return false;
6493 }
6494
6495 // DR1872: An instantiated virtual constexpr function can't be called in a
6496 // constant expression (prior to C++20). We can still constant-fold such a
6497 // call.
6498 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
6499 cast<CXXMethodDecl>(Declaration)->isVirtual())
6500 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6501
6502 if (Definition && Definition->isInvalidDecl()) {
6503 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6504 return false;
6505 }
6506
6507 // Can we evaluate this function call?
6508 if (Definition && Body &&
6509 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6510 Definition->hasAttr<MSConstexprAttr>())))
6511 return true;
6512
6513 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
6514 // Special note for the assert() macro, as the normal error message falsely
6515 // implies we cannot use an assertion during constant evaluation.
6516 if (CallLoc.isMacroID() && DiagDecl->getIdentifier()) {
6517 // FIXME: Instead of checking for an implementation-defined function,
6518 // check and evaluate the assert() macro.
6519 StringRef Name = DiagDecl->getName();
6520 bool AssertFailed =
6521 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
6522 if (AssertFailed) {
6523 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6524 return false;
6525 }
6526 }
6527
6528 if (Info.getLangOpts().CPlusPlus11) {
6529 // If this function is not constexpr because it is an inherited
6530 // non-constexpr constructor, diagnose that directly.
6531 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6532 if (CD && CD->isInheritingConstructor()) {
6533 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6534 if (!Inherited->isConstexpr())
6535 DiagDecl = CD = Inherited;
6536 }
6537
6538 // FIXME: If DiagDecl is an implicitly-declared special member function
6539 // or an inheriting constructor, we should be much more explicit about why
6540 // it's not constexpr.
6541 if (CD && CD->isInheritingConstructor())
6542 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6543 << CD->getInheritedConstructor().getConstructor()->getParent();
6544 else
6545 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6546 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
6547 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
6548 } else {
6549 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6550 }
6551 return false;
6552}
6553
6554namespace {
6555struct CheckDynamicTypeHandler {
6557 typedef bool result_type;
6558 bool failed() { return false; }
6559 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
6560 return true;
6561 }
6562 bool found(APSInt &Value, QualType SubobjType) { return true; }
6563 bool found(APFloat &Value, QualType SubobjType) { return true; }
6564};
6565} // end anonymous namespace
6566
6567/// Check that we can access the notional vptr of an object / determine its
6568/// dynamic type.
6569static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
6570 AccessKinds AK, bool Polymorphic) {
6571 if (This.Designator.Invalid)
6572 return false;
6573
6574 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
6575
6576 if (!Obj)
6577 return false;
6578
6579 if (!Obj.Value) {
6580 // The object is not usable in constant expressions, so we can't inspect
6581 // its value to see if it's in-lifetime or what the active union members
6582 // are. We can still check for a one-past-the-end lvalue.
6583 if (This.Designator.isOnePastTheEnd() ||
6584 This.Designator.isMostDerivedAnUnsizedArray()) {
6585 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6586 ? diag::note_constexpr_access_past_end
6587 : diag::note_constexpr_access_unsized_array)
6588 << AK;
6589 return false;
6590 } else if (Polymorphic) {
6591 // Conservatively refuse to perform a polymorphic operation if we would
6592 // not be able to read a notional 'vptr' value.
6593 if (!Info.checkingPotentialConstantExpression() ||
6594 !This.AllowConstexprUnknown) {
6595 APValue Val;
6596 This.moveInto(Val);
6597 QualType StarThisType =
6598 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6599 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6600 << AK << Val.getAsString(Info.Ctx, StarThisType);
6601 }
6602 return false;
6603 }
6604 return true;
6605 }
6606
6607 CheckDynamicTypeHandler Handler{AK};
6608 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6609}
6610
6611/// Check that the pointee of the 'this' pointer in a member function call is
6612/// either within its lifetime or in its period of construction or destruction.
6613static bool
6615 const LValue &This,
6616 const CXXMethodDecl *NamedMember) {
6617 return checkDynamicType(
6618 Info, E, This,
6619 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6620}
6621
6623 /// The dynamic class type of the object.
6625 /// The corresponding path length in the lvalue.
6626 unsigned PathLength;
6627};
6628
6629static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6630 unsigned PathLength) {
6631 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6632 Designator.Entries.size() && "invalid path length");
6633 return (PathLength == Designator.MostDerivedPathLength)
6634 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6635 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6636}
6637
6638/// Determine the dynamic type of an object.
6639static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6640 const Expr *E,
6641 LValue &This,
6642 AccessKinds AK) {
6643 // If we don't have an lvalue denoting an object of class type, there is no
6644 // meaningful dynamic type. (We consider objects of non-class type to have no
6645 // dynamic type.)
6646 if (!checkDynamicType(Info, E, This, AK,
6647 AK != AK_TypeId || This.AllowConstexprUnknown))
6648 return std::nullopt;
6649
6650 if (This.Designator.Invalid)
6651 return std::nullopt;
6652
6653 // Refuse to compute a dynamic type in the presence of virtual bases
6654 // before C++26. This shouldn't happen other than in constant-folding
6655 // situations, since literal types can't have virtual bases.
6656 const CXXRecordDecl *Class =
6657 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6658 if (!Class || (!Info.getLangOpts().CPlusPlus26 && Class->getNumVBases())) {
6659 Info.FFDiag(E);
6660 return std::nullopt;
6661 }
6662
6663 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6664 // binary search here instead. But the overwhelmingly common case is that
6665 // we're not in the middle of a constructor, so it probably doesn't matter
6666 // in practice.
6667 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6668 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6669 PathLength <= Path.size(); ++PathLength) {
6670 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6671 Path.slice(0, PathLength))) {
6672 case ConstructionPhase::Bases:
6673 case ConstructionPhase::DestroyingBases:
6674 // We're constructing or destroying a base class. This is not the dynamic
6675 // type.
6676 break;
6677
6678 case ConstructionPhase::None:
6679 case ConstructionPhase::AfterBases:
6680 case ConstructionPhase::AfterFields:
6681 case ConstructionPhase::Destroying:
6682 // We've finished constructing the base classes and not yet started
6683 // destroying them again, so this is the dynamic type.
6684 return DynamicType{getBaseClassType(This.Designator, PathLength),
6685 PathLength};
6686 }
6687 }
6688
6689 // CWG issue 1517: we're constructing a base class of the object described by
6690 // 'This', so that object has not yet begun its period of construction and
6691 // any polymorphic operation on it results in undefined behavior.
6692 Info.FFDiag(E);
6693 return std::nullopt;
6694}
6695
6696/// Perform virtual dispatch.
6698 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6699 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6700 std::optional<DynamicType> DynType = ComputeDynamicType(
6701 Info, E, This,
6703 if (!DynType)
6704 return nullptr;
6705
6706 // Find the final overrider. It must be declared in one of the classes on the
6707 // path from the dynamic type to the static type.
6708 // FIXME: If we ever allow literal types to have virtual base classes, that
6709 // won't be true.
6710 const CXXMethodDecl *Callee = Found;
6711 unsigned PathLength = DynType->PathLength;
6712 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6713 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6714 const CXXMethodDecl *Overrider =
6715 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6716 if (Overrider) {
6717 Callee = Overrider;
6718 break;
6719 }
6720 }
6721
6722 // C++2a [class.abstract]p6:
6723 // the effect of making a virtual call to a pure virtual function [...] is
6724 // undefined
6725 if (Callee->isPureVirtual()) {
6726 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6727 Info.Note(Callee->getLocation(), diag::note_declared_at);
6728 return nullptr;
6729 }
6730
6731 // If necessary, walk the rest of the path to determine the sequence of
6732 // covariant adjustment steps to apply.
6733 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6734 Found->getReturnType())) {
6735 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6736 for (unsigned CovariantPathLength = PathLength + 1;
6737 CovariantPathLength != This.Designator.Entries.size();
6738 ++CovariantPathLength) {
6739 const CXXRecordDecl *NextClass =
6740 getBaseClassType(This.Designator, CovariantPathLength);
6741 const CXXMethodDecl *Next =
6742 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6743 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6744 Next->getReturnType(), CovariantAdjustmentPath.back()))
6745 CovariantAdjustmentPath.push_back(Next->getReturnType());
6746 }
6747 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6748 CovariantAdjustmentPath.back()))
6749 CovariantAdjustmentPath.push_back(Found->getReturnType());
6750 }
6751
6752 // Perform 'this' adjustment.
6753 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6754 return nullptr;
6755
6756 return Callee;
6757}
6758
6759/// Perform the adjustment from a value returned by a virtual function to
6760/// a value of the statically expected type, which may be a pointer or
6761/// reference to a base class of the returned type.
6762static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6763 APValue &Result,
6764 ArrayRef<QualType> Path) {
6765 assert(Result.isLValue() &&
6766 "unexpected kind of APValue for covariant return");
6767 if (Result.isNullPointer())
6768 return true;
6769
6770 LValue LVal;
6771 LVal.setFrom(Info.Ctx, Result);
6772
6773 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6774 for (unsigned I = 1; I != Path.size(); ++I) {
6775 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6776 assert(OldClass && NewClass && "unexpected kind of covariant return");
6777 if (OldClass != NewClass &&
6778 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6779 return false;
6780 OldClass = NewClass;
6781 }
6782
6783 LVal.moveInto(Result);
6784 return true;
6785}
6786
6787/// Determine whether \p Base, which is known to be a direct base class of
6788/// \p Derived, is a public base class.
6789static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6790 const CXXRecordDecl *Base) {
6791 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6792 if (BaseSpec.isVirtual())
6793 continue;
6794 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6795 if (BaseClass && declaresSameEntity(BaseClass, Base))
6796 return BaseSpec.getAccessSpecifier() == AS_public;
6797 }
6798 for (const CXXBaseSpecifier &BaseSpec : Derived->vbases()) {
6799 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6800 if (BaseClass && declaresSameEntity(BaseClass, Base))
6801 return BaseSpec.getAccessSpecifier() == AS_public;
6802 }
6803
6804 llvm_unreachable("Base is not a direct base of Derived");
6805}
6806
6807/// Apply the given dynamic cast operation on the provided lvalue.
6808///
6809/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6810/// to find a suitable target subobject.
6811static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6812 LValue &Ptr) {
6813 // We can't do anything with a non-symbolic pointer value.
6814 SubobjectDesignator &D = Ptr.Designator;
6815 if (D.Invalid)
6816 return false;
6817
6818 // C++ [expr.dynamic.cast]p6:
6819 // If v is a null pointer value, the result is a null pointer value.
6820 if (Ptr.isNullPointer() && !E->isGLValue())
6821 return true;
6822
6823 // For all the other cases, we need the pointer to point to an object within
6824 // its lifetime / period of construction / destruction, and we need to know
6825 // its dynamic type.
6826 std::optional<DynamicType> DynType =
6827 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6828 if (!DynType)
6829 return false;
6830
6831 // C++ [expr.dynamic.cast]p7:
6832 // If T is "pointer to cv void", then the result is a pointer to the most
6833 // derived object
6834 if (E->getType()->isVoidPointerType())
6835 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6836
6838 assert(C && "dynamic_cast target is not void pointer nor class");
6839 CanQualType CQT = Info.Ctx.getCanonicalTagType(C);
6840
6841 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6842 // C++ [expr.dynamic.cast]p9:
6843 if (!E->isGLValue()) {
6844 // The value of a failed cast to pointer type is the null pointer value
6845 // of the required result type.
6846 Ptr.setNull(Info.Ctx, E->getType());
6847 return true;
6848 }
6849
6850 // A failed cast to reference type throws [...] std::bad_cast.
6851 unsigned DiagKind;
6852 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6853 DynType->Type->isDerivedFrom(C)))
6854 DiagKind = 0;
6855 else if (!Paths || Paths->begin() == Paths->end())
6856 DiagKind = 1;
6857 else if (Paths->isAmbiguous(CQT))
6858 DiagKind = 2;
6859 else {
6860 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6861 DiagKind = 3;
6862 }
6863 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6864 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6865 << Info.Ctx.getCanonicalTagType(DynType->Type)
6866 << E->getType().getUnqualifiedType();
6867 return false;
6868 };
6869
6870 // Runtime check, phase 1:
6871 // Walk from the base subobject towards the derived object looking for the
6872 // target type.
6873 for (int PathLength = Ptr.Designator.Entries.size();
6874 PathLength >= (int)DynType->PathLength; --PathLength) {
6875 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6876 if (declaresSameEntity(Class, C))
6877 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6878 // We can only walk across public inheritance edges.
6879 if (PathLength > (int)DynType->PathLength &&
6880 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6881 Class))
6882 return RuntimeCheckFailed(nullptr);
6883 }
6884
6885 // Runtime check, phase 2:
6886 // Search the dynamic type for an unambiguous public base of type C.
6887 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6888 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6889 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6890 Paths.front().Access == AS_public) {
6891 // Downcast to the dynamic type...
6892 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6893 return false;
6894 // ... then upcast to the chosen base class subobject.
6895 for (CXXBasePathElement &Elem : Paths.front())
6896 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6897 return false;
6898 return true;
6899 }
6900
6901 // Otherwise, the runtime check fails.
6902 return RuntimeCheckFailed(&Paths);
6903}
6904
6905namespace {
6906struct StartLifetimeOfUnionMemberHandler {
6907 EvalInfo &Info;
6908 const Expr *LHSExpr;
6909 const FieldDecl *Field;
6910 bool DuringInit;
6911 bool Failed = false;
6912 static const AccessKinds AccessKind = AK_Assign;
6913
6914 typedef bool result_type;
6915 bool failed() { return Failed; }
6916 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
6917 // We are supposed to perform no initialization but begin the lifetime of
6918 // the object. We interpret that as meaning to do what default
6919 // initialization of the object would do if all constructors involved were
6920 // trivial:
6921 // * All base, non-variant member, and array element subobjects' lifetimes
6922 // begin
6923 // * No variant members' lifetimes begin
6924 // * All scalar subobjects whose lifetimes begin have indeterminate values
6925 assert(SubobjType->isUnionType());
6926 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6927 // This union member is already active. If it's also in-lifetime, there's
6928 // nothing to do.
6929 if (Subobj.getUnionValue().hasValue())
6930 return true;
6931 } else if (DuringInit) {
6932 // We're currently in the process of initializing a different union
6933 // member. If we carried on, that initialization would attempt to
6934 // store to an inactive union member, resulting in undefined behavior.
6935 Info.FFDiag(LHSExpr,
6936 diag::note_constexpr_union_member_change_during_init);
6937 return false;
6938 }
6940 Failed = !handleDefaultInitValue(Field->getType(), Result);
6941 Subobj.setUnion(Field, Result);
6942 return true;
6943 }
6944 bool found(APSInt &Value, QualType SubobjType) {
6945 llvm_unreachable("wrong value kind for union object");
6946 }
6947 bool found(APFloat &Value, QualType SubobjType) {
6948 llvm_unreachable("wrong value kind for union object");
6949 }
6950};
6951} // end anonymous namespace
6952
6953const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6954
6955/// Handle a builtin simple-assignment or a call to a trivial assignment
6956/// operator whose left-hand side might involve a union member access. If it
6957/// does, implicitly start the lifetime of any accessed union elements per
6958/// C++20 [class.union]5.
6959static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6960 const Expr *LHSExpr,
6961 const LValue &LHS) {
6962 if (LHS.InvalidBase || LHS.Designator.Invalid)
6963 return false;
6964
6966 // C++ [class.union]p5:
6967 // define the set S(E) of subexpressions of E as follows:
6968 unsigned PathLength = LHS.Designator.Entries.size();
6969 for (const Expr *E = LHSExpr; E != nullptr;) {
6970 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6971 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6972 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6973 // Note that we can't implicitly start the lifetime of a reference,
6974 // so we don't need to proceed any further if we reach one.
6975 if (!FD || FD->getType()->isReferenceType())
6976 break;
6977
6978 // ... and also contains A.B if B names a union member ...
6979 if (FD->getParent()->isUnion()) {
6980 // ... of a non-class, non-array type, or of a class type with a
6981 // trivial default constructor that is not deleted, or an array of
6982 // such types.
6983 auto *RD =
6984 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6985 if (!RD || RD->hasTrivialDefaultConstructor())
6986 UnionPathLengths.push_back({PathLength - 1, FD});
6987 }
6988
6989 E = ME->getBase();
6990 --PathLength;
6991 assert(declaresSameEntity(FD,
6992 LHS.Designator.Entries[PathLength]
6993 .getAsBaseOrMember().getPointer()));
6994
6995 // -- If E is of the form A[B] and is interpreted as a built-in array
6996 // subscripting operator, S(E) is [S(the array operand, if any)].
6997 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6998 // Step over an ArrayToPointerDecay implicit cast.
6999 auto *Base = ASE->getBase()->IgnoreImplicit();
7000 if (!Base->getType()->isArrayType())
7001 break;
7002
7003 E = Base;
7004 --PathLength;
7005
7006 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7007 // Step over a derived-to-base conversion.
7008 E = ICE->getSubExpr();
7009 if (ICE->getCastKind() == CK_NoOp)
7010 continue;
7011 if (ICE->getCastKind() != CK_DerivedToBase &&
7012 ICE->getCastKind() != CK_UncheckedDerivedToBase)
7013 break;
7014 // Walk path backwards as we walk up from the base to the derived class.
7015 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
7016 if (Elt->isVirtual()) {
7017 // A class with virtual base classes never has a trivial default
7018 // constructor, so S(E) is empty in this case.
7019 E = nullptr;
7020 break;
7021 }
7022
7023 --PathLength;
7024 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
7025 LHS.Designator.Entries[PathLength]
7026 .getAsBaseOrMember().getPointer()));
7027 }
7028
7029 // -- Otherwise, S(E) is empty.
7030 } else {
7031 break;
7032 }
7033 }
7034
7035 // Common case: no unions' lifetimes are started.
7036 if (UnionPathLengths.empty())
7037 return true;
7038
7039 // if modification of X [would access an inactive union member], an object
7040 // of the type of X is implicitly created
7041 CompleteObject Obj =
7042 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
7043 if (!Obj)
7044 return false;
7045 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
7046 llvm::reverse(UnionPathLengths)) {
7047 // Form a designator for the union object.
7048 SubobjectDesignator D = LHS.Designator;
7049 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
7050
7051 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
7052 ConstructionPhase::AfterBases;
7053 StartLifetimeOfUnionMemberHandler StartLifetime{
7054 Info, LHSExpr, LengthAndField.second, DuringInit};
7055 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
7056 return false;
7057 }
7058
7059 return true;
7060}
7061
7062static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
7063 CallRef Call, EvalInfo &Info, bool NonNull = false,
7064 APValue **EvaluatedArg = nullptr) {
7065 LValue LV;
7066 // Create the parameter slot and register its destruction. For a vararg
7067 // argument, create a temporary.
7068 // FIXME: For calling conventions that destroy parameters in the callee,
7069 // should we consider performing destruction when the function returns
7070 // instead?
7071 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
7072 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
7073 ScopeKind::Call, LV);
7074 if (!EvaluateInPlace(V, Info, LV, Arg))
7075 return false;
7076
7077 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
7078 // undefined behavior, so is non-constant.
7079 if (NonNull && V.isLValue() && V.isNullPointer()) {
7080 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
7081 return false;
7082 }
7083
7084 if (EvaluatedArg)
7085 *EvaluatedArg = &V;
7086
7087 return true;
7088}
7089
7090/// Evaluate the arguments to a function call.
7091static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
7092 EvalInfo &Info, const FunctionDecl *Callee,
7093 bool RightToLeft = false,
7094 LValue *ObjectArg = nullptr) {
7095 bool Success = true;
7096 llvm::SmallBitVector ForbiddenNullArgs;
7097 if (Callee->hasAttr<NonNullAttr>()) {
7098 ForbiddenNullArgs.resize(Args.size());
7099 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
7100 if (!Attr->args_size()) {
7101 ForbiddenNullArgs.set();
7102 break;
7103 } else
7104 for (auto Idx : Attr->args()) {
7105 unsigned ASTIdx = Idx.getASTIndex();
7106 if (ASTIdx >= Args.size())
7107 continue;
7108 ForbiddenNullArgs[ASTIdx] = true;
7109 }
7110 }
7111 }
7112 for (unsigned I = 0; I < Args.size(); I++) {
7113 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
7114 const ParmVarDecl *PVD =
7115 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
7116 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
7117 APValue *That = nullptr;
7118 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull, &That)) {
7119 // If we're checking for a potential constant expression, evaluate all
7120 // initializers even if some of them fail.
7121 if (!Info.noteFailure())
7122 return false;
7123 Success = false;
7124 }
7125 if (PVD && PVD->isExplicitObjectParameter() && That && That->isLValue())
7126 ObjectArg->setFrom(Info.Ctx, *That);
7127 }
7128 return Success;
7129}
7130
7131/// Perform a trivial copy from Param, which is the parameter of a copy or move
7132/// constructor or assignment operator.
7133static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
7134 const Expr *E, APValue &Result,
7135 bool CopyObjectRepresentation) {
7136 // Find the reference argument.
7137 CallStackFrame *Frame = Info.CurrentCall;
7138 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
7139 if (!RefValue) {
7140 Info.FFDiag(E);
7141 return false;
7142 }
7143
7144 // Copy out the contents of the RHS object.
7145 LValue RefLValue;
7146 RefLValue.setFrom(Info.Ctx, *RefValue);
7148 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
7149 CopyObjectRepresentation);
7150}
7151
7152/// Evaluate a function call.
7154 const FunctionDecl *Callee,
7155 const LValue *ObjectArg, const Expr *E,
7156 ArrayRef<const Expr *> Args, CallRef Call,
7157 const Stmt *Body, EvalInfo &Info,
7158 APValue &Result, const LValue *ResultSlot) {
7159 if (!Info.CheckCallLimit(CallLoc))
7160 return false;
7161
7162 CallStackFrame Frame(Info, E->getSourceRange(), Callee, ObjectArg, E, Call);
7163
7164 // For a trivial copy or move assignment, perform an APValue copy. This is
7165 // essential for unions, where the operations performed by the assignment
7166 // operator cannot be represented as statements.
7167 //
7168 // Skip this for non-union classes with no fields; in that case, the defaulted
7169 // copy/move does not actually read the object.
7170 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
7171
7172 auto IsTrivialMemoryOperation = [&](const CXXMethodDecl *MD) {
7173 if (!MD || !MD->isDefaulted())
7174 return false;
7176 return false;
7177 return MD->getParent()->isUnion() ||
7178 (MD->isTrivial() &&
7180 };
7181
7182 if (IsTrivialMemoryOperation(MD)) {
7183 unsigned ExplicitOffset = MD->isExplicitObjectMemberFunction() ? 1 : 0;
7184 assert(ObjectArg);
7185 APValue RHSValue;
7186 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
7187 MD->getParent()->isUnion()))
7188 return false;
7189
7190 LValue Obj;
7191 if (!handleAssignment(Info, Args[ExplicitOffset], *ObjectArg,
7193 RHSValue))
7194 return false;
7195 ObjectArg->moveInto(Result);
7196 return true;
7197 } else if (MD && isLambdaCallOperator(MD)) {
7198 // We're in a lambda; determine the lambda capture field maps unless we're
7199 // just constexpr checking a lambda's call operator. constexpr checking is
7200 // done before the captures have been added to the closure object (unless
7201 // we're inferring constexpr-ness), so we don't have access to them in this
7202 // case. But since we don't need the captures to constexpr check, we can
7203 // just ignore them.
7204 if (!Info.checkingPotentialConstantExpression())
7205 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
7206 Frame.LambdaThisCaptureField);
7207 }
7208
7209 StmtResult Ret = {Result, ResultSlot};
7210 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
7211 if (ESR == ESR_Succeeded) {
7212 if (Callee->getReturnType()->isVoidType())
7213 return true;
7214 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7215 }
7216 return ESR == ESR_Returned;
7217}
7218
7219static bool HandleConstructorCall(const Expr *E, const LValue &This,
7220 CallRef Call,
7221 const CXXConstructorDecl *Definition,
7222 EvalInfo &Info, APValue &Result,
7223 bool IsCompleteClass = true);
7224
7225static bool HandleConstructorCall(const Expr *E, const LValue &This,
7228 EvalInfo &Info, APValue &Result,
7229 bool IsCompleteClass = true) {
7230 CallScopeRAII CallScope(Info);
7231 CallRef Call = Info.CurrentCall->createCall(Definition);
7232 if (!EvaluateArgs(Args, Call, Info, Definition))
7233 return false;
7234
7235 return HandleConstructorCall(E, This, Call, Definition, Info, Result,
7236 IsCompleteClass) &&
7237 CallScope.destroy();
7238}
7239
7240/// Evaluate a constructor call.
7241static bool HandleConstructorCall(const Expr *E, const LValue &This,
7242 CallRef Call,
7244 EvalInfo &Info, APValue &Result,
7245 bool IsCompleteClass) {
7246
7247 SourceLocation CallLoc = E->getExprLoc();
7248 if (!Info.CheckCallLimit(CallLoc))
7249 return false;
7250
7251 const CXXRecordDecl *RD = Definition->getParent();
7252 if (!Info.getLangOpts().CPlusPlus26 && RD->getNumVBases()) {
7253 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7254 return false;
7255 }
7256
7257 EvalInfo::EvaluatingConstructorRAII EvalObj(
7258 Info,
7259 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7260 RD->getNumBases());
7261 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
7262
7263 // FIXME: Creating an APValue just to hold a nonexistent return value is
7264 // wasteful.
7265 APValue RetVal;
7266 StmtResult Ret = {RetVal, nullptr};
7267
7268 // If it's a delegating constructor, delegate.
7269 if (Definition->isDelegatingConstructor()) {
7271 if ((*I)->getInit()->isValueDependent()) {
7272 if (!EvaluateDependentExpr((*I)->getInit(), Info))
7273 return false;
7274 } else {
7275 FullExpressionRAII InitScope(Info);
7276 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
7277 !InitScope.destroy())
7278 return false;
7279 }
7280 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
7281 }
7282
7283 // For a trivial copy or move constructor, perform an APValue copy. This is
7284 // essential for unions (or classes with anonymous union members), where the
7285 // operations performed by the constructor cannot be represented by
7286 // ctor-initializers.
7287 //
7288 // Skip this for empty non-union classes; we should not perform an
7289 // lvalue-to-rvalue conversion on them because their copy constructor does not
7290 // actually read them.
7291 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
7292 (Definition->getParent()->isUnion() ||
7293 (Definition->isTrivial() &&
7295 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
7296 Definition->getParent()->isUnion());
7297 }
7298
7299 // Reserve space for the struct members.
7300 if (!Result.hasValue()) {
7301 if (!RD->isUnion()) {
7302 unsigned NonVirtualBases = countNonVirtualBases(RD);
7303 Result = APValue(APValue::UninitStruct(), NonVirtualBases,
7304 RD->getNumFields(), RD->getNumVBases());
7305 } else
7306 // A union starts with no active member.
7307 Result = APValue((const FieldDecl*)nullptr);
7308 }
7309
7310 if (RD->isInvalidDecl()) return false;
7311 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7312
7313 // A scope for temporaries lifetime-extended by reference members.
7314 BlockScopeRAII LifetimeExtendedScope(Info);
7315
7316 bool Success = true;
7317 unsigned BasesSeen = 0;
7318 unsigned VirtualBasesSeen = 0;
7319 unsigned NonVirtualBases = countNonVirtualBases(RD);
7320
7322 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
7323 // We might be initializing the same field again if this is an indirect
7324 // field initialization.
7325 if (FieldIt == RD->field_end() ||
7326 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
7327 assert(Indirect && "fields out of order?");
7328 return;
7329 }
7330
7331 // Default-initialize any fields with no explicit initializer.
7332 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
7333 assert(FieldIt != RD->field_end() && "missing field?");
7334 if (!FieldIt->isUnnamedBitField())
7336 FieldIt->getType(),
7337 Result.getStructField(FieldIt->getFieldIndex()));
7338 }
7339 ++FieldIt;
7340 };
7341 for (const auto *I : Definition->inits()) {
7342 LValue Subobject = This;
7343 LValue SubobjectParent = This;
7344 APValue *Value = &Result;
7345
7346 // Determine the subobject to initialize.
7347 FieldDecl *FD = nullptr;
7348 if (I->isBaseInitializer()) {
7349 QualType BaseType(I->getBaseClass(), 0);
7350 if (I->isBaseVirtual()) {
7351 if (This.pointsToCompleteClass(RD)) {
7352 if (!HandleLValueDirectVirtualBase(Info, I->getInit(), Subobject, RD,
7353 BaseType->getAsCXXRecordDecl(),
7354 &Layout))
7355 return false;
7356 Value = &Result.getStructVirtualBase(VirtualBasesSeen++);
7357 } else {
7358 continue;
7359 }
7360
7361 } else {
7362 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
7363 BaseType->getAsCXXRecordDecl(), &Layout))
7364 return false;
7365 Value = &Result.getStructBase(BasesSeen++);
7366 }
7367 } else if ((FD = I->getMember())) {
7368 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
7369 return false;
7370 if (RD->isUnion()) {
7371 Result = APValue(FD);
7372 Value = &Result.getUnionValue();
7373 } else {
7374 SkipToField(FD, false);
7375 Value = &Result.getStructField(FD->getFieldIndex());
7376 }
7377 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
7378 // Walk the indirect field decl's chain to find the object to initialize,
7379 // and make sure we've initialized every step along it.
7380 auto IndirectFieldChain = IFD->chain();
7381 for (auto *C : IndirectFieldChain) {
7382 FD = cast<FieldDecl>(C);
7384 // Switch the union field if it differs. This happens if we had
7385 // preceding zero-initialization, and we're now initializing a union
7386 // subobject other than the first.
7387 // FIXME: In this case, the values of the other subobjects are
7388 // specified, since zero-initialization sets all padding bits to zero.
7389 if (!Value->hasValue() ||
7390 (Value->isUnion() &&
7391 !declaresSameEntity(Value->getUnionField(), FD))) {
7392 if (CD->isUnion())
7393 *Value = APValue(FD);
7394 else
7395 // FIXME: This immediately starts the lifetime of all members of
7396 // an anonymous struct. It would be preferable to strictly start
7397 // member lifetime in initialization order.
7398 Success &= handleDefaultInitValue(Info.Ctx.getCanonicalTagType(CD),
7399 *Value);
7400 }
7401 // Store Subobject as its parent before updating it for the last element
7402 // in the chain.
7403 if (C == IndirectFieldChain.back())
7404 SubobjectParent = Subobject;
7405 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
7406 return false;
7407 if (CD->isUnion())
7408 Value = &Value->getUnionValue();
7409 else {
7410 if (C == IndirectFieldChain.front() && !RD->isUnion())
7411 SkipToField(FD, true);
7412 Value = &Value->getStructField(FD->getFieldIndex());
7413 }
7414 }
7415 } else {
7416 llvm_unreachable("unknown base initializer kind");
7417 }
7418
7419 // Need to override This for implicit field initializers as in this case
7420 // This refers to innermost anonymous struct/union containing initializer,
7421 // not to currently constructed class.
7422 const Expr *Init = I->getInit();
7423 if (Init->isValueDependent()) {
7424 if (!EvaluateDependentExpr(Init, Info))
7425 return false;
7426 } else {
7427 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7429 FullExpressionRAII InitScope(Info);
7430 if (FD && FD->getType()->isReferenceType() &&
7431 !FD->getType()->isFunctionReferenceType()) {
7432 LValue Result;
7434 *Value)) {
7435 if (!Info.noteFailure())
7436 return false;
7437 Success = false;
7438 }
7439 } else if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
7440 (FD && FD->isBitField() &&
7441 !truncateBitfieldValue(Info, Init, *Value, FD))) {
7442 // If we're checking for a potential constant expression, evaluate all
7443 // initializers even if some of them fail.
7444 if (!Info.noteFailure())
7445 return false;
7446 Success = false;
7447 }
7448 }
7449
7450 // This is the point at which the dynamic type of the object becomes this
7451 // class type.
7452 if (I->isBaseInitializer() && BasesSeen == NonVirtualBases)
7453 EvalObj.finishedConstructingBases();
7454 }
7455
7456 // Default-initialize any remaining fields.
7457 if (!RD->isUnion()) {
7458 for (; FieldIt != RD->field_end(); ++FieldIt) {
7459 if (!FieldIt->isUnnamedBitField())
7461 FieldIt->getType(),
7462 Result.getStructField(FieldIt->getFieldIndex()));
7463 }
7464 }
7465
7466 EvalObj.finishedConstructingFields();
7467
7468 return Success &&
7469 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
7470 LifetimeExtendedScope.destroy();
7471}
7472
7473static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
7474 const LValue &This, APValue &Value,
7475 QualType T, bool IsCompleteClass = true) {
7476 // Objects can only be destroyed while they're within their lifetimes.
7477 // FIXME: We have no representation for whether an object of type nullptr_t
7478 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
7479 // as indeterminate instead?
7480 if (Value.isAbsent() && !T->isNullPtrType()) {
7481 APValue Printable;
7482 This.moveInto(Printable);
7483 Info.FFDiag(CallRange.getBegin(),
7484 diag::note_constexpr_destroy_out_of_lifetime)
7485 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
7486 return false;
7487 }
7488
7489 // Invent an expression for location purposes.
7490 // FIXME: We shouldn't need to do this.
7491 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
7492
7493 // For arrays, destroy elements right-to-left.
7494 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
7495 uint64_t Size = CAT->getZExtSize();
7496 QualType ElemT = CAT->getElementType();
7497
7498 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
7499 return false;
7500
7501 LValue ElemLV = This;
7502 ElemLV.addArray(Info, &LocE, CAT);
7503 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
7504 return false;
7505
7506 // Ensure that we have actual array elements available to destroy; the
7507 // destructors might mutate the value, so we can't run them on the array
7508 // filler.
7509 if (Size && Size > Value.getArrayInitializedElts())
7510 expandArray(Value, Value.getArraySize() - 1);
7511
7512 // The size of the array might have been reduced by
7513 // a placement new.
7514 for (Size = Value.getArraySize(); Size != 0; --Size) {
7515 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
7516 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
7517 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
7518 return false;
7519 }
7520
7521 // End the lifetime of this array now.
7522 Value = APValue();
7523 return true;
7524 }
7525
7526 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
7527 if (!RD) {
7528 if (T.isDestructedType()) {
7529 Info.FFDiag(CallRange.getBegin(),
7530 diag::note_constexpr_unsupported_destruction)
7531 << T;
7532 return false;
7533 }
7534
7535 Value = APValue();
7536 return true;
7537 }
7538
7539 if (!Info.getLangOpts().CPlusPlus26 && RD->getNumVBases()) {
7540 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
7541 return false;
7542 }
7543
7544 // If an anonymous union would be destroyed, some enclosing destructor must
7545 // have been explicitly defined, and the anonymous union destruction should
7546 // have no effect.
7547 if (RD->isAnonymousStructOrUnion() && RD->isUnion()) {
7548 Value = APValue();
7549 return true;
7550 }
7551
7552 const CXXDestructorDecl *DD = RD->getDestructor();
7553 if (!DD && !RD->hasTrivialDestructor()) {
7554 Info.FFDiag(CallRange.getBegin());
7555 return false;
7556 }
7557
7558 if (!DD || DD->isTrivial()) {
7559 // A trivial destructor just ends the lifetime of the object. Check for
7560 // this case before checking for a body, because we might not bother
7561 // building a body for a trivial destructor. Note that it doesn't matter
7562 // whether the destructor is constexpr in this case; all trivial
7563 // destructors are constexpr.
7564 Value = APValue();
7565 return true;
7566 }
7567
7568 if (!Info.CheckCallLimit(CallRange.getBegin()))
7569 return false;
7570
7571 const FunctionDecl *Definition = nullptr;
7572 const Stmt *Body = DD->getBody(Definition);
7573
7574 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
7575 return false;
7576
7577 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
7578 CallRef());
7579
7580 // We're now in the period of destruction of this object.
7581 EvalInfo::EvaluatingDestructorRAII EvalObj(
7582 Info,
7583 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
7584 unsigned NonVirtualBases = countNonVirtualBases(RD);
7585 unsigned NumVirtualBases = RD->getNumVBases();
7586 unsigned BasesLeft = NonVirtualBases;
7587 if (!EvalObj.DidInsert) {
7588 // C++2a [class.dtor]p19:
7589 // the behavior is undefined if the destructor is invoked for an object
7590 // whose lifetime has ended
7591 // (Note that formally the lifetime ends when the period of destruction
7592 // begins, even though certain uses of the object remain valid until the
7593 // period of destruction ends.)
7594 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
7595 return false;
7596 }
7597
7598 // FIXME: Creating an APValue just to hold a nonexistent return value is
7599 // wasteful.
7600 APValue RetVal;
7601 StmtResult Ret = {RetVal, nullptr};
7602 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
7603 return false;
7604
7605 // A union destructor does not implicitly destroy its members.
7606 if (RD->isUnion())
7607 return true;
7608
7609 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7610
7611 // We don't have a good way to iterate fields in reverse, so collect all the
7612 // fields first and then walk them backwards.
7613 SmallVector<FieldDecl*, 16> Fields(RD->fields());
7614 for (const FieldDecl *FD : llvm::reverse(Fields)) {
7615 if (FD->isUnnamedBitField())
7616 continue;
7617
7618 LValue Subobject = This;
7619 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
7620 return false;
7621
7622 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
7623 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7624 FD->getType()))
7625 return false;
7626 }
7627
7628 if (BasesLeft != 0 || NumVirtualBases != 0)
7629 EvalObj.startedDestroyingBases();
7630
7631 // Destroy base classes in reverse order.
7632 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
7633 if (Base.isVirtual())
7634 continue;
7635 --BasesLeft;
7636
7637 QualType BaseType = Base.getType();
7638 LValue Subobject = This;
7639 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7640 BaseType->getAsCXXRecordDecl(), &Layout))
7641 return false;
7642
7643 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7644 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7645 BaseType, /*IsCompleteClass=*/false))
7646 return false;
7647 }
7648 assert(BasesLeft == 0 && "NumBases was wrong?");
7649
7650 // Virtual bases.
7651 if (IsCompleteClass) {
7652 unsigned VirtualBasesLeft = NumVirtualBases;
7653 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->vbases())) {
7654 --VirtualBasesLeft;
7655
7656 QualType BaseType = Base.getType();
7657 LValue Subobject = This;
7658 if (!HandleLValueDirectVirtualBase(Info, &LocE, Subobject, RD,
7659 BaseType->getAsCXXRecordDecl(),
7660 &Layout))
7661 return false;
7662
7663 APValue *SubobjectValue = &Value.getStructVirtualBase(VirtualBasesLeft);
7664 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7665 BaseType, /*IsCompleteClass=*/false))
7666 return false;
7667 }
7668 assert(VirtualBasesLeft == 0 && "NumVirtualBases was wrong?");
7669 }
7670
7671 // The period of destruction ends now. The object is gone.
7672 Value = APValue();
7673 return true;
7674}
7675
7676namespace {
7677struct DestroyObjectHandler {
7678 EvalInfo &Info;
7679 const Expr *E;
7680 const LValue &This;
7681 const AccessKinds AccessKind;
7682
7683 typedef bool result_type;
7684 bool failed() { return false; }
7685 bool found(APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
7686 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7687 SubobjType);
7688 }
7689 bool found(APSInt &Value, QualType SubobjType) {
7690 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7691 return false;
7692 }
7693 bool found(APFloat &Value, QualType SubobjType) {
7694 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7695 return false;
7696 }
7697};
7698}
7699
7700/// Perform a destructor or pseudo-destructor call on the given object, which
7701/// might in general not be a complete object.
7702static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7703 const LValue &This, QualType ThisType) {
7704 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7705 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7706 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7707}
7708
7709/// Destroy and end the lifetime of the given complete object.
7710static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7712 QualType T) {
7713 // If we've had an unmodeled side-effect, we can't rely on mutable state
7714 // (such as the object we're about to destroy) being correct.
7715 if (Info.EvalStatus.HasSideEffects)
7716 return false;
7717
7718 LValue LV;
7719 LV.set({LVBase});
7720 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7721}
7722
7723/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7724static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7725 LValue &Result) {
7726 if (Info.checkingPotentialConstantExpression() ||
7727 Info.SpeculativeEvaluationDepth)
7728 return false;
7729
7730 // This is permitted only within a call to std::allocator<T>::allocate.
7731 auto Caller = Info.getStdAllocatorCaller("allocate");
7732 if (!Caller) {
7733 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7734 ? diag::note_constexpr_new_untyped
7735 : diag::note_constexpr_new);
7736 return false;
7737 }
7738
7739 QualType ElemType = Caller.ElemType;
7740 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7741 Info.FFDiag(E->getExprLoc(),
7742 diag::note_constexpr_new_not_complete_object_type)
7743 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7744 return false;
7745 }
7746
7747 APSInt ByteSize;
7748 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7749 return false;
7750 bool IsNothrow = false;
7751 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7752 EvaluateIgnoredValue(Info, E->getArg(I));
7753 IsNothrow |= E->getType()->isNothrowT();
7754 }
7755
7756 CharUnits ElemSize;
7757 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7758 return false;
7759 APInt Size, Remainder;
7760 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7761 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7762 if (Remainder != 0) {
7763 // This likely indicates a bug in the implementation of 'std::allocator'.
7764 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7765 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7766 return false;
7767 }
7768
7769 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7770 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7771 if (IsNothrow) {
7772 Result.setNull(Info.Ctx, E->getType());
7773 return true;
7774 }
7775 return false;
7776 }
7777
7778 QualType AllocType = Info.Ctx.getConstantArrayType(
7779 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7780 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7781 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7782 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7783 return true;
7784}
7785
7787 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7788 if (CXXDestructorDecl *DD = RD->getDestructor())
7789 return DD->isVirtual();
7790 return false;
7791}
7792
7794 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7795 if (CXXDestructorDecl *DD = RD->getDestructor())
7796 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7797 return nullptr;
7798}
7799
7800/// Check that the given object is a suitable pointer to a heap allocation that
7801/// still exists and is of the right kind for the purpose of a deletion.
7802///
7803/// On success, returns the heap allocation to deallocate. On failure, produces
7804/// a diagnostic and returns std::nullopt.
7805static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7806 const LValue &Pointer,
7807 DynAlloc::Kind DeallocKind) {
7808 auto PointerAsString = [&] {
7809 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7810 };
7811
7812 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7813 if (!DA) {
7814 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7815 << PointerAsString();
7816 if (Pointer.Base)
7817 NoteLValueLocation(Info, Pointer.Base);
7818 return std::nullopt;
7819 }
7820
7821 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7822 if (!Alloc) {
7823 Info.FFDiag(E, diag::note_constexpr_double_delete);
7824 return std::nullopt;
7825 }
7826
7827 if (DeallocKind != (*Alloc)->getKind()) {
7828 QualType AllocType = Pointer.Base.getDynamicAllocType();
7829 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7830 << DeallocKind << (*Alloc)->getKind() << AllocType;
7831 NoteLValueLocation(Info, Pointer.Base);
7832 return std::nullopt;
7833 }
7834
7835 bool Subobject = false;
7836 if (DeallocKind == DynAlloc::New) {
7837 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7838 Pointer.Designator.isOnePastTheEnd();
7839 } else {
7840 Subobject = Pointer.Designator.Entries.size() != 1 ||
7841 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7842 }
7843 if (Subobject) {
7844 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7845 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7846 return std::nullopt;
7847 }
7848
7849 return Alloc;
7850}
7851
7852// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7853static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7854 if (Info.checkingPotentialConstantExpression() ||
7855 Info.SpeculativeEvaluationDepth)
7856 return false;
7857
7858 // This is permitted only within a call to std::allocator<T>::deallocate.
7859 if (!Info.getStdAllocatorCaller("deallocate")) {
7860 Info.FFDiag(E->getExprLoc());
7861 return true;
7862 }
7863
7864 LValue Pointer;
7865 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7866 return false;
7867 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7868 EvaluateIgnoredValue(Info, E->getArg(I));
7869
7870 if (Pointer.Designator.Invalid)
7871 return false;
7872
7873 // Deleting a null pointer would have no effect, but it's not permitted by
7874 // std::allocator<T>::deallocate's contract.
7875 if (Pointer.isNullPointer()) {
7876 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7877 return true;
7878 }
7879
7880 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7881 return false;
7882
7883 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7884 return true;
7885}
7886
7887//===----------------------------------------------------------------------===//
7888// Generic Evaluation
7889//===----------------------------------------------------------------------===//
7890namespace {
7891
7892class BitCastBuffer {
7893 // FIXME: We're going to need bit-level granularity when we support
7894 // bit-fields.
7895 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7896 // we don't support a host or target where that is the case. Still, we should
7897 // use a more generic type in case we ever do.
7898 SmallVector<std::optional<unsigned char>, 32> Bytes;
7899
7900 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7901 "Need at least 8 bit unsigned char");
7902
7903 bool TargetIsLittleEndian;
7904
7905public:
7906 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7907 : Bytes(Width.getQuantity()),
7908 TargetIsLittleEndian(TargetIsLittleEndian) {}
7909
7910 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7911 SmallVectorImpl<unsigned char> &Output) const {
7912 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7913 // If a byte of an integer is uninitialized, then the whole integer is
7914 // uninitialized.
7915 if (!Bytes[I.getQuantity()])
7916 return false;
7917 Output.push_back(*Bytes[I.getQuantity()]);
7918 }
7919 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7920 std::reverse(Output.begin(), Output.end());
7921 return true;
7922 }
7923
7924 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7925 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7926 std::reverse(Input.begin(), Input.end());
7927
7928 size_t Index = 0;
7929 for (unsigned char Byte : Input) {
7930 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7931 Bytes[Offset.getQuantity() + Index] = Byte;
7932 ++Index;
7933 }
7934 }
7935
7936 size_t size() { return Bytes.size(); }
7937};
7938
7939/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7940/// target would represent the value at runtime.
7941class APValueToBufferConverter {
7942 EvalInfo &Info;
7943 BitCastBuffer Buffer;
7944 const CastExpr *BCE;
7945
7946 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7947 const CastExpr *BCE)
7948 : Info(Info),
7949 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7950 BCE(BCE) {}
7951
7952 bool visit(const APValue &Val, QualType Ty) {
7953 return visit(Val, Ty, CharUnits::fromQuantity(0));
7954 }
7955
7956 // Write out Val with type Ty into Buffer starting at Offset.
7957 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7958 assert((size_t)Offset.getQuantity() <= Buffer.size());
7959
7960 // As a special case, nullptr_t has an indeterminate value.
7961 if (Ty->isNullPtrType())
7962 return true;
7963
7964 // Dig through Src to find the byte at SrcOffset.
7965 switch (Val.getKind()) {
7967 case APValue::None:
7968 return true;
7969
7970 case APValue::Int:
7971 return visitInt(Val.getInt(), Ty, Offset);
7972 case APValue::Float:
7973 return visitFloat(Val.getFloat(), Ty, Offset);
7974 case APValue::Array:
7975 return visitArray(Val, Ty, Offset);
7976 case APValue::Struct:
7977 return visitRecord(Val, Ty, Offset);
7978 case APValue::Vector:
7979 return visitVector(Val, Ty, Offset);
7980
7983 return visitComplex(Val, Ty, Offset);
7985 // FIXME: We should support these.
7986
7987 case APValue::LValue:
7988 case APValue::Matrix:
7989 case APValue::Union:
7992 Info.FFDiag(BCE->getBeginLoc(),
7993 diag::note_constexpr_bit_cast_unsupported_type)
7994 << Ty;
7995 return false;
7996 }
7997 }
7998 llvm_unreachable("Unhandled APValue::ValueKind");
7999 }
8000
8001 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
8002 const RecordDecl *RD = Ty->getAsRecordDecl();
8003 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8004
8005 // Visit the base classes.
8006 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8007 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8008 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8009 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8010 const APValue &Base = Val.getStructBase(I);
8011
8012 // Can happen in error cases.
8013 if (!Base.isStruct())
8014 return false;
8015
8016 if (!visitRecord(Base, BS.getType(),
8017 Layout.getBaseClassOffset(BaseDecl) + Offset))
8018 return false;
8019 }
8020 }
8021
8022 // Visit the fields.
8023 unsigned FieldIdx = 0;
8024 for (FieldDecl *FD : RD->fields()) {
8025 if (FD->isBitField()) {
8026 Info.FFDiag(BCE->getBeginLoc(),
8027 diag::note_constexpr_bit_cast_unsupported_bitfield);
8028 return false;
8029 }
8030
8031 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8032
8033 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
8034 "only bit-fields can have sub-char alignment");
8035 CharUnits FieldOffset =
8036 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
8037 QualType FieldTy = FD->getType();
8038 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
8039 return false;
8040 ++FieldIdx;
8041 }
8042
8043 return true;
8044 }
8045
8046 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
8047 const auto *CAT =
8048 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
8049 if (!CAT)
8050 return false;
8051
8052 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
8053 unsigned NumInitializedElts = Val.getArrayInitializedElts();
8054 unsigned ArraySize = Val.getArraySize();
8055 // First, initialize the initialized elements.
8056 for (unsigned I = 0; I != NumInitializedElts; ++I) {
8057 const APValue &SubObj = Val.getArrayInitializedElt(I);
8058 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
8059 return false;
8060 }
8061
8062 // Next, initialize the rest of the array using the filler.
8063 if (Val.hasArrayFiller()) {
8064 const APValue &Filler = Val.getArrayFiller();
8065 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
8066 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
8067 return false;
8068 }
8069 }
8070
8071 return true;
8072 }
8073
8074 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
8075 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
8076 QualType EltTy = ComplexTy->getElementType();
8077 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8078 bool IsInt = Val.isComplexInt();
8079
8080 if (IsInt) {
8081 if (!visitInt(Val.getComplexIntReal(), EltTy,
8082 Offset + (0 * EltSizeChars)))
8083 return false;
8084 if (!visitInt(Val.getComplexIntImag(), EltTy,
8085 Offset + (1 * EltSizeChars)))
8086 return false;
8087 } else {
8088 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
8089 Offset + (0 * EltSizeChars)))
8090 return false;
8091 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
8092 Offset + (1 * EltSizeChars)))
8093 return false;
8094 }
8095
8096 return true;
8097 }
8098
8099 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
8100 const VectorType *VTy = Ty->castAs<VectorType>();
8101 QualType EltTy = VTy->getElementType();
8102 unsigned NElts = VTy->getNumElements();
8103
8104 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8105 // Special handling for OpenCL bool vectors:
8106 // Since these vectors are stored as packed bits, but we can't write
8107 // individual bits to the BitCastBuffer, we'll buffer all of the elements
8108 // together into an appropriately sized APInt and write them all out at
8109 // once. Because we don't accept vectors where NElts * EltSize isn't a
8110 // multiple of the char size, there will be no padding space, so we don't
8111 // have to worry about writing data which should have been left
8112 // uninitialized.
8113 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8114
8115 llvm::APInt Res = llvm::APInt::getZero(NElts);
8116 for (unsigned I = 0; I < NElts; ++I) {
8117 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
8118 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
8119 "bool vector element must be 1-bit unsigned integer!");
8120
8121 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
8122 }
8123
8124 SmallVector<uint8_t, 8> Bytes(NElts / 8);
8125 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
8126 Buffer.writeObject(Offset, Bytes);
8127 } else {
8128 // Iterate over each of the elements and write them out to the buffer at
8129 // the appropriate offset.
8130 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8131 for (unsigned I = 0; I < NElts; ++I) {
8132 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
8133 return false;
8134 }
8135 }
8136
8137 return true;
8138 }
8139
8140 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
8141 APSInt AdjustedVal = Val;
8142 unsigned Width = AdjustedVal.getBitWidth();
8143 if (Ty->isBooleanType()) {
8144 Width = Info.Ctx.getTypeSize(Ty);
8145 AdjustedVal = AdjustedVal.extend(Width);
8146 }
8147
8148 SmallVector<uint8_t, 8> Bytes(Width / 8);
8149 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
8150 Buffer.writeObject(Offset, Bytes);
8151 return true;
8152 }
8153
8154 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
8155 APSInt AsInt(Val.bitcastToAPInt());
8156 return visitInt(AsInt, Ty, Offset);
8157 }
8158
8159public:
8160 static std::optional<BitCastBuffer>
8161 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
8162 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
8163 APValueToBufferConverter Converter(Info, DstSize, BCE);
8164 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
8165 return std::nullopt;
8166 return Converter.Buffer;
8167 }
8168};
8169
8170/// Write an BitCastBuffer into an APValue.
8171class BufferToAPValueConverter {
8172 EvalInfo &Info;
8173 const BitCastBuffer &Buffer;
8174 const CastExpr *BCE;
8175
8176 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
8177 const CastExpr *BCE)
8178 : Info(Info), Buffer(Buffer), BCE(BCE) {}
8179
8180 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
8181 // with an invalid type, so anything left is a deficiency on our part (FIXME).
8182 // Ideally this will be unreachable.
8183 std::nullopt_t unsupportedType(QualType Ty) {
8184 Info.FFDiag(BCE->getBeginLoc(),
8185 diag::note_constexpr_bit_cast_unsupported_type)
8186 << Ty;
8187 return std::nullopt;
8188 }
8189
8190 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
8191 Info.FFDiag(BCE->getBeginLoc(),
8192 diag::note_constexpr_bit_cast_unrepresentable_value)
8193 << Ty << toString(Val, /*Radix=*/10);
8194 return std::nullopt;
8195 }
8196
8197 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
8198 const EnumType *EnumSugar = nullptr) {
8199 if (T->isNullPtrType()) {
8200 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
8201 return APValue((Expr *)nullptr,
8202 /*Offset=*/CharUnits::fromQuantity(NullValue),
8203 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
8204 }
8205
8206 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
8207
8208 // Work around floating point types that contain unused padding bytes. This
8209 // is really just `long double` on x86, which is the only fundamental type
8210 // with padding bytes.
8211 if (T->isRealFloatingType()) {
8212 const llvm::fltSemantics &Semantics =
8213 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8214 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8215 assert(NumBits % 8 == 0);
8216 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
8217 if (NumBytes != SizeOf)
8218 SizeOf = NumBytes;
8219 }
8220
8221 SmallVector<uint8_t, 8> Bytes;
8222 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
8223 // If this is std::byte or unsigned char, then its okay to store an
8224 // indeterminate value.
8225 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8226 bool IsUChar =
8227 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
8228 T->isSpecificBuiltinType(BuiltinType::Char_U));
8229 if (!IsStdByte && !IsUChar) {
8230 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
8231 Info.FFDiag(BCE->getExprLoc(),
8232 diag::note_constexpr_bit_cast_indet_dest)
8233 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8234 return std::nullopt;
8235 }
8236
8238 }
8239
8240 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
8241 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8242
8244 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
8245
8246 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
8247 if (IntWidth != Val.getBitWidth()) {
8248 APSInt Truncated = Val.trunc(IntWidth);
8249 if (Truncated.extend(Val.getBitWidth()) != Val)
8250 return unrepresentableValue(QualType(T, 0), Val);
8251 Val = Truncated;
8252 }
8253
8254 return APValue(Val);
8255 }
8256
8257 if (T->isRealFloatingType()) {
8258 const llvm::fltSemantics &Semantics =
8259 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
8260 return APValue(APFloat(Semantics, Val));
8261 }
8262
8263 return unsupportedType(QualType(T, 0));
8264 }
8265
8266 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
8267 const RecordDecl *RD = RTy->getAsRecordDecl();
8268 if (RD->isInvalidDecl())
8269 return std::nullopt;
8270 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8271
8272 unsigned NumBases = 0;
8273 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8274 NumBases = CXXRD->getNumBases();
8275
8276 APValue ResultVal(APValue::UninitStruct(), NumBases, RD->getNumFields());
8277
8278 // Visit the base classes.
8279 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8280 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8281 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8282 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
8283
8284 std::optional<APValue> SubObj = visitType(
8285 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
8286 if (!SubObj)
8287 return std::nullopt;
8288 ResultVal.getStructBase(I) = *SubObj;
8289 }
8290 }
8291
8292 // Visit the fields.
8293 unsigned FieldIdx = 0;
8294 for (FieldDecl *FD : RD->fields()) {
8295 // FIXME: We don't currently support bit-fields. A lot of the logic for
8296 // this is in CodeGen, so we need to factor it around.
8297 if (FD->isBitField()) {
8298 Info.FFDiag(BCE->getBeginLoc(),
8299 diag::note_constexpr_bit_cast_unsupported_bitfield);
8300 return std::nullopt;
8301 }
8302
8303 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
8304 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8305
8306 CharUnits FieldOffset =
8307 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
8308 Offset;
8309 QualType FieldTy = FD->getType();
8310 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8311 if (!SubObj)
8312 return std::nullopt;
8313 ResultVal.getStructField(FieldIdx) = *SubObj;
8314 ++FieldIdx;
8315 }
8316
8317 return ResultVal;
8318 }
8319
8320 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
8321 QualType RepresentationType =
8322 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8323 assert(!RepresentationType.isNull() &&
8324 "enum forward decl should be caught by Sema");
8325 const auto *AsBuiltin =
8326 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
8327 // Recurse into the underlying type. Treat std::byte transparently as
8328 // unsigned char.
8329 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
8330 }
8331
8332 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
8333 size_t Size = Ty->getLimitedSize();
8334 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
8335
8336 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8337 for (size_t I = 0; I != Size; ++I) {
8338 std::optional<APValue> ElementValue =
8339 visitType(Ty->getElementType(), Offset + I * ElementWidth);
8340 if (!ElementValue)
8341 return std::nullopt;
8342 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8343 }
8344
8345 return ArrayValue;
8346 }
8347
8348 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
8349 QualType ElementType = Ty->getElementType();
8350 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8351 bool IsInt = ElementType->isIntegerType();
8352
8353 std::optional<APValue> Values[2];
8354 for (unsigned I = 0; I != 2; ++I) {
8355 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
8356 if (!Values[I])
8357 return std::nullopt;
8358 }
8359
8360 if (IsInt)
8361 return APValue(Values[0]->getInt(), Values[1]->getInt());
8362 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8363 }
8364
8365 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
8366 QualType EltTy = VTy->getElementType();
8367 unsigned NElts = VTy->getNumElements();
8368 unsigned EltSize =
8369 VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
8370
8371 SmallVector<APValue, 4> Elts;
8372 Elts.reserve(NElts);
8373 if (VTy->isPackedVectorBoolType(Info.Ctx)) {
8374 // Special handling for OpenCL bool vectors:
8375 // Since these vectors are stored as packed bits, but we can't read
8376 // individual bits from the BitCastBuffer, we'll buffer all of the
8377 // elements together into an appropriately sized APInt and write them all
8378 // out at once. Because we don't accept vectors where NElts * EltSize
8379 // isn't a multiple of the char size, there will be no padding space, so
8380 // we don't have to worry about reading any padding data which didn't
8381 // actually need to be accessed.
8382 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8383
8384 SmallVector<uint8_t, 8> Bytes;
8385 Bytes.reserve(NElts / 8);
8386 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
8387 return std::nullopt;
8388
8389 APSInt SValInt(NElts, true);
8390 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8391
8392 for (unsigned I = 0; I < NElts; ++I) {
8393 llvm::APInt Elt =
8394 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8395 Elts.emplace_back(
8396 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
8397 }
8398 } else {
8399 // Iterate over each of the elements and read them from the buffer at
8400 // the appropriate offset.
8401 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8402 for (unsigned I = 0; I < NElts; ++I) {
8403 std::optional<APValue> EltValue =
8404 visitType(EltTy, Offset + I * EltSizeChars);
8405 if (!EltValue)
8406 return std::nullopt;
8407 Elts.push_back(std::move(*EltValue));
8408 }
8409 }
8410
8411 return APValue(Elts.data(), Elts.size());
8412 }
8413
8414 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
8415 return unsupportedType(QualType(Ty, 0));
8416 }
8417
8418 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8419 QualType Can = Ty.getCanonicalType();
8420
8421 switch (Can->getTypeClass()) {
8422#define TYPE(Class, Base) \
8423 case Type::Class: \
8424 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8425#define ABSTRACT_TYPE(Class, Base)
8426#define NON_CANONICAL_TYPE(Class, Base) \
8427 case Type::Class: \
8428 llvm_unreachable("non-canonical type should be impossible!");
8429#define DEPENDENT_TYPE(Class, Base) \
8430 case Type::Class: \
8431 llvm_unreachable( \
8432 "dependent types aren't supported in the constant evaluator!");
8433#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8434 case Type::Class: \
8435 llvm_unreachable("either dependent or not canonical!");
8436#include "clang/AST/TypeNodes.inc"
8437 }
8438 llvm_unreachable("Unhandled Type::TypeClass");
8439 }
8440
8441public:
8442 // Pull out a full value of type DstType.
8443 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8444 const CastExpr *BCE) {
8445 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8446 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
8447 }
8448};
8449
8450static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8451 QualType Ty, EvalInfo *Info,
8452 const ASTContext &Ctx,
8453 bool CheckingDest) {
8454 Ty = Ty.getCanonicalType();
8455
8456 auto diag = [&](int Reason) {
8457 if (Info)
8458 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8459 << CheckingDest << (Reason == 4) << Reason;
8460 return false;
8461 };
8462 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8463 if (Info)
8464 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8465 << NoteTy << Construct << Ty;
8466 return false;
8467 };
8468
8469 if (Ty->isUnionType())
8470 return diag(0);
8471 if (Ty->isPointerType())
8472 return diag(1);
8473 if (Ty->isMemberPointerType())
8474 return diag(2);
8475 if (Ty.isVolatileQualified())
8476 return diag(3);
8477
8478 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
8479 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
8480 for (CXXBaseSpecifier &BS : CXXRD->bases())
8481 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
8482 CheckingDest))
8483 return note(1, BS.getType(), BS.getBeginLoc());
8484 }
8485 for (FieldDecl *FD : Record->fields()) {
8486 if (FD->getType()->isReferenceType())
8487 return diag(4);
8488 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8489 CheckingDest))
8490 return note(0, FD->getType(), FD->getBeginLoc());
8491 }
8492 }
8493
8494 if (Ty->isArrayType() &&
8495 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
8496 Info, Ctx, CheckingDest))
8497 return false;
8498
8499 if (const auto *VTy = Ty->getAs<VectorType>()) {
8500 QualType EltTy = VTy->getElementType();
8501 unsigned NElts = VTy->getNumElements();
8502 unsigned EltSize =
8503 VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
8504
8505 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
8506 // The vector's size in bits is not a multiple of the target's byte size,
8507 // so its layout is unspecified. For now, we'll simply treat these cases
8508 // as unsupported (this should only be possible with OpenCL bool vectors
8509 // whose element count isn't a multiple of the byte size).
8510 if (Info)
8511 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8512 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
8513 return false;
8514 }
8515
8516 if (EltTy->isRealFloatingType() &&
8517 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
8518 // The layout for x86_fp80 vectors seems to be handled very inconsistently
8519 // by both clang and LLVM, so for now we won't allow bit_casts involving
8520 // it in a constexpr context.
8521 if (Info)
8522 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8523 << EltTy;
8524 return false;
8525 }
8526 }
8527
8528 return true;
8529}
8530
8531static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8532 const ASTContext &Ctx,
8533 const CastExpr *BCE) {
8534 bool DestOK = checkBitCastConstexprEligibilityType(
8535 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
8536 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8537 BCE->getBeginLoc(),
8538 BCE->getSubExpr()->getType(), Info, Ctx, false);
8539 return SourceOK;
8540}
8541
8542static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8543 const APValue &SourceRValue,
8544 const CastExpr *BCE) {
8545 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8546 "no host or target supports non 8-bit chars");
8547
8548 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8549 return false;
8550
8551 // Read out SourceValue into a char buffer.
8552 std::optional<BitCastBuffer> Buffer =
8553 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8554 if (!Buffer)
8555 return false;
8556
8557 // Write out the buffer into a new APValue.
8558 std::optional<APValue> MaybeDestValue =
8559 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8560 if (!MaybeDestValue)
8561 return false;
8562
8563 DestValue = std::move(*MaybeDestValue);
8564 return true;
8565}
8566
8567static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
8568 APValue &SourceValue,
8569 const CastExpr *BCE) {
8570 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8571 "no host or target supports non 8-bit chars");
8572 assert(SourceValue.isLValue() &&
8573 "LValueToRValueBitcast requires an lvalue operand!");
8574
8575 LValue SourceLValue;
8576 APValue SourceRValue;
8577 SourceLValue.setFrom(Info.Ctx, SourceValue);
8579 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
8580 SourceRValue, /*WantObjectRepresentation=*/true))
8581 return false;
8582
8583 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8584}
8585
8586template <class Derived>
8587class ExprEvaluatorBase
8588 : public ConstStmtVisitor<Derived, bool> {
8589private:
8590 Derived &getDerived() { return static_cast<Derived&>(*this); }
8591 bool DerivedSuccess(const APValue &V, const Expr *E) {
8592 return getDerived().Success(V, E);
8593 }
8594 bool DerivedZeroInitialization(const Expr *E) {
8595 return getDerived().ZeroInitialization(E);
8596 }
8597
8598 // Check whether a conditional operator with a non-constant condition is a
8599 // potential constant expression. If neither arm is a potential constant
8600 // expression, then the conditional operator is not either.
8601 template<typename ConditionalOperator>
8602 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
8603 assert(Info.checkingPotentialConstantExpression());
8604
8605 // Speculatively evaluate both arms.
8606 SmallVector<PartialDiagnosticAt, 8> Diag;
8607 {
8608 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8609 StmtVisitorTy::Visit(E->getFalseExpr());
8610 if (Diag.empty())
8611 return;
8612 }
8613
8614 {
8615 SpeculativeEvaluationRAII Speculate(Info, &Diag);
8616 Diag.clear();
8617 Info.EvalStatus.DiagEmitted = false;
8618 StmtVisitorTy::Visit(E->getTrueExpr());
8619 if (Diag.empty())
8620 return;
8621 }
8622
8623 Error(E, diag::note_constexpr_conditional_never_const);
8624 }
8625
8626
8627 template<typename ConditionalOperator>
8628 bool HandleConditionalOperator(const ConditionalOperator *E) {
8629 bool BoolResult;
8630 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
8631 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8632 CheckPotentialConstantConditional(E);
8633 return false;
8634 }
8635 if (Info.noteFailure()) {
8636 StmtVisitorTy::Visit(E->getTrueExpr());
8637 StmtVisitorTy::Visit(E->getFalseExpr());
8638 }
8639 return false;
8640 }
8641
8642 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
8643 return StmtVisitorTy::Visit(EvalExpr);
8644 }
8645
8646protected:
8647 EvalInfo &Info;
8648 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8649 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8650
8651 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8652 return Info.CCEDiag(E, D);
8653 }
8654
8655 bool ZeroInitialization(const Expr *E) { return Error(E); }
8656
8657 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
8658 unsigned BuiltinOp = E->getBuiltinCallee();
8659 return BuiltinOp != 0 &&
8660 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8661 }
8662
8663public:
8664 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8665
8666 EvalInfo &getEvalInfo() { return Info; }
8667
8668 /// Report an evaluation error. This should only be called when an error is
8669 /// first discovered. When propagating an error, just return false.
8670 bool Error(const Expr *E, diag::kind D) {
8671 Info.FFDiag(E, D) << E->getSourceRange();
8672 return false;
8673 }
8674 bool Error(const Expr *E) {
8675 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8676 }
8677
8678 bool VisitStmt(const Stmt *) {
8679 llvm_unreachable("Expression evaluator should not be called on stmts");
8680 }
8681 bool VisitExpr(const Expr *E) {
8682 return Error(E);
8683 }
8684
8685 bool VisitEmbedExpr(const EmbedExpr *E) {
8686 const auto It = E->begin();
8687 return StmtVisitorTy::Visit(*It);
8688 }
8689
8690 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8691 return StmtVisitorTy::Visit(E->getFunctionName());
8692 }
8693 bool VisitConstantExpr(const ConstantExpr *E) {
8694 if (E->hasAPValueResult())
8695 return DerivedSuccess(E->getAPValueResult(), E);
8696
8697 return StmtVisitorTy::Visit(E->getSubExpr());
8698 }
8699
8700 bool VisitParenExpr(const ParenExpr *E)
8701 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8702 bool VisitUnaryExtension(const UnaryOperator *E)
8703 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8704 bool VisitUnaryPlus(const UnaryOperator *E)
8705 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8706 bool VisitChooseExpr(const ChooseExpr *E)
8707 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8708 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8709 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8710 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8711 { return StmtVisitorTy::Visit(E->getReplacement()); }
8712 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8713 TempVersionRAII RAII(*Info.CurrentCall);
8714 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8715 return StmtVisitorTy::Visit(E->getExpr());
8716 }
8717 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8718 TempVersionRAII RAII(*Info.CurrentCall);
8719 // The initializer may not have been parsed yet, or might be erroneous.
8720 if (!E->getExpr())
8721 return Error(E);
8722 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8723 return StmtVisitorTy::Visit(E->getExpr());
8724 }
8725
8726 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8727 FullExpressionRAII Scope(Info);
8728 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8729 }
8730
8731 // Temporaries are registered when created, so we don't care about
8732 // CXXBindTemporaryExpr.
8733 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8734 return StmtVisitorTy::Visit(E->getSubExpr());
8735 }
8736
8737 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8738 CCEDiag(E, diag::note_constexpr_invalid_cast)
8739 << diag::ConstexprInvalidCastKind::Reinterpret;
8740 return static_cast<Derived*>(this)->VisitCastExpr(E);
8741 }
8742 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8743 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8744 CCEDiag(E, diag::note_constexpr_invalid_cast)
8745 << diag::ConstexprInvalidCastKind::Dynamic;
8746 return static_cast<Derived*>(this)->VisitCastExpr(E);
8747 }
8748 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8749 return static_cast<Derived*>(this)->VisitCastExpr(E);
8750 }
8751
8752 bool VisitBinaryOperator(const BinaryOperator *E) {
8753 switch (E->getOpcode()) {
8754 default:
8755 return Error(E);
8756
8757 case BO_Comma:
8758 VisitIgnoredValue(E->getLHS());
8759 return StmtVisitorTy::Visit(E->getRHS());
8760
8761 case BO_PtrMemD:
8762 case BO_PtrMemI: {
8763 LValue Obj;
8764 if (!HandleMemberPointerAccess(Info, E, Obj))
8765 return false;
8767 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8768 return false;
8769 return DerivedSuccess(Result, E);
8770 }
8771 }
8772 }
8773
8774 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8775 return StmtVisitorTy::Visit(E->getSemanticForm());
8776 }
8777
8778 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8779 // Evaluate and cache the common expression. We treat it as a temporary,
8780 // even though it's not quite the same thing.
8781 LValue CommonLV;
8782 if (!Evaluate(Info.CurrentCall->createTemporary(
8783 E->getOpaqueValue(),
8784 getStorageType(Info.Ctx, E->getOpaqueValue()),
8785 ScopeKind::FullExpression, CommonLV),
8786 Info, E->getCommon()))
8787 return false;
8788
8789 return HandleConditionalOperator(E);
8790 }
8791
8792 bool VisitConditionalOperator(const ConditionalOperator *E) {
8793 bool IsBcpCall = false;
8794 // If the condition (ignoring parens) is a __builtin_constant_p call,
8795 // the result is a constant expression if it can be folded without
8796 // side-effects. This is an important GNU extension. See GCC PR38377
8797 // for discussion.
8798 if (const CallExpr *CallCE =
8799 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8800 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8801 IsBcpCall = true;
8802
8803 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8804 // constant expression; we can't check whether it's potentially foldable.
8805 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8806 // it would return 'false' in this mode.
8807 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8808 return false;
8809
8810 FoldConstant Fold(Info, IsBcpCall);
8811 if (!HandleConditionalOperator(E)) {
8812 Fold.keepDiagnostics();
8813 return false;
8814 }
8815
8816 return true;
8817 }
8818
8819 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8820 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8821 Value && !Value->isAbsent())
8822 return DerivedSuccess(*Value, E);
8823
8824 const Expr *Source = E->getSourceExpr();
8825 if (!Source)
8826 return Error(E);
8827 if (Source == E) {
8828 assert(0 && "OpaqueValueExpr recursively refers to itself");
8829 return Error(E);
8830 }
8831 return StmtVisitorTy::Visit(Source);
8832 }
8833
8834 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8835 for (const Expr *SemE : E->semantics()) {
8836 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8837 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8838 // result expression: there could be two different LValues that would
8839 // refer to the same object in that case, and we can't model that.
8840 if (SemE == E->getResultExpr())
8841 return Error(E);
8842
8843 // Unique OVEs get evaluated if and when we encounter them when
8844 // emitting the rest of the semantic form, rather than eagerly.
8845 if (OVE->isUnique())
8846 continue;
8847
8848 LValue LV;
8849 if (!Evaluate(Info.CurrentCall->createTemporary(
8850 OVE, getStorageType(Info.Ctx, OVE),
8851 ScopeKind::FullExpression, LV),
8852 Info, OVE->getSourceExpr()))
8853 return false;
8854 } else if (SemE == E->getResultExpr()) {
8855 if (!StmtVisitorTy::Visit(SemE))
8856 return false;
8857 } else {
8858 if (!EvaluateIgnoredValue(Info, SemE))
8859 return false;
8860 }
8861 }
8862 return true;
8863 }
8864
8865 bool VisitCallExpr(const CallExpr *E) {
8867 if (!handleCallExpr(E, Result, nullptr))
8868 return false;
8869 return DerivedSuccess(Result, E);
8870 }
8871
8872 bool handleCallExpr(const CallExpr *E, APValue &Result,
8873 const LValue *ResultSlot) {
8874 CallScopeRAII CallScope(Info);
8875
8876 const Expr *Callee = E->getCallee()->IgnoreParens();
8877 QualType CalleeType = Callee->getType();
8878
8879 const FunctionDecl *FD = nullptr;
8880 LValue *This = nullptr, ObjectArg;
8881 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
8882 bool HasQualifier = false;
8883
8884 CallRef Call;
8885
8886 // Extract function decl and 'this' pointer from the callee.
8887 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8888 const CXXMethodDecl *Member = nullptr;
8889 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8890 // Explicit bound member calls, such as x.f() or p->g();
8891 if (!EvaluateObjectArgument(Info, ME->getBase(), ObjectArg))
8892 return false;
8893 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8894 if (!Member)
8895 return Error(Callee);
8896 This = &ObjectArg;
8897 HasQualifier = ME->hasQualifier();
8898 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8899 // Indirect bound member calls ('.*' or '->*').
8900 const ValueDecl *D =
8901 HandleMemberPointerAccess(Info, BE, ObjectArg, false);
8902 if (!D)
8903 return false;
8904 Member = dyn_cast<CXXMethodDecl>(D);
8905 if (!Member)
8906 return Error(Callee);
8907 This = &ObjectArg;
8908 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8909 if (!Info.getLangOpts().CPlusPlus20)
8910 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8911 return EvaluateObjectArgument(Info, PDE->getBase(), ObjectArg) &&
8912 HandleDestruction(Info, PDE, ObjectArg, PDE->getDestroyedType());
8913 } else
8914 return Error(Callee);
8915 FD = Member;
8916 } else if (CalleeType->isFunctionPointerType()) {
8917 LValue CalleeLV;
8918 if (!EvaluatePointer(Callee, CalleeLV, Info))
8919 return false;
8920
8921 if (!CalleeLV.getLValueOffset().isZero())
8922 return Error(Callee);
8923 if (CalleeLV.isNullPointer()) {
8924 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8925 << const_cast<Expr *>(Callee);
8926 return false;
8927 }
8928 FD = dyn_cast_or_null<FunctionDecl>(
8929 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8930 if (!FD)
8931 return Error(Callee);
8932 // Don't call function pointers which have been cast to some other type.
8933 // Per DR (no number yet), the caller and callee can differ in noexcept.
8934 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8935 CalleeType->getPointeeType(), FD->getType())) {
8936 return Error(E);
8937 }
8938
8939 // For an (overloaded) assignment expression, evaluate the RHS before the
8940 // LHS.
8941 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8942 if (OCE && OCE->isAssignmentOp()) {
8943 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8944 Call = Info.CurrentCall->createCall(FD);
8945 bool HasThis = false;
8946 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8947 HasThis = MD->isImplicitObjectMemberFunction();
8948 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8949 /*RightToLeft=*/true, &ObjectArg))
8950 return false;
8951 }
8952
8953 // Overloaded operator calls to member functions are represented as normal
8954 // calls with '*this' as the first argument.
8955 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8956 if (MD &&
8957 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8958 // FIXME: When selecting an implicit conversion for an overloaded
8959 // operator delete, we sometimes try to evaluate calls to conversion
8960 // operators without a 'this' parameter!
8961 if (Args.empty())
8962 return Error(E);
8963
8964 if (!EvaluateObjectArgument(Info, Args[0], ObjectArg))
8965 return false;
8966
8967 // If we are calling a static operator, the 'this' argument needs to be
8968 // ignored after being evaluated.
8969 if (MD->isInstance())
8970 This = &ObjectArg;
8971
8972 // If this is syntactically a simple assignment using a trivial
8973 // assignment operator, start the lifetimes of union members as needed,
8974 // per C++20 [class.union]5.
8975 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8976 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8977 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ObjectArg))
8978 return false;
8979
8980 Args = Args.slice(1);
8981 } else if (MD && MD->isLambdaStaticInvoker()) {
8982 // Map the static invoker for the lambda back to the call operator.
8983 // Conveniently, we don't have to slice out the 'this' argument (as is
8984 // being done for the non-static case), since a static member function
8985 // doesn't have an implicit argument passed in.
8986 const CXXRecordDecl *ClosureClass = MD->getParent();
8987 assert(
8988 ClosureClass->captures().empty() &&
8989 "Number of captures must be zero for conversion to function-ptr");
8990
8991 const CXXMethodDecl *LambdaCallOp =
8992 ClosureClass->getLambdaCallOperator();
8993
8994 // Set 'FD', the function that will be called below, to the call
8995 // operator. If the closure object represents a generic lambda, find
8996 // the corresponding specialization of the call operator.
8997
8998 if (ClosureClass->isGenericLambda()) {
8999 assert(MD->isFunctionTemplateSpecialization() &&
9000 "A generic lambda's static-invoker function must be a "
9001 "template specialization");
9002 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
9003 FunctionTemplateDecl *CallOpTemplate =
9004 LambdaCallOp->getDescribedFunctionTemplate();
9005 void *InsertPos = nullptr;
9006 FunctionDecl *CorrespondingCallOpSpecialization =
9007 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
9008 assert(CorrespondingCallOpSpecialization &&
9009 "We must always have a function call operator specialization "
9010 "that corresponds to our static invoker specialization");
9011 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
9012 FD = CorrespondingCallOpSpecialization;
9013 } else
9014 FD = LambdaCallOp;
9016 if (FD->getDeclName().isAnyOperatorNew()) {
9017 LValue Ptr;
9018 if (!HandleOperatorNewCall(Info, E, Ptr))
9019 return false;
9020 Ptr.moveInto(Result);
9021 return CallScope.destroy();
9022 } else {
9023 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
9024 }
9025 }
9026 } else
9027 return Error(E);
9028
9029 // Evaluate the arguments now if we've not already done so.
9030 if (!Call) {
9031 Call = Info.CurrentCall->createCall(FD);
9032 if (!EvaluateArgs(Args, Call, Info, FD, /*RightToLeft*/ false,
9033 &ObjectArg))
9034 return false;
9035 }
9036
9037 SmallVector<QualType, 4> CovariantAdjustmentPath;
9038 if (This) {
9039 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
9040 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
9041 // Perform virtual dispatch, if necessary.
9042 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
9043 CovariantAdjustmentPath);
9044 if (!FD)
9045 return false;
9046 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
9047 // Check that the 'this' pointer points to an object of the right type.
9048 // FIXME: If this is an assignment operator call, we may need to change
9049 // the active union member before we check this.
9050 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
9051 return false;
9052 }
9053 }
9054
9055 // Destructor calls are different enough that they have their own codepath.
9056 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
9057 assert(This && "no 'this' pointer for destructor call");
9058 return HandleDestruction(Info, E, *This,
9059 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
9060 CallScope.destroy();
9061 }
9062
9063 const FunctionDecl *Definition = nullptr;
9064 Stmt *Body = FD->getBody(Definition);
9065 SourceLocation Loc = E->getExprLoc();
9066
9067 // Treat the object argument as `this` when evaluating defaulted
9068 // special menmber functions
9070 This = &ObjectArg;
9071
9072 if (!CheckConstexprFunction(Info, Loc, FD, Definition, Body) ||
9073 !HandleFunctionCall(Loc, Definition, This, E, Args, Call, Body, Info,
9074 Result, ResultSlot))
9075 return false;
9076
9077 if (!CovariantAdjustmentPath.empty() &&
9079 CovariantAdjustmentPath))
9080 return false;
9081
9082 return CallScope.destroy();
9083 }
9084
9085 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9086 return StmtVisitorTy::Visit(E->getInitializer());
9087 }
9088 bool VisitInitListExpr(const InitListExpr *E) {
9089 if (E->getNumInits() == 0)
9090 return DerivedZeroInitialization(E);
9091 if (E->getNumInits() == 1)
9092 return StmtVisitorTy::Visit(E->getInit(0));
9093 return Error(E);
9094 }
9095 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
9096 return DerivedZeroInitialization(E);
9097 }
9098 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
9099 return DerivedZeroInitialization(E);
9100 }
9101 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
9102 return DerivedZeroInitialization(E);
9103 }
9104
9105 /// A member expression where the object is a prvalue is itself a prvalue.
9106 bool VisitMemberExpr(const MemberExpr *E) {
9107 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
9108 "missing temporary materialization conversion");
9109 assert(!E->isArrow() && "missing call to bound member function?");
9110
9111 APValue Val;
9112 if (!Evaluate(Val, Info, E->getBase()))
9113 return false;
9114
9115 QualType BaseTy = E->getBase()->getType();
9116
9117 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
9118 if (!FD) return Error(E);
9119 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
9120 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9121 FD->getParent()->getCanonicalDecl() &&
9122 "record / field mismatch");
9123
9124 // Note: there is no lvalue base here. But this case should only ever
9125 // happen in C or in C++98, where we cannot be evaluating a constexpr
9126 // constructor, which is the only case the base matters.
9127 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
9128 SubobjectDesignator Designator(BaseTy);
9129 Designator.addDeclUnchecked(FD);
9130
9132 return extractSubobject(Info, E, Obj, Designator, Result) &&
9133 DerivedSuccess(Result, E);
9134 }
9135
9136 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
9137 APValue Val;
9138 if (!Evaluate(Val, Info, E->getBase()))
9139 return false;
9140
9141 if (Val.isVector()) {
9142 SmallVector<uint32_t, 4> Indices;
9143 E->getEncodedElementAccess(Indices);
9144 if (Indices.size() == 1) {
9145 // Return scalar.
9146 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
9147 } else {
9148 // Construct new APValue vector.
9149 SmallVector<APValue, 4> Elts;
9150 for (unsigned I = 0; I < Indices.size(); ++I) {
9151 Elts.push_back(Val.getVectorElt(Indices[I]));
9152 }
9153 APValue VecResult(Elts.data(), Indices.size());
9154 return DerivedSuccess(VecResult, E);
9155 }
9156 }
9157
9158 return false;
9159 }
9160
9161 bool VisitCastExpr(const CastExpr *E) {
9162 switch (E->getCastKind()) {
9163 default:
9164 break;
9165
9166 case CK_AtomicToNonAtomic: {
9167 APValue AtomicVal;
9168 // This does not need to be done in place even for class/array types:
9169 // atomic-to-non-atomic conversion implies copying the object
9170 // representation.
9171 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
9172 return false;
9173 return DerivedSuccess(AtomicVal, E);
9174 }
9175
9176 case CK_NoOp:
9177 case CK_UserDefinedConversion:
9178 return StmtVisitorTy::Visit(E->getSubExpr());
9179
9180 case CK_HLSLArrayRValue: {
9181 const Expr *SubExpr = E->getSubExpr();
9182 if (!SubExpr->isGLValue()) {
9183 APValue Val;
9184 if (!Evaluate(Val, Info, SubExpr))
9185 return false;
9186 return DerivedSuccess(Val, E);
9187 }
9188
9189 LValue LVal;
9190 if (!EvaluateLValue(SubExpr, LVal, Info))
9191 return false;
9192 APValue RVal;
9193 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9194 if (!handleLValueToRValueConversion(Info, E, SubExpr->getType(), LVal,
9195 RVal))
9196 return false;
9197 return DerivedSuccess(RVal, E);
9198 }
9199 case CK_LValueToRValue: {
9200 LValue LVal;
9201 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
9202 return false;
9203 APValue RVal;
9204 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9206 LVal, RVal))
9207 return false;
9208 return DerivedSuccess(RVal, E);
9209 }
9210 case CK_LValueToRValueBitCast: {
9211 APValue DestValue, SourceValue;
9212 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
9213 return false;
9214 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9215 return false;
9216 return DerivedSuccess(DestValue, E);
9217 }
9218
9219 case CK_AddressSpaceConversion: {
9220 APValue Value;
9221 if (!Evaluate(Value, Info, E->getSubExpr()))
9222 return false;
9223 return DerivedSuccess(Value, E);
9224 }
9225 }
9226
9227 return Error(E);
9228 }
9229
9230 bool VisitUnaryPostInc(const UnaryOperator *UO) {
9231 return VisitUnaryPostIncDec(UO);
9232 }
9233 bool VisitUnaryPostDec(const UnaryOperator *UO) {
9234 return VisitUnaryPostIncDec(UO);
9235 }
9236 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
9237 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9238 return Error(UO);
9239
9240 LValue LVal;
9241 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
9242 return false;
9243 APValue RVal;
9244 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
9245 UO->isIncrementOp(), &RVal))
9246 return false;
9247 return DerivedSuccess(RVal, UO);
9248 }
9249
9250 bool VisitStmtExpr(const StmtExpr *E) {
9251 // We will have checked the full-expressions inside the statement expression
9252 // when they were completed, and don't need to check them again now.
9253 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9254 false);
9255
9256 const CompoundStmt *CS = E->getSubStmt();
9257 if (CS->body_empty())
9258 return true;
9259
9260 BlockScopeRAII Scope(Info);
9262 BE = CS->body_end();
9263 /**/; ++BI) {
9264 if (BI + 1 == BE) {
9265 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9266 if (!FinalExpr) {
9267 Info.FFDiag((*BI)->getBeginLoc(),
9268 diag::note_constexpr_stmt_expr_unsupported);
9269 return false;
9270 }
9271 return this->Visit(FinalExpr) && Scope.destroy();
9272 }
9273
9275 StmtResult Result = { ReturnValue, nullptr };
9276 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
9277 if (ESR != ESR_Succeeded) {
9278 // FIXME: If the statement-expression terminated due to 'return',
9279 // 'break', or 'continue', it would be nice to propagate that to
9280 // the outer statement evaluation rather than bailing out.
9281 if (ESR != ESR_Failed)
9282 Info.FFDiag((*BI)->getBeginLoc(),
9283 diag::note_constexpr_stmt_expr_unsupported);
9284 return false;
9285 }
9286 }
9287
9288 llvm_unreachable("Return from function from the loop above.");
9289 }
9290
9291 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
9292 return StmtVisitorTy::Visit(E->getSelectedExpr());
9293 }
9294
9295 /// Visit a value which is evaluated, but whose value is ignored.
9296 void VisitIgnoredValue(const Expr *E) {
9297 EvaluateIgnoredValue(Info, E);
9298 }
9299
9300 /// Potentially visit a MemberExpr's base expression.
9301 void VisitIgnoredBaseExpression(const Expr *E) {
9302 // While MSVC doesn't evaluate the base expression, it does diagnose the
9303 // presence of side-effecting behavior.
9304 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
9305 return;
9306 VisitIgnoredValue(E);
9307 }
9308};
9309
9310} // namespace
9311
9312//===----------------------------------------------------------------------===//
9313// Common base class for lvalue and temporary evaluation.
9314//===----------------------------------------------------------------------===//
9315namespace {
9316template<class Derived>
9317class LValueExprEvaluatorBase
9318 : public ExprEvaluatorBase<Derived> {
9319protected:
9320 LValue &Result;
9321 bool InvalidBaseOK;
9322 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9323 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9324
9325 bool Success(APValue::LValueBase B) {
9326 Result.set(B);
9327 return true;
9328 }
9329
9330 bool evaluatePointer(const Expr *E, LValue &Result) {
9331 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
9332 }
9333
9334public:
9335 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
9336 : ExprEvaluatorBaseTy(Info), Result(Result),
9337 InvalidBaseOK(InvalidBaseOK) {}
9338
9339 bool Success(const APValue &V, const Expr *E) {
9340 Result.setFrom(this->Info.Ctx, V);
9341 return true;
9342 }
9343
9344 bool VisitMemberExpr(const MemberExpr *E) {
9345 // Handle non-static data members.
9346 QualType BaseTy;
9347 bool EvalOK;
9348 if (E->isArrow()) {
9349 EvalOK = evaluatePointer(E->getBase(), Result);
9350 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
9351 } else if (E->getBase()->isPRValue()) {
9352 assert(E->getBase()->getType()->isRecordType());
9353 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
9354 BaseTy = E->getBase()->getType();
9355 } else {
9356 EvalOK = this->Visit(E->getBase());
9357 BaseTy = E->getBase()->getType();
9358 }
9359 if (!EvalOK) {
9360 if (!InvalidBaseOK)
9361 return false;
9362 Result.setInvalid(E);
9363 return true;
9364 }
9365
9366 const ValueDecl *MD = E->getMemberDecl();
9367 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
9368 assert(BaseTy->castAsCanonical<RecordType>()->getDecl() ==
9369 FD->getParent()->getCanonicalDecl() &&
9370 "record / field mismatch");
9371 (void)BaseTy;
9372 if (!HandleLValueMember(this->Info, E, Result, FD))
9373 return false;
9374 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9375 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
9376 return false;
9377 } else
9378 return this->Error(E);
9379
9380 if (MD->getType()->isReferenceType()) {
9381 APValue RefValue;
9382 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
9383 RefValue))
9384 return false;
9385 return Success(RefValue, E);
9386 }
9387 return true;
9388 }
9389
9390 bool VisitBinaryOperator(const BinaryOperator *E) {
9391 switch (E->getOpcode()) {
9392 default:
9393 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9394
9395 case BO_PtrMemD:
9396 case BO_PtrMemI:
9397 return HandleMemberPointerAccess(this->Info, E, Result);
9398 }
9399 }
9400
9401 bool VisitCastExpr(const CastExpr *E) {
9402 switch (E->getCastKind()) {
9403 default:
9404 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9405
9406 case CK_DerivedToBase:
9407 case CK_UncheckedDerivedToBase:
9408 if (!this->Visit(E->getSubExpr()))
9409 return false;
9410
9411 // Now figure out the necessary offset to add to the base LV to get from
9412 // the derived class to the base class.
9413 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
9414 Result);
9415 }
9416 }
9417};
9418}
9419
9420//===----------------------------------------------------------------------===//
9421// LValue Evaluation
9422//
9423// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
9424// function designators (in C), decl references to void objects (in C), and
9425// temporaries (if building with -Wno-address-of-temporary).
9426//
9427// LValue evaluation produces values comprising a base expression of one of the
9428// following types:
9429// - Declarations
9430// * VarDecl
9431// * FunctionDecl
9432// - Literals
9433// * CompoundLiteralExpr in C (and in global scope in C++)
9434// * StringLiteral
9435// * PredefinedExpr
9436// * ObjCStringLiteralExpr
9437// * ObjCEncodeExpr
9438// * AddrLabelExpr
9439// * BlockExpr
9440// * CallExpr for a MakeStringConstant builtin
9441// - typeid(T) expressions, as TypeInfoLValues
9442// - Locals and temporaries
9443// * MaterializeTemporaryExpr
9444// * Any Expr, with a CallIndex indicating the function in which the temporary
9445// was evaluated, for cases where the MaterializeTemporaryExpr is missing
9446// from the AST (FIXME).
9447// * A MaterializeTemporaryExpr that has static storage duration, with no
9448// CallIndex, for a lifetime-extended temporary.
9449// * The ConstantExpr that is currently being evaluated during evaluation of an
9450// immediate invocation.
9451// plus an offset in bytes.
9452//===----------------------------------------------------------------------===//
9453namespace {
9454class LValueExprEvaluator
9455 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
9456public:
9457 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
9458 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
9459
9460 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
9461 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
9462
9463 bool VisitCallExpr(const CallExpr *E);
9464 bool VisitDeclRefExpr(const DeclRefExpr *E);
9465 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
9466 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
9467 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
9468 bool VisitMemberExpr(const MemberExpr *E);
9469 bool VisitStringLiteral(const StringLiteral *E) {
9470 return Success(
9471 APValue::LValueBase(E, 0, Info.Ctx.getNextStringLiteralVersion()));
9472 }
9473 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
9474 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
9475 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
9476 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
9477 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
9478 bool VisitUnaryDeref(const UnaryOperator *E);
9479 bool VisitUnaryReal(const UnaryOperator *E);
9480 bool VisitUnaryImag(const UnaryOperator *E);
9481 bool VisitUnaryPreInc(const UnaryOperator *UO) {
9482 return VisitUnaryPreIncDec(UO);
9483 }
9484 bool VisitUnaryPreDec(const UnaryOperator *UO) {
9485 return VisitUnaryPreIncDec(UO);
9486 }
9487 bool VisitBinAssign(const BinaryOperator *BO);
9488 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
9489
9490 bool VisitCastExpr(const CastExpr *E) {
9491 switch (E->getCastKind()) {
9492 default:
9493 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9494
9495 case CK_LValueBitCast:
9496 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9497 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9498 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
9499 if (!Visit(E->getSubExpr()))
9500 return false;
9501 Result.Designator.setInvalid();
9502 return true;
9503
9504 case CK_BaseToDerived:
9505 if (!Visit(E->getSubExpr()))
9506 return false;
9507 return HandleBaseToDerivedCast(Info, E, Result);
9508
9509 case CK_Dynamic:
9510 if (!Visit(E->getSubExpr()))
9511 return false;
9513 }
9514 }
9515};
9516} // end anonymous namespace
9517
9518/// Get an lvalue to a field of a lambda's closure type.
9519static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
9520 const CXXMethodDecl *MD, const FieldDecl *FD,
9521 bool LValueToRValueConversion) {
9522 // Static lambda function call operators can't have captures. We already
9523 // diagnosed this, so bail out here.
9524 if (MD->isStatic()) {
9525 assert(Info.CurrentCall->This == nullptr &&
9526 "This should not be set for a static call operator");
9527 return false;
9528 }
9529
9530 // Start with 'Result' referring to the complete closure object...
9532 // Self may be passed by reference or by value.
9533 const ParmVarDecl *Self = MD->getParamDecl(0);
9534 if (Self->getType()->isReferenceType()) {
9535 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
9536 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
9537 Result.setFrom(Info.Ctx, *RefValue);
9538 } else {
9539 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
9540 CallStackFrame *Frame =
9541 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9542 .first;
9543 unsigned Version = Info.CurrentCall->Arguments.Version;
9544 Result.set({VD, Frame->Index, Version});
9545 }
9546 } else
9547 Result = *Info.CurrentCall->This;
9548
9549 // ... then update it to refer to the field of the closure object
9550 // that represents the capture.
9551 if (!HandleLValueMember(Info, E, Result, FD))
9552 return false;
9553
9554 // And if the field is of reference type (or if we captured '*this' by
9555 // reference), update 'Result' to refer to what
9556 // the field refers to.
9557 if (LValueToRValueConversion) {
9558 APValue RVal;
9559 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
9560 return false;
9561 Result.setFrom(Info.Ctx, RVal);
9562 }
9563 return true;
9564}
9565
9566/// Evaluate an expression as an lvalue. This can be legitimately called on
9567/// expressions which are not glvalues, in three cases:
9568/// * function designators in C, and
9569/// * "extern void" objects
9570/// * @selector() expressions in Objective-C
9571static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
9572 bool InvalidBaseOK) {
9573 assert(!E->isValueDependent());
9574 assert(E->isGLValue() || E->getType()->isFunctionType() ||
9576 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9577}
9578
9579bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
9580 const ValueDecl *D = E->getDecl();
9581
9582 // If we are within a lambda's call operator, check whether the 'VD' referred
9583 // to within 'E' actually represents a lambda-capture that maps to a
9584 // data-member/field within the closure object, and if so, evaluate to the
9585 // field or what the field refers to.
9586 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
9588 // We don't always have a complete capture-map when checking or inferring if
9589 // the function call operator meets the requirements of a constexpr function
9590 // - but we don't need to evaluate the captures to determine constexprness
9591 // (dcl.constexpr C++17).
9592 if (Info.checkingPotentialConstantExpression())
9593 return false;
9594
9595 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9596 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9597 return HandleLambdaCapture(Info, E, Result, MD, FD,
9598 FD->getType()->isReferenceType());
9599 }
9600 }
9601
9602 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9603 UnnamedGlobalConstantDecl>(D))
9604 return Success(cast<ValueDecl>(D));
9605 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9606 return VisitVarDecl(E, VD);
9607 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9608 return Visit(BD->getBinding());
9609 return Error(E);
9610}
9611
9612bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
9613 CallStackFrame *Frame = nullptr;
9614 unsigned Version = 0;
9615 if (VD->hasLocalStorage()) {
9616 // Only if a local variable was declared in the function currently being
9617 // evaluated, do we expect to be able to find its value in the current
9618 // frame. (Otherwise it was likely declared in an enclosing context and
9619 // could either have a valid evaluatable value (for e.g. a constexpr
9620 // variable) or be ill-formed (and trigger an appropriate evaluation
9621 // diagnostic)).
9622 CallStackFrame *CurrFrame = Info.CurrentCall;
9623 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
9624 // Function parameters are stored in some caller's frame. (Usually the
9625 // immediate caller, but for an inherited constructor they may be more
9626 // distant.)
9627 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9628 if (CurrFrame->Arguments) {
9629 VD = CurrFrame->Arguments.getOrigParam(PVD);
9630 Frame =
9631 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9632 Version = CurrFrame->Arguments.Version;
9633 }
9634 } else {
9635 Frame = CurrFrame;
9636 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9637 }
9638 }
9639 }
9640
9641 if (!VD->getType()->isReferenceType()) {
9642 if (Frame) {
9643 Result.set({VD, Frame->Index, Version});
9644 return true;
9645 }
9646 return Success(VD);
9647 }
9648
9649 if (!Info.getLangOpts().CPlusPlus11) {
9650 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9651 << VD << VD->getType();
9652 Info.Note(VD->getLocation(), diag::note_declared_at);
9653 }
9654
9655 APValue *V;
9656 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
9657 return false;
9658
9659 if (!V) {
9660 Result.set(VD);
9661 Result.AllowConstexprUnknown = true;
9662 return true;
9663 }
9664
9665 return Success(*V, E);
9666}
9667
9668bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
9669 if (!IsConstantEvaluatedBuiltinCall(E))
9670 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9671
9672 switch (E->getBuiltinCallee()) {
9673 default:
9674 return false;
9675 case Builtin::BIas_const:
9676 case Builtin::BIforward:
9677 case Builtin::BIforward_like:
9678 case Builtin::BImove:
9679 case Builtin::BImove_if_noexcept:
9680 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9681 return Visit(E->getArg(0));
9682 break;
9683 }
9684
9685 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9686}
9687
9688bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9689 const MaterializeTemporaryExpr *E) {
9690 // Walk through the expression to find the materialized temporary itself.
9693 const Expr *Inner =
9694 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9695
9696 // If we passed any comma operators, evaluate their LHSs.
9697 for (const Expr *E : CommaLHSs)
9698 if (!EvaluateIgnoredValue(Info, E))
9699 return false;
9700
9701 // A materialized temporary with static storage duration can appear within the
9702 // result of a constant expression evaluation, so we need to preserve its
9703 // value for use outside this evaluation.
9704 APValue *Value;
9705 if (E->getStorageDuration() == SD_Static) {
9706 if (Info.EvalMode == EvaluationMode::ConstantFold)
9707 return false;
9708 // FIXME: What about SD_Thread?
9709 Value = E->getOrCreateValue(true);
9710 *Value = APValue();
9711 Result.set(E);
9712 } else {
9713 Value = &Info.CurrentCall->createTemporary(
9714 E, Inner->getType(),
9715 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9716 : ScopeKind::Block,
9717 Result);
9718 }
9719
9720 QualType Type = Inner->getType();
9721
9722 // Materialize the temporary itself.
9723 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9724 *Value = APValue();
9725 return false;
9726 }
9727
9728 // Adjust our lvalue to refer to the desired subobject.
9729 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9730 --I;
9731 switch (Adjustments[I].Kind) {
9733 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9734 Type, Result))
9735 return false;
9736 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9737 break;
9738
9740 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9741 return false;
9742 Type = Adjustments[I].Field->getType();
9743 break;
9744
9746 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9747 Adjustments[I].Ptr.RHS))
9748 return false;
9749 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9750 break;
9751 }
9752 }
9753
9754 return true;
9755}
9756
9757bool
9758LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9759 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9760 "lvalue compound literal in c++?");
9761 APValue *Lit;
9762 // If CompountLiteral has static storage, its value can be used outside
9763 // this expression. So evaluate it once and store it in ASTContext.
9764 if (E->hasStaticStorage()) {
9765 Lit = &E->getOrCreateStaticValue(Info.Ctx);
9766 Result.set(E);
9767 // Reset any previously evaluated state, otherwise evaluation below might
9768 // fail.
9769 // FIXME: Should we just re-use the previously evaluated value instead?
9770 *Lit = APValue();
9771 } else {
9772 assert(!Info.getLangOpts().CPlusPlus);
9773 Lit = &Info.CurrentCall->createTemporary(E, E->getInitializer()->getType(),
9774 ScopeKind::Block, Result);
9775 }
9776 // FIXME: Evaluating in place isn't always right. We should figure out how to
9777 // use appropriate evaluation context here, see
9778 // clang/test/AST/static-compound-literals-reeval.cpp for a failure.
9779 if (!EvaluateInPlace(*Lit, Info, Result, E->getInitializer())) {
9780 *Lit = APValue();
9781 return false;
9782 }
9783 return true;
9784}
9785
9786bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9787 TypeInfoLValue TypeInfo;
9788
9789 if (!E->isPotentiallyEvaluated()) {
9790 if (E->isTypeOperand())
9791 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9792 else
9793 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9794 } else {
9795 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9796 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9797 << E->getExprOperand()->getType()
9798 << E->getExprOperand()->getSourceRange();
9799 }
9800
9801 if (!Visit(E->getExprOperand()))
9802 return false;
9803
9804 std::optional<DynamicType> DynType =
9806 if (!DynType)
9807 return false;
9808
9809 TypeInfo = TypeInfoLValue(
9810 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9811 }
9812
9813 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9814}
9815
9816bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9817 return Success(E->getGuidDecl());
9818}
9819
9820bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9821 // Handle static data members.
9822 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9823 VisitIgnoredBaseExpression(E->getBase());
9824 return VisitVarDecl(E, VD);
9825 }
9826
9827 // Handle static member functions.
9828 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9829 if (MD->isStatic()) {
9830 VisitIgnoredBaseExpression(E->getBase());
9831 return Success(MD);
9832 }
9833 }
9834
9835 // Handle non-static data members.
9836 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9837}
9838
9839bool LValueExprEvaluator::VisitExtVectorElementExpr(
9840 const ExtVectorElementExpr *E) {
9841 bool Success = true;
9842
9843 APValue Val;
9844 if (!Evaluate(Val, Info, E->getBase())) {
9845 if (!Info.noteFailure())
9846 return false;
9847 Success = false;
9848 }
9849
9851 E->getEncodedElementAccess(Indices);
9852 // FIXME: support accessing more than one element
9853 if (Indices.size() > 1)
9854 return false;
9855
9856 if (Success) {
9857 Result.setFrom(Info.Ctx, Val);
9858 QualType BaseType = E->getBase()->getType();
9859 if (E->isArrow())
9860 BaseType = BaseType->getPointeeType();
9861 const auto *VT = BaseType->castAs<VectorType>();
9862 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9863 VT->getNumElements(), Indices[0]);
9864 }
9865
9866 return Success;
9867}
9868
9869bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9870 if (E->getBase()->getType()->isSveVLSBuiltinType())
9871 return Error(E);
9872
9873 APSInt Index;
9874 bool Success = true;
9875
9876 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9877 APValue Val;
9878 if (!Evaluate(Val, Info, E->getBase())) {
9879 if (!Info.noteFailure())
9880 return false;
9881 Success = false;
9882 }
9883
9884 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9885 if (!Info.noteFailure())
9886 return false;
9887 Success = false;
9888 }
9889
9890 if (Success) {
9891 Result.setFrom(Info.Ctx, Val);
9892 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9893 VT->getNumElements(), Index.getZExtValue());
9894 }
9895
9896 return Success;
9897 }
9898
9899 // C++17's rules require us to evaluate the LHS first, regardless of which
9900 // side is the base.
9901 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9902 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9903 : !EvaluateInteger(SubExpr, Index, Info)) {
9904 if (!Info.noteFailure())
9905 return false;
9906 Success = false;
9907 }
9908 }
9909
9910 return Success &&
9911 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9912}
9913
9914bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9915 bool Success = evaluatePointer(E->getSubExpr(), Result);
9916 // [C++26][expr.unary.op]
9917 // If the operand points to an object or function, the result
9918 // denotes that object or function; otherwise, the behavior is undefined.
9919 // Because &(*(type*)0) is a common pattern, we do not fail the evaluation
9920 // immediately.
9922 return Success;
9924 E->getType())) ||
9925 Info.noteUndefinedBehavior();
9926}
9927
9928bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9929 if (!Visit(E->getSubExpr()))
9930 return false;
9931 // __real is a no-op on scalar lvalues.
9932 if (E->getSubExpr()->getType()->isAnyComplexType())
9933 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9934 return true;
9935}
9936
9937bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9938 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9939 "lvalue __imag__ on scalar?");
9940 if (!Visit(E->getSubExpr()))
9941 return false;
9942 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9943 return true;
9944}
9945
9946bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9947 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9948 return Error(UO);
9949
9950 if (!this->Visit(UO->getSubExpr()))
9951 return false;
9952
9953 return handleIncDec(
9954 this->Info, UO, Result, UO->getSubExpr()->getType(),
9955 UO->isIncrementOp(), nullptr);
9956}
9957
9958bool LValueExprEvaluator::VisitCompoundAssignOperator(
9959 const CompoundAssignOperator *CAO) {
9960 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9961 return Error(CAO);
9962
9963 bool Success = true;
9964
9965 // C++17 onwards require that we evaluate the RHS first.
9966 APValue RHS;
9967 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9968 if (!Info.noteFailure())
9969 return false;
9970 Success = false;
9971 }
9972
9973 // The overall lvalue result is the result of evaluating the LHS.
9974 if (!this->Visit(CAO->getLHS()) || !Success)
9975 return false;
9976
9978 this->Info, CAO,
9979 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9980 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9981}
9982
9983bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9984 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9985 return Error(E);
9986
9987 bool Success = true;
9988
9989 // C++17 onwards require that we evaluate the RHS first.
9990 APValue NewVal;
9991 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9992 if (!Info.noteFailure())
9993 return false;
9994 Success = false;
9995 }
9996
9997 if (!this->Visit(E->getLHS()) || !Success)
9998 return false;
9999
10000 if (Info.getLangOpts().CPlusPlus20 &&
10002 return false;
10003
10004 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
10005 NewVal);
10006}
10007
10008//===----------------------------------------------------------------------===//
10009// Pointer Evaluation
10010//===----------------------------------------------------------------------===//
10011
10012/// Convenience function. LVal's base must be a call to an alloc_size
10013/// function.
10015 const LValue &LVal,
10016 llvm::APInt &Result) {
10017 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10018 "Can't get the size of a non alloc_size function");
10019 const auto *Base = LVal.getLValueBase().get<const Expr *>();
10020 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
10021 std::optional<llvm::APInt> Size =
10022 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
10023 if (!Size)
10024 return false;
10025
10026 Result = std::move(*Size);
10027 return true;
10028}
10029
10030/// Attempts to evaluate the given LValueBase as the result of a call to
10031/// a function with the alloc_size attribute. If it was possible to do so, this
10032/// function will return true, make Result's Base point to said function call,
10033/// and mark Result's Base as invalid.
10035 LValue &Result) {
10036 if (Base.isNull())
10037 return false;
10038
10039 // Because we do no form of static analysis, we only support const variables.
10040 //
10041 // Additionally, we can't support parameters, nor can we support static
10042 // variables (in the latter case, use-before-assign isn't UB; in the former,
10043 // we have no clue what they'll be assigned to).
10044 const auto *VD =
10045 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
10046 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
10047 return false;
10048
10049 const Expr *Init = VD->getAnyInitializer();
10050 if (!Init || Init->getType().isNull())
10051 return false;
10052
10053 const Expr *E = Init->IgnoreParens();
10054 if (!tryUnwrapAllocSizeCall(E))
10055 return false;
10056
10057 // Store E instead of E unwrapped so that the type of the LValue's base is
10058 // what the user wanted.
10059 Result.setInvalid(E);
10060
10061 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
10062 Result.addUnsizedArray(Info, E, Pointee);
10063 return true;
10064}
10065
10066namespace {
10067class PointerExprEvaluator
10068 : public ExprEvaluatorBase<PointerExprEvaluator> {
10069 LValue &Result;
10070 bool InvalidBaseOK;
10071
10072 bool Success(const Expr *E) {
10073 Result.set(E);
10074 return true;
10075 }
10076
10077 bool evaluateLValue(const Expr *E, LValue &Result) {
10078 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
10079 }
10080
10081 bool evaluatePointer(const Expr *E, LValue &Result) {
10082 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
10083 }
10084
10085 bool visitNonBuiltinCallExpr(const CallExpr *E);
10086public:
10087
10088 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
10089 : ExprEvaluatorBaseTy(info), Result(Result),
10090 InvalidBaseOK(InvalidBaseOK) {}
10091
10092 bool Success(const APValue &V, const Expr *E) {
10093 Result.setFrom(Info.Ctx, V);
10094 return true;
10095 }
10096 bool ZeroInitialization(const Expr *E) {
10097 Result.setNull(Info.Ctx, E->getType());
10098 return true;
10099 }
10100
10101 bool VisitBinaryOperator(const BinaryOperator *E);
10102 bool VisitCastExpr(const CastExpr* E);
10103 bool VisitUnaryAddrOf(const UnaryOperator *E);
10104 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
10105 { return Success(E); }
10106 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
10108 return Success(E);
10109 if (Info.noteFailure())
10110 EvaluateIgnoredValue(Info, E->getSubExpr());
10111 return Error(E);
10112 }
10113 bool VisitObjCArrayLiteral(const ObjCArrayLiteral *E) {
10114 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
10115 }
10116 bool VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E) {
10117 return E->isExpressibleAsConstantInitializer() ? Success(E) : Error(E);
10118 }
10119 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
10120 { return Success(E); }
10121 bool VisitCallExpr(const CallExpr *E);
10122 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10123 bool VisitBlockExpr(const BlockExpr *E) {
10124 if (!E->getBlockDecl()->hasCaptures())
10125 return Success(E);
10126 return Error(E);
10127 }
10128 bool VisitCXXThisExpr(const CXXThisExpr *E) {
10129 auto DiagnoseInvalidUseOfThis = [&] {
10130 if (Info.getLangOpts().CPlusPlus11)
10131 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
10132 else
10133 Info.FFDiag(E);
10134 };
10135
10136 // Can't look at 'this' when checking a potential constant expression.
10137 if (Info.checkingPotentialConstantExpression())
10138 return false;
10139
10140 bool IsExplicitLambda =
10141 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
10142 if (!IsExplicitLambda) {
10143 if (!Info.CurrentCall->This) {
10144 DiagnoseInvalidUseOfThis();
10145 return false;
10146 }
10147
10148 Result = *Info.CurrentCall->This;
10149 }
10150
10151 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
10152 // Ensure we actually have captured 'this'. If something was wrong with
10153 // 'this' capture, the error would have been previously reported.
10154 // Otherwise we can be inside of a default initialization of an object
10155 // declared by lambda's body, so no need to return false.
10156 if (!Info.CurrentCall->LambdaThisCaptureField) {
10157 if (IsExplicitLambda && !Info.CurrentCall->This) {
10158 DiagnoseInvalidUseOfThis();
10159 return false;
10160 }
10161
10162 return true;
10163 }
10164
10165 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
10166 return HandleLambdaCapture(
10167 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
10168 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
10169 }
10170 return true;
10171 }
10172
10173 bool VisitCXXNewExpr(const CXXNewExpr *E);
10174
10175 bool VisitSourceLocExpr(const SourceLocExpr *E) {
10176 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
10177 APValue LValResult = E->EvaluateInContext(
10178 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10179 Result.setFrom(Info.Ctx, LValResult);
10180 return true;
10181 }
10182
10183 bool VisitEmbedExpr(const EmbedExpr *E) {
10184 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
10185 return true;
10186 }
10187
10188 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
10189 std::string ResultStr = E->ComputeName(Info.Ctx);
10190
10191 QualType CharTy = Info.Ctx.CharTy.withConst();
10192 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
10193 ResultStr.size() + 1);
10194 QualType ArrayTy = Info.Ctx.getConstantArrayType(
10195 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
10196
10197 StringLiteral *SL =
10198 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
10199 /*Pascal*/ false, ArrayTy, E->getLocation());
10200
10201 evaluateLValue(SL, Result);
10202 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
10203 return true;
10204 }
10205
10206 // FIXME: Missing: @protocol, @selector
10207};
10208} // end anonymous namespace
10209
10210static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
10211 bool InvalidBaseOK) {
10212 assert(!E->isValueDependent());
10213 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
10214 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
10215}
10216
10217bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10218 if (E->getOpcode() != BO_Add &&
10219 E->getOpcode() != BO_Sub)
10220 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10221
10222 const Expr *PExp = E->getLHS();
10223 const Expr *IExp = E->getRHS();
10224 if (IExp->getType()->isPointerType())
10225 std::swap(PExp, IExp);
10226
10227 bool EvalPtrOK = evaluatePointer(PExp, Result);
10228 if (!EvalPtrOK && !Info.noteFailure())
10229 return false;
10230
10231 llvm::APSInt Offset;
10232 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
10233 return false;
10234
10235 if (E->getOpcode() == BO_Sub)
10236 negateAsSigned(Offset);
10237
10238 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
10239 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
10240}
10241
10242bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10243 // [C11 6.5.3.2p3]: if the operand of '&' is the result of a unary '*'
10244 // operator, neither operator is evaluated and the result is as if both were
10245 // omitted (except that the operators' constraints, already enforced by Sema,
10246 // still apply, and the result is not an lvalue). So '&*p' is just the pointer
10247 // value 'p' with no dereference, and forming it is therefore not undefined
10248 // behavior even when 'p' is null, e.g. '&*(int *)0'. Evaluate the pointer
10249 // operand directly so we don't spuriously diagnose a null dereference.
10250 if (!Info.getLangOpts().CPlusPlus) {
10251 const Expr *Sub = E->getSubExpr()->IgnoreParens();
10252 if (const auto *Deref = dyn_cast<UnaryOperator>(Sub);
10253 Deref && Deref->getOpcode() == UO_Deref)
10254 return evaluatePointer(Deref->getSubExpr(), Result);
10255 }
10256 return evaluateLValue(E->getSubExpr(), Result);
10257}
10258
10259// Is the provided decl 'std::source_location::current'?
10261 if (!FD)
10262 return false;
10263 const IdentifierInfo *FnII = FD->getIdentifier();
10264 if (!FnII || !FnII->isStr("current"))
10265 return false;
10266
10267 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
10268 if (!RD)
10269 return false;
10270
10271 const IdentifierInfo *ClassII = RD->getIdentifier();
10272 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
10273}
10274
10275bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10276 const Expr *SubExpr = E->getSubExpr();
10277
10278 switch (E->getCastKind()) {
10279 default:
10280 break;
10281 case CK_BitCast:
10282 case CK_CPointerToObjCPointerCast:
10283 case CK_BlockPointerToObjCPointerCast:
10284 case CK_AnyPointerToBlockPointerCast:
10285 case CK_AddressSpaceConversion:
10286 if (!Visit(SubExpr))
10287 return false;
10288 if (E->getType()->isFunctionPointerType() ||
10289 SubExpr->getType()->isFunctionPointerType()) {
10290 // Casting between two function pointer types, or between a function
10291 // pointer and an object pointer, is always a reinterpret_cast.
10292 CCEDiag(E, diag::note_constexpr_invalid_cast)
10293 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10294 << Info.Ctx.getLangOpts().CPlusPlus;
10295 Result.Designator.setInvalid();
10296 } else if (!E->getType()->isVoidPointerType()) {
10297 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
10298 // permitted in constant expressions in C++11. Bitcasts from cv void* are
10299 // also static_casts, but we disallow them as a resolution to DR1312.
10300 //
10301 // In some circumstances, we permit casting from void* to cv1 T*, when the
10302 // actual pointee object is actually a cv2 T.
10303 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
10304 !Result.IsNullPtr;
10305 bool VoidPtrCastMaybeOK =
10306 Result.IsNullPtr ||
10307 (HasValidResult &&
10308 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
10309 E->getType()->getPointeeType()));
10310 // 1. We'll allow it in std::allocator::allocate, and anything which that
10311 // calls.
10312 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
10313 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
10314 // We'll allow it in the body of std::source_location::current. GCC's
10315 // implementation had a parameter of type `void*`, and casts from
10316 // that back to `const __impl*` in its body.
10317 if (VoidPtrCastMaybeOK &&
10318 (Info.getStdAllocatorCaller("allocate") ||
10319 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
10320 Info.getLangOpts().CPlusPlus26)) {
10321 // Permitted.
10322 } else {
10323 if (SubExpr->getType()->isVoidPointerType() &&
10324 Info.getLangOpts().CPlusPlus) {
10325 if (HasValidResult)
10326 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10327 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
10328 << Result.Designator.getType(Info.Ctx).getCanonicalType()
10329 << E->getType()->getPointeeType();
10330 else
10331 CCEDiag(E, diag::note_constexpr_invalid_cast)
10332 << diag::ConstexprInvalidCastKind::CastFrom
10333 << SubExpr->getType();
10334 } else
10335 CCEDiag(E, diag::note_constexpr_invalid_cast)
10336 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10337 << Info.Ctx.getLangOpts().CPlusPlus;
10338 Result.Designator.setInvalid();
10339 }
10340 }
10341 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
10342 ZeroInitialization(E);
10343 return true;
10344
10345 case CK_DerivedToBase:
10346 case CK_UncheckedDerivedToBase:
10347 if (!evaluatePointer(E->getSubExpr(), Result))
10348 return false;
10349 if (!Result.Base && Result.Offset.isZero())
10350 return true;
10351
10352 // Now figure out the necessary offset to add to the base LV to get from
10353 // the derived class to the base class.
10354 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
10355 castAs<PointerType>()->getPointeeType(),
10356 Result);
10357
10358 case CK_BaseToDerived:
10359 if (!Visit(E->getSubExpr()))
10360 return false;
10361 if (!Result.Base && Result.Offset.isZero())
10362 return true;
10363 return HandleBaseToDerivedCast(Info, E, Result);
10364
10365 case CK_Dynamic:
10366 if (!Visit(E->getSubExpr()))
10367 return false;
10369
10370 case CK_NullToPointer:
10371 VisitIgnoredValue(E->getSubExpr());
10372 return ZeroInitialization(E);
10373
10374 case CK_IntegralToPointer: {
10375 CCEDiag(E, diag::note_constexpr_invalid_cast)
10376 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10377 << Info.Ctx.getLangOpts().CPlusPlus;
10378
10379 APValue Value;
10380 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
10381 break;
10382
10383 if (Value.isInt()) {
10384 unsigned Size = Info.Ctx.getTypeSize(E->getType());
10385 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
10386 if (N == Info.Ctx.getTargetNullPointerValue(E->getType())) {
10387 Result.setNull(Info.Ctx, E->getType());
10388 } else {
10389 Result.Base = (Expr *)nullptr;
10390 Result.InvalidBase = false;
10391 Result.Offset = CharUnits::fromQuantity(N);
10392 Result.Designator.setInvalid();
10393 Result.IsNullPtr = false;
10394 }
10395 return true;
10396 } else {
10397 // In rare instances, the value isn't an lvalue.
10398 // For example, when the value is the difference between the addresses of
10399 // two labels. We reject that as a constant expression because we can't
10400 // compute a valid offset to convert into a pointer.
10401 if (!Value.isLValue())
10402 return false;
10403
10404 // Cast is of an lvalue, no need to change value.
10405 Result.setFrom(Info.Ctx, Value);
10406 return true;
10407 }
10408 }
10409
10410 case CK_ArrayToPointerDecay: {
10411 if (SubExpr->isGLValue()) {
10412 if (!evaluateLValue(SubExpr, Result))
10413 return false;
10414 } else {
10415 APValue &Value = Info.CurrentCall->createTemporary(
10416 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
10417 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
10418 return false;
10419 }
10420 // The result is a pointer to the first element of the array.
10421 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
10422 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
10423 Result.addArray(Info, E, CAT);
10424 else
10425 Result.addUnsizedArray(Info, E, AT->getElementType());
10426 return true;
10427 }
10428
10429 case CK_FunctionToPointerDecay:
10430 return evaluateLValue(SubExpr, Result);
10431
10432 case CK_LValueToRValue: {
10433 LValue LVal;
10434 if (!evaluateLValue(E->getSubExpr(), LVal))
10435 return false;
10436
10437 APValue RVal;
10438 // Note, we use the subexpression's type in order to retain cv-qualifiers.
10440 LVal, RVal))
10441 return InvalidBaseOK &&
10442 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
10443 return Success(RVal, E);
10444 }
10445 }
10446
10447 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10448}
10449
10451 UnaryExprOrTypeTrait ExprKind) {
10452 // C++ [expr.alignof]p3:
10453 // When alignof is applied to a reference type, the result is the
10454 // alignment of the referenced type.
10455 T = T.getNonReferenceType();
10456
10457 if (T.getQualifiers().hasUnaligned())
10458 return CharUnits::One();
10459
10460 const bool AlignOfReturnsPreferred =
10461 Ctx.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver7);
10462
10463 // __alignof is defined to return the preferred alignment.
10464 // Before 8, clang returned the preferred alignment for alignof and _Alignof
10465 // as well.
10466 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10467 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
10468 // alignof and _Alignof are defined to return the ABI alignment.
10469 else if (ExprKind == UETT_AlignOf)
10470 return Ctx.getTypeAlignInChars(T.getTypePtr());
10471 else
10472 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
10473}
10474
10475// Convert a builtin ID to the canonical x86 builtin ID the constant evaluators
10476// dispatch on in their x86 target-specific cases, or 0 if \p BuiltinOp is a
10477// target builtin those cases should not handle.
10478//
10479// Target-independent builtins are returned unchanged. Target builtin IDs of
10480// different targets overlap (each target numbers its builtins from
10481// Builtin::FirstTSBuiltin), so a target builtin ID is only meaningful for the
10482// target that owns it. Determine the owning target (translating an auxiliary ID
10483// back to its canonical value) and only return the ID when x86 owns it;
10484// otherwise an overlapping ID could be misinterpreted as an unrelated x86
10485// builtin.
10487 unsigned BuiltinOp) {
10488 // Target-independent builtins have the same ID regardless of the target, so
10489 // they can be dispatched as-is. This is the common case and is intentionally
10490 // kept to a single comparison so callers can use this on hot paths (e.g. the
10491 // bytecode interpreter's builtin dispatch) without re-deriving the ID from
10492 // the call expression.
10493 if (BuiltinOp < Builtin::FirstTSBuiltin)
10494 return BuiltinOp;
10495
10496 // Determine the target that owns this builtin, translating an auxiliary ID
10497 // back to its canonical value.
10498 const TargetInfo *OwningTarget;
10499 if (Ctx.BuiltinInfo.isAuxBuiltinID(BuiltinOp)) {
10500 OwningTarget = Ctx.getAuxTargetInfo();
10501 BuiltinOp = Ctx.BuiltinInfo.getAuxBuiltinID(BuiltinOp);
10502 } else {
10503 OwningTarget = &Ctx.getTargetInfo();
10504 }
10505
10506 if (!OwningTarget)
10507 return 0;
10508
10509 // x86 and x86_64 share a single builtin set and are the only architectures
10510 // whose target-specific builtins the constant evaluators currently fold.
10511 switch (OwningTarget->getTriple().getArch()) {
10512 case llvm::Triple::x86:
10513 case llvm::Triple::x86_64:
10514 return BuiltinOp;
10515 default:
10516 return 0;
10517 }
10518}
10519
10521 const CallExpr *E) {
10523}
10524
10526 UnaryExprOrTypeTrait ExprKind) {
10527 E = E->IgnoreParens();
10528
10529 // The kinds of expressions that we have special-case logic here for
10530 // should be kept up to date with the special checks for those
10531 // expressions in Sema.
10532
10533 // alignof decl is always accepted, even if it doesn't make sense: we default
10534 // to 1 in those cases.
10535 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10536 return Ctx.getDeclAlign(DRE->getDecl(),
10537 /*RefAsPointee*/ true);
10538
10539 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10540 return Ctx.getDeclAlign(ME->getMemberDecl(),
10541 /*RefAsPointee*/ true);
10542
10543 return GetAlignOfType(Ctx, E->getType(), ExprKind);
10544}
10545
10546static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
10547 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
10548 return Info.Ctx.getDeclAlign(VD);
10549 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
10550 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
10551 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
10552}
10553
10554/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
10555/// __builtin_is_aligned and __builtin_assume_aligned.
10556static bool getAlignmentArgument(const Expr *E, QualType ForType,
10557 EvalInfo &Info, APSInt &Alignment) {
10558 if (!EvaluateInteger(E, Alignment, Info))
10559 return false;
10560 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10561 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10562 return false;
10563 }
10564 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10565 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10566 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10567 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10568 << MaxValue << ForType << Alignment;
10569 return false;
10570 }
10571 // Ensure both alignment and source value have the same bit width so that we
10572 // don't assert when computing the resulting value.
10573 APSInt ExtAlignment =
10574 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
10575 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10576 "Alignment should not be changed by ext/trunc");
10577 Alignment = ExtAlignment;
10578 assert(Alignment.getBitWidth() == SrcWidth);
10579 return true;
10580}
10581
10582// To be clear: this happily visits unsupported builtins. Better name welcomed.
10583bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
10584 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10585 return true;
10586
10587 if (!(InvalidBaseOK && E->getCalleeAllocSizeAttr()))
10588 return false;
10589
10590 Result.setInvalid(E);
10591 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
10592 Result.addUnsizedArray(Info, E, PointeeTy);
10593 return true;
10594}
10595
10596bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
10597 if (!IsConstantEvaluatedBuiltinCall(E))
10598 return visitNonBuiltinCallExpr(E);
10599 return VisitBuiltinCallExpr(E, ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E));
10600}
10601
10602// Determine if T is a character type for which we guarantee that
10603// sizeof(T) == 1.
10605 return T->isCharType() || T->isChar8Type();
10606}
10607
10608bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10609 unsigned BuiltinOp) {
10610 if (IsOpaqueConstantCall(E))
10611 return Success(E);
10612
10613 switch (BuiltinOp) {
10614 case Builtin::BIaddressof:
10615 case Builtin::BI__addressof:
10616 case Builtin::BI__builtin_addressof:
10617 return evaluateLValue(E->getArg(0), Result);
10618 case Builtin::BI__builtin_assume_aligned: {
10619 // We need to be very careful here because: if the pointer does not have the
10620 // asserted alignment, then the behavior is undefined, and undefined
10621 // behavior is non-constant.
10622 if (!evaluatePointer(E->getArg(0), Result))
10623 return false;
10624
10625 LValue OffsetResult(Result);
10626 APSInt Alignment;
10627 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10628 Alignment))
10629 return false;
10630 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
10631
10632 if (E->getNumArgs() > 2) {
10633 APSInt Offset;
10634 if (!EvaluateInteger(E->getArg(2), Offset, Info))
10635 return false;
10636
10637 int64_t AdditionalOffset = -Offset.getZExtValue();
10638 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
10639 }
10640
10641 // If there is a base object, then it must have the correct alignment.
10642 if (OffsetResult.Base) {
10643 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
10644
10645 if (BaseAlignment < Align) {
10646 Result.Designator.setInvalid();
10647 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10648 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
10649 return false;
10650 }
10651 }
10652
10653 // The offset must also have the correct alignment.
10654 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10655 Result.Designator.setInvalid();
10656
10657 (OffsetResult.Base
10658 ? CCEDiag(E->getArg(0),
10659 diag::note_constexpr_baa_insufficient_alignment)
10660 << 1
10661 : CCEDiag(E->getArg(0),
10662 diag::note_constexpr_baa_value_insufficient_alignment))
10663 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
10664 return false;
10665 }
10666
10667 return true;
10668 }
10669 case Builtin::BI__builtin_align_up:
10670 case Builtin::BI__builtin_align_down: {
10671 if (!evaluatePointer(E->getArg(0), Result))
10672 return false;
10673 APSInt Alignment;
10674 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
10675 Alignment))
10676 return false;
10677 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
10678 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
10679 // For align_up/align_down, we can return the same value if the alignment
10680 // is known to be greater or equal to the requested value.
10681 if (PtrAlign.getQuantity() >= Alignment)
10682 return true;
10683
10684 // The alignment could be greater than the minimum at run-time, so we cannot
10685 // infer much about the resulting pointer value. One case is possible:
10686 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
10687 // can infer the correct index if the requested alignment is smaller than
10688 // the base alignment so we can perform the computation on the offset.
10689 if (BaseAlignment.getQuantity() >= Alignment) {
10690 assert(Alignment.getBitWidth() <= 64 &&
10691 "Cannot handle > 64-bit address-space");
10692 uint64_t Alignment64 = Alignment.getZExtValue();
10693 CharUnits NewOffset = CharUnits::fromQuantity(
10694 BuiltinOp == Builtin::BI__builtin_align_down
10695 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
10696 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
10697 Result.adjustOffset(NewOffset - Result.Offset);
10698 // TODO: diagnose out-of-bounds values/only allow for arrays?
10699 return true;
10700 }
10701 // Otherwise, we cannot constant-evaluate the result.
10702 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
10703 << Alignment;
10704 return false;
10705 }
10706 case Builtin::BI__builtin_operator_new:
10707 return HandleOperatorNewCall(Info, E, Result);
10708 case Builtin::BI__builtin_launder:
10709 return evaluatePointer(E->getArg(0), Result);
10710 case Builtin::BIstrchr:
10711 case Builtin::BIwcschr:
10712 case Builtin::BImemchr:
10713 case Builtin::BIwmemchr:
10714 if (Info.getLangOpts().CPlusPlus11)
10715 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10716 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10717 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10718 else
10719 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10720 [[fallthrough]];
10721 case Builtin::BI__builtin_strchr:
10722 case Builtin::BI__builtin_wcschr:
10723 case Builtin::BI__builtin_memchr:
10724 case Builtin::BI__builtin_char_memchr:
10725 case Builtin::BI__builtin_wmemchr: {
10726 if (!Visit(E->getArg(0)))
10727 return false;
10728 APSInt Desired;
10729 if (!EvaluateInteger(E->getArg(1), Desired, Info))
10730 return false;
10731 uint64_t MaxLength = uint64_t(-1);
10732 if (BuiltinOp != Builtin::BIstrchr &&
10733 BuiltinOp != Builtin::BIwcschr &&
10734 BuiltinOp != Builtin::BI__builtin_strchr &&
10735 BuiltinOp != Builtin::BI__builtin_wcschr) {
10736 APSInt N;
10737 if (!EvaluateInteger(E->getArg(2), N, Info))
10738 return false;
10739 MaxLength = N.getZExtValue();
10740 }
10741 // We cannot find the value if there are no candidates to match against.
10742 if (MaxLength == 0u)
10743 return ZeroInitialization(E);
10744 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10745 Result.Designator.Invalid)
10746 return false;
10747 QualType CharTy = Result.Designator.getType(Info.Ctx);
10748 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10749 BuiltinOp == Builtin::BI__builtin_memchr;
10750 assert(IsRawByte ||
10751 Info.Ctx.hasSameUnqualifiedType(
10752 CharTy, E->getArg(0)->getType()->getPointeeType()));
10753 // Pointers to const void may point to objects of incomplete type.
10754 if (IsRawByte && CharTy->isIncompleteType()) {
10755 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10756 return false;
10757 }
10758 // Give up on byte-oriented matching against multibyte elements.
10759 // FIXME: We can compare the bytes in the correct order.
10760 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10761 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10762 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10763 return false;
10764 }
10765 // Figure out what value we're actually looking for (after converting to
10766 // the corresponding unsigned type if necessary).
10767 uint64_t DesiredVal;
10768 bool StopAtNull = false;
10769 switch (BuiltinOp) {
10770 case Builtin::BIstrchr:
10771 case Builtin::BI__builtin_strchr:
10772 // strchr compares directly to the passed integer, and therefore
10773 // always fails if given an int that is not a char.
10774 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10775 E->getArg(1)->getType(),
10776 Desired),
10777 Desired))
10778 return ZeroInitialization(E);
10779 StopAtNull = true;
10780 [[fallthrough]];
10781 case Builtin::BImemchr:
10782 case Builtin::BI__builtin_memchr:
10783 case Builtin::BI__builtin_char_memchr:
10784 // memchr compares by converting both sides to unsigned char. That's also
10785 // correct for strchr if we get this far (to cope with plain char being
10786 // unsigned in the strchr case).
10787 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10788 break;
10789
10790 case Builtin::BIwcschr:
10791 case Builtin::BI__builtin_wcschr:
10792 StopAtNull = true;
10793 [[fallthrough]];
10794 case Builtin::BIwmemchr:
10795 case Builtin::BI__builtin_wmemchr:
10796 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10797 DesiredVal = Desired.getZExtValue();
10798 break;
10799 }
10800
10801 for (; MaxLength; --MaxLength) {
10802 APValue Char;
10803 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10804 !Char.isInt())
10805 return false;
10806 if (Char.getInt().getZExtValue() == DesiredVal)
10807 return true;
10808 if (StopAtNull && !Char.getInt())
10809 break;
10810 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10811 return false;
10812 }
10813 // Not found: return nullptr.
10814 return ZeroInitialization(E);
10815 }
10816
10817 case Builtin::BImemcpy:
10818 case Builtin::BImemmove:
10819 case Builtin::BIwmemcpy:
10820 case Builtin::BIwmemmove:
10821 if (Info.getLangOpts().CPlusPlus11)
10822 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10823 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10824 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10825 else
10826 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10827 [[fallthrough]];
10828 case Builtin::BI__builtin_memcpy:
10829 case Builtin::BI__builtin_memmove:
10830 case Builtin::BI__builtin_wmemcpy:
10831 case Builtin::BI__builtin_wmemmove: {
10832 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10833 BuiltinOp == Builtin::BIwmemmove ||
10834 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10835 BuiltinOp == Builtin::BI__builtin_wmemmove;
10836 bool Move = BuiltinOp == Builtin::BImemmove ||
10837 BuiltinOp == Builtin::BIwmemmove ||
10838 BuiltinOp == Builtin::BI__builtin_memmove ||
10839 BuiltinOp == Builtin::BI__builtin_wmemmove;
10840
10841 // The result of mem* is the first argument.
10842 if (!Visit(E->getArg(0)))
10843 return false;
10844 LValue Dest = Result;
10845
10846 LValue Src;
10847 if (!EvaluatePointer(E->getArg(1), Src, Info))
10848 return false;
10849
10850 APSInt N;
10851 if (!EvaluateInteger(E->getArg(2), N, Info))
10852 return false;
10853 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10854
10855 // If the size is zero, we treat this as always being a valid no-op.
10856 // (Even if one of the src and dest pointers is null.)
10857 if (!N)
10858 return true;
10859
10860 // Otherwise, if either of the operands is null, we can't proceed. Don't
10861 // try to determine the type of the copied objects, because there aren't
10862 // any.
10863 if (!Src.Base || !Dest.Base) {
10864 APValue Val;
10865 (!Src.Base ? Src : Dest).moveInto(Val);
10866 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10867 << Move << WChar << !!Src.Base
10868 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10869 return false;
10870 }
10871 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10872 return false;
10873
10874 // We require that Src and Dest are both pointers to arrays of
10875 // trivially-copyable type. (For the wide version, the designator will be
10876 // invalid if the designated object is not a wchar_t.)
10877 QualType T = Dest.Designator.getType(Info.Ctx);
10878 QualType SrcT = Src.Designator.getType(Info.Ctx);
10879 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10880 // FIXME: Consider using our bit_cast implementation to support this.
10881 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10882 return false;
10883 }
10884 if (T->isIncompleteType()) {
10885 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10886 return false;
10887 }
10888 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10889 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10890 return false;
10891 }
10892
10893 // Figure out how many T's we're copying.
10894 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10895 if (TSize == 0)
10896 return false;
10897 if (!WChar) {
10898 uint64_t Remainder;
10899 llvm::APInt OrigN = N;
10900 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10901 if (Remainder) {
10902 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10903 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10904 << (unsigned)TSize;
10905 return false;
10906 }
10907 }
10908
10909 // Check that the copying will remain within the arrays, just so that we
10910 // can give a more meaningful diagnostic. This implicitly also checks that
10911 // N fits into 64 bits.
10912 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10913 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10914 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10915 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10916 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10917 << toString(N, 10, /*Signed*/false);
10918 return false;
10919 }
10920 uint64_t NElems = N.getZExtValue();
10921 uint64_t NBytes = NElems * TSize;
10922
10923 // Check for overlap.
10924 int Direction = 1;
10925 if (HasSameBase(Src, Dest)) {
10926 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10927 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10928 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10929 // Dest is inside the source region.
10930 if (!Move) {
10931 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10932 return false;
10933 }
10934 // For memmove and friends, copy backwards.
10935 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10936 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10937 return false;
10938 Direction = -1;
10939 } else if (!Move && SrcOffset >= DestOffset &&
10940 SrcOffset - DestOffset < NBytes) {
10941 // Src is inside the destination region for memcpy: invalid.
10942 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10943 return false;
10944 }
10945 }
10946
10947 while (true) {
10948 APValue Val;
10949 // FIXME: Set WantObjectRepresentation to true if we're copying a
10950 // char-like type?
10951 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10952 !handleAssignment(Info, E, Dest, T, Val))
10953 return false;
10954 // Do not iterate past the last element; if we're copying backwards, that
10955 // might take us off the start of the array.
10956 if (--NElems == 0)
10957 return true;
10958 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10959 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10960 return false;
10961 }
10962 }
10963
10964 default:
10965 return false;
10966 }
10967}
10968
10969static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10970 APValue &Result, const InitListExpr *ILE,
10971 QualType AllocType);
10972static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10973 APValue &Result,
10974 const CXXConstructExpr *CCE,
10975 QualType AllocType);
10976
10977bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10978 if (!Info.getLangOpts().CPlusPlus20)
10979 Info.CCEDiag(E, diag::note_constexpr_new);
10980
10981 // We cannot speculatively evaluate a delete expression.
10982 if (Info.SpeculativeEvaluationDepth)
10983 return false;
10984
10985 FunctionDecl *OperatorNew = E->getOperatorNew();
10986 QualType AllocType = E->getAllocatedType();
10987 QualType TargetType = AllocType;
10988
10989 bool IsNothrow = false;
10990 bool IsPlacement = false;
10991
10992 if (E->getNumPlacementArgs() == 1 &&
10993 E->getPlacementArg(0)->getType()->isNothrowT()) {
10994 // The only new-placement list we support is of the form (std::nothrow).
10995 //
10996 // FIXME: There is no restriction on this, but it's not clear that any
10997 // other form makes any sense. We get here for cases such as:
10998 //
10999 // new (std::align_val_t{N}) X(int)
11000 //
11001 // (which should presumably be valid only if N is a multiple of
11002 // alignof(int), and in any case can't be deallocated unless N is
11003 // alignof(X) and X has new-extended alignment).
11004 LValue Nothrow;
11005 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
11006 return false;
11007 IsNothrow = true;
11008 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
11009 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
11010 (Info.CurrentCall->CanEvalMSConstexpr &&
11011 OperatorNew->hasAttr<MSConstexprAttr>())) {
11012 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
11013 return false;
11014 if (Result.Designator.Invalid)
11015 return false;
11016 TargetType = E->getPlacementArg(0)->getType();
11017 IsPlacement = true;
11018 } else {
11019 Info.FFDiag(E, diag::note_constexpr_new_placement)
11020 << /*C++26 feature*/ 1 << E->getSourceRange();
11021 return false;
11022 }
11023 } else if (E->getNumPlacementArgs()) {
11024 Info.FFDiag(E, diag::note_constexpr_new_placement)
11025 << /*Unsupported*/ 0 << E->getSourceRange();
11026 return false;
11027 } else if (!OperatorNew
11028 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
11029 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
11030 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
11031 return false;
11032 }
11033
11034 const Expr *Init = E->getInitializer();
11035 const InitListExpr *ResizedArrayILE = nullptr;
11036 const CXXConstructExpr *ResizedArrayCCE = nullptr;
11037 bool ValueInit = false;
11038
11039 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
11040 const Expr *Stripped = *ArraySize;
11041 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
11042 Stripped = ICE->getSubExpr())
11043 if (ICE->getCastKind() != CK_NoOp &&
11044 ICE->getCastKind() != CK_IntegralCast)
11045 break;
11046
11047 llvm::APSInt ArrayBound;
11048 if (!EvaluateInteger(Stripped, ArrayBound, Info))
11049 return false;
11050
11051 // C++ [expr.new]p9:
11052 // The expression is erroneous if:
11053 // -- [...] its value before converting to size_t [or] applying the
11054 // second standard conversion sequence is less than zero
11055 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
11056 if (IsNothrow)
11057 return ZeroInitialization(E);
11058
11059 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
11060 << ArrayBound << (*ArraySize)->getSourceRange();
11061 return false;
11062 }
11063
11064 // -- its value is such that the size of the allocated object would
11065 // exceed the implementation-defined limit
11066 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
11068 Info.Ctx, AllocType, ArrayBound),
11069 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
11070 if (IsNothrow)
11071 return ZeroInitialization(E);
11072 return false;
11073 }
11074
11075 // -- the new-initializer is a braced-init-list and the number of
11076 // array elements for which initializers are provided [...]
11077 // exceeds the number of elements to initialize
11078 if (!Init) {
11079 // No initialization is performed.
11080 } else if (isa<CXXScalarValueInitExpr>(Init) ||
11082 ValueInit = true;
11083 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
11084 ResizedArrayCCE = CCE;
11085 } else {
11086 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
11087 assert(CAT && "unexpected type for array initializer");
11088
11089 unsigned Bits =
11090 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
11091 llvm::APInt InitBound = CAT->getSize().zext(Bits);
11092 llvm::APInt AllocBound = ArrayBound.zext(Bits);
11093 if (InitBound.ugt(AllocBound)) {
11094 if (IsNothrow)
11095 return ZeroInitialization(E);
11096
11097 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
11098 << toString(AllocBound, 10, /*Signed=*/false)
11099 << toString(InitBound, 10, /*Signed=*/false)
11100 << (*ArraySize)->getSourceRange();
11101 return false;
11102 }
11103
11104 // If the sizes differ, we must have an initializer list, and we need
11105 // special handling for this case when we initialize.
11106 if (InitBound != AllocBound)
11107 ResizedArrayILE = cast<InitListExpr>(Init);
11108 }
11109
11110 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
11111 ArraySizeModifier::Normal, 0);
11112 } else if (E->isArray()) {
11113 // We have an array new-expression whose array size could not be
11114 // determined, e.g. 'new int[]()', where the bound is neither given nor
11115 // deducible from the initializer. This is ill-formed and already
11116 // diagnosed, so bail out rather than mis-evaluating a scalar allocation
11117 // as an array (which would later crash the evaluator).
11118 return false;
11119 } else {
11120 assert(!AllocType->isArrayType() &&
11121 "array allocation with non-array new");
11122 }
11123
11124 APValue *Val;
11125 if (IsPlacement) {
11127 struct FindObjectHandler {
11128 EvalInfo &Info;
11129 const Expr *E;
11130 QualType AllocType;
11131 const AccessKinds AccessKind;
11132 APValue *Value;
11133
11134 typedef bool result_type;
11135 bool failed() { return false; }
11136 bool checkConst(QualType QT) {
11137 if (QT.isConstQualified()) {
11138 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
11139 return false;
11140 }
11141 return true;
11142 }
11143 bool found(APValue &Subobj, QualType SubobjType,
11144 APValue::LValueBase Base) {
11145 if (!checkConst(SubobjType))
11146 return false;
11147 // FIXME: Reject the cases where [basic.life]p8 would not permit the
11148 // old name of the object to be used to name the new object.
11149 if (!Info.Ctx.hasSimilarType(SubobjType, AllocType)) {
11150 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
11151 << SubobjType << AllocType;
11152 return false;
11153 }
11154 Value = &Subobj;
11155 return true;
11156 }
11157 bool found(APSInt &Value, QualType SubobjType) {
11158 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
11159 return false;
11160 }
11161 bool found(APFloat &Value, QualType SubobjType) {
11162 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
11163 return false;
11164 }
11165 } Handler = {Info, E, AllocType, AK, nullptr};
11166
11167 if (AllocType->isArrayType() &&
11168 Result.Designator.MostDerivedIsArrayElement &&
11169 Result.Designator.Entries.back().getAsArrayIndex() == 0) {
11170 // The destination of placement new is pointing to the first element
11171 // of an array. There's a special case in [expr.const]: "[...] if T is an
11172 // array type, to the first element of such an object [...]". Handle
11173 // that case here by dropping the last entry in the designator list.
11174 QualType AllocElementType =
11175 Info.Ctx.getAsArrayType(AllocType)->getElementType();
11176 if (Info.Ctx.hasSimilarType(AllocElementType,
11177 Result.Designator.MostDerivedType)) {
11178 Result.Designator.truncate(Info.Ctx, Result.Base,
11179 Result.Designator.MostDerivedPathLength - 1);
11180 }
11181 }
11182
11183 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
11184 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
11185 return false;
11186
11187 Val = Handler.Value;
11188
11189 // [basic.life]p1:
11190 // The lifetime of an object o of type T ends when [...] the storage
11191 // which the object occupies is [...] reused by an object that is not
11192 // nested within o (6.6.2).
11193 *Val = APValue();
11194 } else {
11195 // Perform the allocation and obtain a pointer to the resulting object.
11196 Val = Info.createHeapAlloc(E, AllocType, Result);
11197 if (!Val)
11198 return false;
11199 }
11200
11201 if (ValueInit) {
11202 ImplicitValueInitExpr VIE(AllocType);
11203 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
11204 return false;
11205 } else if (ResizedArrayILE) {
11206 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
11207 AllocType))
11208 return false;
11209 } else if (ResizedArrayCCE) {
11210 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
11211 AllocType))
11212 return false;
11213 } else if (Init) {
11214 if (!EvaluateInPlace(*Val, Info, Result, Init))
11215 return false;
11216 } else if (!handleDefaultInitValue(AllocType, *Val)) {
11217 return false;
11218 }
11219
11220 // Array new returns a pointer to the first element, not a pointer to the
11221 // array.
11222 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
11223 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
11224
11225 return true;
11226}
11227//===----------------------------------------------------------------------===//
11228// Member Pointer Evaluation
11229//===----------------------------------------------------------------------===//
11230
11231namespace {
11232class MemberPointerExprEvaluator
11233 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
11234 MemberPtr &Result;
11235
11236 bool Success(const ValueDecl *D) {
11237 Result = MemberPtr(D);
11238 return true;
11239 }
11240public:
11241
11242 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
11243 : ExprEvaluatorBaseTy(Info), Result(Result) {}
11244
11245 bool Success(const APValue &V, const Expr *E) {
11246 Result.setFrom(V);
11247 return true;
11248 }
11249 bool ZeroInitialization(const Expr *E) {
11250 return Success((const ValueDecl*)nullptr);
11251 }
11252
11253 bool VisitCastExpr(const CastExpr *E);
11254 bool VisitUnaryAddrOf(const UnaryOperator *E);
11255};
11256} // end anonymous namespace
11257
11258static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
11259 EvalInfo &Info) {
11260 assert(!E->isValueDependent());
11261 assert(E->isPRValue() && E->getType()->isMemberPointerType());
11262 return MemberPointerExprEvaluator(Info, Result).Visit(E);
11263}
11264
11265bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
11266 switch (E->getCastKind()) {
11267 default:
11268 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11269
11270 case CK_NullToMemberPointer:
11271 VisitIgnoredValue(E->getSubExpr());
11272 return ZeroInitialization(E);
11273
11274 case CK_BaseToDerivedMemberPointer: {
11275 if (!Visit(E->getSubExpr()))
11276 return false;
11277 if (E->path_empty())
11278 return true;
11279 // Base-to-derived member pointer casts store the path in derived-to-base
11280 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
11281 // the wrong end of the derived->base arc, so stagger the path by one class.
11282 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
11283 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
11284 PathI != PathE; ++PathI) {
11285 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11286 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
11287 if (!Result.castToDerived(Derived))
11288 return Error(E);
11289 }
11290 if (!Result.castToDerived(E->getType()
11291 ->castAs<MemberPointerType>()
11292 ->getMostRecentCXXRecordDecl()))
11293 return Error(E);
11294 return true;
11295 }
11296
11297 case CK_DerivedToBaseMemberPointer:
11298 if (!Visit(E->getSubExpr()))
11299 return false;
11300 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11301 PathE = E->path_end(); PathI != PathE; ++PathI) {
11302 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
11303 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11304 if (!Result.castToBase(Base))
11305 return Error(E);
11306 }
11307 return true;
11308 }
11309}
11310
11311bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
11312 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
11313 // member can be formed.
11314 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
11315}
11316
11317//===----------------------------------------------------------------------===//
11318// Record Evaluation
11319//===----------------------------------------------------------------------===//
11320
11321namespace {
11322 class RecordExprEvaluator
11323 : public ExprEvaluatorBase<RecordExprEvaluator> {
11324 const LValue &This;
11325 APValue &Result;
11326 public:
11327
11328 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
11329 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
11330
11331 bool Success(const APValue &V, const Expr *E) {
11332 Result = V;
11333 return true;
11334 }
11335 bool ZeroInitialization(const Expr *E) {
11336 return ZeroInitialization(E, E->getType());
11337 }
11338 bool ZeroInitialization(const Expr *E, QualType T);
11339
11340 bool VisitCallExpr(const CallExpr *E) {
11341 return handleCallExpr(E, Result, &This);
11342 }
11343 bool VisitCastExpr(const CastExpr *E);
11344 bool VisitInitListExpr(const InitListExpr *E);
11345 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11346 return VisitCXXConstructExpr(E, E->getType());
11347 }
11348 bool VisitLambdaExpr(const LambdaExpr *E);
11349 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
11350 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
11351 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
11352 bool VisitBinCmp(const BinaryOperator *E);
11353 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11354 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11355 ArrayRef<Expr *> Args);
11356 bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E);
11357 };
11358}
11359
11360/// Perform zero-initialization on an object of non-union class type.
11361/// C++11 [dcl.init]p5:
11362/// To zero-initialize an object or reference of type T means:
11363/// [...]
11364/// -- if T is a (possibly cv-qualified) non-union class type,
11365/// each non-static data member and each base-class subobject is
11366/// zero-initialized
11367static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
11368 const RecordDecl *RD,
11369 const LValue &This, APValue &Result,
11370 bool IsCompleteClass = true) {
11371 assert(!RD->isUnion() && "Expected non-union class type");
11372 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
11373
11374 if (CD) {
11375 unsigned NonVirtualBases = countNonVirtualBases(CD);
11376 Result =
11377 APValue(APValue::UninitStruct(), NonVirtualBases, RD->getNumFields(),
11378 IsCompleteClass ? CD->getNumVBases() : 0);
11379 } else {
11381 }
11382
11383 if (RD->isInvalidDecl()) return false;
11384 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11385
11386 if (CD) {
11387 unsigned Index = 0;
11388
11389 for (const auto &B : CD->bases()) {
11390 if (B.isVirtual())
11391 continue;
11393 LValue Subobject = This;
11394 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
11395 return false;
11396 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11397 Result.getStructBase(Index),
11398 /*IsCompleteClass=*/false))
11399 return false;
11400 ++Index;
11401 }
11402 }
11403
11404 for (const auto *I : RD->fields()) {
11405 // -- if T is a reference type, no initialization is performed.
11406 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11407 continue;
11408
11409 LValue Subobject = This;
11410 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
11411 return false;
11412
11413 ImplicitValueInitExpr VIE(I->getType());
11414 if (!EvaluateInPlace(
11415 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11416 return false;
11417 }
11418
11419 if (CD && This.pointsToCompleteClass(CD)) {
11420 unsigned Index = 0;
11421 for (const auto &B : CD->vbases()) {
11423 LValue Subobject = This;
11424 if (!HandleLValueDirectVirtualBase(Info, E, Subobject, CD, Base, &Layout))
11425 return false;
11426 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
11427 Result.getStructVirtualBase(Index),
11428 /*IsCompleteClass=*/false))
11429 return false;
11430 ++Index;
11431 }
11432 }
11433
11434 return true;
11435}
11436
11437bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
11438 const auto *RD = T->castAsRecordDecl();
11439 if (RD->isInvalidDecl()) return false;
11440 if (RD->isUnion()) {
11441 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
11442 // object's first non-static named data member is zero-initialized
11444 while (I != RD->field_end() && (*I)->isUnnamedBitField())
11445 ++I;
11446 if (I == RD->field_end()) {
11447 Result = APValue((const FieldDecl*)nullptr);
11448 return true;
11449 }
11450
11451 LValue Subobject = This;
11452 if (!HandleLValueMember(Info, E, Subobject, *I))
11453 return false;
11454 Result = APValue(*I);
11455 ImplicitValueInitExpr VIE(I->getType());
11456 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
11457 }
11458
11459 if (!Info.getLangOpts().CPlusPlus26) {
11460 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11461 CXXRD && CXXRD->getNumVBases()) {
11462 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11463 return false;
11464 }
11465 }
11466
11467 return HandleClassZeroInitialization(Info, E, RD, This, Result);
11468}
11469
11470bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
11471 switch (E->getCastKind()) {
11472 default:
11473 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11474
11475 case CK_ConstructorConversion:
11476 return Visit(E->getSubExpr());
11477
11478 case CK_DerivedToBase:
11479 case CK_UncheckedDerivedToBase: {
11480 APValue DerivedObject;
11481 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
11482 return false;
11483 if (!DerivedObject.isStruct())
11484 return Error(E->getSubExpr());
11485
11486 // Derived-to-base rvalue conversion: just slice off the derived part.
11487 APValue *Value = &DerivedObject;
11488 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
11489 for (CastExpr::path_const_iterator PathI = E->path_begin(),
11490 PathE = E->path_end(); PathI != PathE; ++PathI) {
11491 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
11492 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
11493 Value = &Value->getStructBase(getBaseIndex(RD, Base));
11494 RD = Base;
11495 }
11496 Result = *Value;
11497 return true;
11498 }
11499 case CK_HLSLAggregateSplatCast: {
11500 APValue Val;
11501 QualType ValTy;
11502
11503 if (!hlslAggSplatHelper(Info, E->getSubExpr(), Val, ValTy))
11504 return false;
11505
11506 unsigned NEls = elementwiseSize(Info, E->getType());
11507 // splat our Val
11508 SmallVector<APValue> SplatEls(NEls, Val);
11509 SmallVector<QualType> SplatType(NEls, ValTy);
11510
11511 // cast the elements and construct our struct result
11512 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11513 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
11514 SplatType))
11515 return false;
11516
11517 return true;
11518 }
11519 case CK_HLSLElementwiseCast: {
11520 SmallVector<APValue> SrcEls;
11521 SmallVector<QualType> SrcTypes;
11522
11523 if (!hlslElementwiseCastHelper(Info, E->getSubExpr(), E->getType(), SrcEls,
11524 SrcTypes))
11525 return false;
11526
11527 // cast the elements and construct our struct result
11528 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11529 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
11530 SrcTypes))
11531 return false;
11532
11533 return true;
11534 }
11535 case CK_ToUnion: {
11536 const FieldDecl *Field = E->getTargetUnionField();
11537 LValue Subobject = This;
11538 if (!HandleLValueMember(Info, E, Subobject, Field))
11539 return false;
11540 Result = APValue(Field);
11541 if (!EvaluateInPlace(Result.getUnionValue(), Info, Subobject,
11542 E->getSubExpr()))
11543 return false;
11544 if (Field->isBitField()) {
11545 if (!truncateBitfieldValue(Info, E->getSubExpr(), Result.getUnionValue(),
11546 Field))
11547 return false;
11548 }
11549 return true;
11550 }
11551 }
11552}
11553
11554bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11555 if (E->isTransparent())
11556 return Visit(E->getInit(0));
11557 return VisitCXXParenListOrInitListExpr(E, E->inits());
11558}
11559
11560bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11561 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
11562 const auto *RD = ExprToVisit->getType()->castAsRecordDecl();
11563 if (RD->isInvalidDecl()) return false;
11564 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11565 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11566
11567 EvalInfo::EvaluatingConstructorRAII EvalObj(
11568 Info,
11569 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
11570 CXXRD && CXXRD->getNumBases());
11571
11572 if (RD->isUnion()) {
11573 const FieldDecl *Field;
11574 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11575 Field = ILE->getInitializedFieldInUnion();
11576 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11577 Field = PLIE->getInitializedFieldInUnion();
11578 } else {
11579 llvm_unreachable(
11580 "Expression is neither an init list nor a C++ paren list");
11581 }
11582
11583 Result = APValue(Field);
11584 if (!Field)
11585 return true;
11586
11587 // If the initializer list for a union does not contain any elements, the
11588 // first element of the union is value-initialized.
11589 // FIXME: The element should be initialized from an initializer list.
11590 // Is this difference ever observable for initializer lists which
11591 // we don't build?
11592 ImplicitValueInitExpr VIE(Field->getType());
11593 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11594
11595 LValue Subobject = This;
11596 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
11597 return false;
11598
11599 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11600 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11601 isa<CXXDefaultInitExpr>(InitExpr));
11602
11603 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
11604 if (Field->isBitField())
11605 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
11606 Field);
11607 return true;
11608 }
11609
11610 return false;
11611 }
11612
11613 if (!Result.hasValue())
11614 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11615 RD->getNumFields());
11616 unsigned ElementNo = 0;
11617 bool Success = true;
11618
11619 // Initialize base classes.
11620 if (CXXRD && CXXRD->getNumBases()) {
11621 for (const auto &Base : CXXRD->bases()) {
11622 assert(ElementNo < Args.size() && "missing init for base class");
11623 const Expr *Init = Args[ElementNo];
11624
11625 LValue Subobject = This;
11626 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
11627 return false;
11628
11629 APValue &FieldVal = Result.getStructBase(ElementNo);
11630 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
11631 if (!Info.noteFailure())
11632 return false;
11633 Success = false;
11634 }
11635 ++ElementNo;
11636 }
11637
11638 EvalObj.finishedConstructingBases();
11639 }
11640
11641 // Initialize members.
11642 for (const auto *Field : RD->fields()) {
11643 // Anonymous bit-fields are not considered members of the class for
11644 // purposes of aggregate initialization.
11645 if (Field->isUnnamedBitField())
11646 continue;
11647
11648 LValue Subobject = This;
11649
11650 bool HaveInit = ElementNo < Args.size();
11651
11652 // FIXME: Diagnostics here should point to the end of the initializer
11653 // list, not the start.
11654 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
11655 Subobject, Field, &Layout))
11656 return false;
11657
11658 // Perform an implicit value-initialization for members beyond the end of
11659 // the initializer list.
11660 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
11661 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
11662
11663 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
11664 // aren't supposed to be modified.
11665 if (isa<NoInitExpr>(Init))
11666 continue;
11667
11668 if (Field->getType()->isIncompleteArrayType()) {
11669 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
11670 if (!CAT->isZeroSize()) {
11671 // Bail out for now. This might sort of "work", but the rest of the
11672 // code isn't really prepared to handle it.
11673 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
11674 return false;
11675 }
11676 }
11677 }
11678
11679 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
11680 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11682
11683 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11684 if (Field->getType()->isReferenceType()) {
11685 LValue Result;
11687 FieldVal)) {
11688 if (!Info.noteFailure())
11689 return false;
11690 Success = false;
11691 }
11692 } else if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
11693 (Field->isBitField() &&
11694 !truncateBitfieldValue(Info, Init, FieldVal, Field))) {
11695 if (!Info.noteFailure())
11696 return false;
11697 Success = false;
11698 }
11699 }
11700
11701 EvalObj.finishedConstructingFields();
11702
11703 return Success;
11704}
11705
11706bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11707 QualType T) {
11708 // Note that E's type is not necessarily the type of our class here; we might
11709 // be initializing an array element instead.
11710 const CXXConstructorDecl *FD = E->getConstructor();
11711 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
11712
11713 bool ZeroInit = E->requiresZeroInitialization();
11714 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
11715 if (ZeroInit)
11716 return ZeroInitialization(E, T);
11717
11719 }
11720
11721 const FunctionDecl *Definition = nullptr;
11722 auto Body = FD->getBody(Definition);
11723
11724 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11725 return false;
11726
11727 // Avoid materializing a temporary for an elidable copy/move constructor.
11728 if (E->isElidable() && !ZeroInit) {
11729 // FIXME: This only handles the simplest case, where the source object
11730 // is passed directly as the first argument to the constructor.
11731 // This should also handle stepping though implicit casts and
11732 // and conversion sequences which involve two steps, with a
11733 // conversion operator followed by a converting constructor.
11734 const Expr *SrcObj = E->getArg(0);
11735 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
11736 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
11737 if (const MaterializeTemporaryExpr *ME =
11738 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
11739 return Visit(ME->getSubExpr());
11740 }
11741
11742 if (ZeroInit && !ZeroInitialization(E, T))
11743 return false;
11744
11745 auto Args = ArrayRef(E->getArgs(), E->getNumArgs());
11746 return HandleConstructorCall(E, This, Args,
11748 Result);
11749}
11750
11751bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
11752 const CXXInheritedCtorInitExpr *E) {
11753 if (!Info.CurrentCall) {
11754 assert(Info.checkingPotentialConstantExpression());
11755 return false;
11756 }
11757
11758 const CXXConstructorDecl *FD = E->getConstructor();
11759 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
11760 return false;
11761
11762 const FunctionDecl *Definition = nullptr;
11763 auto Body = FD->getBody(Definition);
11764
11765 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
11766 return false;
11767
11768 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
11770 Result);
11771}
11772
11773bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
11774 const CXXStdInitializerListExpr *E) {
11775 const ConstantArrayType *ArrayType =
11776 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
11777
11778 LValue Array;
11779 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
11780 return false;
11781
11782 assert(ArrayType && "unexpected type for array initializer");
11783
11784 // Get a pointer to the first element of the array.
11785 Array.addArray(Info, E, ArrayType);
11786
11787 // FIXME: What if the initializer_list type has base classes, etc?
11788 Result = APValue(APValue::UninitStruct(), 0, 2);
11789 Array.moveInto(Result.getStructField(0));
11790
11791 auto *Record = E->getType()->castAsRecordDecl();
11792 RecordDecl::field_iterator Field = Record->field_begin();
11793 assert(Field != Record->field_end() &&
11794 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11795 ArrayType->getElementType()) &&
11796 "Expected std::initializer_list first field to be const E *");
11797 ++Field;
11798 assert(Field != Record->field_end() &&
11799 "Expected std::initializer_list to have two fields");
11800
11801 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
11802 // Length.
11803 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
11804 } else {
11805 // End pointer.
11806 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
11807 ArrayType->getElementType()) &&
11808 "Expected std::initializer_list second field to be const E *");
11809 if (!HandleLValueArrayAdjustment(Info, E, Array,
11810 ArrayType->getElementType(),
11811 ArrayType->getZExtSize()))
11812 return false;
11813 Array.moveInto(Result.getStructField(1));
11814 }
11815
11816 assert(++Field == Record->field_end() &&
11817 "Expected std::initializer_list to only have two fields");
11818
11819 return true;
11820}
11821
11822bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
11823 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
11824 if (ClosureClass->isInvalidDecl())
11825 return false;
11826
11827 const size_t NumFields = ClosureClass->getNumFields();
11828
11829 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
11830 E->capture_init_end()) &&
11831 "The number of lambda capture initializers should equal the number of "
11832 "fields within the closure type");
11833
11834 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
11835 // Iterate through all the lambda's closure object's fields and initialize
11836 // them.
11837 auto *CaptureInitIt = E->capture_init_begin();
11838 bool Success = true;
11839 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
11840 for (const auto *Field : ClosureClass->fields()) {
11841 assert(CaptureInitIt != E->capture_init_end());
11842 // Get the initializer for this field
11843 Expr *const CurFieldInit = *CaptureInitIt++;
11844
11845 // If there is no initializer, either this is a VLA or an error has
11846 // occurred.
11847 if (!CurFieldInit || CurFieldInit->containsErrors())
11848 return Error(E);
11849
11850 LValue Subobject = This;
11851
11852 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
11853 return false;
11854
11855 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
11856 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
11857 if (!Info.keepEvaluatingAfterFailure())
11858 return false;
11859 Success = false;
11860 }
11861 }
11862 return Success;
11863}
11864
11865bool RecordExprEvaluator::VisitDesignatedInitUpdateExpr(
11866 const DesignatedInitUpdateExpr *E) {
11867 if (!Visit(E->getBase()))
11868 return false;
11869 return Visit(E->getUpdater());
11870}
11871
11872static bool EvaluateRecord(const Expr *E, const LValue &This,
11873 APValue &Result, EvalInfo &Info) {
11874 assert(!E->isValueDependent());
11875 assert(E->isPRValue() && E->getType()->isRecordType() &&
11876 "can't evaluate expression as a record rvalue");
11877 return RecordExprEvaluator(Info, This, Result).Visit(E);
11878}
11879
11880//===----------------------------------------------------------------------===//
11881// Temporary Evaluation
11882//
11883// Temporaries are represented in the AST as rvalues, but generally behave like
11884// lvalues. The full-object of which the temporary is a subobject is implicitly
11885// materialized so that a reference can bind to it.
11886//===----------------------------------------------------------------------===//
11887namespace {
11888class TemporaryExprEvaluator
11889 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11890public:
11891 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11892 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11893
11894 /// Visit an expression which constructs the value of this temporary.
11895 bool VisitConstructExpr(const Expr *E) {
11896 APValue &Value = Info.CurrentCall->createTemporary(
11897 E, E->getType(), ScopeKind::FullExpression, Result);
11898 return EvaluateInPlace(Value, Info, Result, E);
11899 }
11900
11901 bool VisitCastExpr(const CastExpr *E) {
11902 switch (E->getCastKind()) {
11903 default:
11904 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11905
11906 case CK_ConstructorConversion:
11907 return VisitConstructExpr(E->getSubExpr());
11908 }
11909 }
11910 bool VisitInitListExpr(const InitListExpr *E) {
11911 return VisitConstructExpr(E);
11912 }
11913 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11914 return VisitConstructExpr(E);
11915 }
11916 bool VisitCallExpr(const CallExpr *E) {
11917 return VisitConstructExpr(E);
11918 }
11919 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11920 return VisitConstructExpr(E);
11921 }
11922 bool VisitLambdaExpr(const LambdaExpr *E) {
11923 return VisitConstructExpr(E);
11924 }
11925};
11926} // end anonymous namespace
11927
11928/// Evaluate an expression of record type as a temporary.
11929static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11930 assert(!E->isValueDependent());
11931 assert(E->isPRValue() && E->getType()->isRecordType());
11932 return TemporaryExprEvaluator(Info, Result).Visit(E);
11933}
11934
11935//===----------------------------------------------------------------------===//
11936// Vector Evaluation
11937//===----------------------------------------------------------------------===//
11938
11939namespace {
11940 class VectorExprEvaluator
11941 : public ExprEvaluatorBase<VectorExprEvaluator> {
11942 APValue &Result;
11943 public:
11944
11945 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11946 : ExprEvaluatorBaseTy(info), Result(Result) {}
11947
11948 bool Success(ArrayRef<APValue> V, const Expr *E) {
11949 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11950 // FIXME: remove this APValue copy.
11951 Result = APValue(V.data(), V.size());
11952 return true;
11953 }
11954 bool Success(const APValue &V, const Expr *E) {
11955 assert(V.isVector());
11956 Result = V;
11957 return true;
11958 }
11959 bool ZeroInitialization(const Expr *E);
11960
11961 bool VisitUnaryReal(const UnaryOperator *E)
11962 { return Visit(E->getSubExpr()); }
11963 bool VisitCastExpr(const CastExpr* E);
11964 bool VisitInitListExpr(const InitListExpr *E);
11965 bool VisitUnaryImag(const UnaryOperator *E);
11966 bool VisitBinaryOperator(const BinaryOperator *E);
11967 bool VisitUnaryOperator(const UnaryOperator *E);
11968 bool VisitCallExpr(const CallExpr *E);
11969 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11970 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11971
11972 // FIXME: Missing: conditional operator (for GNU
11973 // conditional select), ExtVectorElementExpr
11974 };
11975} // end anonymous namespace
11976
11977static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11978 assert(E->isPRValue() && E->getType()->isVectorType() &&
11979 "not a vector prvalue");
11980 return VectorExprEvaluator(Info, Result).Visit(E);
11981}
11982
11983static llvm::APInt ConvertBoolVectorToInt(const APValue &Val) {
11984 assert(Val.isVector() && "expected vector APValue");
11985 unsigned NumElts = Val.getVectorLength();
11986
11987 // Each element is one bit, so create an integer with NumElts bits.
11988 llvm::APInt Result(NumElts, 0);
11989
11990 for (unsigned I = 0; I < NumElts; ++I) {
11991 const APValue &Elt = Val.getVectorElt(I);
11992 assert(Elt.isInt() && "expected integer element in bool vector");
11993
11994 if (Elt.getInt().getBoolValue())
11995 Result.setBit(I);
11996 }
11997
11998 return Result;
11999}
12000
12001bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
12002 const VectorType *VTy = E->getType()->castAs<VectorType>();
12003 unsigned NElts = VTy->getNumElements();
12004
12005 const Expr *SE = E->getSubExpr();
12006 QualType SETy = SE->getType();
12007
12008 switch (E->getCastKind()) {
12009 case CK_VectorSplat: {
12010 APValue Val = APValue();
12011 if (SETy->isIntegerType()) {
12012 APSInt IntResult;
12013 if (!EvaluateInteger(SE, IntResult, Info))
12014 return false;
12015 Val = APValue(std::move(IntResult));
12016 } else if (SETy->isRealFloatingType()) {
12017 APFloat FloatResult(0.0);
12018 if (!EvaluateFloat(SE, FloatResult, Info))
12019 return false;
12020 Val = APValue(std::move(FloatResult));
12021 } else {
12022 return Error(E);
12023 }
12024
12025 // Splat and create vector APValue.
12026 SmallVector<APValue, 4> Elts(NElts, Val);
12027 return Success(Elts, E);
12028 }
12029 case CK_BitCast: {
12030 APValue SVal;
12031 if (!Evaluate(SVal, Info, SE))
12032 return false;
12033
12034 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
12035 // Give up if the input isn't an int, float, or vector. For example, we
12036 // reject "(v4i16)(intptr_t)&a".
12037 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
12038 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
12039 << Info.Ctx.getLangOpts().CPlusPlus;
12040 return false;
12041 }
12042
12043 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
12044 return false;
12045
12046 return true;
12047 }
12048 case CK_HLSLVectorTruncation: {
12049 APValue Val;
12050 SmallVector<APValue, 4> Elements;
12051 if (!EvaluateVector(SE, Val, Info))
12052 return Error(E);
12053 for (unsigned I = 0; I < NElts; I++)
12054 Elements.push_back(Val.getVectorElt(I));
12055 return Success(Elements, E);
12056 }
12057 case CK_HLSLMatrixTruncation: {
12058 // Matrix truncation occurs in row-major order.
12059 APValue Val;
12060 if (!EvaluateMatrix(SE, Val, Info))
12061 return Error(E);
12062 SmallVector<APValue, 16> Elements;
12063 for (unsigned Row = 0;
12064 Row < Val.getMatrixNumRows() && Elements.size() < NElts; Row++)
12065 for (unsigned Col = 0;
12066 Col < Val.getMatrixNumColumns() && Elements.size() < NElts; Col++)
12067 Elements.push_back(Val.getMatrixElt(Row, Col));
12068 return Success(Elements, E);
12069 }
12070 case CK_HLSLAggregateSplatCast: {
12071 APValue Val;
12072 QualType ValTy;
12073
12074 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
12075 return false;
12076
12077 // cast our Val once.
12079 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12080 if (!handleScalarCast(Info, FPO, E, ValTy, VTy->getElementType(), Val,
12081 Result))
12082 return false;
12083
12084 SmallVector<APValue, 4> SplatEls(NElts, Result);
12085 return Success(SplatEls, E);
12086 }
12087 case CK_HLSLElementwiseCast: {
12088 SmallVector<APValue> SrcVals;
12089 SmallVector<QualType> SrcTypes;
12090
12091 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
12092 return false;
12093
12094 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12095 SmallVector<QualType, 4> DestTypes(NElts, VTy->getElementType());
12096 SmallVector<APValue, 4> ResultEls(NElts);
12097 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
12098 ResultEls))
12099 return false;
12100 return Success(ResultEls, E);
12101 }
12102 case CK_IntegralToFloating:
12103 case CK_FloatingToIntegral:
12104 case CK_IntegralCast:
12105 case CK_FloatingCast:
12106 case CK_FloatingToBoolean:
12107 case CK_IntegralToBoolean: {
12108 // These casts apply element-wise when the source is a vector type.
12109 assert(SETy->isVectorType() && "expected vector source type");
12110 APValue SrcVal;
12111 if (!EvaluateVector(SE, SrcVal, Info))
12112 return Error(E);
12113
12114 assert(SrcVal.getVectorLength() == NElts);
12115 QualType SrcEltTy = SETy->castAs<VectorType>()->getElementType();
12116 QualType DstEltTy = VTy->getElementType();
12117 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
12118
12119 SmallVector<APValue, 4> ResultEls(NElts);
12120 for (unsigned I = 0; I < NElts; ++I) {
12121 if (!handleScalarCast(Info, FPO, E, SrcEltTy, DstEltTy,
12122 SrcVal.getVectorElt(I), ResultEls[I]))
12123 return Error(E);
12124 }
12125 return Success(ResultEls, E);
12126 }
12127 default:
12128 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12129 }
12130}
12131
12132bool
12133VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12134 const VectorType *VT = E->getType()->castAs<VectorType>();
12135 unsigned NumInits = E->getNumInits();
12136 unsigned NumElements = VT->getNumElements();
12137
12138 QualType EltTy = VT->getElementType();
12139 SmallVector<APValue, 4> Elements;
12140
12141 // MFloat8 type doesn't have constants and thus constant folding
12142 // is impossible.
12143 if (EltTy->isMFloat8Type())
12144 return false;
12145
12146 // The number of initializers can be less than the number of
12147 // vector elements. For OpenCL, this can be due to nested vector
12148 // initialization. For GCC compatibility, missing trailing elements
12149 // should be initialized with zeroes.
12150 unsigned CountInits = 0, CountElts = 0;
12151 while (CountElts < NumElements) {
12152 // Handle nested vector initialization.
12153 if (CountInits < NumInits
12154 && E->getInit(CountInits)->getType()->isVectorType()) {
12155 APValue v;
12156 if (!EvaluateVector(E->getInit(CountInits), v, Info))
12157 return Error(E);
12158 unsigned vlen = v.getVectorLength();
12159 for (unsigned j = 0; j < vlen; j++)
12160 Elements.push_back(v.getVectorElt(j));
12161 CountElts += vlen;
12162 } else if (EltTy->isIntegerType()) {
12163 llvm::APSInt sInt(32);
12164 if (CountInits < NumInits) {
12165 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
12166 return false;
12167 } else // trailing integer zero.
12168 sInt = Info.Ctx.MakeIntValue(0, EltTy);
12169 Elements.push_back(APValue(sInt));
12170 CountElts++;
12171 } else {
12172 llvm::APFloat f(0.0);
12173 if (CountInits < NumInits) {
12174 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
12175 return false;
12176 } else // trailing float zero.
12177 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
12178 Elements.push_back(APValue(f));
12179 CountElts++;
12180 }
12181 CountInits++;
12182 }
12183 return Success(Elements, E);
12184}
12185
12186bool
12187VectorExprEvaluator::ZeroInitialization(const Expr *E) {
12188 const auto *VT = E->getType()->castAs<VectorType>();
12189 QualType EltTy = VT->getElementType();
12190 APValue ZeroElement;
12191 if (EltTy->isIntegerType())
12192 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
12193 else
12194 ZeroElement =
12195 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
12196
12197 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
12198 return Success(Elements, E);
12199}
12200
12201bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12202 VisitIgnoredValue(E->getSubExpr());
12203 return ZeroInitialization(E);
12204}
12205
12206bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12207 BinaryOperatorKind Op = E->getOpcode();
12208 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
12209 "Operation not supported on vector types");
12210
12211 if (Op == BO_Comma)
12212 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12213
12214 Expr *LHS = E->getLHS();
12215 Expr *RHS = E->getRHS();
12216
12217 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
12218 "Must both be vector types");
12219 // Checking JUST the types are the same would be fine, except shifts don't
12220 // need to have their types be the same (since you always shift by an int).
12221 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
12222 E->getType()->castAs<VectorType>()->getNumElements() &&
12223 RHS->getType()->castAs<VectorType>()->getNumElements() ==
12224 E->getType()->castAs<VectorType>()->getNumElements() &&
12225 "All operands must be the same size.");
12226
12227 APValue LHSValue;
12228 APValue RHSValue;
12229 bool LHSOK = Evaluate(LHSValue, Info, LHS);
12230 if (!LHSOK && !Info.noteFailure())
12231 return false;
12232 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
12233 return false;
12234
12235 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
12236 return false;
12237
12238 return Success(LHSValue, E);
12239}
12240
12241static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
12242 QualType ResultTy,
12244 APValue Elt) {
12245 switch (Op) {
12246 case UO_Plus:
12247 // Nothing to do here.
12248 return Elt;
12249 case UO_Minus:
12250 if (Elt.getKind() == APValue::Int) {
12251 Elt.getInt().negate();
12252 } else {
12253 assert(Elt.getKind() == APValue::Float &&
12254 "Vector can only be int or float type");
12255 Elt.getFloat().changeSign();
12256 }
12257 return Elt;
12258 case UO_Not:
12259 // This is only valid for integral types anyway, so we don't have to handle
12260 // float here.
12261 assert(Elt.getKind() == APValue::Int &&
12262 "Vector operator ~ can only be int");
12263 Elt.getInt().flipAllBits();
12264 return Elt;
12265 case UO_LNot: {
12266 if (Elt.getKind() == APValue::Int) {
12267 Elt.getInt() = !Elt.getInt();
12268 // operator ! on vectors returns -1 for 'truth', so negate it.
12269 Elt.getInt().negate();
12270 return Elt;
12271 }
12272 assert(Elt.getKind() == APValue::Float &&
12273 "Vector can only be int or float type");
12274 // Float types result in an int of the same size, but -1 for true, or 0 for
12275 // false.
12276 APSInt EltResult{Ctx.getIntWidth(ResultTy),
12277 ResultTy->isUnsignedIntegerType()};
12278 if (Elt.getFloat().isZero())
12279 EltResult.setAllBits();
12280 else
12281 EltResult.clearAllBits();
12282
12283 return APValue{EltResult};
12284 }
12285 default:
12286 // FIXME: Implement the rest of the unary operators.
12287 return std::nullopt;
12288 }
12289}
12290
12291bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12292 Expr *SubExpr = E->getSubExpr();
12293 const auto *VD = SubExpr->getType()->castAs<VectorType>();
12294 // This result element type differs in the case of negating a floating point
12295 // vector, since the result type is the a vector of the equivilant sized
12296 // integer.
12297 const QualType ResultEltTy = VD->getElementType();
12298 UnaryOperatorKind Op = E->getOpcode();
12299
12300 APValue SubExprValue;
12301 if (!Evaluate(SubExprValue, Info, SubExpr))
12302 return false;
12303
12304 // FIXME: This vector evaluator someday needs to be changed to be LValue
12305 // aware/keep LValue information around, rather than dealing with just vector
12306 // types directly. Until then, we cannot handle cases where the operand to
12307 // these unary operators is an LValue. The only case I've been able to see
12308 // cause this is operator++ assigning to a member expression (only valid in
12309 // altivec compilations) in C mode, so this shouldn't limit us too much.
12310 if (SubExprValue.isLValue())
12311 return false;
12312
12313 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
12314 "Vector length doesn't match type?");
12315
12316 SmallVector<APValue, 4> ResultElements;
12317 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
12318 std::optional<APValue> Elt = handleVectorUnaryOperator(
12319 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
12320 if (!Elt)
12321 return false;
12322 ResultElements.push_back(*Elt);
12323 }
12324 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12325}
12326
12327static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
12328 const Expr *E, QualType SourceTy,
12329 QualType DestTy, APValue const &Original,
12330 APValue &Result) {
12331 if (SourceTy->isIntegerType()) {
12332 if (DestTy->isRealFloatingType()) {
12333 Result = APValue(APFloat(0.0));
12334 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
12335 DestTy, Result.getFloat());
12336 }
12337 if (DestTy->isIntegerType()) {
12338 Result = APValue(
12339 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
12340 return true;
12341 }
12342 } else if (SourceTy->isRealFloatingType()) {
12343 if (DestTy->isRealFloatingType()) {
12344 Result = Original;
12345 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
12346 Result.getFloat());
12347 }
12348 if (DestTy->isIntegerType()) {
12349 Result = APValue(APSInt());
12350 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
12351 DestTy, Result.getInt());
12352 }
12353 }
12354
12355 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
12356 << SourceTy << DestTy;
12357 return false;
12358}
12359
12360static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result,
12361 llvm::function_ref<APInt(const APSInt &)> PackFn) {
12362 APValue LHS, RHS;
12363 if (!EvaluateAsRValue(Info, E->getArg(0), LHS) ||
12364 !EvaluateAsRValue(Info, E->getArg(1), RHS))
12365 return false;
12366
12367 unsigned LHSVecLen = LHS.getVectorLength();
12368 unsigned RHSVecLen = RHS.getVectorLength();
12369
12370 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12371 "pack builtin LHSVecLen must equal to RHSVecLen");
12372
12373 const VectorType *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
12374 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->getElementType());
12375
12376 const VectorType *DstVT = E->getType()->castAs<VectorType>();
12377 QualType DstElemTy = DstVT->getElementType();
12378 const bool DstIsUnsigned = DstElemTy->isUnsignedIntegerType();
12379
12380 const unsigned SrcPerLane = 128 / SrcBits;
12381 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12382
12384 Out.reserve(LHSVecLen + RHSVecLen);
12385
12386 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
12387 unsigned base = Lane * SrcPerLane;
12388 for (unsigned I = 0; I != SrcPerLane; ++I)
12389 Out.emplace_back(APValue(
12390 APSInt(PackFn(LHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12391 for (unsigned I = 0; I != SrcPerLane; ++I)
12392 Out.emplace_back(APValue(
12393 APSInt(PackFn(RHS.getVectorElt(base + I).getInt()), DstIsUnsigned)));
12394 }
12395
12396 Result = APValue(Out.data(), Out.size());
12397 return true;
12398}
12399
12401 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12402 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
12403 GetSourceIndex) {
12404
12405 const auto *VT = Call->getType()->getAs<VectorType>();
12406 if (!VT)
12407 return false;
12408
12409 unsigned ShuffleMask = 0;
12410 APValue A, MaskVector, B;
12411 bool IsVectorMask = false;
12412 bool IsSingleOperand = (Call->getNumArgs() == 2);
12413
12414 if (IsSingleOperand) {
12415 QualType MaskType = Call->getArg(1)->getType();
12416 if (MaskType->isVectorType()) {
12417 IsVectorMask = true;
12418 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12419 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector))
12420 return false;
12421 B = A;
12422 } else if (MaskType->isIntegerType()) {
12423 APSInt MaskImm;
12424 if (!EvaluateInteger(Call->getArg(1), MaskImm, Info))
12425 return false;
12426 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12427 if (!EvaluateAsRValue(Info, Call->getArg(0), A))
12428 return false;
12429 B = A;
12430 } else {
12431 return false;
12432 }
12433 } else {
12434 QualType Arg2Type = Call->getArg(2)->getType();
12435 if (Arg2Type->isVectorType()) {
12436 IsVectorMask = true;
12437 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12438 !EvaluateAsRValue(Info, Call->getArg(1), MaskVector) ||
12439 !EvaluateAsRValue(Info, Call->getArg(2), B))
12440 return false;
12441 } else if (Arg2Type->isIntegerType()) {
12442 APSInt MaskImm;
12443 if (!EvaluateInteger(Call->getArg(2), MaskImm, Info))
12444 return false;
12445 ShuffleMask = static_cast<unsigned>(MaskImm.getZExtValue());
12446 if (!EvaluateAsRValue(Info, Call->getArg(0), A) ||
12447 !EvaluateAsRValue(Info, Call->getArg(1), B))
12448 return false;
12449 } else {
12450 return false;
12451 }
12452 }
12453
12454 unsigned NumElts = VT->getNumElements();
12455 SmallVector<APValue, 64> ResultElements;
12456 ResultElements.reserve(NumElts);
12457
12458 for (unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12459 if (IsVectorMask) {
12460 ShuffleMask = static_cast<unsigned>(
12461 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12462 }
12463 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12464
12465 if (SrcIdx < 0) {
12466 // Zero out this element
12467 QualType ElemTy = VT->getElementType();
12468 if (ElemTy->isRealFloatingType()) {
12469 ResultElements.push_back(
12470 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12471 } else if (ElemTy->isIntegerType()) {
12472 APValue Zero(Info.Ctx.MakeIntValue(0, ElemTy));
12473 ResultElements.push_back(APValue(Zero));
12474 } else {
12475 // Other types of fallback logic
12476 ResultElements.push_back(APValue());
12477 }
12478 } else {
12479 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12480 ResultElements.push_back(Src.getVectorElt(SrcIdx));
12481 }
12482 }
12483
12484 Out = APValue(ResultElements.data(), ResultElements.size());
12485 return true;
12486}
12487static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E,
12488 APFloat OrigVal, APValue &Result) {
12489
12490 if (OrigVal.isInfinity()) {
12491 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 0;
12492 return false;
12493 }
12494 if (OrigVal.isNaN()) {
12495 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 1;
12496 return false;
12497 }
12498
12499 APFloat Val = OrigVal;
12500 bool LosesInfo = false;
12501 APFloat::opStatus Status = Val.convert(
12502 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
12503
12504 if (LosesInfo || Val.isDenormal()) {
12505 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic_strict);
12506 return false;
12507 }
12508
12509 if (Status != APFloat::opOK) {
12510 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12511 return false;
12512 }
12513
12514 Result = APValue(Val);
12515 return true;
12516}
12518 EvalInfo &Info, const CallExpr *Call, APValue &Out,
12519 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
12520 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
12521
12522 APValue Source, Count;
12523 if (!EvaluateAsRValue(Info, Call->getArg(0), Source) ||
12524 !EvaluateAsRValue(Info, Call->getArg(1), Count))
12525 return false;
12526
12527 assert(Call->getNumArgs() == 2);
12528
12529 QualType SourceTy = Call->getArg(0)->getType();
12530 assert(SourceTy->isVectorType() &&
12531 Call->getArg(1)->getType()->isVectorType());
12532
12533 QualType DestEltTy = SourceTy->castAs<VectorType>()->getElementType();
12534 unsigned DestEltWidth = Source.getVectorElt(0).getInt().getBitWidth();
12535 unsigned DestLen = Source.getVectorLength();
12536 bool IsDestUnsigned = DestEltTy->isUnsignedIntegerType();
12537 unsigned CountEltWidth = Count.getVectorElt(0).getInt().getBitWidth();
12538 unsigned NumBitsInQWord = 64;
12539 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
12541 Result.reserve(DestLen);
12542
12543 uint64_t CountLQWord = 0;
12544 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
12545 uint64_t Elt = Count.getVectorElt(EltIdx).getInt().getZExtValue();
12546 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
12547 }
12548
12549 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
12550 APInt Elt = Source.getVectorElt(EltIdx).getInt();
12551 if (CountLQWord < DestEltWidth) {
12552 Result.push_back(
12553 APValue(APSInt(ShiftOp(Elt, CountLQWord), IsDestUnsigned)));
12554 } else {
12555 Result.push_back(
12556 APValue(APSInt(OverflowOp(Elt, DestEltWidth), IsDestUnsigned)));
12557 }
12558 }
12559 Out = APValue(Result.data(), Result.size());
12560 return true;
12561}
12562
12563std::optional<APFloat> EvalScalarMinMaxFp(const APFloat &A, const APFloat &B,
12564 std::optional<APSInt> RoundingMode,
12565 bool IsMin) {
12566 APSInt DefaultMode(APInt(32, 4), /*isUnsigned=*/true);
12567 if (RoundingMode.value_or(DefaultMode) != 4)
12568 return std::nullopt;
12569 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
12570 B.isInfinity() || B.isDenormal())
12571 return std::nullopt;
12572 if (A.isZero() && B.isZero())
12573 return B;
12574 return IsMin ? llvm::minimum(A, B) : llvm::maximum(A, B);
12575}
12576
12577bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
12578 if (!IsConstantEvaluatedBuiltinCall(E))
12579 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12580
12581 unsigned BuiltinOp = ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E);
12582
12583 auto EvaluateBinOpExpr =
12584 [&](llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
12585 APValue SourceLHS, SourceRHS;
12586 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12587 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12588 return false;
12589
12590 auto *DestTy = E->getType()->castAs<VectorType>();
12591 QualType DestEltTy = DestTy->getElementType();
12592 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12593 unsigned SourceLen = SourceLHS.getVectorLength();
12594 SmallVector<APValue, 4> ResultElements;
12595 ResultElements.reserve(SourceLen);
12596
12597 if (SourceRHS.isInt()) {
12598 const APSInt &RHS = SourceRHS.getInt();
12599 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12600 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12601 ResultElements.push_back(
12602 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12603 }
12604 } else {
12605 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12606 const APSInt &LHS = SourceLHS.getVectorElt(EltNum).getInt();
12607 const APSInt &RHS = SourceRHS.getVectorElt(EltNum).getInt();
12608 ResultElements.push_back(
12609 APValue(APSInt(Fn(LHS, RHS), DestUnsigned)));
12610 }
12611 }
12612 return Success(APValue(ResultElements.data(), SourceLen), E);
12613 };
12614
12615 auto EvaluateFpBinOpExpr =
12616 [&](llvm::function_ref<std::optional<APFloat>(
12617 const APFloat &, const APFloat &, std::optional<APSInt>)>
12618 Fn,
12619 bool IsScalar = false) {
12620 assert(E->getNumArgs() == 2 || E->getNumArgs() == 3);
12621 APValue A, B;
12622 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
12623 !EvaluateAsRValue(Info, E->getArg(1), B))
12624 return false;
12625
12626 assert(A.isVector() && B.isVector());
12627 assert(A.getVectorLength() == B.getVectorLength());
12628
12629 std::optional<APSInt> RoundingMode;
12630 if (E->getNumArgs() == 3) {
12631 APSInt Imm;
12632 if (!EvaluateInteger(E->getArg(2), Imm, Info))
12633 return false;
12634 RoundingMode = Imm;
12635 }
12636
12637 unsigned NumElems = A.getVectorLength();
12638 SmallVector<APValue, 4> ResultElements;
12639 ResultElements.reserve(NumElems);
12640
12641 for (unsigned EltNum = 0; EltNum < NumElems; ++EltNum) {
12642 if (IsScalar && EltNum > 0) {
12643 ResultElements.push_back(A.getVectorElt(EltNum));
12644 continue;
12645 }
12646 const APFloat &EltA = A.getVectorElt(EltNum).getFloat();
12647 const APFloat &EltB = B.getVectorElt(EltNum).getFloat();
12648 std::optional<APFloat> Result = Fn(EltA, EltB, RoundingMode);
12649 if (!Result)
12650 return false;
12651 ResultElements.push_back(APValue(*Result));
12652 }
12653 return Success(APValue(ResultElements.data(), NumElems), E);
12654 };
12655
12656 auto EvaluateScalarFpRoundMaskBinOp =
12657 [&](llvm::function_ref<std::optional<APFloat>(
12658 const APFloat &, const APFloat &, std::optional<APSInt>)>
12659 Fn) {
12660 assert(E->getNumArgs() == 5);
12661 APValue VecA, VecB, VecSrc;
12662 APSInt MaskVal, Rounding;
12663
12664 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
12665 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
12666 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
12667 !EvaluateInteger(E->getArg(3), MaskVal, Info) ||
12668 !EvaluateInteger(E->getArg(4), Rounding, Info))
12669 return false;
12670
12671 unsigned NumElems = VecA.getVectorLength();
12672 SmallVector<APValue, 8> ResultElements;
12673 ResultElements.reserve(NumElems);
12674
12675 if (MaskVal.getZExtValue() & 1) {
12676 const APFloat &EltA = VecA.getVectorElt(0).getFloat();
12677 const APFloat &EltB = VecB.getVectorElt(0).getFloat();
12678 std::optional<APFloat> Result = Fn(EltA, EltB, Rounding);
12679 if (!Result)
12680 return false;
12681 ResultElements.push_back(APValue(*Result));
12682 } else {
12683 ResultElements.push_back(VecSrc.getVectorElt(0));
12684 }
12685
12686 for (unsigned I = 1; I < NumElems; ++I)
12687 ResultElements.push_back(VecA.getVectorElt(I));
12688
12689 return Success(APValue(ResultElements.data(), NumElems), E);
12690 };
12691
12692 auto EvalSelectScalar = [&](unsigned Len) -> bool {
12693 APSInt Mask;
12694 APValue AVal, WVal;
12695 if (!EvaluateInteger(E->getArg(0), Mask, Info) ||
12696 !EvaluateAsRValue(Info, E->getArg(1), AVal) ||
12697 !EvaluateAsRValue(Info, E->getArg(2), WVal))
12698 return false;
12699
12700 bool TakeA0 = (Mask.getZExtValue() & 1u) != 0;
12702 Res.reserve(Len);
12703 Res.push_back(TakeA0 ? AVal.getVectorElt(0) : WVal.getVectorElt(0));
12704 for (unsigned I = 1; I < Len; ++I)
12705 Res.push_back(WVal.getVectorElt(I));
12706 APValue V(Res.data(), Res.size());
12707 return Success(V, E);
12708 };
12709
12710 auto EvalVectorDotProduct = [&](bool IsSaturating) -> bool {
12711 APValue Source, OperandA, OperandB;
12712 if (!EvaluateVector(E->getArg(0), Source, Info) ||
12713 !EvaluateVector(E->getArg(1), OperandA, Info) ||
12714 !EvaluateVector(E->getArg(2), OperandB, Info)) {
12715 return false;
12716 }
12717
12718 unsigned NumSrcElems = Source.getVectorLength();
12719 unsigned NumOperandElems = OperandA.getVectorLength();
12720 unsigned ElemsPerLane = NumOperandElems / NumSrcElems;
12721
12722 assert(OperandA.getVectorLength() == OperandB.getVectorLength());
12723
12725 Result.reserve(NumSrcElems);
12726 for (unsigned I = 0; I != NumSrcElems; ++I) {
12727 APSInt DotProduct = Source.getVectorElt(I).getInt();
12728 DotProduct = DotProduct.extend(64);
12729 for (unsigned J = 0; J != ElemsPerLane; ++J) {
12730 APSInt OpA = APSInt(
12731 OperandA.getVectorElt(ElemsPerLane * I + J).getInt().extend(64),
12732 false);
12733 APSInt OpB = APSInt(
12734 OperandB.getVectorElt(ElemsPerLane * I + J).getInt().extend(64),
12735 false);
12736 DotProduct += OpA * OpB;
12737 }
12738 if (IsSaturating) {
12739 DotProduct = APSInt(DotProduct.truncSSat(32), false);
12740 } else {
12741 DotProduct = APSInt(DotProduct.trunc(32), false);
12742 }
12743 Result.push_back(APValue(DotProduct));
12744 }
12745
12746 return Success(APValue(Result.data(), Result.size()), E);
12747 };
12748
12749 switch (BuiltinOp) {
12750 default:
12751 return false;
12752 case Builtin::BI__builtin_elementwise_popcount:
12753 case Builtin::BI__builtin_elementwise_bitreverse: {
12754 APValue Source;
12755 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12756 return false;
12757
12758 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12759 unsigned SourceLen = Source.getVectorLength();
12760 SmallVector<APValue, 4> ResultElements;
12761 ResultElements.reserve(SourceLen);
12762
12763 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12764 APSInt Elt = Source.getVectorElt(EltNum).getInt();
12765 switch (BuiltinOp) {
12766 case Builtin::BI__builtin_elementwise_popcount:
12767 ResultElements.push_back(APValue(
12768 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
12769 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12770 break;
12771 case Builtin::BI__builtin_elementwise_bitreverse:
12772 ResultElements.push_back(
12773 APValue(APSInt(Elt.reverseBits(),
12774 DestEltTy->isUnsignedIntegerOrEnumerationType())));
12775 break;
12776 }
12777 }
12778
12779 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12780 }
12781 case Builtin::BI__builtin_elementwise_abs: {
12782 APValue Source;
12783 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
12784 return false;
12785
12786 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
12787 unsigned SourceLen = Source.getVectorLength();
12788 SmallVector<APValue, 4> ResultElements;
12789 ResultElements.reserve(SourceLen);
12790
12791 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12792 APValue CurrentEle = Source.getVectorElt(EltNum);
12793 APValue Val = DestEltTy->isFloatingType()
12794 ? APValue(llvm::abs(CurrentEle.getFloat()))
12795 : APValue(APSInt(
12796 CurrentEle.getInt().abs(),
12797 DestEltTy->isUnsignedIntegerOrEnumerationType()));
12798 ResultElements.push_back(Val);
12799 }
12800
12801 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12802 }
12803
12804 case Builtin::BI__builtin_elementwise_add_sat:
12805 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12806 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
12807 });
12808
12809 case Builtin::BI__builtin_elementwise_sub_sat:
12810 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12811 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
12812 });
12813
12814 case X86::BI__builtin_ia32_extract128i256:
12815 case X86::BI__builtin_ia32_vextractf128_pd256:
12816 case X86::BI__builtin_ia32_vextractf128_ps256:
12817 case X86::BI__builtin_ia32_vextractf128_si256: {
12818 APValue SourceVec, SourceImm;
12819 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12820 !EvaluateAsRValue(Info, E->getArg(1), SourceImm))
12821 return false;
12822
12823 if (!SourceVec.isVector())
12824 return false;
12825
12826 const auto *RetVT = E->getType()->castAs<VectorType>();
12827 unsigned RetLen = RetVT->getNumElements();
12828 unsigned Idx = SourceImm.getInt().getZExtValue() & 1;
12829
12830 SmallVector<APValue, 32> ResultElements;
12831 ResultElements.reserve(RetLen);
12832
12833 for (unsigned I = 0; I < RetLen; I++)
12834 ResultElements.push_back(SourceVec.getVectorElt(Idx * RetLen + I));
12835
12836 return Success(APValue(ResultElements.data(), RetLen), E);
12837 }
12838
12839 case clang::X86::BI__builtin_ia32_cvtmask2b128:
12840 case clang::X86::BI__builtin_ia32_cvtmask2b256:
12841 case clang::X86::BI__builtin_ia32_cvtmask2b512:
12842 case clang::X86::BI__builtin_ia32_cvtmask2w128:
12843 case clang::X86::BI__builtin_ia32_cvtmask2w256:
12844 case clang::X86::BI__builtin_ia32_cvtmask2w512:
12845 case clang::X86::BI__builtin_ia32_cvtmask2d128:
12846 case clang::X86::BI__builtin_ia32_cvtmask2d256:
12847 case clang::X86::BI__builtin_ia32_cvtmask2d512:
12848 case clang::X86::BI__builtin_ia32_cvtmask2q128:
12849 case clang::X86::BI__builtin_ia32_cvtmask2q256:
12850 case clang::X86::BI__builtin_ia32_cvtmask2q512: {
12851 assert(E->getNumArgs() == 1);
12852 APSInt Mask;
12853 if (!EvaluateInteger(E->getArg(0), Mask, Info))
12854 return false;
12855
12856 QualType VecTy = E->getType();
12857 const VectorType *VT = VecTy->castAs<VectorType>();
12858 unsigned VectorLen = VT->getNumElements();
12859 QualType ElemTy = VT->getElementType();
12860 unsigned ElemWidth = Info.Ctx.getTypeSize(ElemTy);
12861
12863 for (unsigned I = 0; I != VectorLen; ++I) {
12864 bool BitSet = Mask[I];
12865 APSInt ElemVal(ElemWidth, /*isUnsigned=*/false);
12866 if (BitSet) {
12867 ElemVal.setAllBits();
12868 }
12869 Elems.push_back(APValue(ElemVal));
12870 }
12871 return Success(APValue(Elems.data(), VectorLen), E);
12872 }
12873
12874 case X86::BI__builtin_ia32_extracti32x4_256_mask:
12875 case X86::BI__builtin_ia32_extractf32x4_256_mask:
12876 case X86::BI__builtin_ia32_extracti32x4_mask:
12877 case X86::BI__builtin_ia32_extractf32x4_mask:
12878 case X86::BI__builtin_ia32_extracti32x8_mask:
12879 case X86::BI__builtin_ia32_extractf32x8_mask:
12880 case X86::BI__builtin_ia32_extracti64x2_256_mask:
12881 case X86::BI__builtin_ia32_extractf64x2_256_mask:
12882 case X86::BI__builtin_ia32_extracti64x2_512_mask:
12883 case X86::BI__builtin_ia32_extractf64x2_512_mask:
12884 case X86::BI__builtin_ia32_extracti64x4_mask:
12885 case X86::BI__builtin_ia32_extractf64x4_mask: {
12886 APValue SourceVec, MergeVec;
12887 APSInt Imm, MaskImm;
12888
12889 if (!EvaluateAsRValue(Info, E->getArg(0), SourceVec) ||
12890 !EvaluateInteger(E->getArg(1), Imm, Info) ||
12891 !EvaluateAsRValue(Info, E->getArg(2), MergeVec) ||
12892 !EvaluateInteger(E->getArg(3), MaskImm, Info))
12893 return false;
12894
12895 const auto *RetVT = E->getType()->castAs<VectorType>();
12896 unsigned RetLen = RetVT->getNumElements();
12897
12898 if (!SourceVec.isVector() || !MergeVec.isVector())
12899 return false;
12900 unsigned SrcLen = SourceVec.getVectorLength();
12901 unsigned Lanes = SrcLen / RetLen;
12902 unsigned Lane = static_cast<unsigned>(Imm.getZExtValue() % Lanes);
12903 unsigned Base = Lane * RetLen;
12904
12905 SmallVector<APValue, 32> ResultElements;
12906 ResultElements.reserve(RetLen);
12907 for (unsigned I = 0; I < RetLen; ++I) {
12908 if (MaskImm[I])
12909 ResultElements.push_back(SourceVec.getVectorElt(Base + I));
12910 else
12911 ResultElements.push_back(MergeVec.getVectorElt(I));
12912 }
12913 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12914 }
12915
12916 case clang::X86::BI__builtin_ia32_pavgb128:
12917 case clang::X86::BI__builtin_ia32_pavgw128:
12918 case clang::X86::BI__builtin_ia32_pavgb256:
12919 case clang::X86::BI__builtin_ia32_pavgw256:
12920 case clang::X86::BI__builtin_ia32_pavgb512:
12921 case clang::X86::BI__builtin_ia32_pavgw512:
12922 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
12923
12924 case clang::X86::BI__builtin_ia32_pmulhrsw128:
12925 case clang::X86::BI__builtin_ia32_pmulhrsw256:
12926 case clang::X86::BI__builtin_ia32_pmulhrsw512:
12927 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
12928 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
12929 .extractBits(16, 1);
12930 });
12931
12932 case clang::X86::BI__builtin_ia32_psadbw128:
12933 case clang::X86::BI__builtin_ia32_psadbw256:
12934 case clang::X86::BI__builtin_ia32_psadbw512: {
12935 APValue SourceLHS, SourceRHS;
12936 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12937 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12938 return false;
12939
12940 assert(SourceLHS.isVector() && SourceRHS.isVector());
12941 unsigned SourceLen = SourceLHS.getVectorLength();
12942 assert(SourceLen == SourceRHS.getVectorLength());
12943 assert((SourceLen % 8) == 0);
12944
12945 auto *DestTy = E->getType()->castAs<VectorType>();
12946 QualType DestEltTy = DestTy->getElementType();
12947 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12948 SmallVector<APValue, 8> ResultElements;
12949 ResultElements.reserve(SourceLen / 8);
12950
12951 for (unsigned Lane = 0; Lane != SourceLen; Lane += 8) {
12952 APInt Sum(64, 0);
12953 for (unsigned I = 0; I != 8; ++I) {
12954 APInt LHS = SourceLHS.getVectorElt(Lane + I).getInt().extOrTrunc(8);
12955 APInt RHS = SourceRHS.getVectorElt(Lane + I).getInt().extOrTrunc(8);
12956 Sum += llvm::APIntOps::abdu(LHS, RHS).zext(64);
12957 }
12958 ResultElements.push_back(APValue(APSInt(Sum, DestUnsigned)));
12959 }
12960
12961 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
12962 }
12963
12964 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12965 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12966 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12967 case clang::X86::BI__builtin_ia32_pmaddwd128:
12968 case clang::X86::BI__builtin_ia32_pmaddwd256:
12969 case clang::X86::BI__builtin_ia32_pmaddwd512: {
12970 APValue SourceLHS, SourceRHS;
12971 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
12972 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
12973 return false;
12974
12975 auto *DestTy = E->getType()->castAs<VectorType>();
12976 QualType DestEltTy = DestTy->getElementType();
12977 unsigned SourceLen = SourceLHS.getVectorLength();
12978 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12979 SmallVector<APValue, 4> ResultElements;
12980 ResultElements.reserve(SourceLen / 2);
12981
12982 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
12983 const APSInt &LoLHS = SourceLHS.getVectorElt(EltNum).getInt();
12984 const APSInt &HiLHS = SourceLHS.getVectorElt(EltNum + 1).getInt();
12985 const APSInt &LoRHS = SourceRHS.getVectorElt(EltNum).getInt();
12986 const APSInt &HiRHS = SourceRHS.getVectorElt(EltNum + 1).getInt();
12987 unsigned BitWidth = 2 * LoLHS.getBitWidth();
12988
12989 switch (BuiltinOp) {
12990 case clang::X86::BI__builtin_ia32_pmaddubsw128:
12991 case clang::X86::BI__builtin_ia32_pmaddubsw256:
12992 case clang::X86::BI__builtin_ia32_pmaddubsw512:
12993 ResultElements.push_back(APValue(
12994 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
12995 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
12996 DestUnsigned)));
12997 break;
12998 case clang::X86::BI__builtin_ia32_pmaddwd128:
12999 case clang::X86::BI__builtin_ia32_pmaddwd256:
13000 case clang::X86::BI__builtin_ia32_pmaddwd512:
13001 ResultElements.push_back(
13002 APValue(APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
13003 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
13004 DestUnsigned)));
13005 break;
13006 }
13007 }
13008
13009 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13010 }
13011
13012 case clang::X86::BI__builtin_ia32_bmacor16x16x16_v16hi:
13013 case clang::X86::BI__builtin_ia32_bmacor16x16x16_v32hi:
13014 case clang::X86::BI__builtin_ia32_bmacxor16x16x16_v16hi:
13015 case clang::X86::BI__builtin_ia32_bmacxor16x16x16_v32hi: {
13016 // Bit Matrix Multiply and Accumulate (AVX512BMM). Each 256-bit lane holds
13017 // a 16x16 bit matrix as 16 x i16 elements; element i is row i and bit j of
13018 // that element is entry [i][j]. The accumulator (third argument, src1 in
13019 // the AMD ISA) provides the initial value of each result bit, into which
13020 // the bit-matrix product of the first two arguments (src2 * src3) is
13021 // reduced with OR (vbmacor) or XOR (vbmacxor):
13022 // for i in 0..15, j in 0..15:
13023 // bit = C[16*i+j]
13024 // for k in 0..15: bit OP= A[16*i+k] & B[16*k+j]
13025 // dest[16*i+j] = bit
13026 APValue SourceA, SourceB, SourceC;
13027 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
13028 !EvaluateAsRValue(Info, E->getArg(1), SourceB) ||
13029 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13030 return false;
13031
13032 bool IsXor = E->getBuiltinCallee() ==
13033 clang::X86::BI__builtin_ia32_bmacxor16x16x16_v16hi ||
13034 E->getBuiltinCallee() ==
13035 clang::X86::BI__builtin_ia32_bmacxor16x16x16_v32hi;
13036
13037 unsigned SourceLen = SourceA.getVectorLength();
13038 assert(SourceLen % 16 == 0 && "BMM operates on 256-bit lanes of 16 x i16");
13039 auto *DestTy = E->getType()->castAs<VectorType>();
13040 QualType DestEltTy = DestTy->getElementType();
13041 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13042
13043 SmallVector<APValue, 32> ResultElements(SourceLen);
13044 for (unsigned Lane = 0; Lane != SourceLen; Lane += 16) {
13045 for (unsigned I = 0; I != 16; ++I) {
13046 uint16_t A =
13047 (uint16_t)SourceA.getVectorElt(Lane + I).getInt().getZExtValue();
13048 uint16_t Dst =
13049 (uint16_t)SourceC.getVectorElt(Lane + I).getInt().getZExtValue();
13050 for (unsigned J = 0; J != 16; ++J) {
13051 // Seed the reduction with the accumulator bit, then fold in each
13052 // product term with the same operator (OR for vbmacor, XOR for
13053 // vbmacxor).
13054 unsigned Bit = (Dst >> J) & 1u;
13055 for (unsigned K = 0; K != 16; ++K) {
13056 uint16_t B = (uint16_t)SourceB.getVectorElt(Lane + K)
13057 .getInt()
13058 .getZExtValue();
13059 unsigned Product = ((A >> K) & 1u) & ((B >> J) & 1u);
13060 Bit = IsXor ? (Bit ^ Product) : (Bit | Product);
13061 }
13062 Dst = (Dst & ~(uint16_t(1) << J)) | (uint16_t(Bit) << J);
13063 }
13064 ResultElements[Lane + I] =
13065 APValue(APSInt(APInt(16, Dst), DestUnsigned));
13066 }
13067 }
13068 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13069 }
13070
13071 case clang::X86::BI__builtin_ia32_dbpsadbw128:
13072 case clang::X86::BI__builtin_ia32_dbpsadbw256:
13073 case clang::X86::BI__builtin_ia32_dbpsadbw512: {
13074 APValue SourceA, SourceB, SourceImm;
13075 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
13076 !EvaluateAsRValue(Info, E->getArg(1), SourceB) ||
13077 !EvaluateAsRValue(Info, E->getArg(2), SourceImm))
13078 return false;
13079
13080 unsigned SourceLen = SourceA.getVectorLength();
13081 constexpr unsigned LaneSize = 16; // 128-bit lane = 16 bytes
13082 unsigned Imm = SourceImm.getInt().getZExtValue();
13083
13084 auto *DestTy = E->getType()->castAs<VectorType>();
13085 QualType DestEltTy = DestTy->getElementType();
13086 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13087 SmallVector<APValue, 32> ResultElements;
13088 ResultElements.reserve(SourceLen / 2);
13089
13090 // Phase 1: Shuffle SourceB using all four 2-bit fields of imm8.
13091 // Within each 128-bit lane, for group j (0..3), select a 4-byte block
13092 // from SourceB based on bits [2*j+1:2*j] of imm8.
13093 SmallVector<uint8_t, 64> Shuffled(SourceLen);
13094 for (unsigned I = 0; I < SourceLen; I += LaneSize) {
13095 for (unsigned J = 0; J < 4; ++J) {
13096 unsigned Part = (Imm >> (2 * J)) & 3;
13097 for (unsigned K = 0; K < 4; ++K) {
13098 Shuffled[I + 4 * J + K] = static_cast<uint8_t>(
13099 SourceB.getVectorElt(I + 4 * Part + K).getInt().getZExtValue());
13100 }
13101 }
13102 }
13103
13104 // Phase 2: Sliding SAD computation.
13105 // For every group of 4 output u16 values, compute absolute differences
13106 // using overlapping windows into SourceA and the shuffled array.
13107 unsigned Size = SourceLen / 2; // number of output u16 elements
13108 for (unsigned I = 0; I < Size; I += 4) {
13109 unsigned Sad[4] = {0, 0, 0, 0};
13110 for (unsigned J = 0; J < 4; ++J) {
13111 uint8_t A1 = static_cast<uint8_t>(
13112 SourceA.getVectorElt(2 * I + J).getInt().getZExtValue());
13113 uint8_t A2 = static_cast<uint8_t>(
13114 SourceA.getVectorElt(2 * I + J + 4).getInt().getZExtValue());
13115 uint8_t B0 = Shuffled[2 * I + J];
13116 uint8_t B1 = Shuffled[2 * I + J + 1];
13117 uint8_t B2 = Shuffled[2 * I + J + 2];
13118 uint8_t B3 = Shuffled[2 * I + J + 3];
13119 Sad[0] += (A1 > B0) ? (A1 - B0) : (B0 - A1);
13120 Sad[1] += (A1 > B1) ? (A1 - B1) : (B1 - A1);
13121 Sad[2] += (A2 > B2) ? (A2 - B2) : (B2 - A2);
13122 Sad[3] += (A2 > B3) ? (A2 - B3) : (B3 - A2);
13123 }
13124 for (unsigned R = 0; R < 4; ++R)
13125 ResultElements.push_back(
13126 APValue(APSInt(APInt(16, Sad[R]), DestUnsigned)));
13127 }
13128
13129 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13130 }
13131
13132 case clang::X86::BI__builtin_ia32_mpsadbw128:
13133 case clang::X86::BI__builtin_ia32_mpsadbw256: {
13134 APValue SourceA, SourceB;
13135 APSInt SourceImm;
13136 if (!EvaluateVector(E->getArg(0), SourceA, Info) ||
13137 !EvaluateVector(E->getArg(1), SourceB, Info) ||
13138 !EvaluateInteger(E->getArg(2), SourceImm, Info))
13139 return false;
13140 unsigned SourceLen = SourceA.getVectorLength();
13141 constexpr unsigned LaneSize = 16;
13142 assert((SourceLen == LaneSize || SourceLen == 2 * LaneSize) &&
13143 "MPSADBW operates on 128-bit or 256-bit vectors");
13144 unsigned NumLanes = SourceLen / LaneSize;
13145 unsigned Imm = SourceImm.getZExtValue();
13146
13147 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13148 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13149 SmallVector<APValue, 16> ResultElements;
13150 ResultElements.reserve(SourceLen / 2);
13151
13152 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
13153 unsigned Ctrl = (Imm >> (3 * Lane)) & 0x7;
13154 unsigned AOff = ((Ctrl >> 2) & 1) * 4;
13155 unsigned BOff = (Ctrl & 3) * 4;
13156 for (unsigned J = 0; J != 8; ++J) {
13157 uint16_t Sad = 0;
13158 for (unsigned K = 0; K != 4; ++K) {
13159 uint8_t A = static_cast<uint8_t>(
13160 SourceA.getVectorElt(Lane * LaneSize + AOff + J + K)
13161 .getInt()
13162 .getZExtValue());
13163 uint8_t B = static_cast<uint8_t>(
13164 SourceB.getVectorElt(Lane * LaneSize + BOff + K)
13165 .getInt()
13166 .getZExtValue());
13167 Sad += (A > B) ? (A - B) : (B - A);
13168 }
13169 ResultElements.push_back(APValue(APSInt(APInt(16, Sad), DestUnsigned)));
13170 }
13171 }
13172 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13173 }
13174
13175 case clang::X86::BI__builtin_ia32_pmulhuw128:
13176 case clang::X86::BI__builtin_ia32_pmulhuw256:
13177 case clang::X86::BI__builtin_ia32_pmulhuw512:
13178 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
13179
13180 case clang::X86::BI__builtin_ia32_pmulhw128:
13181 case clang::X86::BI__builtin_ia32_pmulhw256:
13182 case clang::X86::BI__builtin_ia32_pmulhw512:
13183 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
13184
13185 case clang::X86::BI__builtin_ia32_psllv2di:
13186 case clang::X86::BI__builtin_ia32_psllv4di:
13187 case clang::X86::BI__builtin_ia32_psllv4si:
13188 case clang::X86::BI__builtin_ia32_psllv8di:
13189 case clang::X86::BI__builtin_ia32_psllv8hi:
13190 case clang::X86::BI__builtin_ia32_psllv8si:
13191 case clang::X86::BI__builtin_ia32_psllv16hi:
13192 case clang::X86::BI__builtin_ia32_psllv16si:
13193 case clang::X86::BI__builtin_ia32_psllv32hi:
13194 case clang::X86::BI__builtin_ia32_psllwi128:
13195 case clang::X86::BI__builtin_ia32_pslldi128:
13196 case clang::X86::BI__builtin_ia32_psllqi128:
13197 case clang::X86::BI__builtin_ia32_psllwi256:
13198 case clang::X86::BI__builtin_ia32_pslldi256:
13199 case clang::X86::BI__builtin_ia32_psllqi256:
13200 case clang::X86::BI__builtin_ia32_psllwi512:
13201 case clang::X86::BI__builtin_ia32_pslldi512:
13202 case clang::X86::BI__builtin_ia32_psllqi512:
13203 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13204 if (RHS.uge(LHS.getBitWidth())) {
13205 return APInt::getZero(LHS.getBitWidth());
13206 }
13207 return LHS.shl(RHS.getZExtValue());
13208 });
13209
13210 case clang::X86::BI__builtin_ia32_psrav4si:
13211 case clang::X86::BI__builtin_ia32_psrav8di:
13212 case clang::X86::BI__builtin_ia32_psrav8hi:
13213 case clang::X86::BI__builtin_ia32_psrav8si:
13214 case clang::X86::BI__builtin_ia32_psrav16hi:
13215 case clang::X86::BI__builtin_ia32_psrav16si:
13216 case clang::X86::BI__builtin_ia32_psrav32hi:
13217 case clang::X86::BI__builtin_ia32_psravq128:
13218 case clang::X86::BI__builtin_ia32_psravq256:
13219 case clang::X86::BI__builtin_ia32_psrawi128:
13220 case clang::X86::BI__builtin_ia32_psradi128:
13221 case clang::X86::BI__builtin_ia32_psraqi128:
13222 case clang::X86::BI__builtin_ia32_psrawi256:
13223 case clang::X86::BI__builtin_ia32_psradi256:
13224 case clang::X86::BI__builtin_ia32_psraqi256:
13225 case clang::X86::BI__builtin_ia32_psrawi512:
13226 case clang::X86::BI__builtin_ia32_psradi512:
13227 case clang::X86::BI__builtin_ia32_psraqi512:
13228 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13229 if (RHS.uge(LHS.getBitWidth())) {
13230 return LHS.ashr(LHS.getBitWidth() - 1);
13231 }
13232 return LHS.ashr(RHS.getZExtValue());
13233 });
13234
13235 case clang::X86::BI__builtin_ia32_psrlv2di:
13236 case clang::X86::BI__builtin_ia32_psrlv4di:
13237 case clang::X86::BI__builtin_ia32_psrlv4si:
13238 case clang::X86::BI__builtin_ia32_psrlv8di:
13239 case clang::X86::BI__builtin_ia32_psrlv8hi:
13240 case clang::X86::BI__builtin_ia32_psrlv8si:
13241 case clang::X86::BI__builtin_ia32_psrlv16hi:
13242 case clang::X86::BI__builtin_ia32_psrlv16si:
13243 case clang::X86::BI__builtin_ia32_psrlv32hi:
13244 case clang::X86::BI__builtin_ia32_psrlwi128:
13245 case clang::X86::BI__builtin_ia32_psrldi128:
13246 case clang::X86::BI__builtin_ia32_psrlqi128:
13247 case clang::X86::BI__builtin_ia32_psrlwi256:
13248 case clang::X86::BI__builtin_ia32_psrldi256:
13249 case clang::X86::BI__builtin_ia32_psrlqi256:
13250 case clang::X86::BI__builtin_ia32_psrlwi512:
13251 case clang::X86::BI__builtin_ia32_psrldi512:
13252 case clang::X86::BI__builtin_ia32_psrlqi512:
13253 return EvaluateBinOpExpr([](const APSInt &LHS, const APSInt &RHS) {
13254 if (RHS.uge(LHS.getBitWidth())) {
13255 return APInt::getZero(LHS.getBitWidth());
13256 }
13257 return LHS.lshr(RHS.getZExtValue());
13258 });
13259 case X86::BI__builtin_ia32_packsswb128:
13260 case X86::BI__builtin_ia32_packsswb256:
13261 case X86::BI__builtin_ia32_packsswb512:
13262 case X86::BI__builtin_ia32_packssdw128:
13263 case X86::BI__builtin_ia32_packssdw256:
13264 case X86::BI__builtin_ia32_packssdw512:
13265 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
13266 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
13267 });
13268 case X86::BI__builtin_ia32_packusdw128:
13269 case X86::BI__builtin_ia32_packusdw256:
13270 case X86::BI__builtin_ia32_packusdw512:
13271 case X86::BI__builtin_ia32_packuswb128:
13272 case X86::BI__builtin_ia32_packuswb256:
13273 case X86::BI__builtin_ia32_packuswb512:
13274 return evalPackBuiltin(E, Info, Result, [](const APSInt &Src) {
13275 return APSInt(Src).truncSSatU(Src.getBitWidth() / 2);
13276 });
13277 case clang::X86::BI__builtin_ia32_selectss_128:
13278 return EvalSelectScalar(4);
13279 case clang::X86::BI__builtin_ia32_selectsd_128:
13280 return EvalSelectScalar(2);
13281 case clang::X86::BI__builtin_ia32_selectsh_128:
13282 case clang::X86::BI__builtin_ia32_selectsbf_128:
13283 return EvalSelectScalar(8);
13284 case clang::X86::BI__builtin_ia32_pmuldq128:
13285 case clang::X86::BI__builtin_ia32_pmuldq256:
13286 case clang::X86::BI__builtin_ia32_pmuldq512:
13287 case clang::X86::BI__builtin_ia32_pmuludq128:
13288 case clang::X86::BI__builtin_ia32_pmuludq256:
13289 case clang::X86::BI__builtin_ia32_pmuludq512: {
13290 APValue SourceLHS, SourceRHS;
13291 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13292 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13293 return false;
13294
13295 unsigned SourceLen = SourceLHS.getVectorLength();
13296 SmallVector<APValue, 4> ResultElements;
13297 ResultElements.reserve(SourceLen / 2);
13298
13299 for (unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
13300 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13301 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
13302
13303 switch (BuiltinOp) {
13304 case clang::X86::BI__builtin_ia32_pmuludq128:
13305 case clang::X86::BI__builtin_ia32_pmuludq256:
13306 case clang::X86::BI__builtin_ia32_pmuludq512:
13307 ResultElements.push_back(
13308 APValue(APSInt(llvm::APIntOps::muluExtended(LHS, RHS), true)));
13309 break;
13310 case clang::X86::BI__builtin_ia32_pmuldq128:
13311 case clang::X86::BI__builtin_ia32_pmuldq256:
13312 case clang::X86::BI__builtin_ia32_pmuldq512:
13313 ResultElements.push_back(
13314 APValue(APSInt(llvm::APIntOps::mulsExtended(LHS, RHS), false)));
13315 break;
13316 }
13317 }
13318
13319 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13320 }
13321
13322 case X86::BI__builtin_ia32_vpmadd52luq128:
13323 case X86::BI__builtin_ia32_vpmadd52luq256:
13324 case X86::BI__builtin_ia32_vpmadd52luq512: {
13325 APValue A, B, C;
13326 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
13327 !EvaluateAsRValue(Info, E->getArg(1), B) ||
13328 !EvaluateAsRValue(Info, E->getArg(2), C))
13329 return false;
13330
13331 unsigned ALen = A.getVectorLength();
13332 SmallVector<APValue, 4> ResultElements;
13333 ResultElements.reserve(ALen);
13334
13335 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
13336 APInt AElt = A.getVectorElt(EltNum).getInt();
13337 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
13338 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
13339 APSInt ResElt(AElt + (BElt * CElt).zext(64), false);
13340 ResultElements.push_back(APValue(ResElt));
13341 }
13342
13343 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13344 }
13345 case X86::BI__builtin_ia32_vpmadd52huq128:
13346 case X86::BI__builtin_ia32_vpmadd52huq256:
13347 case X86::BI__builtin_ia32_vpmadd52huq512: {
13348 APValue A, B, C;
13349 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
13350 !EvaluateAsRValue(Info, E->getArg(1), B) ||
13351 !EvaluateAsRValue(Info, E->getArg(2), C))
13352 return false;
13353
13354 unsigned ALen = A.getVectorLength();
13355 SmallVector<APValue, 4> ResultElements;
13356 ResultElements.reserve(ALen);
13357
13358 for (unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
13359 APInt AElt = A.getVectorElt(EltNum).getInt();
13360 APInt BElt = B.getVectorElt(EltNum).getInt().trunc(52);
13361 APInt CElt = C.getVectorElt(EltNum).getInt().trunc(52);
13362 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64), false);
13363 ResultElements.push_back(APValue(ResElt));
13364 }
13365
13366 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13367 }
13368
13369 case clang::X86::BI__builtin_ia32_vprotbi:
13370 case clang::X86::BI__builtin_ia32_vprotdi:
13371 case clang::X86::BI__builtin_ia32_vprotqi:
13372 case clang::X86::BI__builtin_ia32_vprotwi:
13373 case clang::X86::BI__builtin_ia32_prold128:
13374 case clang::X86::BI__builtin_ia32_prold256:
13375 case clang::X86::BI__builtin_ia32_prold512:
13376 case clang::X86::BI__builtin_ia32_prolq128:
13377 case clang::X86::BI__builtin_ia32_prolq256:
13378 case clang::X86::BI__builtin_ia32_prolq512:
13379 return EvaluateBinOpExpr(
13380 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
13381
13382 case clang::X86::BI__builtin_ia32_prord128:
13383 case clang::X86::BI__builtin_ia32_prord256:
13384 case clang::X86::BI__builtin_ia32_prord512:
13385 case clang::X86::BI__builtin_ia32_prorq128:
13386 case clang::X86::BI__builtin_ia32_prorq256:
13387 case clang::X86::BI__builtin_ia32_prorq512:
13388 return EvaluateBinOpExpr(
13389 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
13390
13391 case Builtin::BI__builtin_elementwise_max:
13392 case Builtin::BI__builtin_elementwise_min: {
13393 APValue SourceLHS, SourceRHS;
13394 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
13395 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
13396 return false;
13397
13398 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13399
13400 if (!DestEltTy->isIntegerType())
13401 return false;
13402
13403 unsigned SourceLen = SourceLHS.getVectorLength();
13404 SmallVector<APValue, 4> ResultElements;
13405 ResultElements.reserve(SourceLen);
13406
13407 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13408 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
13409 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
13410 switch (BuiltinOp) {
13411 case Builtin::BI__builtin_elementwise_max:
13412 ResultElements.push_back(
13413 APValue(APSInt(std::max(LHS, RHS),
13414 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13415 break;
13416 case Builtin::BI__builtin_elementwise_min:
13417 ResultElements.push_back(
13418 APValue(APSInt(std::min(LHS, RHS),
13419 DestEltTy->isUnsignedIntegerOrEnumerationType())));
13420 break;
13421 }
13422 }
13423
13424 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13425 }
13426 case X86::BI__builtin_ia32_vpshldd128:
13427 case X86::BI__builtin_ia32_vpshldd256:
13428 case X86::BI__builtin_ia32_vpshldd512:
13429 case X86::BI__builtin_ia32_vpshldq128:
13430 case X86::BI__builtin_ia32_vpshldq256:
13431 case X86::BI__builtin_ia32_vpshldq512:
13432 case X86::BI__builtin_ia32_vpshldw128:
13433 case X86::BI__builtin_ia32_vpshldw256:
13434 case X86::BI__builtin_ia32_vpshldw512: {
13435 APValue SourceHi, SourceLo, SourceAmt;
13436 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
13437 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
13438 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
13439 return false;
13440
13441 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13442 unsigned SourceLen = SourceHi.getVectorLength();
13443 SmallVector<APValue, 32> ResultElements;
13444 ResultElements.reserve(SourceLen);
13445
13446 APInt Amt = SourceAmt.getInt();
13447 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13448 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
13449 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
13450 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
13451 ResultElements.push_back(
13453 }
13454
13455 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13456 }
13457 case X86::BI__builtin_ia32_vpshrdd128:
13458 case X86::BI__builtin_ia32_vpshrdd256:
13459 case X86::BI__builtin_ia32_vpshrdd512:
13460 case X86::BI__builtin_ia32_vpshrdq128:
13461 case X86::BI__builtin_ia32_vpshrdq256:
13462 case X86::BI__builtin_ia32_vpshrdq512:
13463 case X86::BI__builtin_ia32_vpshrdw128:
13464 case X86::BI__builtin_ia32_vpshrdw256:
13465 case X86::BI__builtin_ia32_vpshrdw512: {
13466 // NOTE: Reversed Hi/Lo operands.
13467 APValue SourceHi, SourceLo, SourceAmt;
13468 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLo) ||
13469 !EvaluateAsRValue(Info, E->getArg(1), SourceHi) ||
13470 !EvaluateAsRValue(Info, E->getArg(2), SourceAmt))
13471 return false;
13472
13473 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
13474 unsigned SourceLen = SourceHi.getVectorLength();
13475 SmallVector<APValue, 32> ResultElements;
13476 ResultElements.reserve(SourceLen);
13477
13478 APInt Amt = SourceAmt.getInt();
13479 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13480 APInt Hi = SourceHi.getVectorElt(EltNum).getInt();
13481 APInt Lo = SourceLo.getVectorElt(EltNum).getInt();
13482 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
13483 ResultElements.push_back(
13485 }
13486
13487 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13488 }
13489 case X86::BI__builtin_ia32_compressdf128_mask:
13490 case X86::BI__builtin_ia32_compressdf256_mask:
13491 case X86::BI__builtin_ia32_compressdf512_mask:
13492 case X86::BI__builtin_ia32_compressdi128_mask:
13493 case X86::BI__builtin_ia32_compressdi256_mask:
13494 case X86::BI__builtin_ia32_compressdi512_mask:
13495 case X86::BI__builtin_ia32_compresshi128_mask:
13496 case X86::BI__builtin_ia32_compresshi256_mask:
13497 case X86::BI__builtin_ia32_compresshi512_mask:
13498 case X86::BI__builtin_ia32_compressqi128_mask:
13499 case X86::BI__builtin_ia32_compressqi256_mask:
13500 case X86::BI__builtin_ia32_compressqi512_mask:
13501 case X86::BI__builtin_ia32_compresssf128_mask:
13502 case X86::BI__builtin_ia32_compresssf256_mask:
13503 case X86::BI__builtin_ia32_compresssf512_mask:
13504 case X86::BI__builtin_ia32_compresssi128_mask:
13505 case X86::BI__builtin_ia32_compresssi256_mask:
13506 case X86::BI__builtin_ia32_compresssi512_mask: {
13507 APValue Source, Passthru;
13508 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13509 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13510 return false;
13511 APSInt Mask;
13512 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13513 return false;
13514
13515 unsigned NumElts = Source.getVectorLength();
13516 SmallVector<APValue, 64> ResultElements;
13517 ResultElements.reserve(NumElts);
13518
13519 for (unsigned I = 0; I != NumElts; ++I) {
13520 if (Mask[I])
13521 ResultElements.push_back(Source.getVectorElt(I));
13522 }
13523 for (unsigned I = ResultElements.size(); I != NumElts; ++I) {
13524 ResultElements.push_back(Passthru.getVectorElt(I));
13525 }
13526
13527 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13528 }
13529 case X86::BI__builtin_ia32_expanddf128_mask:
13530 case X86::BI__builtin_ia32_expanddf256_mask:
13531 case X86::BI__builtin_ia32_expanddf512_mask:
13532 case X86::BI__builtin_ia32_expanddi128_mask:
13533 case X86::BI__builtin_ia32_expanddi256_mask:
13534 case X86::BI__builtin_ia32_expanddi512_mask:
13535 case X86::BI__builtin_ia32_expandhi128_mask:
13536 case X86::BI__builtin_ia32_expandhi256_mask:
13537 case X86::BI__builtin_ia32_expandhi512_mask:
13538 case X86::BI__builtin_ia32_expandqi128_mask:
13539 case X86::BI__builtin_ia32_expandqi256_mask:
13540 case X86::BI__builtin_ia32_expandqi512_mask:
13541 case X86::BI__builtin_ia32_expandsf128_mask:
13542 case X86::BI__builtin_ia32_expandsf256_mask:
13543 case X86::BI__builtin_ia32_expandsf512_mask:
13544 case X86::BI__builtin_ia32_expandsi128_mask:
13545 case X86::BI__builtin_ia32_expandsi256_mask:
13546 case X86::BI__builtin_ia32_expandsi512_mask: {
13547 APValue Source, Passthru;
13548 if (!EvaluateAsRValue(Info, E->getArg(0), Source) ||
13549 !EvaluateAsRValue(Info, E->getArg(1), Passthru))
13550 return false;
13551 APSInt Mask;
13552 if (!EvaluateInteger(E->getArg(2), Mask, Info))
13553 return false;
13554
13555 unsigned NumElts = Source.getVectorLength();
13556 SmallVector<APValue, 64> ResultElements;
13557 ResultElements.reserve(NumElts);
13558
13559 unsigned SourceIdx = 0;
13560 for (unsigned I = 0; I != NumElts; ++I) {
13561 if (Mask[I])
13562 ResultElements.push_back(Source.getVectorElt(SourceIdx++));
13563 else
13564 ResultElements.push_back(Passthru.getVectorElt(I));
13565 }
13566 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13567 }
13568 case X86::BI__builtin_ia32_vpconflictsi_128:
13569 case X86::BI__builtin_ia32_vpconflictsi_256:
13570 case X86::BI__builtin_ia32_vpconflictsi_512:
13571 case X86::BI__builtin_ia32_vpconflictdi_128:
13572 case X86::BI__builtin_ia32_vpconflictdi_256:
13573 case X86::BI__builtin_ia32_vpconflictdi_512: {
13574 APValue Source;
13575
13576 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13577 return false;
13578
13579 unsigned SourceLen = Source.getVectorLength();
13580 SmallVector<APValue, 32> ResultElements;
13581 ResultElements.reserve(SourceLen);
13582
13583 const auto *VecT = E->getType()->castAs<VectorType>();
13584 bool DestUnsigned =
13585 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
13586
13587 for (unsigned I = 0; I != SourceLen; ++I) {
13588 const APValue &EltI = Source.getVectorElt(I);
13589
13590 APInt ConflictMask(EltI.getInt().getBitWidth(), 0);
13591 for (unsigned J = 0; J != I; ++J) {
13592 const APValue &EltJ = Source.getVectorElt(J);
13593 ConflictMask.setBitVal(J, EltI.getInt() == EltJ.getInt());
13594 }
13595 ResultElements.push_back(APValue(APSInt(ConflictMask, DestUnsigned)));
13596 }
13597 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13598 }
13599 case X86::BI__builtin_ia32_blendpd:
13600 case X86::BI__builtin_ia32_blendpd256:
13601 case X86::BI__builtin_ia32_blendps:
13602 case X86::BI__builtin_ia32_blendps256:
13603 case X86::BI__builtin_ia32_pblendw128:
13604 case X86::BI__builtin_ia32_pblendw256:
13605 case X86::BI__builtin_ia32_pblendd128:
13606 case X86::BI__builtin_ia32_pblendd256: {
13607 APValue SourceF, SourceT, SourceC;
13608 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13609 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13610 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13611 return false;
13612
13613 const APInt &C = SourceC.getInt();
13614 unsigned SourceLen = SourceF.getVectorLength();
13615 SmallVector<APValue, 32> ResultElements;
13616 ResultElements.reserve(SourceLen);
13617 for (unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
13618 const APValue &F = SourceF.getVectorElt(EltNum);
13619 const APValue &T = SourceT.getVectorElt(EltNum);
13620 ResultElements.push_back(C[EltNum % 8] ? T : F);
13621 }
13622
13623 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13624 }
13625
13626 case X86::BI__builtin_ia32_psignb128:
13627 case X86::BI__builtin_ia32_psignb256:
13628 case X86::BI__builtin_ia32_psignw128:
13629 case X86::BI__builtin_ia32_psignw256:
13630 case X86::BI__builtin_ia32_psignd128:
13631 case X86::BI__builtin_ia32_psignd256:
13632 return EvaluateBinOpExpr([](const APInt &AElem, const APInt &BElem) {
13633 if (BElem.isZero())
13634 return APInt::getZero(AElem.getBitWidth());
13635 if (BElem.isNegative())
13636 return -AElem;
13637 return AElem;
13638 });
13639
13640 case X86::BI__builtin_ia32_blendvpd:
13641 case X86::BI__builtin_ia32_blendvpd256:
13642 case X86::BI__builtin_ia32_blendvps:
13643 case X86::BI__builtin_ia32_blendvps256:
13644 case X86::BI__builtin_ia32_pblendvb128:
13645 case X86::BI__builtin_ia32_pblendvb256: {
13646 // SSE blendv by mask signbit: "Result = C[] < 0 ? T[] : F[]".
13647 APValue SourceF, SourceT, SourceC;
13648 if (!EvaluateAsRValue(Info, E->getArg(0), SourceF) ||
13649 !EvaluateAsRValue(Info, E->getArg(1), SourceT) ||
13650 !EvaluateAsRValue(Info, E->getArg(2), SourceC))
13651 return false;
13652
13653 unsigned SourceLen = SourceF.getVectorLength();
13654 SmallVector<APValue, 32> ResultElements;
13655 ResultElements.reserve(SourceLen);
13656
13657 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13658 const APValue &F = SourceF.getVectorElt(EltNum);
13659 const APValue &T = SourceT.getVectorElt(EltNum);
13660 const APValue &C = SourceC.getVectorElt(EltNum);
13661 APInt M = C.isInt() ? (APInt)C.getInt() : C.getFloat().bitcastToAPInt();
13662 ResultElements.push_back(M.isNegative() ? T : F);
13663 }
13664
13665 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13666 }
13667 case X86::BI__builtin_ia32_selectb_128:
13668 case X86::BI__builtin_ia32_selectb_256:
13669 case X86::BI__builtin_ia32_selectb_512:
13670 case X86::BI__builtin_ia32_selectw_128:
13671 case X86::BI__builtin_ia32_selectw_256:
13672 case X86::BI__builtin_ia32_selectw_512:
13673 case X86::BI__builtin_ia32_selectd_128:
13674 case X86::BI__builtin_ia32_selectd_256:
13675 case X86::BI__builtin_ia32_selectd_512:
13676 case X86::BI__builtin_ia32_selectq_128:
13677 case X86::BI__builtin_ia32_selectq_256:
13678 case X86::BI__builtin_ia32_selectq_512:
13679 case X86::BI__builtin_ia32_selectph_128:
13680 case X86::BI__builtin_ia32_selectph_256:
13681 case X86::BI__builtin_ia32_selectph_512:
13682 case X86::BI__builtin_ia32_selectpbf_128:
13683 case X86::BI__builtin_ia32_selectpbf_256:
13684 case X86::BI__builtin_ia32_selectpbf_512:
13685 case X86::BI__builtin_ia32_selectps_128:
13686 case X86::BI__builtin_ia32_selectps_256:
13687 case X86::BI__builtin_ia32_selectps_512:
13688 case X86::BI__builtin_ia32_selectpd_128:
13689 case X86::BI__builtin_ia32_selectpd_256:
13690 case X86::BI__builtin_ia32_selectpd_512: {
13691 // AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
13692 APValue SourceMask, SourceLHS, SourceRHS;
13693 if (!EvaluateAsRValue(Info, E->getArg(0), SourceMask) ||
13694 !EvaluateAsRValue(Info, E->getArg(1), SourceLHS) ||
13695 !EvaluateAsRValue(Info, E->getArg(2), SourceRHS))
13696 return false;
13697
13698 APSInt Mask = SourceMask.getInt();
13699 unsigned SourceLen = SourceLHS.getVectorLength();
13700 SmallVector<APValue, 4> ResultElements;
13701 ResultElements.reserve(SourceLen);
13702
13703 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13704 const APValue &LHS = SourceLHS.getVectorElt(EltNum);
13705 const APValue &RHS = SourceRHS.getVectorElt(EltNum);
13706 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
13707 }
13708
13709 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
13710 }
13711
13712 case X86::BI__builtin_ia32_cvtsd2ss: {
13713 APValue VecA, VecB;
13714 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13715 !EvaluateAsRValue(Info, E->getArg(1), VecB))
13716 return false;
13717
13718 SmallVector<APValue, 4> Elements;
13719
13720 APValue ResultVal;
13721 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13722 ResultVal))
13723 return false;
13724
13725 Elements.push_back(ResultVal);
13726
13727 unsigned NumEltsA = VecA.getVectorLength();
13728 for (unsigned I = 1; I < NumEltsA; ++I) {
13729 Elements.push_back(VecA.getVectorElt(I));
13730 }
13731
13732 return Success(Elements, E);
13733 }
13734 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: {
13735 APValue VecA, VecB, VecSrc, MaskValue;
13736
13737 if (!EvaluateAsRValue(Info, E->getArg(0), VecA) ||
13738 !EvaluateAsRValue(Info, E->getArg(1), VecB) ||
13739 !EvaluateAsRValue(Info, E->getArg(2), VecSrc) ||
13740 !EvaluateAsRValue(Info, E->getArg(3), MaskValue))
13741 return false;
13742
13743 unsigned Mask = MaskValue.getInt().getZExtValue();
13744 SmallVector<APValue, 4> Elements;
13745
13746 if (Mask & 1) {
13747 APValue ResultVal;
13748 if (!ConvertDoubleToFloatStrict(Info, E, VecB.getVectorElt(0).getFloat(),
13749 ResultVal))
13750 return false;
13751 Elements.push_back(ResultVal);
13752 } else {
13753 Elements.push_back(VecSrc.getVectorElt(0));
13754 }
13755
13756 unsigned NumEltsA = VecA.getVectorLength();
13757 for (unsigned I = 1; I < NumEltsA; ++I) {
13758 Elements.push_back(VecA.getVectorElt(I));
13759 }
13760
13761 return Success(Elements, E);
13762 }
13763 case X86::BI__builtin_ia32_cvtpd2ps:
13764 case X86::BI__builtin_ia32_cvtpd2ps256:
13765 case X86::BI__builtin_ia32_cvtpd2ps_mask:
13766 case X86::BI__builtin_ia32_cvtpd2ps512_mask: {
13767
13768 const auto BuiltinID = BuiltinOp;
13769 bool IsMasked = (BuiltinID == X86::BI__builtin_ia32_cvtpd2ps_mask ||
13770 BuiltinID == X86::BI__builtin_ia32_cvtpd2ps512_mask);
13771
13772 APValue InputValue;
13773 if (!EvaluateAsRValue(Info, E->getArg(0), InputValue))
13774 return false;
13775
13776 APValue MergeValue;
13777 unsigned Mask = 0xFFFFFFFF;
13778 bool NeedsMerge = false;
13779 if (IsMasked) {
13780 APValue MaskValue;
13781 if (!EvaluateAsRValue(Info, E->getArg(2), MaskValue))
13782 return false;
13783 Mask = MaskValue.getInt().getZExtValue();
13784 auto NumEltsResult = E->getType()->getAs<VectorType>()->getNumElements();
13785 for (unsigned I = 0; I < NumEltsResult; ++I) {
13786 if (!((Mask >> I) & 1)) {
13787 NeedsMerge = true;
13788 break;
13789 }
13790 }
13791 if (NeedsMerge) {
13792 if (!EvaluateAsRValue(Info, E->getArg(1), MergeValue))
13793 return false;
13794 }
13795 }
13796
13797 unsigned NumEltsResult =
13798 E->getType()->getAs<VectorType>()->getNumElements();
13799 unsigned NumEltsInput = InputValue.getVectorLength();
13800 SmallVector<APValue, 8> Elements;
13801 for (unsigned I = 0; I < NumEltsResult; ++I) {
13802 if (IsMasked && !((Mask >> I) & 1)) {
13803 if (!NeedsMerge) {
13804 return false;
13805 }
13806 Elements.push_back(MergeValue.getVectorElt(I));
13807 continue;
13808 }
13809
13810 if (I >= NumEltsInput) {
13811 Elements.push_back(APValue(APFloat::getZero(APFloat::IEEEsingle())));
13812 continue;
13813 }
13814
13815 APValue ResultVal;
13817 Info, E, InputValue.getVectorElt(I).getFloat(), ResultVal))
13818 return false;
13819
13820 Elements.push_back(ResultVal);
13821 }
13822 return Success(Elements, E);
13823 }
13824
13825 case X86::BI__builtin_ia32_shufps:
13826 case X86::BI__builtin_ia32_shufps256:
13827 case X86::BI__builtin_ia32_shufps512: {
13828 APValue R;
13829 if (!evalShuffleGeneric(
13830 Info, E, R,
13831 [](unsigned DstIdx,
13832 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13833 constexpr unsigned LaneBits = 128u;
13834 unsigned NumElemPerLane = LaneBits / 32;
13835 unsigned NumSelectableElems = NumElemPerLane / 2;
13836 unsigned BitsPerElem = 2;
13837 unsigned IndexMask = (1u << BitsPerElem) - 1;
13838 unsigned MaskBits = 8;
13839 unsigned Lane = DstIdx / NumElemPerLane;
13840 unsigned ElemInLane = DstIdx % NumElemPerLane;
13841 unsigned LaneOffset = Lane * NumElemPerLane;
13842 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13843 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13844 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13845 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13846 }))
13847 return false;
13848 return Success(R, E);
13849 }
13850 case X86::BI__builtin_ia32_shufpd:
13851 case X86::BI__builtin_ia32_shufpd256:
13852 case X86::BI__builtin_ia32_shufpd512: {
13853 APValue R;
13854 if (!evalShuffleGeneric(
13855 Info, E, R,
13856 [](unsigned DstIdx,
13857 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13858 constexpr unsigned LaneBits = 128u;
13859 unsigned NumElemPerLane = LaneBits / 64;
13860 unsigned NumSelectableElems = NumElemPerLane / 2;
13861 unsigned BitsPerElem = 1;
13862 unsigned IndexMask = (1u << BitsPerElem) - 1;
13863 unsigned MaskBits = 8;
13864 unsigned Lane = DstIdx / NumElemPerLane;
13865 unsigned ElemInLane = DstIdx % NumElemPerLane;
13866 unsigned LaneOffset = Lane * NumElemPerLane;
13867 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
13868 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
13869 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
13870 return {SrcIdx, static_cast<int>(LaneOffset + Index)};
13871 }))
13872 return false;
13873 return Success(R, E);
13874 }
13875 case X86::BI__builtin_ia32_insertps128: {
13876 APValue R;
13877 if (!evalShuffleGeneric(
13878 Info, E, R,
13879 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13880 // Bits [3:0]: zero mask - if bit is set, zero this element
13881 if ((Mask & (1 << DstIdx)) != 0) {
13882 return {0, -1};
13883 }
13884 // Bits [7:6]: select element from source vector Y (0-3)
13885 // Bits [5:4]: select destination position (0-3)
13886 unsigned SrcElem = (Mask >> 6) & 0x3;
13887 unsigned DstElem = (Mask >> 4) & 0x3;
13888 if (DstIdx == DstElem) {
13889 // Insert element from source vector (B) at this position
13890 return {1, static_cast<int>(SrcElem)};
13891 } else {
13892 // Copy from destination vector (A)
13893 return {0, static_cast<int>(DstIdx)};
13894 }
13895 }))
13896 return false;
13897 return Success(R, E);
13898 }
13899 case X86::BI__builtin_ia32_pshufb128:
13900 case X86::BI__builtin_ia32_pshufb256:
13901 case X86::BI__builtin_ia32_pshufb512: {
13902 APValue R;
13903 if (!evalShuffleGeneric(
13904 Info, E, R,
13905 [](unsigned DstIdx,
13906 unsigned ShuffleMask) -> std::pair<unsigned, int> {
13907 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
13908 if (Ctlb & 0x80)
13909 return std::make_pair(0, -1);
13910
13911 unsigned LaneBase = (DstIdx / 16) * 16;
13912 unsigned SrcOffset = Ctlb & 0x0F;
13913 unsigned SrcIdx = LaneBase + SrcOffset;
13914 return std::make_pair(0, static_cast<int>(SrcIdx));
13915 }))
13916 return false;
13917 return Success(R, E);
13918 }
13919
13920 case X86::BI__builtin_ia32_pshuflw:
13921 case X86::BI__builtin_ia32_pshuflw256:
13922 case X86::BI__builtin_ia32_pshuflw512: {
13923 APValue R;
13924 if (!evalShuffleGeneric(
13925 Info, E, R,
13926 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13927 constexpr unsigned LaneBits = 128u;
13928 constexpr unsigned ElemBits = 16u;
13929 constexpr unsigned LaneElts = LaneBits / ElemBits;
13930 constexpr unsigned HalfSize = 4;
13931 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13932 unsigned LaneIdx = DstIdx % LaneElts;
13933 if (LaneIdx < HalfSize) {
13934 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13935 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13936 }
13937 return std::make_pair(0, static_cast<int>(DstIdx));
13938 }))
13939 return false;
13940 return Success(R, E);
13941 }
13942
13943 case X86::BI__builtin_ia32_pshufhw:
13944 case X86::BI__builtin_ia32_pshufhw256:
13945 case X86::BI__builtin_ia32_pshufhw512: {
13946 APValue R;
13947 if (!evalShuffleGeneric(
13948 Info, E, R,
13949 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13950 constexpr unsigned LaneBits = 128u;
13951 constexpr unsigned ElemBits = 16u;
13952 constexpr unsigned LaneElts = LaneBits / ElemBits;
13953 constexpr unsigned HalfSize = 4;
13954 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13955 unsigned LaneIdx = DstIdx % LaneElts;
13956 if (LaneIdx >= HalfSize) {
13957 unsigned Rel = LaneIdx - HalfSize;
13958 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
13959 return std::make_pair(
13960 0, static_cast<int>(LaneBase + HalfSize + Sel));
13961 }
13962 return std::make_pair(0, static_cast<int>(DstIdx));
13963 }))
13964 return false;
13965 return Success(R, E);
13966 }
13967
13968 case X86::BI__builtin_ia32_pshufd:
13969 case X86::BI__builtin_ia32_pshufd256:
13970 case X86::BI__builtin_ia32_pshufd512:
13971 case X86::BI__builtin_ia32_vpermilps:
13972 case X86::BI__builtin_ia32_vpermilps256:
13973 case X86::BI__builtin_ia32_vpermilps512: {
13974 APValue R;
13975 if (!evalShuffleGeneric(
13976 Info, E, R,
13977 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13978 constexpr unsigned LaneBits = 128u;
13979 constexpr unsigned ElemBits = 32u;
13980 constexpr unsigned LaneElts = LaneBits / ElemBits;
13981 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
13982 unsigned LaneIdx = DstIdx % LaneElts;
13983 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
13984 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
13985 }))
13986 return false;
13987 return Success(R, E);
13988 }
13989
13990 case X86::BI__builtin_ia32_vpermilvarpd:
13991 case X86::BI__builtin_ia32_vpermilvarpd256:
13992 case X86::BI__builtin_ia32_vpermilvarpd512: {
13993 APValue R;
13994 if (!evalShuffleGeneric(
13995 Info, E, R,
13996 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
13997 unsigned NumElemPerLane = 2;
13998 unsigned Lane = DstIdx / NumElemPerLane;
13999 unsigned Offset = Mask & 0b10 ? 1 : 0;
14000 return std::make_pair(
14001 0, static_cast<int>(Lane * NumElemPerLane + Offset));
14002 }))
14003 return false;
14004 return Success(R, E);
14005 }
14006
14007 case X86::BI__builtin_ia32_vpermilpd:
14008 case X86::BI__builtin_ia32_vpermilpd256:
14009 case X86::BI__builtin_ia32_vpermilpd512: {
14010 APValue R;
14011 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
14012 unsigned NumElemPerLane = 2;
14013 unsigned BitsPerElem = 1;
14014 unsigned MaskBits = 8;
14015 unsigned IndexMask = 0x1;
14016 unsigned Lane = DstIdx / NumElemPerLane;
14017 unsigned LaneOffset = Lane * NumElemPerLane;
14018 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
14019 unsigned Index = (Control >> BitIndex) & IndexMask;
14020 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
14021 }))
14022 return false;
14023 return Success(R, E);
14024 }
14025
14026 case X86::BI__builtin_ia32_permdf256:
14027 case X86::BI__builtin_ia32_permdi256: {
14028 APValue R;
14029 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Control) {
14030 // permute4x64 operates on 4 64-bit elements
14031 // For element i (0-3), extract bits [2*i+1:2*i] from Control
14032 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
14033 return std::make_pair(0, static_cast<int>(Index));
14034 }))
14035 return false;
14036 return Success(R, E);
14037 }
14038
14039 case X86::BI__builtin_ia32_vpermilvarps:
14040 case X86::BI__builtin_ia32_vpermilvarps256:
14041 case X86::BI__builtin_ia32_vpermilvarps512: {
14042 APValue R;
14043 if (!evalShuffleGeneric(
14044 Info, E, R,
14045 [](unsigned DstIdx, unsigned Mask) -> std::pair<unsigned, int> {
14046 unsigned NumElemPerLane = 4;
14047 unsigned Lane = DstIdx / NumElemPerLane;
14048 unsigned Offset = Mask & 0b11;
14049 return std::make_pair(
14050 0, static_cast<int>(Lane * NumElemPerLane + Offset));
14051 }))
14052 return false;
14053 return Success(R, E);
14054 }
14055
14056 case X86::BI__builtin_ia32_vpmultishiftqb128:
14057 case X86::BI__builtin_ia32_vpmultishiftqb256:
14058 case X86::BI__builtin_ia32_vpmultishiftqb512: {
14059 assert(E->getNumArgs() == 2);
14060
14061 APValue A, B;
14062 if (!Evaluate(A, Info, E->getArg(0)) || !Evaluate(B, Info, E->getArg(1)))
14063 return false;
14064
14065 assert(A.getVectorLength() == B.getVectorLength());
14066 unsigned NumBytesInQWord = 8;
14067 unsigned NumBitsInByte = 8;
14068 unsigned NumBytes = A.getVectorLength();
14069 unsigned NumQWords = NumBytes / NumBytesInQWord;
14071 Result.reserve(NumBytes);
14072
14073 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
14074 APInt BQWord(64, 0);
14075 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14076 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
14077 uint64_t Byte = B.getVectorElt(Idx).getInt().getZExtValue();
14078 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
14079 }
14080
14081 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14082 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
14083 uint64_t Ctrl = A.getVectorElt(Idx).getInt().getZExtValue() & 0x3F;
14084
14085 APInt Byte(8, 0);
14086 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
14087 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
14088 }
14089 Result.push_back(APValue(APSInt(Byte, /*isUnsigned*/ true)));
14090 }
14091 }
14092 return Success(APValue(Result.data(), Result.size()), E);
14093 }
14094
14095 case X86::BI__builtin_ia32_phminposuw128: {
14096 APValue Source;
14097 if (!Evaluate(Source, Info, E->getArg(0)))
14098 return false;
14099 unsigned SourceLen = Source.getVectorLength();
14100 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14101 QualType ElemQT = VT->getElementType();
14102 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
14103
14104 APInt MinIndex(ElemBitWidth, 0);
14105 APInt MinVal = Source.getVectorElt(0).getInt();
14106 for (unsigned I = 1; I != SourceLen; ++I) {
14107 APInt Val = Source.getVectorElt(I).getInt();
14108 if (MinVal.ugt(Val)) {
14109 MinVal = Val;
14110 MinIndex = I;
14111 }
14112 }
14113
14114 bool ResultUnsigned = E->getCallReturnType(Info.Ctx)
14115 ->castAs<VectorType>()
14116 ->getElementType()
14117 ->isUnsignedIntegerOrEnumerationType();
14118
14120 Result.reserve(SourceLen);
14121 Result.emplace_back(APSInt(MinVal, ResultUnsigned));
14122 Result.emplace_back(APSInt(MinIndex, ResultUnsigned));
14123 for (unsigned I = 0; I != SourceLen - 2; ++I) {
14124 Result.emplace_back(APSInt(APInt(ElemBitWidth, 0), ResultUnsigned));
14125 }
14126 return Success(APValue(Result.data(), Result.size()), E);
14127 }
14128
14129 case X86::BI__builtin_ia32_psraq128:
14130 case X86::BI__builtin_ia32_psraq256:
14131 case X86::BI__builtin_ia32_psraq512:
14132 case X86::BI__builtin_ia32_psrad128:
14133 case X86::BI__builtin_ia32_psrad256:
14134 case X86::BI__builtin_ia32_psrad512:
14135 case X86::BI__builtin_ia32_psraw128:
14136 case X86::BI__builtin_ia32_psraw256:
14137 case X86::BI__builtin_ia32_psraw512: {
14138 APValue R;
14139 if (!evalShiftWithCount(
14140 Info, E, R,
14141 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
14142 [](const APInt &Elt, unsigned Width) {
14143 return Elt.ashr(Width - 1);
14144 }))
14145 return false;
14146 return Success(R, E);
14147 }
14148
14149 case X86::BI__builtin_ia32_psllq128:
14150 case X86::BI__builtin_ia32_psllq256:
14151 case X86::BI__builtin_ia32_psllq512:
14152 case X86::BI__builtin_ia32_pslld128:
14153 case X86::BI__builtin_ia32_pslld256:
14154 case X86::BI__builtin_ia32_pslld512:
14155 case X86::BI__builtin_ia32_psllw128:
14156 case X86::BI__builtin_ia32_psllw256:
14157 case X86::BI__builtin_ia32_psllw512: {
14158 APValue R;
14159 if (!evalShiftWithCount(
14160 Info, E, R,
14161 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
14162 [](const APInt &Elt, unsigned Width) {
14163 return APInt::getZero(Width);
14164 }))
14165 return false;
14166 return Success(R, E);
14167 }
14168
14169 case X86::BI__builtin_ia32_psrlq128:
14170 case X86::BI__builtin_ia32_psrlq256:
14171 case X86::BI__builtin_ia32_psrlq512:
14172 case X86::BI__builtin_ia32_psrld128:
14173 case X86::BI__builtin_ia32_psrld256:
14174 case X86::BI__builtin_ia32_psrld512:
14175 case X86::BI__builtin_ia32_psrlw128:
14176 case X86::BI__builtin_ia32_psrlw256:
14177 case X86::BI__builtin_ia32_psrlw512: {
14178 APValue R;
14179 if (!evalShiftWithCount(
14180 Info, E, R,
14181 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
14182 [](const APInt &Elt, unsigned Width) {
14183 return APInt::getZero(Width);
14184 }))
14185 return false;
14186 return Success(R, E);
14187 }
14188
14189 case X86::BI__builtin_ia32_pternlogd128_mask:
14190 case X86::BI__builtin_ia32_pternlogd256_mask:
14191 case X86::BI__builtin_ia32_pternlogd512_mask:
14192 case X86::BI__builtin_ia32_pternlogq128_mask:
14193 case X86::BI__builtin_ia32_pternlogq256_mask:
14194 case X86::BI__builtin_ia32_pternlogq512_mask: {
14195 APValue AValue, BValue, CValue, ImmValue, UValue;
14196 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
14197 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
14198 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
14199 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
14200 !EvaluateAsRValue(Info, E->getArg(4), UValue))
14201 return false;
14202
14203 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14204 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14205 APInt Imm = ImmValue.getInt();
14206 APInt U = UValue.getInt();
14207 unsigned ResultLen = AValue.getVectorLength();
14208 SmallVector<APValue, 16> ResultElements;
14209 ResultElements.reserve(ResultLen);
14210
14211 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
14212 APInt ALane = AValue.getVectorElt(EltNum).getInt();
14213 APInt BLane = BValue.getVectorElt(EltNum).getInt();
14214 APInt CLane = CValue.getVectorElt(EltNum).getInt();
14215
14216 if (U[EltNum]) {
14217 unsigned BitWidth = ALane.getBitWidth();
14218 APInt ResLane(BitWidth, 0);
14219
14220 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
14221 unsigned ABit = ALane[Bit];
14222 unsigned BBit = BLane[Bit];
14223 unsigned CBit = CLane[Bit];
14224
14225 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
14226 ResLane.setBitVal(Bit, Imm[Idx]);
14227 }
14228 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
14229 } else {
14230 ResultElements.push_back(APValue(APSInt(ALane, DestUnsigned)));
14231 }
14232 }
14233 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14234 }
14235 case X86::BI__builtin_ia32_pternlogd128_maskz:
14236 case X86::BI__builtin_ia32_pternlogd256_maskz:
14237 case X86::BI__builtin_ia32_pternlogd512_maskz:
14238 case X86::BI__builtin_ia32_pternlogq128_maskz:
14239 case X86::BI__builtin_ia32_pternlogq256_maskz:
14240 case X86::BI__builtin_ia32_pternlogq512_maskz: {
14241 APValue AValue, BValue, CValue, ImmValue, UValue;
14242 if (!EvaluateAsRValue(Info, E->getArg(0), AValue) ||
14243 !EvaluateAsRValue(Info, E->getArg(1), BValue) ||
14244 !EvaluateAsRValue(Info, E->getArg(2), CValue) ||
14245 !EvaluateAsRValue(Info, E->getArg(3), ImmValue) ||
14246 !EvaluateAsRValue(Info, E->getArg(4), UValue))
14247 return false;
14248
14249 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14250 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14251 APInt Imm = ImmValue.getInt();
14252 APInt U = UValue.getInt();
14253 unsigned ResultLen = AValue.getVectorLength();
14254 SmallVector<APValue, 16> ResultElements;
14255 ResultElements.reserve(ResultLen);
14256
14257 for (unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
14258 APInt ALane = AValue.getVectorElt(EltNum).getInt();
14259 APInt BLane = BValue.getVectorElt(EltNum).getInt();
14260 APInt CLane = CValue.getVectorElt(EltNum).getInt();
14261
14262 unsigned BitWidth = ALane.getBitWidth();
14263 APInt ResLane(BitWidth, 0);
14264
14265 if (U[EltNum]) {
14266 for (unsigned Bit = 0; Bit < BitWidth; ++Bit) {
14267 unsigned ABit = ALane[Bit];
14268 unsigned BBit = BLane[Bit];
14269 unsigned CBit = CLane[Bit];
14270
14271 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
14272 ResLane.setBitVal(Bit, Imm[Idx]);
14273 }
14274 }
14275 ResultElements.push_back(APValue(APSInt(ResLane, DestUnsigned)));
14276 }
14277 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14278 }
14279
14280 case Builtin::BI__builtin_elementwise_clzg:
14281 case Builtin::BI__builtin_elementwise_ctzg: {
14282 APValue SourceLHS;
14283 std::optional<APValue> Fallback;
14284 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS))
14285 return false;
14286 if (E->getNumArgs() > 1) {
14287 APValue FallbackTmp;
14288 if (!EvaluateAsRValue(Info, E->getArg(1), FallbackTmp))
14289 return false;
14290 Fallback = FallbackTmp;
14291 }
14292
14293 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14294 unsigned SourceLen = SourceLHS.getVectorLength();
14295 SmallVector<APValue, 4> ResultElements;
14296 ResultElements.reserve(SourceLen);
14297
14298 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14299 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
14300 if (!LHS) {
14301 // Without a fallback, a zero element is undefined
14302 if (!Fallback) {
14303 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
14304 << /*IsTrailing=*/(BuiltinOp ==
14305 Builtin::BI__builtin_elementwise_ctzg);
14306 return false;
14307 }
14308 ResultElements.push_back(Fallback->getVectorElt(EltNum));
14309 continue;
14310 }
14311 switch (BuiltinOp) {
14312 case Builtin::BI__builtin_elementwise_clzg:
14313 ResultElements.push_back(APValue(
14314 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
14315 DestEltTy->isUnsignedIntegerOrEnumerationType())));
14316 break;
14317 case Builtin::BI__builtin_elementwise_ctzg:
14318 ResultElements.push_back(APValue(
14319 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
14320 DestEltTy->isUnsignedIntegerOrEnumerationType())));
14321 break;
14322 }
14323 }
14324
14325 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14326 }
14327
14328 case Builtin::BI__builtin_elementwise_fma: {
14329 APValue SourceX, SourceY, SourceZ;
14330 if (!EvaluateAsRValue(Info, E->getArg(0), SourceX) ||
14331 !EvaluateAsRValue(Info, E->getArg(1), SourceY) ||
14332 !EvaluateAsRValue(Info, E->getArg(2), SourceZ))
14333 return false;
14334
14335 unsigned SourceLen = SourceX.getVectorLength();
14336 SmallVector<APValue> ResultElements;
14337 ResultElements.reserve(SourceLen);
14338 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14339 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14340 const APFloat &X = SourceX.getVectorElt(EltNum).getFloat();
14341 const APFloat &Y = SourceY.getVectorElt(EltNum).getFloat();
14342 const APFloat &Z = SourceZ.getVectorElt(EltNum).getFloat();
14343 APFloat Result(X);
14344 (void)Result.fusedMultiplyAdd(Y, Z, RM);
14345 ResultElements.push_back(APValue(Result));
14346 }
14347 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14348 }
14349
14350 case clang::X86::BI__builtin_ia32_phaddw128:
14351 case clang::X86::BI__builtin_ia32_phaddw256:
14352 case clang::X86::BI__builtin_ia32_phaddd128:
14353 case clang::X86::BI__builtin_ia32_phaddd256:
14354 case clang::X86::BI__builtin_ia32_phaddsw128:
14355 case clang::X86::BI__builtin_ia32_phaddsw256:
14356
14357 case clang::X86::BI__builtin_ia32_phsubw128:
14358 case clang::X86::BI__builtin_ia32_phsubw256:
14359 case clang::X86::BI__builtin_ia32_phsubd128:
14360 case clang::X86::BI__builtin_ia32_phsubd256:
14361 case clang::X86::BI__builtin_ia32_phsubsw128:
14362 case clang::X86::BI__builtin_ia32_phsubsw256: {
14363 APValue SourceLHS, SourceRHS;
14364 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14365 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14366 return false;
14367 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14368 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14369
14370 unsigned NumElts = SourceLHS.getVectorLength();
14371 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
14372 unsigned EltsPerLane = 128 / EltBits;
14373 SmallVector<APValue, 4> ResultElements;
14374 ResultElements.reserve(NumElts);
14375
14376 for (unsigned LaneStart = 0; LaneStart != NumElts;
14377 LaneStart += EltsPerLane) {
14378 for (unsigned I = 0; I != EltsPerLane; I += 2) {
14379 APSInt LHSA = SourceLHS.getVectorElt(LaneStart + I).getInt();
14380 APSInt LHSB = SourceLHS.getVectorElt(LaneStart + I + 1).getInt();
14381 switch (BuiltinOp) {
14382 case clang::X86::BI__builtin_ia32_phaddw128:
14383 case clang::X86::BI__builtin_ia32_phaddw256:
14384 case clang::X86::BI__builtin_ia32_phaddd128:
14385 case clang::X86::BI__builtin_ia32_phaddd256: {
14386 APSInt Res(LHSA + LHSB, DestUnsigned);
14387 ResultElements.push_back(APValue(Res));
14388 break;
14389 }
14390 case clang::X86::BI__builtin_ia32_phaddsw128:
14391 case clang::X86::BI__builtin_ia32_phaddsw256: {
14392 APSInt Res(LHSA.sadd_sat(LHSB));
14393 ResultElements.push_back(APValue(Res));
14394 break;
14395 }
14396 case clang::X86::BI__builtin_ia32_phsubw128:
14397 case clang::X86::BI__builtin_ia32_phsubw256:
14398 case clang::X86::BI__builtin_ia32_phsubd128:
14399 case clang::X86::BI__builtin_ia32_phsubd256: {
14400 APSInt Res(LHSA - LHSB, DestUnsigned);
14401 ResultElements.push_back(APValue(Res));
14402 break;
14403 }
14404 case clang::X86::BI__builtin_ia32_phsubsw128:
14405 case clang::X86::BI__builtin_ia32_phsubsw256: {
14406 APSInt Res(LHSA.ssub_sat(LHSB));
14407 ResultElements.push_back(APValue(Res));
14408 break;
14409 }
14410 }
14411 }
14412 for (unsigned I = 0; I != EltsPerLane; I += 2) {
14413 APSInt RHSA = SourceRHS.getVectorElt(LaneStart + I).getInt();
14414 APSInt RHSB = SourceRHS.getVectorElt(LaneStart + I + 1).getInt();
14415 switch (BuiltinOp) {
14416 case clang::X86::BI__builtin_ia32_phaddw128:
14417 case clang::X86::BI__builtin_ia32_phaddw256:
14418 case clang::X86::BI__builtin_ia32_phaddd128:
14419 case clang::X86::BI__builtin_ia32_phaddd256: {
14420 APSInt Res(RHSA + RHSB, DestUnsigned);
14421 ResultElements.push_back(APValue(Res));
14422 break;
14423 }
14424 case clang::X86::BI__builtin_ia32_phaddsw128:
14425 case clang::X86::BI__builtin_ia32_phaddsw256: {
14426 APSInt Res(RHSA.sadd_sat(RHSB));
14427 ResultElements.push_back(APValue(Res));
14428 break;
14429 }
14430 case clang::X86::BI__builtin_ia32_phsubw128:
14431 case clang::X86::BI__builtin_ia32_phsubw256:
14432 case clang::X86::BI__builtin_ia32_phsubd128:
14433 case clang::X86::BI__builtin_ia32_phsubd256: {
14434 APSInt Res(RHSA - RHSB, DestUnsigned);
14435 ResultElements.push_back(APValue(Res));
14436 break;
14437 }
14438 case clang::X86::BI__builtin_ia32_phsubsw128:
14439 case clang::X86::BI__builtin_ia32_phsubsw256: {
14440 APSInt Res(RHSA.ssub_sat(RHSB));
14441 ResultElements.push_back(APValue(Res));
14442 break;
14443 }
14444 }
14445 }
14446 }
14447 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14448 }
14449 case clang::X86::BI__builtin_ia32_haddpd:
14450 case clang::X86::BI__builtin_ia32_haddps:
14451 case clang::X86::BI__builtin_ia32_haddps256:
14452 case clang::X86::BI__builtin_ia32_haddpd256:
14453 case clang::X86::BI__builtin_ia32_hsubpd:
14454 case clang::X86::BI__builtin_ia32_hsubps:
14455 case clang::X86::BI__builtin_ia32_hsubps256:
14456 case clang::X86::BI__builtin_ia32_hsubpd256: {
14457 APValue SourceLHS, SourceRHS;
14458 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14459 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14460 return false;
14461 unsigned NumElts = SourceLHS.getVectorLength();
14462 SmallVector<APValue, 4> ResultElements;
14463 ResultElements.reserve(NumElts);
14464 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14465 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14466 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
14467 unsigned NumLanes = NumElts * EltBits / 128;
14468 unsigned NumElemsPerLane = NumElts / NumLanes;
14469 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
14470
14471 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
14472 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
14473 APFloat LHSA = SourceLHS.getVectorElt(L + (2 * I) + 0).getFloat();
14474 APFloat LHSB = SourceLHS.getVectorElt(L + (2 * I) + 1).getFloat();
14475 switch (BuiltinOp) {
14476 case clang::X86::BI__builtin_ia32_haddpd:
14477 case clang::X86::BI__builtin_ia32_haddps:
14478 case clang::X86::BI__builtin_ia32_haddps256:
14479 case clang::X86::BI__builtin_ia32_haddpd256:
14480 LHSA.add(LHSB, RM);
14481 break;
14482 case clang::X86::BI__builtin_ia32_hsubpd:
14483 case clang::X86::BI__builtin_ia32_hsubps:
14484 case clang::X86::BI__builtin_ia32_hsubps256:
14485 case clang::X86::BI__builtin_ia32_hsubpd256:
14486 LHSA.subtract(LHSB, RM);
14487 break;
14488 }
14489 ResultElements.push_back(APValue(LHSA));
14490 }
14491 for (unsigned I = 0; I != HalfElemsPerLane; ++I) {
14492 APFloat RHSA = SourceRHS.getVectorElt(L + (2 * I) + 0).getFloat();
14493 APFloat RHSB = SourceRHS.getVectorElt(L + (2 * I) + 1).getFloat();
14494 switch (BuiltinOp) {
14495 case clang::X86::BI__builtin_ia32_haddpd:
14496 case clang::X86::BI__builtin_ia32_haddps:
14497 case clang::X86::BI__builtin_ia32_haddps256:
14498 case clang::X86::BI__builtin_ia32_haddpd256:
14499 RHSA.add(RHSB, RM);
14500 break;
14501 case clang::X86::BI__builtin_ia32_hsubpd:
14502 case clang::X86::BI__builtin_ia32_hsubps:
14503 case clang::X86::BI__builtin_ia32_hsubps256:
14504 case clang::X86::BI__builtin_ia32_hsubpd256:
14505 RHSA.subtract(RHSB, RM);
14506 break;
14507 }
14508 ResultElements.push_back(APValue(RHSA));
14509 }
14510 }
14511 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14512 }
14513 case clang::X86::BI__builtin_ia32_addsubpd:
14514 case clang::X86::BI__builtin_ia32_addsubps:
14515 case clang::X86::BI__builtin_ia32_addsubpd256:
14516 case clang::X86::BI__builtin_ia32_addsubps256: {
14517 // Addsub: alternates between subtraction and addition
14518 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
14519 APValue SourceLHS, SourceRHS;
14520 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14521 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14522 return false;
14523 unsigned NumElems = SourceLHS.getVectorLength();
14524 SmallVector<APValue, 8> ResultElements;
14525 ResultElements.reserve(NumElems);
14526 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
14527
14528 for (unsigned I = 0; I != NumElems; ++I) {
14529 APFloat LHS = SourceLHS.getVectorElt(I).getFloat();
14530 APFloat RHS = SourceRHS.getVectorElt(I).getFloat();
14531 if (I % 2 == 0) {
14532 // Even indices: subtract
14533 LHS.subtract(RHS, RM);
14534 } else {
14535 // Odd indices: add
14536 LHS.add(RHS, RM);
14537 }
14538 ResultElements.push_back(APValue(LHS));
14539 }
14540 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14541 }
14542 case clang::X86::BI__builtin_ia32_pclmulqdq128:
14543 case clang::X86::BI__builtin_ia32_pclmulqdq256:
14544 case clang::X86::BI__builtin_ia32_pclmulqdq512: {
14545 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
14546 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
14547 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
14548 APValue SourceLHS, SourceRHS;
14549 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
14550 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
14551 return false;
14552
14553 APSInt Imm8;
14554 if (!EvaluateInteger(E->getArg(2), Imm8, Info))
14555 return false;
14556
14557 // Extract bits 0 and 4 from imm8
14558 bool SelectUpperA = (Imm8 & 0x01) != 0;
14559 bool SelectUpperB = (Imm8 & 0x10) != 0;
14560
14561 unsigned NumElems = SourceLHS.getVectorLength();
14562 SmallVector<APValue, 8> ResultElements;
14563 ResultElements.reserve(NumElems);
14564 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14565 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
14566
14567 // Process each 128-bit lane
14568 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
14569 // Get the two 64-bit halves of the first operand
14570 APSInt A0 = SourceLHS.getVectorElt(Lane + 0).getInt();
14571 APSInt A1 = SourceLHS.getVectorElt(Lane + 1).getInt();
14572 // Get the two 64-bit halves of the second operand
14573 APSInt B0 = SourceRHS.getVectorElt(Lane + 0).getInt();
14574 APSInt B1 = SourceRHS.getVectorElt(Lane + 1).getInt();
14575
14576 // Select the appropriate 64-bit values based on imm8
14577 APInt A = SelectUpperA ? A1 : A0;
14578 APInt B = SelectUpperB ? B1 : B0;
14579
14580 // Extend both operands to 128 bits for carry-less multiplication
14581 APInt A128 = A.zext(128);
14582 APInt B128 = B.zext(128);
14583
14584 // Use APIntOps::clmul for carry-less multiplication
14585 APInt Result = llvm::APIntOps::clmul(A128, B128);
14586
14587 // Split the 128-bit result into two 64-bit halves
14588 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
14589 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
14590
14591 ResultElements.push_back(APValue(ResultLow));
14592 ResultElements.push_back(APValue(ResultHigh));
14593 }
14594
14595 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14596 }
14597 case Builtin::BI__builtin_elementwise_clmul:
14598 return EvaluateBinOpExpr(llvm::APIntOps::clmul);
14599 case Builtin::BI__builtin_elementwise_pext:
14600 return EvaluateBinOpExpr(llvm::APIntOps::pext);
14601 case Builtin::BI__builtin_elementwise_pdep:
14602 return EvaluateBinOpExpr(llvm::APIntOps::pdep);
14603 case Builtin::BI__builtin_elementwise_fshl:
14604 case Builtin::BI__builtin_elementwise_fshr: {
14605 APValue SourceHi, SourceLo, SourceShift;
14606 if (!EvaluateAsRValue(Info, E->getArg(0), SourceHi) ||
14607 !EvaluateAsRValue(Info, E->getArg(1), SourceLo) ||
14608 !EvaluateAsRValue(Info, E->getArg(2), SourceShift))
14609 return false;
14610
14611 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
14612 if (!DestEltTy->isIntegerType())
14613 return false;
14614
14615 unsigned SourceLen = SourceHi.getVectorLength();
14616 SmallVector<APValue> ResultElements;
14617 ResultElements.reserve(SourceLen);
14618 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14619 const APSInt &Hi = SourceHi.getVectorElt(EltNum).getInt();
14620 const APSInt &Lo = SourceLo.getVectorElt(EltNum).getInt();
14621 const APSInt &Shift = SourceShift.getVectorElt(EltNum).getInt();
14622 switch (BuiltinOp) {
14623 case Builtin::BI__builtin_elementwise_fshl:
14624 ResultElements.push_back(APValue(
14625 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
14626 break;
14627 case Builtin::BI__builtin_elementwise_fshr:
14628 ResultElements.push_back(APValue(
14629 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
14630 break;
14631 }
14632 }
14633
14634 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14635 }
14636
14637 case X86::BI__builtin_ia32_shuf_f32x4_256:
14638 case X86::BI__builtin_ia32_shuf_i32x4_256:
14639 case X86::BI__builtin_ia32_shuf_f64x2_256:
14640 case X86::BI__builtin_ia32_shuf_i64x2_256:
14641 case X86::BI__builtin_ia32_shuf_f32x4:
14642 case X86::BI__builtin_ia32_shuf_i32x4:
14643 case X86::BI__builtin_ia32_shuf_f64x2:
14644 case X86::BI__builtin_ia32_shuf_i64x2: {
14645 APValue SourceA, SourceB;
14646 if (!EvaluateAsRValue(Info, E->getArg(0), SourceA) ||
14647 !EvaluateAsRValue(Info, E->getArg(1), SourceB))
14648 return false;
14649
14650 APSInt Imm;
14651 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14652 return false;
14653
14654 // Destination and sources A, B all have the same type.
14655 unsigned NumElems = SourceA.getVectorLength();
14656 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
14657 QualType ElemQT = VT->getElementType();
14658 unsigned ElemBits = Info.Ctx.getTypeSize(ElemQT);
14659 unsigned LaneBits = 128u;
14660 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
14661 unsigned NumElemsPerLane = LaneBits / ElemBits;
14662
14663 unsigned DstLen = SourceA.getVectorLength();
14664 SmallVector<APValue, 16> ResultElements;
14665 ResultElements.reserve(DstLen);
14666
14667 APValue R;
14668 if (!evalShuffleGeneric(
14669 Info, E, R,
14670 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask)
14671 -> std::pair<unsigned, int> {
14672 // DstIdx determines source. ShuffleMask selects lane in source.
14673 unsigned BitsPerElem = NumLanes / 2;
14674 unsigned IndexMask = (1u << BitsPerElem) - 1;
14675 unsigned Lane = DstIdx / NumElemsPerLane;
14676 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
14677 unsigned BitIdx = BitsPerElem * Lane;
14678 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
14679 unsigned ElemInLane = DstIdx % NumElemsPerLane;
14680 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
14681 return {SrcIdx, IdxToPick};
14682 }))
14683 return false;
14684 return Success(R, E);
14685 }
14686
14687 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14688 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14689 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
14690 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
14691 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
14692 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi: {
14693
14694 APValue X, A;
14695 APSInt Imm;
14696 if (!EvaluateAsRValue(Info, E->getArg(0), X) ||
14697 !EvaluateAsRValue(Info, E->getArg(1), A) ||
14698 !EvaluateInteger(E->getArg(2), Imm, Info))
14699 return false;
14700
14701 assert(X.isVector() && A.isVector());
14702 assert(X.getVectorLength() == A.getVectorLength());
14703
14704 bool IsInverse = false;
14705 switch (BuiltinOp) {
14706 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14707 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14708 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi: {
14709 IsInverse = true;
14710 }
14711 }
14712
14713 unsigned NumBitsInByte = 8;
14714 unsigned NumBytesInQWord = 8;
14715 unsigned NumBitsInQWord = 64;
14716 unsigned NumBytes = A.getVectorLength();
14717 unsigned NumQWords = NumBytes / NumBytesInQWord;
14719 Result.reserve(NumBytes);
14720
14721 // computing A*X + Imm
14722 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
14723 // Extract the QWords from X, A
14724 APInt XQWord(NumBitsInQWord, 0);
14725 APInt AQWord(NumBitsInQWord, 0);
14726 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14727 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
14728 APInt XByte = X.getVectorElt(Idx).getInt();
14729 APInt AByte = A.getVectorElt(Idx).getInt();
14730 XQWord.insertBits(XByte, ByteIdx * NumBitsInByte);
14731 AQWord.insertBits(AByte, ByteIdx * NumBitsInByte);
14732 }
14733
14734 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14735 uint8_t XByte =
14736 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
14737 Result.push_back(APValue(APSInt(
14738 APInt(8, GFNIAffine(XByte, AQWord, Imm, IsInverse)), false)));
14739 }
14740 }
14741
14742 return Success(APValue(Result.data(), Result.size()), E);
14743 }
14744
14745 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
14746 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
14747 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi: {
14748 APValue A, B;
14749 if (!EvaluateAsRValue(Info, E->getArg(0), A) ||
14750 !EvaluateAsRValue(Info, E->getArg(1), B))
14751 return false;
14752
14753 assert(A.isVector() && B.isVector());
14754 assert(A.getVectorLength() == B.getVectorLength());
14755
14756 unsigned NumBytes = A.getVectorLength();
14758 Result.reserve(NumBytes);
14759
14760 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
14761 uint8_t AByte = A.getVectorElt(ByteIdx).getInt().getZExtValue();
14762 uint8_t BByte = B.getVectorElt(ByteIdx).getInt().getZExtValue();
14763 Result.push_back(APValue(
14764 APSInt(APInt(8, GFNIMul(AByte, BByte)), /*IsUnsigned=*/false)));
14765 }
14766
14767 return Success(APValue(Result.data(), Result.size()), E);
14768 }
14769
14770 case X86::BI__builtin_ia32_insertf32x4_256:
14771 case X86::BI__builtin_ia32_inserti32x4_256:
14772 case X86::BI__builtin_ia32_insertf64x2_256:
14773 case X86::BI__builtin_ia32_inserti64x2_256:
14774 case X86::BI__builtin_ia32_insertf32x4:
14775 case X86::BI__builtin_ia32_inserti32x4:
14776 case X86::BI__builtin_ia32_insertf64x2_512:
14777 case X86::BI__builtin_ia32_inserti64x2_512:
14778 case X86::BI__builtin_ia32_insertf32x8:
14779 case X86::BI__builtin_ia32_inserti32x8:
14780 case X86::BI__builtin_ia32_insertf64x4:
14781 case X86::BI__builtin_ia32_inserti64x4:
14782 case X86::BI__builtin_ia32_vinsertf128_ps256:
14783 case X86::BI__builtin_ia32_vinsertf128_pd256:
14784 case X86::BI__builtin_ia32_vinsertf128_si256:
14785 case X86::BI__builtin_ia32_insert128i256: {
14786 APValue SourceDst, SourceSub;
14787 if (!EvaluateAsRValue(Info, E->getArg(0), SourceDst) ||
14788 !EvaluateAsRValue(Info, E->getArg(1), SourceSub))
14789 return false;
14790
14791 APSInt Imm;
14792 if (!EvaluateInteger(E->getArg(2), Imm, Info))
14793 return false;
14794
14795 assert(SourceDst.isVector() && SourceSub.isVector());
14796 unsigned DstLen = SourceDst.getVectorLength();
14797 unsigned SubLen = SourceSub.getVectorLength();
14798 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
14799 unsigned NumLanes = DstLen / SubLen;
14800 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
14801
14802 SmallVector<APValue, 16> ResultElements;
14803 ResultElements.reserve(DstLen);
14804
14805 for (unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
14806 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
14807 ResultElements.push_back(SourceSub.getVectorElt(EltNum - LaneIdx));
14808 else
14809 ResultElements.push_back(SourceDst.getVectorElt(EltNum));
14810 }
14811
14812 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
14813 }
14814
14815 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
14816 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
14817 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
14818 case clang::X86::BI__builtin_ia32_vec_set_v4si:
14819 case clang::X86::BI__builtin_ia32_vec_set_v2di:
14820 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
14821 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
14822 case clang::X86::BI__builtin_ia32_vec_set_v8si:
14823 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
14824 APValue VecVal;
14825 APSInt Scalar, IndexAPS;
14826 if (!EvaluateVector(E->getArg(0), VecVal, Info) ||
14827 !EvaluateInteger(E->getArg(1), Scalar, Info) ||
14828 !EvaluateInteger(E->getArg(2), IndexAPS, Info))
14829 return false;
14830
14831 QualType ElemTy = E->getType()->castAs<VectorType>()->getElementType();
14832 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
14833 bool ElemUnsigned = ElemTy->isUnsignedIntegerOrEnumerationType();
14834 Scalar.setIsUnsigned(ElemUnsigned);
14835 APSInt ElemAPS = Scalar.extOrTrunc(ElemWidth);
14836 APValue ElemAV(ElemAPS);
14837
14838 unsigned NumElems = VecVal.getVectorLength();
14839 unsigned Index =
14840 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
14841
14843 Elems.reserve(NumElems);
14844 for (unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
14845 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.getVectorElt(ElemNum));
14846
14847 return Success(APValue(Elems.data(), NumElems), E);
14848 }
14849
14850 case X86::BI__builtin_ia32_pslldqi128_byteshift:
14851 case X86::BI__builtin_ia32_pslldqi256_byteshift:
14852 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
14853 APValue R;
14854 if (!evalShuffleGeneric(
14855 Info, E, R,
14856 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14857 unsigned LaneBase = (DstIdx / 16) * 16;
14858 unsigned LaneIdx = DstIdx % 16;
14859 if (LaneIdx < Shift)
14860 return std::make_pair(0, -1);
14861
14862 return std::make_pair(
14863 0, static_cast<int>(LaneBase + LaneIdx - Shift));
14864 }))
14865 return false;
14866 return Success(R, E);
14867 }
14868
14869 case X86::BI__builtin_ia32_psrldqi128_byteshift:
14870 case X86::BI__builtin_ia32_psrldqi256_byteshift:
14871 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
14872 APValue R;
14873 if (!evalShuffleGeneric(
14874 Info, E, R,
14875 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
14876 unsigned LaneBase = (DstIdx / 16) * 16;
14877 unsigned LaneIdx = DstIdx % 16;
14878 if (LaneIdx + Shift < 16)
14879 return std::make_pair(
14880 0, static_cast<int>(LaneBase + LaneIdx + Shift));
14881
14882 return std::make_pair(0, -1);
14883 }))
14884 return false;
14885 return Success(R, E);
14886 }
14887
14888 case X86::BI__builtin_ia32_palignr128:
14889 case X86::BI__builtin_ia32_palignr256:
14890 case X86::BI__builtin_ia32_palignr512: {
14891 APValue R;
14892 if (!evalShuffleGeneric(Info, E, R, [](unsigned DstIdx, unsigned Shift) {
14893 // Default to -1 → zero-fill this destination element
14894 unsigned VecIdx = 1;
14895 int ElemIdx = -1;
14896
14897 int Lane = DstIdx / 16;
14898 int Offset = DstIdx % 16;
14899
14900 // Elements come from VecB first, then VecA after the shift boundary
14901 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
14902 if (ShiftedIdx < 16) { // from VecB
14903 ElemIdx = ShiftedIdx + (Lane * 16);
14904 } else if (ShiftedIdx < 32) { // from VecA
14905 VecIdx = 0;
14906 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
14907 }
14908
14909 return std::pair<unsigned, int>{VecIdx, ElemIdx};
14910 }))
14911 return false;
14912 return Success(R, E);
14913 }
14914 case X86::BI__builtin_ia32_alignd128:
14915 case X86::BI__builtin_ia32_alignd256:
14916 case X86::BI__builtin_ia32_alignd512:
14917 case X86::BI__builtin_ia32_alignq128:
14918 case X86::BI__builtin_ia32_alignq256:
14919 case X86::BI__builtin_ia32_alignq512: {
14920 APValue R;
14921 unsigned NumElems = E->getType()->castAs<VectorType>()->getNumElements();
14922 if (!evalShuffleGeneric(Info, E, R,
14923 [NumElems](unsigned DstIdx, unsigned Shift) {
14924 unsigned Imm = Shift & 0xFF;
14925 unsigned EffectiveShift = Imm & (NumElems - 1);
14926 unsigned SourcePos = DstIdx + EffectiveShift;
14927 unsigned VecIdx = SourcePos < NumElems ? 1 : 0;
14928 unsigned ElemIdx = SourcePos & (NumElems - 1);
14929
14930 return std::pair<unsigned, int>{
14931 VecIdx, static_cast<int>(ElemIdx)};
14932 }))
14933 return false;
14934 return Success(R, E);
14935 }
14936 case X86::BI__builtin_ia32_permvarsi256:
14937 case X86::BI__builtin_ia32_permvarsf256:
14938 case X86::BI__builtin_ia32_permvardf512:
14939 case X86::BI__builtin_ia32_permvardi512:
14940 case X86::BI__builtin_ia32_permvarhi128: {
14941 APValue R;
14942 if (!evalShuffleGeneric(Info, E, R,
14943 [](unsigned DstIdx, unsigned ShuffleMask) {
14944 int Offset = ShuffleMask & 0x7;
14945 return std::pair<unsigned, int>{0, Offset};
14946 }))
14947 return false;
14948 return Success(R, E);
14949 }
14950 case X86::BI__builtin_ia32_permvarqi128:
14951 case X86::BI__builtin_ia32_permvarhi256:
14952 case X86::BI__builtin_ia32_permvarsi512:
14953 case X86::BI__builtin_ia32_permvarsf512: {
14954 APValue R;
14955 if (!evalShuffleGeneric(Info, E, R,
14956 [](unsigned DstIdx, unsigned ShuffleMask) {
14957 int Offset = ShuffleMask & 0xF;
14958 return std::pair<unsigned, int>{0, Offset};
14959 }))
14960 return false;
14961 return Success(R, E);
14962 }
14963 case X86::BI__builtin_ia32_permvardi256:
14964 case X86::BI__builtin_ia32_permvardf256: {
14965 APValue R;
14966 if (!evalShuffleGeneric(Info, E, R,
14967 [](unsigned DstIdx, unsigned ShuffleMask) {
14968 int Offset = ShuffleMask & 0x3;
14969 return std::pair<unsigned, int>{0, Offset};
14970 }))
14971 return false;
14972 return Success(R, E);
14973 }
14974 case X86::BI__builtin_ia32_permvarqi256:
14975 case X86::BI__builtin_ia32_permvarhi512: {
14976 APValue R;
14977 if (!evalShuffleGeneric(Info, E, R,
14978 [](unsigned DstIdx, unsigned ShuffleMask) {
14979 int Offset = ShuffleMask & 0x1F;
14980 return std::pair<unsigned, int>{0, Offset};
14981 }))
14982 return false;
14983 return Success(R, E);
14984 }
14985 case X86::BI__builtin_ia32_permvarqi512: {
14986 APValue R;
14987 if (!evalShuffleGeneric(Info, E, R,
14988 [](unsigned DstIdx, unsigned ShuffleMask) {
14989 int Offset = ShuffleMask & 0x3F;
14990 return std::pair<unsigned, int>{0, Offset};
14991 }))
14992 return false;
14993 return Success(R, E);
14994 }
14995 case X86::BI__builtin_ia32_vpermi2varq128:
14996 case X86::BI__builtin_ia32_vpermi2varpd128: {
14997 APValue R;
14998 if (!evalShuffleGeneric(Info, E, R,
14999 [](unsigned DstIdx, unsigned ShuffleMask) {
15000 int Offset = ShuffleMask & 0x1;
15001 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
15002 return std::pair<unsigned, int>{SrcIdx, Offset};
15003 }))
15004 return false;
15005 return Success(R, E);
15006 }
15007 case X86::BI__builtin_ia32_vpermi2vard128:
15008 case X86::BI__builtin_ia32_vpermi2varps128:
15009 case X86::BI__builtin_ia32_vpermi2varq256:
15010 case X86::BI__builtin_ia32_vpermi2varpd256: {
15011 APValue R;
15012 if (!evalShuffleGeneric(Info, E, R,
15013 [](unsigned DstIdx, unsigned ShuffleMask) {
15014 int Offset = ShuffleMask & 0x3;
15015 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
15016 return std::pair<unsigned, int>{SrcIdx, Offset};
15017 }))
15018 return false;
15019 return Success(R, E);
15020 }
15021 case X86::BI__builtin_ia32_vpermi2varhi128:
15022 case X86::BI__builtin_ia32_vpermi2vard256:
15023 case X86::BI__builtin_ia32_vpermi2varps256:
15024 case X86::BI__builtin_ia32_vpermi2varq512:
15025 case X86::BI__builtin_ia32_vpermi2varpd512: {
15026 APValue R;
15027 if (!evalShuffleGeneric(Info, E, R,
15028 [](unsigned DstIdx, unsigned ShuffleMask) {
15029 int Offset = ShuffleMask & 0x7;
15030 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
15031 return std::pair<unsigned, int>{SrcIdx, Offset};
15032 }))
15033 return false;
15034 return Success(R, E);
15035 }
15036 case X86::BI__builtin_ia32_vpermi2varqi128:
15037 case X86::BI__builtin_ia32_vpermi2varhi256:
15038 case X86::BI__builtin_ia32_vpermi2vard512:
15039 case X86::BI__builtin_ia32_vpermi2varps512: {
15040 APValue R;
15041 if (!evalShuffleGeneric(Info, E, R,
15042 [](unsigned DstIdx, unsigned ShuffleMask) {
15043 int Offset = ShuffleMask & 0xF;
15044 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
15045 return std::pair<unsigned, int>{SrcIdx, Offset};
15046 }))
15047 return false;
15048 return Success(R, E);
15049 }
15050 case X86::BI__builtin_ia32_vpermi2varqi256:
15051 case X86::BI__builtin_ia32_vpermi2varhi512: {
15052 APValue R;
15053 if (!evalShuffleGeneric(Info, E, R,
15054 [](unsigned DstIdx, unsigned ShuffleMask) {
15055 int Offset = ShuffleMask & 0x1F;
15056 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
15057 return std::pair<unsigned, int>{SrcIdx, Offset};
15058 }))
15059 return false;
15060 return Success(R, E);
15061 }
15062 case X86::BI__builtin_ia32_vpermi2varqi512: {
15063 APValue R;
15064 if (!evalShuffleGeneric(Info, E, R,
15065 [](unsigned DstIdx, unsigned ShuffleMask) {
15066 int Offset = ShuffleMask & 0x3F;
15067 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
15068 return std::pair<unsigned, int>{SrcIdx, Offset};
15069 }))
15070 return false;
15071 return Success(R, E);
15072 }
15073
15074 case clang::X86::BI__builtin_ia32_minps:
15075 case clang::X86::BI__builtin_ia32_minpd:
15076 case clang::X86::BI__builtin_ia32_minps256:
15077 case clang::X86::BI__builtin_ia32_minpd256:
15078 case clang::X86::BI__builtin_ia32_minps512:
15079 case clang::X86::BI__builtin_ia32_minpd512:
15080 case clang::X86::BI__builtin_ia32_minph128:
15081 case clang::X86::BI__builtin_ia32_minph256:
15082 case clang::X86::BI__builtin_ia32_minph512:
15083 return EvaluateFpBinOpExpr(
15084 [](const APFloat &A, const APFloat &B,
15085 std::optional<APSInt>) -> std::optional<APFloat> {
15086 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
15087 B.isInfinity() || B.isDenormal())
15088 return std::nullopt;
15089 if (A.isZero() && B.isZero())
15090 return B;
15091 return llvm::minimum(A, B);
15092 });
15093
15094 case clang::X86::BI__builtin_ia32_minss:
15095 case clang::X86::BI__builtin_ia32_minsd:
15096 return EvaluateFpBinOpExpr(
15097 [](const APFloat &A, const APFloat &B,
15098 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15099 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/true);
15100 },
15101 /*IsScalar=*/true);
15102
15103 case clang::X86::BI__builtin_ia32_minsd_round_mask:
15104 case clang::X86::BI__builtin_ia32_minss_round_mask:
15105 case clang::X86::BI__builtin_ia32_minsh_round_mask:
15106 case clang::X86::BI__builtin_ia32_maxsd_round_mask:
15107 case clang::X86::BI__builtin_ia32_maxss_round_mask:
15108 case clang::X86::BI__builtin_ia32_maxsh_round_mask: {
15109 bool IsMin = BuiltinOp == clang::X86::BI__builtin_ia32_minsd_round_mask ||
15110 BuiltinOp == clang::X86::BI__builtin_ia32_minss_round_mask ||
15111 BuiltinOp == clang::X86::BI__builtin_ia32_minsh_round_mask;
15112 return EvaluateScalarFpRoundMaskBinOp(
15113 [IsMin](const APFloat &A, const APFloat &B,
15114 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15115 return EvalScalarMinMaxFp(A, B, RoundingMode, IsMin);
15116 });
15117 }
15118
15119 case clang::X86::BI__builtin_ia32_maxps:
15120 case clang::X86::BI__builtin_ia32_maxpd:
15121 case clang::X86::BI__builtin_ia32_maxps256:
15122 case clang::X86::BI__builtin_ia32_maxpd256:
15123 case clang::X86::BI__builtin_ia32_maxps512:
15124 case clang::X86::BI__builtin_ia32_maxpd512:
15125 case clang::X86::BI__builtin_ia32_maxph128:
15126 case clang::X86::BI__builtin_ia32_maxph256:
15127 case clang::X86::BI__builtin_ia32_maxph512:
15128 return EvaluateFpBinOpExpr(
15129 [](const APFloat &A, const APFloat &B,
15130 std::optional<APSInt>) -> std::optional<APFloat> {
15131 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
15132 B.isInfinity() || B.isDenormal())
15133 return std::nullopt;
15134 if (A.isZero() && B.isZero())
15135 return B;
15136 return llvm::maximum(A, B);
15137 });
15138
15139 case clang::X86::BI__builtin_ia32_maxss:
15140 case clang::X86::BI__builtin_ia32_maxsd:
15141 return EvaluateFpBinOpExpr(
15142 [](const APFloat &A, const APFloat &B,
15143 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15144 return EvalScalarMinMaxFp(A, B, RoundingMode, /*IsMin=*/false);
15145 },
15146 /*IsScalar=*/true);
15147
15148 case clang::X86::BI__builtin_ia32_vcvtps2ph:
15149 case clang::X86::BI__builtin_ia32_vcvtps2ph256: {
15150 APValue SrcVec;
15151 if (!EvaluateAsRValue(Info, E->getArg(0), SrcVec))
15152 return false;
15153
15154 APSInt Imm;
15155 if (!EvaluateInteger(E->getArg(1), Imm, Info))
15156 return false;
15157
15158 const auto *SrcVTy = E->getArg(0)->getType()->castAs<VectorType>();
15159 unsigned SrcNumElems = SrcVTy->getNumElements();
15160 const auto *DstVTy = E->getType()->castAs<VectorType>();
15161 unsigned DstNumElems = DstVTy->getNumElements();
15162 QualType DstElemTy = DstVTy->getElementType();
15163
15164 const llvm::fltSemantics &HalfSem =
15165 Info.Ctx.getFloatTypeSemantics(Info.Ctx.HalfTy);
15166
15167 int ImmVal = Imm.getZExtValue();
15168 bool UseMXCSR = (ImmVal & 4) != 0;
15169 bool IsFPConstrained =
15170 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained();
15171
15172 llvm::RoundingMode RM;
15173 if (!UseMXCSR) {
15174 switch (ImmVal & 3) {
15175 case 0:
15176 RM = llvm::RoundingMode::NearestTiesToEven;
15177 break;
15178 case 1:
15179 RM = llvm::RoundingMode::TowardNegative;
15180 break;
15181 case 2:
15182 RM = llvm::RoundingMode::TowardPositive;
15183 break;
15184 case 3:
15185 RM = llvm::RoundingMode::TowardZero;
15186 break;
15187 default:
15188 llvm_unreachable("Invalid immediate rounding mode");
15189 }
15190 } else {
15191 RM = llvm::RoundingMode::NearestTiesToEven;
15192 }
15193
15194 SmallVector<APValue, 8> ResultElements;
15195 ResultElements.reserve(DstNumElems);
15196
15197 for (unsigned I = 0; I < SrcNumElems; ++I) {
15198 APFloat SrcVal = SrcVec.getVectorElt(I).getFloat();
15199
15200 bool LostInfo;
15201 APFloat::opStatus St = SrcVal.convert(HalfSem, RM, &LostInfo);
15202
15203 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
15204 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
15205 return false;
15206 }
15207
15208 APSInt DstInt(SrcVal.bitcastToAPInt(),
15210 ResultElements.push_back(APValue(DstInt));
15211 }
15212
15213 if (DstNumElems > SrcNumElems) {
15214 APSInt Zero = Info.Ctx.MakeIntValue(0, DstElemTy);
15215 for (unsigned I = SrcNumElems; I < DstNumElems; ++I) {
15216 ResultElements.push_back(APValue(Zero));
15217 }
15218 }
15219
15220 return Success(ResultElements, E);
15221 }
15222 case X86::BI__builtin_ia32_vperm2f128_pd256:
15223 case X86::BI__builtin_ia32_vperm2f128_ps256:
15224 case X86::BI__builtin_ia32_vperm2f128_si256:
15225 case X86::BI__builtin_ia32_permti256: {
15226 unsigned NumElements =
15227 E->getArg(0)->getType()->getAs<VectorType>()->getNumElements();
15228 unsigned PreservedBitsCnt = NumElements >> 2;
15229 APValue R;
15230 if (!evalShuffleGeneric(
15231 Info, E, R,
15232 [PreservedBitsCnt](unsigned DstIdx, unsigned ShuffleMask) {
15233 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
15234 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
15235
15236 if (ControlBits & 0b1000)
15237 return std::make_pair(0u, -1);
15238
15239 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
15240 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
15241 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
15242 (DstIdx & PreservedBitsMask);
15243 return std::make_pair(SrcVecIdx, SrcIdx);
15244 }))
15245 return false;
15246 return Success(R, E);
15247 }
15248 case X86::BI__builtin_ia32_vpdpwssd128:
15249 case X86::BI__builtin_ia32_vpdpwssd256:
15250 case X86::BI__builtin_ia32_vpdpwssd512:
15251 case X86::BI__builtin_ia32_vpdpbusd128:
15252 case X86::BI__builtin_ia32_vpdpbusd256:
15253 case X86::BI__builtin_ia32_vpdpbusd512:
15254 return EvalVectorDotProduct(false);
15255 case X86::BI__builtin_ia32_vpdpwssds128:
15256 case X86::BI__builtin_ia32_vpdpwssds256:
15257 case X86::BI__builtin_ia32_vpdpwssds512:
15258 case X86::BI__builtin_ia32_vpdpbusds128:
15259 case X86::BI__builtin_ia32_vpdpbusds256:
15260 case X86::BI__builtin_ia32_vpdpbusds512:
15261 return EvalVectorDotProduct(true);
15262 }
15263}
15264
15265bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
15266 APValue Source;
15267 QualType SourceVecType = E->getSrcExpr()->getType();
15268 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
15269 return false;
15270
15271 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
15272 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
15273
15274 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15275
15276 auto SourceLen = Source.getVectorLength();
15277 SmallVector<APValue, 4> ResultElements;
15278 ResultElements.reserve(SourceLen);
15279 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
15280 APValue Elt;
15281 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
15282 Source.getVectorElt(EltNum), Elt))
15283 return false;
15284 ResultElements.push_back(std::move(Elt));
15285 }
15286
15287 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
15288}
15289
15290static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
15291 QualType ElemType, APValue const &VecVal1,
15292 APValue const &VecVal2, unsigned EltNum,
15293 APValue &Result) {
15294 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
15295 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
15296
15297 APSInt IndexVal = E->getShuffleMaskIdx(EltNum);
15298 int64_t index = IndexVal.getExtValue();
15299 // The spec says that -1 should be treated as undef for optimizations,
15300 // but in constexpr we'd have to produce an APValue::Indeterminate,
15301 // which is prohibited from being a top-level constant value. Emit a
15302 // diagnostic instead.
15303 if (index == -1) {
15304 Info.FFDiag(
15305 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
15306 << EltNum;
15307 return false;
15308 }
15309
15310 if (index < 0 ||
15311 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
15312 llvm_unreachable("Out of bounds shuffle index");
15313
15314 if (index >= TotalElementsInInputVector1)
15315 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
15316 else
15317 Result = VecVal1.getVectorElt(index);
15318 return true;
15319}
15320
15321bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
15322 // FIXME: Unary shuffle with mask not currently supported.
15323 if (E->getNumSubExprs() == 2)
15324 return Error(E);
15325 APValue VecVal1;
15326 const Expr *Vec1 = E->getExpr(0);
15327 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
15328 return false;
15329 APValue VecVal2;
15330 const Expr *Vec2 = E->getExpr(1);
15331 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
15332 return false;
15333
15334 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
15335 QualType DestElTy = DestVecTy->getElementType();
15336
15337 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
15338
15339 SmallVector<APValue, 4> ResultElements;
15340 ResultElements.reserve(TotalElementsInOutputVector);
15341 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
15342 APValue Elt;
15343 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
15344 return false;
15345 ResultElements.push_back(std::move(Elt));
15346 }
15347
15348 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
15349}
15350
15351//===----------------------------------------------------------------------===//
15352// Matrix Evaluation
15353//===----------------------------------------------------------------------===//
15354
15355namespace {
15356class MatrixExprEvaluator : public ExprEvaluatorBase<MatrixExprEvaluator> {
15357 APValue &Result;
15358
15359public:
15360 MatrixExprEvaluator(EvalInfo &Info, APValue &Result)
15361 : ExprEvaluatorBaseTy(Info), Result(Result) {}
15362
15363 bool Success(ArrayRef<APValue> M, const Expr *E) {
15364 auto *CMTy = E->getType()->castAs<ConstantMatrixType>();
15365 assert(M.size() == CMTy->getNumElementsFlattened());
15366 // FIXME: remove this APValue copy.
15367 Result = APValue(M.data(), CMTy->getNumRows(), CMTy->getNumColumns());
15368 return true;
15369 }
15370 bool Success(const APValue &M, const Expr *E) {
15371 assert(M.isMatrix() && "expected matrix");
15372 Result = M;
15373 return true;
15374 }
15375
15376 bool VisitCastExpr(const CastExpr *E);
15377 bool VisitInitListExpr(const InitListExpr *E);
15378};
15379} // end anonymous namespace
15380
15381static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info) {
15382 assert(E->isPRValue() && E->getType()->isConstantMatrixType() &&
15383 "not a matrix prvalue");
15384 return MatrixExprEvaluator(Info, Result).Visit(E);
15385}
15386
15387bool MatrixExprEvaluator::VisitCastExpr(const CastExpr *E) {
15388 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
15389 unsigned NumRows = MT->getNumRows();
15390 unsigned NumCols = MT->getNumColumns();
15391 unsigned NElts = NumRows * NumCols;
15392 QualType EltTy = MT->getElementType();
15393 const Expr *SE = E->getSubExpr();
15394
15395 switch (E->getCastKind()) {
15396 case CK_HLSLAggregateSplatCast: {
15397 APValue Val;
15398 QualType ValTy;
15399
15400 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
15401 return false;
15402
15403 APValue CastedVal;
15404 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15405 if (!handleScalarCast(Info, FPO, E, ValTy, EltTy, Val, CastedVal))
15406 return false;
15407
15408 SmallVector<APValue, 16> SplatEls(NElts, CastedVal);
15409 return Success(SplatEls, E);
15410 }
15411 case CK_HLSLElementwiseCast: {
15412 SmallVector<APValue> SrcVals;
15413 SmallVector<QualType> SrcTypes;
15414
15415 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcVals, SrcTypes))
15416 return false;
15417
15418 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15419 SmallVector<QualType, 16> DestTypes(NElts, EltTy);
15420 SmallVector<APValue, 16> ResultEls(NElts);
15421 if (!handleElementwiseCast(Info, E, FPO, SrcVals, SrcTypes, DestTypes,
15422 ResultEls))
15423 return false;
15424 return Success(ResultEls, E);
15425 }
15426 default:
15427 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15428 }
15429}
15430
15431bool MatrixExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
15432 const auto *MT = E->getType()->castAs<ConstantMatrixType>();
15433 QualType EltTy = MT->getElementType();
15434
15435 assert(E->getNumInits() == MT->getNumElementsFlattened() &&
15436 "Expected number of elements in initializer list to match the number "
15437 "of matrix elements");
15438
15439 SmallVector<APValue, 16> Elements;
15440 Elements.reserve(MT->getNumElementsFlattened());
15441
15442 // The following loop assumes the elements of the matrix InitListExpr are in
15443 // row-major order, which matches the row-major ordering assumption of the
15444 // matrix APValue.
15445 for (unsigned I = 0, N = MT->getNumElementsFlattened(); I < N; ++I) {
15446 if (EltTy->isIntegerType()) {
15447 llvm::APSInt IntVal;
15448 if (!EvaluateInteger(E->getInit(I), IntVal, Info))
15449 return false;
15450 Elements.push_back(APValue(IntVal));
15451 } else {
15452 llvm::APFloat FloatVal(0.0);
15453 if (!EvaluateFloat(E->getInit(I), FloatVal, Info))
15454 return false;
15455 Elements.push_back(APValue(FloatVal));
15456 }
15457 }
15458
15459 return Success(Elements, E);
15460}
15461
15462//===----------------------------------------------------------------------===//
15463// Array Evaluation
15464//===----------------------------------------------------------------------===//
15465
15466namespace {
15467 class ArrayExprEvaluator
15468 : public ExprEvaluatorBase<ArrayExprEvaluator> {
15469 const LValue &This;
15470 APValue &Result;
15471 public:
15472
15473 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
15474 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
15475
15476 bool Success(const APValue &V, const Expr *E) {
15477 assert(V.isArray() && "expected array");
15478 Result = V;
15479 return true;
15480 }
15481
15482 bool ZeroInitialization(const Expr *E) {
15483 const ConstantArrayType *CAT =
15484 Info.Ctx.getAsConstantArrayType(E->getType());
15485 if (!CAT) {
15486 if (E->getType()->isIncompleteArrayType()) {
15487 // We can be asked to zero-initialize a flexible array member; this
15488 // is represented as an ImplicitValueInitExpr of incomplete array
15489 // type. In this case, the array has zero elements.
15490 Result = APValue(APValue::UninitArray(), 0, 0);
15491 return true;
15492 }
15493 // FIXME: We could handle VLAs here.
15494 return Error(E);
15495 }
15496
15497 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
15498 if (!Result.hasArrayFiller())
15499 return true;
15500
15501 // Zero-initialize all elements.
15502 LValue Subobject = This;
15503 Subobject.addArray(Info, E, CAT);
15504 ImplicitValueInitExpr VIE(CAT->getElementType());
15505 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
15506 }
15507
15508 bool VisitCallExpr(const CallExpr *E) {
15509 return handleCallExpr(E, Result, &This);
15510 }
15511 bool VisitCastExpr(const CastExpr *E);
15512 bool VisitInitListExpr(const InitListExpr *E,
15513 QualType AllocType = QualType());
15514 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
15515 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
15516 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
15517 const LValue &Subobject,
15518 APValue *Value, QualType Type);
15519 bool VisitStringLiteral(const StringLiteral *E,
15520 QualType AllocType = QualType()) {
15521 expandStringLiteral(Info, E, Result, AllocType);
15522 return true;
15523 }
15524 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
15525 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
15526 ArrayRef<Expr *> Args,
15527 const Expr *ArrayFiller,
15528 QualType AllocType = QualType());
15529 bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E);
15530 };
15531} // end anonymous namespace
15532
15533static bool EvaluateArray(const Expr *E, const LValue &This,
15534 APValue &Result, EvalInfo &Info) {
15535 assert(!E->isValueDependent());
15536 assert(E->isPRValue() && E->getType()->isArrayType() &&
15537 "not an array prvalue");
15538 return ArrayExprEvaluator(Info, This, Result).Visit(E);
15539}
15540
15541static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
15542 APValue &Result, const InitListExpr *ILE,
15543 QualType AllocType) {
15544 assert(!ILE->isValueDependent());
15545 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
15546 "not an array prvalue");
15547 return ArrayExprEvaluator(Info, This, Result)
15548 .VisitInitListExpr(ILE, AllocType);
15549}
15550
15551static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
15552 APValue &Result,
15553 const CXXConstructExpr *CCE,
15554 QualType AllocType) {
15555 assert(!CCE->isValueDependent());
15556 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
15557 "not an array prvalue");
15558 return ArrayExprEvaluator(Info, This, Result)
15559 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
15560}
15561
15562// Return true iff the given array filler may depend on the element index.
15563static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
15564 // For now, just allow non-class value-initialization and initialization
15565 // lists comprised of them.
15566 if (isa<ImplicitValueInitExpr>(FillerExpr))
15567 return false;
15568 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
15569 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
15570 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
15571 return true;
15572 }
15573
15574 if (ILE->hasArrayFiller() &&
15575 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
15576 return true;
15577
15578 return false;
15579 }
15580 return true;
15581}
15582
15583bool ArrayExprEvaluator::VisitCastExpr(const CastExpr *E) {
15584 const Expr *SE = E->getSubExpr();
15585
15586 switch (E->getCastKind()) {
15587 default:
15588 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15589 case CK_HLSLAggregateSplatCast: {
15590 APValue Val;
15591 QualType ValTy;
15592
15593 if (!hlslAggSplatHelper(Info, SE, Val, ValTy))
15594 return false;
15595
15596 unsigned NEls = elementwiseSize(Info, E->getType());
15597
15598 SmallVector<APValue> SplatEls(NEls, Val);
15599 SmallVector<QualType> SplatType(NEls, ValTy);
15600
15601 // cast the elements
15602 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15603 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SplatEls,
15604 SplatType))
15605 return false;
15606
15607 return true;
15608 }
15609 case CK_HLSLElementwiseCast: {
15610 SmallVector<APValue> SrcEls;
15611 SmallVector<QualType> SrcTypes;
15612
15613 if (!hlslElementwiseCastHelper(Info, SE, E->getType(), SrcEls, SrcTypes))
15614 return false;
15615
15616 // cast the elements
15617 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15618 if (!constructAggregate(Info, FPO, E, Result, E->getType(), SrcEls,
15619 SrcTypes))
15620 return false;
15621 return true;
15622 }
15623 }
15624}
15625
15626bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
15627 QualType AllocType) {
15628 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15629 AllocType.isNull() ? E->getType() : AllocType);
15630 if (!CAT)
15631 return Error(E);
15632
15633 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
15634 // an appropriately-typed string literal enclosed in braces.
15635 if (E->isStringLiteralInit()) {
15636 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
15637 // FIXME: Support ObjCEncodeExpr here once we support it in
15638 // ArrayExprEvaluator generally.
15639 if (!SL)
15640 return Error(E);
15641 return VisitStringLiteral(SL, AllocType);
15642 }
15643 // Any other transparent list init will need proper handling of the
15644 // AllocType; we can't just recurse to the inner initializer.
15645 assert(!E->isTransparent() &&
15646 "transparent array list initialization is not string literal init?");
15647
15648 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
15649 AllocType);
15650}
15651
15652bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
15653 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
15654 QualType AllocType) {
15655 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15656 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
15657
15658 bool Success = true;
15659
15660 unsigned NumEltsToInit = Args.size();
15661 unsigned NumElts = CAT->getZExtSize();
15662
15663 // If the initializer might depend on the array index, run it for each
15664 // array element.
15665 if (NumEltsToInit != NumElts &&
15666 MaybeElementDependentArrayFiller(ArrayFiller)) {
15667 NumEltsToInit = NumElts;
15668 } else {
15669 // Add additional elements represented by EmbedExpr.
15670 for (auto *Init : Args) {
15671 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
15672 NumEltsToInit += EmbedS->getDataElementCount() - 1;
15673 }
15674 // If we have extra elements in the list, they will be discarded.
15675 if (NumEltsToInit > NumElts)
15676 NumEltsToInit = NumElts;
15677 // If we're overwriting memory which already has an object, make sure we
15678 // don't reduce the number of non-filler elements. (It's possible to
15679 // optimize this in some cases, but the logic gets really complicated.)
15680 if (Result.hasValue() && NumEltsToInit < Result.getArrayInitializedElts())
15681 NumEltsToInit = Result.getArrayInitializedElts();
15682 }
15683
15684 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
15685 << NumEltsToInit << ".\n");
15686
15687 if (!Result.hasValue()) {
15688 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15689 } else if (Result.getArrayInitializedElts() != NumEltsToInit) {
15690 // Number of inititalized elts changed. Recreate the APValue, and copy over
15691 // the relevant elements. (This is essentially just fixing the internal
15692 // representation of the value, because it's tied to the number of
15693 // non-filler elements.)
15694 //
15695 // This should be hit rarely, but there are some edge cases:
15696 //
15697 // - The array could be zero-initialized.
15698 // - There could be a DesignatedInitListExpr.
15699 // - operator new[] can be used to start the lifetime early.
15700 APValue NewResult = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15701 // First copy existing elements.
15702 unsigned NumOldElts = Result.getArrayInitializedElts();
15703 for (unsigned I = 0; I < NumOldElts; ++I) {
15704 NewResult.getArrayInitializedElt(I) =
15705 std::move(Result.getArrayInitializedElt(I));
15706 }
15707 // Then copy the array filler over the remaining elements.
15708 for (unsigned I = Result.getArrayInitializedElts(); I < NumEltsToInit; ++I)
15710 if (NewResult.hasArrayFiller() && Result.hasArrayFiller())
15711 NewResult.getArrayFiller() = Result.getArrayFiller();
15712 Result = std::move(NewResult);
15713 }
15714
15715 LValue Subobject = This;
15716 Subobject.addArray(Info, ExprToVisit, CAT);
15717 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
15718 if (Init->isValueDependent())
15719 return EvaluateDependentExpr(Init, Info);
15720
15721 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
15722 // aren't supposed to be modified.
15723 if (isa<NoInitExpr>(Init))
15724 return true;
15725
15726 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
15727 Subobject, Init) ||
15728 !HandleLValueArrayAdjustment(Info, Init, Subobject,
15729 CAT->getElementType(), 1)) {
15730 if (!Info.noteFailure())
15731 return false;
15732 Success = false;
15733 }
15734 return true;
15735 };
15736 unsigned ArrayIndex = 0;
15737 QualType DestTy = CAT->getElementType();
15738 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
15739 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
15740 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
15741 if (ArrayIndex >= NumEltsToInit)
15742 break;
15743 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
15744 StringLiteral *SL = EmbedS->getDataStringLiteral();
15745 for (unsigned I = EmbedS->getStartingElementPos(),
15746 N = EmbedS->getDataElementCount();
15747 I != EmbedS->getStartingElementPos() + N; ++I) {
15748 Value = SL->getCodeUnit(I);
15749 if (DestTy->isIntegerType()) {
15750 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
15751 } else {
15752 assert(DestTy->isFloatingType() && "unexpected type");
15753 const FPOptions FPO =
15754 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
15755 APFloat FValue(0.0);
15756 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
15757 DestTy, FValue))
15758 return false;
15759 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
15760 }
15761 ArrayIndex++;
15762 }
15763 } else {
15764 if (!Eval(Init, ArrayIndex))
15765 return false;
15766 ++ArrayIndex;
15767 }
15768 }
15769
15770 if (!Result.hasArrayFiller())
15771 return Success;
15772
15773 // If we get here, we have a trivial filler, which we can just evaluate
15774 // once and splat over the rest of the array elements.
15775 assert(ArrayFiller && "no array filler for incomplete init list");
15776 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
15777 ArrayFiller) &&
15778 Success;
15779}
15780
15781bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
15782 LValue CommonLV;
15783 if (E->getCommonExpr() &&
15784 !Evaluate(Info.CurrentCall->createTemporary(
15785 E->getCommonExpr(),
15786 getStorageType(Info.Ctx, E->getCommonExpr()),
15787 ScopeKind::FullExpression, CommonLV),
15788 Info, E->getCommonExpr()->getSourceExpr()))
15789 return false;
15790
15792
15793 uint64_t Elements = CAT->getZExtSize();
15794 Result = APValue(APValue::UninitArray(), Elements, Elements);
15795
15796 LValue Subobject = This;
15797 Subobject.addArray(Info, E, CAT);
15798
15799 bool Success = true;
15800 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
15801 // C++ [class.temporary]/5
15802 // There are four contexts in which temporaries are destroyed at a different
15803 // point than the end of the full-expression. [...] The second context is
15804 // when a copy constructor is called to copy an element of an array while
15805 // the entire array is copied [...]. In either case, if the constructor has
15806 // one or more default arguments, the destruction of every temporary created
15807 // in a default argument is sequenced before the construction of the next
15808 // array element, if any.
15809 FullExpressionRAII Scope(Info);
15810
15811 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
15812 Info, Subobject, E->getSubExpr()) ||
15813 !HandleLValueArrayAdjustment(Info, E, Subobject,
15814 CAT->getElementType(), 1)) {
15815 if (!Info.noteFailure())
15816 return false;
15817 Success = false;
15818 }
15819
15820 // Make sure we run the destructors too.
15821 Scope.destroy();
15822 }
15823
15824 return Success;
15825}
15826
15827bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
15828 return VisitCXXConstructExpr(E, This, &Result, E->getType());
15829}
15830
15831bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
15832 const LValue &Subobject,
15833 APValue *Value,
15834 QualType Type) {
15835 bool HadZeroInit = Value->hasValue();
15836
15837 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
15838 unsigned FinalSize = CAT->getZExtSize();
15839
15840 // Preserve the array filler if we had prior zero-initialization.
15841 APValue Filler =
15842 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
15843 : APValue();
15844
15845 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
15846 if (FinalSize == 0)
15847 return true;
15848
15849 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
15850 Info, E->getExprLoc(), E->getConstructor(),
15852 LValue ArrayElt = Subobject;
15853 ArrayElt.addArray(Info, E, CAT);
15854 // We do the whole initialization in two passes, first for just one element,
15855 // then for the whole array. It's possible we may find out we can't do const
15856 // init in the first pass, in which case we avoid allocating a potentially
15857 // large array. We don't do more passes because expanding array requires
15858 // copying the data, which is wasteful.
15859 for (const unsigned N : {1u, FinalSize}) {
15860 unsigned OldElts = Value->getArrayInitializedElts();
15861 if (OldElts == N)
15862 break;
15863
15864 // Expand the array to appropriate size.
15865 APValue NewValue(APValue::UninitArray(), N, FinalSize);
15866 for (unsigned I = 0; I < OldElts; ++I)
15867 NewValue.getArrayInitializedElt(I).swap(
15868 Value->getArrayInitializedElt(I));
15869 Value->swap(NewValue);
15870
15871 if (HadZeroInit)
15872 for (unsigned I = OldElts; I < N; ++I)
15873 Value->getArrayInitializedElt(I) = Filler;
15874
15875 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
15876 // If we have a trivial constructor, only evaluate it once and copy
15877 // the result into all the array elements.
15878 APValue &FirstResult = Value->getArrayInitializedElt(0);
15879 for (unsigned I = OldElts; I < FinalSize; ++I)
15880 Value->getArrayInitializedElt(I) = FirstResult;
15881 } else {
15882 for (unsigned I = OldElts; I < N; ++I) {
15883 if (!VisitCXXConstructExpr(E, ArrayElt,
15884 &Value->getArrayInitializedElt(I),
15885 CAT->getElementType()) ||
15886 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
15887 CAT->getElementType(), 1))
15888 return false;
15889 // When checking for const initilization any diagnostic is considered
15890 // an error.
15891 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
15892 !Info.keepEvaluatingAfterFailure())
15893 return false;
15894 }
15895 }
15896 }
15897
15898 return true;
15899 }
15900
15901 if (!Type->isRecordType())
15902 return Error(E);
15903
15904 return RecordExprEvaluator(Info, Subobject, *Value)
15905 .VisitCXXConstructExpr(E, Type);
15906}
15907
15908bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
15909 const CXXParenListInitExpr *E) {
15910 assert(E->getType()->isConstantArrayType() &&
15911 "Expression result is not a constant array type");
15912
15913 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
15914 E->getArrayFiller());
15915}
15916
15917bool ArrayExprEvaluator::VisitDesignatedInitUpdateExpr(
15918 const DesignatedInitUpdateExpr *E) {
15919 if (!Visit(E->getBase()))
15920 return false;
15921 return Visit(E->getUpdater());
15922}
15923
15924//===----------------------------------------------------------------------===//
15925// Integer Evaluation
15926//
15927// As a GNU extension, we support casting pointers to sufficiently-wide integer
15928// types and back in constant folding. Integer values are thus represented
15929// either as an integer-valued APValue, or as an lvalue-valued APValue.
15930//===----------------------------------------------------------------------===//
15931
15932namespace {
15933class IntExprEvaluator
15934 : public ExprEvaluatorBase<IntExprEvaluator> {
15935 APValue &Result;
15936public:
15937 IntExprEvaluator(EvalInfo &info, APValue &result)
15938 : ExprEvaluatorBaseTy(info), Result(result) {}
15939
15940 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
15941 assert(E->getType()->isIntegralOrEnumerationType() &&
15942 "Invalid evaluation result.");
15943 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
15944 "Invalid evaluation result.");
15945 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15946 "Invalid evaluation result.");
15947 Result = APValue(SI);
15948 return true;
15949 }
15950 bool Success(const llvm::APSInt &SI, const Expr *E) {
15951 return Success(SI, E, Result);
15952 }
15953
15954 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
15955 assert(E->getType()->isIntegralOrEnumerationType() &&
15956 "Invalid evaluation result.");
15957 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
15958 "Invalid evaluation result.");
15959 Result = APValue(APSInt(I));
15960 Result.getInt().setIsUnsigned(
15962 return true;
15963 }
15964 bool Success(const llvm::APInt &I, const Expr *E) {
15965 return Success(I, E, Result);
15966 }
15967
15968 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
15969 assert(E->getType()->isIntegralOrEnumerationType() &&
15970 "Invalid evaluation result.");
15971 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
15972 return true;
15973 }
15974 bool Success(uint64_t Value, const Expr *E) {
15975 return Success(Value, E, Result);
15976 }
15977
15978 bool Success(CharUnits Size, const Expr *E) {
15979 return Success(Size.getQuantity(), E);
15980 }
15981
15982 bool Success(const APValue &V, const Expr *E) {
15983 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
15984 // pointer allow further evaluation of the value.
15985 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
15986 V.allowConstexprUnknown()) {
15987 Result = V;
15988 return true;
15989 }
15990 return Success(V.getInt(), E);
15991 }
15992
15993 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
15994
15995 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
15996 const CallExpr *);
15997
15998 //===--------------------------------------------------------------------===//
15999 // Visitor Methods
16000 //===--------------------------------------------------------------------===//
16001
16002 bool VisitIntegerLiteral(const IntegerLiteral *E) {
16003 return Success(E->getValue(), E);
16004 }
16005 bool VisitCharacterLiteral(const CharacterLiteral *E) {
16006 return Success(E->getValue(), E);
16007 }
16008
16009 bool CheckReferencedDecl(const Expr *E, const Decl *D);
16010 bool VisitDeclRefExpr(const DeclRefExpr *E) {
16011 if (CheckReferencedDecl(E, E->getDecl()))
16012 return true;
16013
16014 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
16015 }
16016 bool VisitMemberExpr(const MemberExpr *E) {
16017 if (CheckReferencedDecl(E, E->getMemberDecl())) {
16018 VisitIgnoredBaseExpression(E->getBase());
16019 return true;
16020 }
16021
16022 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
16023 }
16024
16025 bool VisitCallExpr(const CallExpr *E);
16026 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
16027 bool VisitBinaryOperator(const BinaryOperator *E);
16028 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
16029 bool VisitUnaryOperator(const UnaryOperator *E);
16030
16031 bool VisitCastExpr(const CastExpr* E);
16032 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
16033
16034 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
16035 return Success(E->getValue(), E);
16036 }
16037
16038 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
16039 return Success(E->getValue(), E);
16040 }
16041
16042 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
16043 if (Info.ArrayInitIndex == uint64_t(-1)) {
16044 // We were asked to evaluate this subexpression independent of the
16045 // enclosing ArrayInitLoopExpr. We can't do that.
16046 Info.FFDiag(E);
16047 return false;
16048 }
16049 return Success(Info.ArrayInitIndex, E);
16050 }
16051
16052 // Note, GNU defines __null as an integer, not a pointer.
16053 bool VisitGNUNullExpr(const GNUNullExpr *E) {
16054 return ZeroInitialization(E);
16055 }
16056
16057 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
16058 if (E->isStoredAsBoolean())
16059 return Success(E->getBoolValue(), E);
16060 if (E->getAPValue().isAbsent())
16061 return false;
16062 assert(E->getAPValue().isInt() && "APValue type not supported");
16063 return Success(E->getAPValue().getInt(), E);
16064 }
16065
16066 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
16067 return Success(E->getValue(), E);
16068 }
16069
16070 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
16071 return Success(E->getValue(), E);
16072 }
16073
16074 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
16075 // This should not be evaluated during constant expr evaluation, as it
16076 // should always be in an unevaluated context (the args list of a 'gang' or
16077 // 'tile' clause).
16078 return Error(E);
16079 }
16080
16081 bool VisitUnaryReal(const UnaryOperator *E);
16082 bool VisitUnaryImag(const UnaryOperator *E);
16083
16084 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
16085 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
16086 bool VisitSourceLocExpr(const SourceLocExpr *E);
16087 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
16088 bool VisitRequiresExpr(const RequiresExpr *E);
16089 // FIXME: Missing: array subscript of vector, member of vector
16090};
16091
16092class FixedPointExprEvaluator
16093 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
16094 APValue &Result;
16095
16096 public:
16097 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
16098 : ExprEvaluatorBaseTy(info), Result(result) {}
16099
16100 bool Success(const llvm::APInt &I, const Expr *E) {
16101 return Success(
16102 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
16103 }
16104
16105 bool Success(uint64_t Value, const Expr *E) {
16106 return Success(
16107 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
16108 }
16109
16110 bool Success(const APValue &V, const Expr *E) {
16111 return Success(V.getFixedPoint(), E);
16112 }
16113
16114 bool Success(const APFixedPoint &V, const Expr *E) {
16115 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
16116 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
16117 "Invalid evaluation result.");
16118 Result = APValue(V);
16119 return true;
16120 }
16121
16122 bool ZeroInitialization(const Expr *E) {
16123 return Success(0, E);
16124 }
16125
16126 //===--------------------------------------------------------------------===//
16127 // Visitor Methods
16128 //===--------------------------------------------------------------------===//
16129
16130 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
16131 return Success(E->getValue(), E);
16132 }
16133
16134 bool VisitCastExpr(const CastExpr *E);
16135 bool VisitUnaryOperator(const UnaryOperator *E);
16136 bool VisitBinaryOperator(const BinaryOperator *E);
16137};
16138} // end anonymous namespace
16139
16140/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
16141/// produce either the integer value or a pointer.
16142///
16143/// GCC has a heinous extension which folds casts between pointer types and
16144/// pointer-sized integral types. We support this by allowing the evaluation of
16145/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
16146/// Some simple arithmetic on such values is supported (they are treated much
16147/// like char*).
16149 EvalInfo &Info) {
16150 assert(!E->isValueDependent());
16151 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
16152 return IntExprEvaluator(Info, Result).Visit(E);
16153}
16154
16155static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
16156 assert(!E->isValueDependent());
16157 APValue Val;
16158 if (!EvaluateIntegerOrLValue(E, Val, Info))
16159 return false;
16160 if (!Val.isInt()) {
16161 // FIXME: It would be better to produce the diagnostic for casting
16162 // a pointer to an integer.
16163 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16164 return false;
16165 }
16166 Result = Val.getInt();
16167 return true;
16168}
16169
16170bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
16172 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
16173 return Success(Evaluated, E);
16174}
16175
16176static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
16177 EvalInfo &Info) {
16178 assert(!E->isValueDependent());
16179 if (E->getType()->isFixedPointType()) {
16180 APValue Val;
16181 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
16182 return false;
16183 if (!Val.isFixedPoint())
16184 return false;
16185
16186 Result = Val.getFixedPoint();
16187 return true;
16188 }
16189 return false;
16190}
16191
16192static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
16193 EvalInfo &Info) {
16194 assert(!E->isValueDependent());
16195 if (E->getType()->isIntegerType()) {
16196 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
16197 APSInt Val;
16198 if (!EvaluateInteger(E, Val, Info))
16199 return false;
16200 Result = APFixedPoint(Val, FXSema);
16201 return true;
16202 } else if (E->getType()->isFixedPointType()) {
16203 return EvaluateFixedPoint(E, Result, Info);
16204 }
16205 return false;
16206}
16207
16208/// Check whether the given declaration can be directly converted to an integral
16209/// rvalue. If not, no diagnostic is produced; there are other things we can
16210/// try.
16211bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
16212 // Enums are integer constant exprs.
16213 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
16214 // Check for signedness/width mismatches between E type and ECD value.
16215 bool SameSign = (ECD->getInitVal().isSigned()
16217 bool SameWidth = (ECD->getInitVal().getBitWidth()
16218 == Info.Ctx.getIntWidth(E->getType()));
16219 if (SameSign && SameWidth)
16220 return Success(ECD->getInitVal(), E);
16221 else {
16222 // Get rid of mismatch (otherwise Success assertions will fail)
16223 // by computing a new value matching the type of E.
16224 llvm::APSInt Val = ECD->getInitVal();
16225 if (!SameSign)
16226 Val.setIsSigned(!ECD->getInitVal().isSigned());
16227 if (!SameWidth)
16228 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
16229 return Success(Val, E);
16230 }
16231 }
16232 return false;
16233}
16234
16235/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
16236/// as GCC.
16238 const LangOptions &LangOpts) {
16239 assert(!T->isDependentType() && "unexpected dependent type");
16240
16241 QualType CanTy = T.getCanonicalType();
16242
16243 switch (CanTy->getTypeClass()) {
16244#define TYPE(ID, BASE)
16245#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
16246#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
16247#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
16248#include "clang/AST/TypeNodes.inc"
16249 case Type::Auto:
16250 case Type::DeducedTemplateSpecialization:
16251 llvm_unreachable("unexpected non-canonical or dependent type");
16252
16253 case Type::Builtin:
16254 switch (cast<BuiltinType>(CanTy)->getKind()) {
16255#define BUILTIN_TYPE(ID, SINGLETON_ID)
16256#define SIGNED_TYPE(ID, SINGLETON_ID) \
16257 case BuiltinType::ID: return GCCTypeClass::Integer;
16258#define FLOATING_TYPE(ID, SINGLETON_ID) \
16259 case BuiltinType::ID: return GCCTypeClass::RealFloat;
16260#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
16261 case BuiltinType::ID: break;
16262#include "clang/AST/BuiltinTypes.def"
16263 case BuiltinType::Void:
16264 return GCCTypeClass::Void;
16265
16266 case BuiltinType::Bool:
16267 return GCCTypeClass::Bool;
16268
16269 case BuiltinType::Char_U:
16270 case BuiltinType::UChar:
16271 case BuiltinType::WChar_U:
16272 case BuiltinType::Char8:
16273 case BuiltinType::Char16:
16274 case BuiltinType::Char32:
16275 case BuiltinType::UShort:
16276 case BuiltinType::UInt:
16277 case BuiltinType::ULong:
16278 case BuiltinType::ULongLong:
16279 case BuiltinType::UInt128:
16280 return GCCTypeClass::Integer;
16281
16282 case BuiltinType::UShortAccum:
16283 case BuiltinType::UAccum:
16284 case BuiltinType::ULongAccum:
16285 case BuiltinType::UShortFract:
16286 case BuiltinType::UFract:
16287 case BuiltinType::ULongFract:
16288 case BuiltinType::SatUShortAccum:
16289 case BuiltinType::SatUAccum:
16290 case BuiltinType::SatULongAccum:
16291 case BuiltinType::SatUShortFract:
16292 case BuiltinType::SatUFract:
16293 case BuiltinType::SatULongFract:
16294 return GCCTypeClass::None;
16295
16296 case BuiltinType::NullPtr:
16297
16298 case BuiltinType::ObjCId:
16299 case BuiltinType::ObjCClass:
16300 case BuiltinType::ObjCSel:
16301#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16302 case BuiltinType::Id:
16303#include "clang/Basic/OpenCLImageTypes.def"
16304#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16305 case BuiltinType::Id:
16306#include "clang/Basic/OpenCLExtensionTypes.def"
16307 case BuiltinType::OCLSampler:
16308 case BuiltinType::OCLEvent:
16309 case BuiltinType::OCLClkEvent:
16310 case BuiltinType::OCLQueue:
16311 case BuiltinType::OCLReserveID:
16312#define SVE_TYPE(Name, Id, SingletonId) \
16313 case BuiltinType::Id:
16314#include "clang/Basic/AArch64ACLETypes.def"
16315#define PPC_VECTOR_TYPE(Name, Id, Size) \
16316 case BuiltinType::Id:
16317#include "clang/Basic/PPCTypes.def"
16318#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16319#include "clang/Basic/RISCVVTypes.def"
16320#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16321#include "clang/Basic/WebAssemblyReferenceTypes.def"
16322#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
16323#include "clang/Basic/AMDGPUTypes.def"
16324#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16325#include "clang/Basic/HLSLIntangibleTypes.def"
16326 return GCCTypeClass::None;
16327
16328 case BuiltinType::Dependent:
16329 llvm_unreachable("unexpected dependent type");
16330 };
16331 llvm_unreachable("unexpected placeholder type");
16332
16333 case Type::Enum:
16334 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
16335
16336 case Type::Pointer:
16337 case Type::ConstantArray:
16338 case Type::VariableArray:
16339 case Type::IncompleteArray:
16340 case Type::FunctionNoProto:
16341 case Type::FunctionProto:
16342 case Type::ArrayParameter:
16343 return GCCTypeClass::Pointer;
16344
16345 case Type::MemberPointer:
16346 return CanTy->isMemberDataPointerType()
16349
16350 case Type::Complex:
16351 return GCCTypeClass::Complex;
16352
16353 case Type::Record:
16354 return CanTy->isUnionType() ? GCCTypeClass::Union
16356
16357 case Type::Atomic:
16358 // GCC classifies _Atomic T the same as T.
16360 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
16361
16362 case Type::Vector:
16363 case Type::ExtVector:
16364 return GCCTypeClass::Vector;
16365
16366 case Type::BlockPointer:
16367 case Type::ConstantMatrix:
16368 case Type::ObjCObject:
16369 case Type::ObjCInterface:
16370 case Type::ObjCObjectPointer:
16371 case Type::Pipe:
16372 case Type::HLSLAttributedResource:
16373 case Type::HLSLInlineSpirv:
16374 case Type::OverflowBehavior:
16375 // Classify all other types that don't fit into the regular
16376 // classification the same way.
16377 return GCCTypeClass::None;
16378
16379 case Type::BitInt:
16380 return GCCTypeClass::BitInt;
16381
16382 case Type::LValueReference:
16383 case Type::RValueReference:
16384 llvm_unreachable("invalid type for expression");
16385 }
16386
16387 llvm_unreachable("unexpected type class");
16388}
16389
16390/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
16391/// as GCC.
16392static GCCTypeClass
16394 // If no argument was supplied, default to None. This isn't
16395 // ideal, however it is what gcc does.
16396 if (E->getNumArgs() == 0)
16397 return GCCTypeClass::None;
16398
16399 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
16400 // being an ICE, but still folds it to a constant using the type of the first
16401 // argument.
16402 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
16403}
16404
16405/// EvaluateBuiltinConstantPForLValue - Determine the result of
16406/// __builtin_constant_p when applied to the given pointer.
16407///
16408/// A pointer is only "constant" if it is null (or a pointer cast to integer)
16409/// or it points to the first character of a string literal.
16412 if (Base.isNull()) {
16413 // A null base is acceptable.
16414 return true;
16415 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
16416 if (!isa<StringLiteral>(E))
16417 return false;
16418 return LV.getLValueOffset().isZero();
16419 } else if (Base.is<TypeInfoLValue>()) {
16420 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
16421 // evaluate to true.
16422 return true;
16423 } else {
16424 // Any other base is not constant enough for GCC.
16425 return false;
16426 }
16427}
16428
16429/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
16430/// GCC as we can manage.
16431static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
16432 // This evaluation is not permitted to have side-effects, so evaluate it in
16433 // a speculative evaluation context.
16434 SpeculativeEvaluationRAII SpeculativeEval(Info);
16435
16436 // Constant-folding is always enabled for the operand of __builtin_constant_p
16437 // (even when the enclosing evaluation context otherwise requires a strict
16438 // language-specific constant expression).
16439 FoldConstant Fold(Info, true);
16440
16441 QualType ArgType = Arg->getType();
16442
16443 // __builtin_constant_p always has one operand. The rules which gcc follows
16444 // are not precisely documented, but are as follows:
16445 //
16446 // - If the operand is of integral, floating, complex or enumeration type,
16447 // and can be folded to a known value of that type, it returns 1.
16448 // - If the operand can be folded to a pointer to the first character
16449 // of a string literal (or such a pointer cast to an integral type)
16450 // or to a null pointer or an integer cast to a pointer, it returns 1.
16451 //
16452 // Otherwise, it returns 0.
16453 //
16454 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
16455 // its support for this did not work prior to GCC 9 and is not yet well
16456 // understood.
16457 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
16458 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
16459 ArgType->isNullPtrType()) {
16460 APValue V;
16461 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
16462 Fold.keepDiagnostics();
16463 return false;
16464 }
16465
16466 // For a pointer (possibly cast to integer), there are special rules.
16467 if (V.getKind() == APValue::LValue)
16469
16470 // Otherwise, any constant value is good enough.
16471 return V.hasValue();
16472 }
16473
16474 // Anything else isn't considered to be sufficiently constant.
16475 return false;
16476}
16477
16478/// Retrieves the "underlying object type" of the given expression,
16479/// as used by __builtin_object_size.
16481 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
16482 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
16483 return VD->getType();
16484 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
16486 return E->getType();
16487 } else if (B.is<TypeInfoLValue>()) {
16488 return B.getTypeInfoType();
16489 } else if (B.is<DynamicAllocLValue>()) {
16490 return B.getDynamicAllocType();
16491 }
16492
16493 return QualType();
16494}
16495
16496/// A more selective version of E->IgnoreParenCasts for
16497/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
16498/// to change the type of E.
16499/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
16500///
16501/// Always returns an RValue with a pointer representation.
16502static const Expr *ignorePointerCastsAndParens(const Expr *E) {
16503 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
16504
16505 const Expr *NoParens = E->IgnoreParens();
16506 const auto *Cast = dyn_cast<CastExpr>(NoParens);
16507 if (Cast == nullptr)
16508 return NoParens;
16509
16510 // We only conservatively allow a few kinds of casts, because this code is
16511 // inherently a simple solution that seeks to support the common case.
16512 auto CastKind = Cast->getCastKind();
16513 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
16514 CastKind != CK_AddressSpaceConversion)
16515 return NoParens;
16516
16517 const auto *SubExpr = Cast->getSubExpr();
16518 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
16519 return NoParens;
16520 return ignorePointerCastsAndParens(SubExpr);
16521}
16522
16523/// Checks to see if the given LValue's Designator is at the end of the LValue's
16524/// record layout. e.g.
16525/// struct { struct { int a, b; } fst, snd; } obj;
16526/// obj.fst // no
16527/// obj.snd // yes
16528/// obj.fst.a // no
16529/// obj.fst.b // no
16530/// obj.snd.a // no
16531/// obj.snd.b // yes
16532///
16533/// Please note: this function is specialized for how __builtin_object_size
16534/// views "objects".
16535///
16536/// If this encounters an invalid RecordDecl or otherwise cannot determine the
16537/// correct result, it will always return true.
16538static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
16539 assert(!LVal.Designator.Invalid);
16540
16541 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD) {
16542 const RecordDecl *Parent = FD->getParent();
16543 if (Parent->isInvalidDecl() || Parent->isUnion())
16544 return true;
16545 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
16546 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
16547 };
16548
16549 auto &Base = LVal.getLValueBase();
16550 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
16551 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
16552 if (!IsLastOrInvalidFieldDecl(FD))
16553 return false;
16554 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
16555 for (auto *FD : IFD->chain()) {
16556 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD)))
16557 return false;
16558 }
16559 }
16560 }
16561
16562 unsigned I = 0;
16563 QualType BaseType = getType(Base);
16564 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
16565 // If we don't know the array bound, conservatively assume we're looking at
16566 // the final array element.
16567 ++I;
16568 if (BaseType->isIncompleteArrayType())
16569 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
16570 else
16571 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
16572 }
16573
16574 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
16575 const auto &Entry = LVal.Designator.Entries[I];
16576 if (BaseType->isArrayType()) {
16577 // Because __builtin_object_size treats arrays as objects, we can ignore
16578 // the index iff this is the last array in the Designator.
16579 if (I + 1 == E)
16580 return true;
16581 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
16582 uint64_t Index = Entry.getAsArrayIndex();
16583 if (Index + 1 != CAT->getZExtSize())
16584 return false;
16585 BaseType = CAT->getElementType();
16586 } else if (BaseType->isAnyComplexType()) {
16587 const auto *CT = BaseType->castAs<ComplexType>();
16588 uint64_t Index = Entry.getAsArrayIndex();
16589 if (Index != 1)
16590 return false;
16591 BaseType = CT->getElementType();
16592 } else if (auto *FD = getAsField(Entry)) {
16593 if (!IsLastOrInvalidFieldDecl(FD))
16594 return false;
16595 BaseType = FD->getType();
16596 } else {
16597 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
16598 return false;
16599 }
16600 }
16601 return true;
16602}
16603
16604/// Tests to see if the LValue has a user-specified designator (that isn't
16605/// necessarily valid). Note that this always returns 'true' if the LValue has
16606/// an unsized array as its first designator entry, because there's currently no
16607/// way to tell if the user typed *foo or foo[0].
16608static bool refersToCompleteObject(const LValue &LVal) {
16609 if (LVal.Designator.Invalid)
16610 return false;
16611
16612 if (!LVal.Designator.Entries.empty())
16613 return LVal.Designator.isMostDerivedAnUnsizedArray();
16614
16615 if (!LVal.InvalidBase)
16616 return true;
16617
16618 // If `E` is a MemberExpr, then the first part of the designator is hiding in
16619 // the LValueBase.
16620 const auto *E = LVal.Base.dyn_cast<const Expr *>();
16621 return !E || !isa<MemberExpr>(E);
16622}
16623
16624/// Attempts to detect a user writing into a piece of memory that's impossible
16625/// to figure out the size of by just using types.
16626static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
16627 const SubobjectDesignator &Designator = LVal.Designator;
16628 // Notes:
16629 // - Users can only write off of the end when we have an invalid base. Invalid
16630 // bases imply we don't know where the memory came from.
16631 // - We used to be a bit more aggressive here; we'd only be conservative if
16632 // the array at the end was flexible, or if it had 0 or 1 elements. This
16633 // broke some common standard library extensions (PR30346), but was
16634 // otherwise seemingly fine. It may be useful to reintroduce this behavior
16635 // with some sort of list. OTOH, it seems that GCC is always
16636 // conservative with the last element in structs (if it's an array), so our
16637 // current behavior is more compatible than an explicit list approach would
16638 // be.
16639 auto isFlexibleArrayMember = [&] {
16641 FAMKind StrictFlexArraysLevel =
16642 Ctx.getLangOpts().getStrictFlexArraysLevel();
16643
16644 if (Designator.isMostDerivedAnUnsizedArray())
16645 return true;
16646
16647 if (StrictFlexArraysLevel == FAMKind::Default)
16648 return true;
16649
16650 if (Designator.getMostDerivedArraySize() == 0 &&
16651 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
16652 return true;
16653
16654 if (Designator.getMostDerivedArraySize() == 1 &&
16655 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
16656 return true;
16657
16658 return false;
16659 };
16660
16661 return LVal.InvalidBase &&
16662 Designator.Entries.size() == Designator.MostDerivedPathLength &&
16663 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
16664 isDesignatorAtObjectEnd(Ctx, LVal);
16665}
16666
16667/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
16668/// Fails if the conversion would cause loss of precision.
16669static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
16670 CharUnits &Result) {
16671 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
16672 if (Int.ugt(CharUnitsMax))
16673 return false;
16674 Result = CharUnits::fromQuantity(Int.getZExtValue());
16675 return true;
16676}
16677
16678/// If we're evaluating the object size of an instance of a struct that
16679/// contains a flexible array member, add the size of the initializer.
16680static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
16681 const LValue &LV, CharUnits &Size) {
16682 if (!T.isNull() && T->isStructureType() &&
16683 T->castAsRecordDecl()->hasFlexibleArrayMember())
16684 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
16685 if (const auto *VD = dyn_cast<VarDecl>(V))
16686 if (VD->hasInit())
16687 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
16688}
16689
16690/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
16691/// determine how many bytes exist from the beginning of the object to either
16692/// the end of the current subobject, or the end of the object itself, depending
16693/// on what the LValue looks like + the value of Type.
16694///
16695/// If this returns false, the value of Result is undefined.
16696static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
16697 unsigned Type, const LValue &LVal,
16698 CharUnits &EndOffset) {
16699 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
16700
16701 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
16702 if (Ty.isNull())
16703 return false;
16704
16705 Ty = Ty.getNonReferenceType();
16706
16707 if (Ty->isIncompleteType() || Ty->isFunctionType())
16708 return false;
16709
16710 return HandleSizeof(Info, ExprLoc, Ty, Result);
16711 };
16712
16713 // We want to evaluate the size of the entire object. This is a valid fallback
16714 // for when Type=1 and the designator is invalid, because we're asked for an
16715 // upper-bound.
16716 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
16717 // Type=3 wants a lower bound, so we can't fall back to this.
16718 if (Type == 3 && !DetermineForCompleteObject)
16719 return false;
16720
16721 llvm::APInt APEndOffset;
16722 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16723 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16724 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16725
16726 if (LVal.InvalidBase)
16727 return false;
16728
16729 QualType BaseTy = getObjectType(LVal.getLValueBase());
16730 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
16731 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
16732 return Ret;
16733 }
16734
16735 // We want to evaluate the size of a subobject.
16736 const SubobjectDesignator &Designator = LVal.Designator;
16737
16738 // The following is a moderately common idiom in C:
16739 //
16740 // struct Foo { int a; char c[1]; };
16741 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
16742 // strcpy(&F->c[0], Bar);
16743 //
16744 // In order to not break too much legacy code, we need to support it.
16745 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
16746 // If we can resolve this to an alloc_size call, we can hand that back,
16747 // because we know for certain how many bytes there are to write to.
16748 llvm::APInt APEndOffset;
16749 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
16750 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
16751 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
16752
16753 // If we cannot determine the size of the initial allocation, then we can't
16754 // given an accurate upper-bound. However, we are still able to give
16755 // conservative lower-bounds for Type=3.
16756 if (Type == 1)
16757 return false;
16758 }
16759
16760 CharUnits BytesPerElem;
16761 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
16762 return false;
16763
16764 // According to the GCC documentation, we want the size of the subobject
16765 // denoted by the pointer. But that's not quite right -- what we actually
16766 // want is the size of the immediately-enclosing array, if there is one.
16767 int64_t ElemsRemaining;
16768 if (Designator.MostDerivedIsArrayElement &&
16769 Designator.Entries.size() == Designator.MostDerivedPathLength) {
16770 uint64_t ArraySize = Designator.getMostDerivedArraySize();
16771 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
16772 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
16773 } else {
16774 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
16775 }
16776
16777 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
16778 return true;
16779}
16780
16781/// Tries to evaluate the __builtin_object_size for @p E. If successful,
16782/// returns true and stores the result in @p Size.
16783///
16784/// If @p WasError is non-null, this will report whether the failure to evaluate
16785/// is to be treated as an Error in IntExprEvaluator.
16786///
16787/// If @p IsDynamic is true (i.e. we're evaluating
16788/// __builtin_dynamic_object_size) and the operand designates a flexible array
16789/// member annotated with 'counted_by', we refuse to fold so that IR generation
16790/// can emit the count-based runtime size computation.
16791static std::optional<uint64_t>
16792tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info,
16793 bool IsDynamic = false) {
16794
16795 // Determine the denoted object.
16796 LValue LVal;
16797 {
16798 // The operand of __builtin_object_size is never evaluated for side-effects.
16799 // If there are any, but we can determine the pointed-to object anyway, then
16800 // ignore the side-effects.
16801 SpeculativeEvaluationRAII SpeculativeEval(Info);
16802 IgnoreSideEffectsRAII Fold(Info);
16803
16804 if (E->isGLValue()) {
16805 // It's possible for us to be given GLValues if we're called via
16806 // Expr::tryEvaluateObjectSize.
16807 APValue RVal;
16808 if (!EvaluateAsRValue(Info, E, RVal))
16809 return std::nullopt;
16810 LVal.setFrom(Info.Ctx, RVal);
16811 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
16812 /*InvalidBaseOK=*/true))
16813 return std::nullopt;
16814 }
16815
16816 // If we point to before the start of the object, there are no accessible
16817 // bytes.
16818 if (LVal.getLValueOffset().isNegative())
16819 return 0;
16820
16821 // For __builtin_dynamic_object_size on a counted_by-annotated flexible
16822 // array member, defer to IR generation (emitCountedBySize in CGBuiltin):
16823 // its runtime computation uses the live 'count' field and is more accurate
16824 // than the layout/initializer-derived size we'd produce here. Use the same
16825 // findStructFieldAccess form-recognition CGBuiltin does, so we refuse to
16826 // fold on exactly the shapes that path handles (and, importantly, *not*
16827 // on '&af.fam' which designates the array-as-a-whole and stays on the
16828 // layout-derived path to match GCC). Checked after the negative-offset
16829 // early return above so that obviously out-of-bounds operands still fold
16830 // to 0, preserving existing behavior.
16831 if (IsDynamic) {
16832 const auto *ME = dyn_cast_or_null<MemberExpr>(findStructFieldAccess(E));
16833 const auto *FD = ME ? dyn_cast<FieldDecl>(ME->getMemberDecl()) : nullptr;
16834 if (FD && FD->getType()->isCountAttributedType())
16835 return std::nullopt;
16836 }
16837
16838 CharUnits EndOffset;
16839 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
16840 return std::nullopt;
16841
16842 // If we've fallen outside of the end offset, just pretend there's nothing to
16843 // write to/read from.
16844 if (EndOffset <= LVal.getLValueOffset())
16845 return 0;
16846 return (EndOffset - LVal.getLValueOffset()).getQuantity();
16847}
16848
16849bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
16850 if (!IsConstantEvaluatedBuiltinCall(E))
16851 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16852 return VisitBuiltinCallExpr(E, ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E));
16853}
16854
16855static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
16856 APValue &Val, APSInt &Alignment) {
16857 QualType SrcTy = E->getArg(0)->getType();
16858 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
16859 return false;
16860 // Even though we are evaluating integer expressions we could get a pointer
16861 // argument for the __builtin_is_aligned() case.
16862 if (SrcTy->isPointerType()) {
16863 LValue Ptr;
16864 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
16865 return false;
16866 Ptr.moveInto(Val);
16867 } else if (!SrcTy->isIntegralOrEnumerationType()) {
16868 Info.FFDiag(E->getArg(0));
16869 return false;
16870 } else {
16871 APSInt SrcInt;
16872 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
16873 return false;
16874 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
16875 "Bit widths must be the same");
16876 Val = APValue(SrcInt);
16877 }
16878 assert(Val.hasValue());
16879 return true;
16880}
16881
16882bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
16883 unsigned BuiltinOp) {
16884 auto EvalTestOp = [&](llvm::function_ref<bool(const APInt &, const APInt &)>
16885 Fn) {
16886 APValue SourceLHS, SourceRHS;
16887 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
16888 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
16889 return false;
16890
16891 unsigned SourceLen = SourceLHS.getVectorLength();
16892 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
16893 QualType ElemQT = VT->getElementType();
16894 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
16895
16896 APInt AWide(LaneWidth * SourceLen, 0);
16897 APInt BWide(LaneWidth * SourceLen, 0);
16898
16899 for (unsigned I = 0; I != SourceLen; ++I) {
16900 APInt ALane;
16901 APInt BLane;
16902 if (ElemQT->isIntegerType()) { // Get value.
16903 ALane = SourceLHS.getVectorElt(I).getInt();
16904 BLane = SourceRHS.getVectorElt(I).getInt();
16905 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
16906 ALane =
16907 SourceLHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16908 BLane =
16909 SourceRHS.getVectorElt(I).getFloat().bitcastToAPInt().isNegative();
16910 } else { // Must be integer or floating type.
16911 return false;
16912 }
16913 AWide.insertBits(ALane, I * LaneWidth);
16914 BWide.insertBits(BLane, I * LaneWidth);
16915 }
16916 return Success(Fn(AWide, BWide), E);
16917 };
16918
16919 auto HandleMaskBinOp =
16920 [&](llvm::function_ref<APSInt(const APSInt &, const APSInt &)> Fn)
16921 -> bool {
16922 APValue LHS, RHS;
16923 if (!Evaluate(LHS, Info, E->getArg(0)) ||
16924 !Evaluate(RHS, Info, E->getArg(1)))
16925 return false;
16926
16927 APSInt ResultInt = Fn(LHS.getInt(), RHS.getInt());
16928
16929 return Success(APValue(ResultInt), E);
16930 };
16931
16932 auto HandleCRC32 = [&](unsigned DataBytes) -> bool {
16933 APSInt CRC, Data;
16934 if (!EvaluateInteger(E->getArg(0), CRC, Info) ||
16935 !EvaluateInteger(E->getArg(1), Data, Info))
16936 return false;
16937
16938 uint64_t CRCVal = CRC.getZExtValue();
16939 uint64_t DataVal = Data.getZExtValue();
16940
16941 // CRC32C polynomial (iSCSI polynomial, bit-reversed)
16942 static const uint32_t CRC32C_POLY = 0x82F63B78;
16943
16944 // Process each byte
16945 uint32_t Result = static_cast<uint32_t>(CRCVal);
16946 for (unsigned I = 0; I != DataBytes; ++I) {
16947 uint8_t Byte = static_cast<uint8_t>((DataVal >> (I * 8)) & 0xFF);
16948 Result ^= Byte;
16949 for (int J = 0; J != 8; ++J) {
16950 Result = (Result >> 1) ^ ((Result & 1) ? CRC32C_POLY : 0);
16951 }
16952 }
16953
16954 return Success(Result, E);
16955 };
16956
16957 switch (BuiltinOp) {
16958 default:
16959 return false;
16960
16961 case X86::BI__builtin_ia32_crc32qi:
16962 return HandleCRC32(1);
16963 case X86::BI__builtin_ia32_crc32hi:
16964 return HandleCRC32(2);
16965 case X86::BI__builtin_ia32_crc32si:
16966 return HandleCRC32(4);
16967 case X86::BI__builtin_ia32_crc32di:
16968 return HandleCRC32(8);
16969
16970 case Builtin::BI__builtin_dynamic_object_size:
16971 case Builtin::BI__builtin_object_size: {
16972 // The type was checked when we built the expression.
16973 unsigned Type =
16974 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
16975 assert(Type <= 3 && "unexpected type");
16976
16977 bool IsDynamic = BuiltinOp == Builtin::BI__builtin_dynamic_object_size;
16978 if (std::optional<uint64_t> Size =
16979 tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, IsDynamic))
16980 return Success(*Size, E);
16981
16982 if (E->getArg(0)->HasSideEffects(Info.Ctx))
16983 return Success((Type & 2) ? 0 : -1, E);
16984
16985 // Expression had no side effects, but we couldn't statically determine the
16986 // size of the referenced object.
16987 switch (Info.EvalMode) {
16988 case EvaluationMode::ConstantExpression:
16989 case EvaluationMode::ConstantFold:
16990 case EvaluationMode::IgnoreSideEffects:
16991 // Leave it to IR generation.
16992 return Error(E);
16993 case EvaluationMode::ConstantExpressionUnevaluated:
16994 // Reduce it to a constant now.
16995 return Success((Type & 2) ? 0 : -1, E);
16996 }
16997
16998 llvm_unreachable("unexpected EvalMode");
16999 }
17000
17001 case Builtin::BI__builtin_os_log_format_buffer_size: {
17002 analyze_os_log::OSLogBufferLayout Layout;
17003 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
17004 return Success(Layout.size().getQuantity(), E);
17005 }
17006
17007 case Builtin::BI__builtin_is_aligned: {
17008 APValue Src;
17009 APSInt Alignment;
17010 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
17011 return false;
17012 if (Src.isLValue()) {
17013 // If we evaluated a pointer, check the minimum known alignment.
17014 LValue Ptr;
17015 Ptr.setFrom(Info.Ctx, Src);
17016 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
17017 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
17018 // We can return true if the known alignment at the computed offset is
17019 // greater than the requested alignment.
17020 assert(PtrAlign.isPowerOfTwo());
17021 assert(Alignment.isPowerOf2());
17022 if (PtrAlign.getQuantity() >= Alignment)
17023 return Success(1, E);
17024 // If the alignment is not known to be sufficient, some cases could still
17025 // be aligned at run time. However, if the requested alignment is less or
17026 // equal to the base alignment and the offset is not aligned, we know that
17027 // the run-time value can never be aligned.
17028 if (BaseAlignment.getQuantity() >= Alignment &&
17029 PtrAlign.getQuantity() < Alignment)
17030 return Success(0, E);
17031 // Otherwise we can't infer whether the value is sufficiently aligned.
17032 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
17033 // in cases where we can't fully evaluate the pointer.
17034 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
17035 << Alignment;
17036 return false;
17037 }
17038 assert(Src.isInt());
17039 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
17040 }
17041 case Builtin::BI__builtin_align_up: {
17042 APValue Src;
17043 APSInt Alignment;
17044 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
17045 return false;
17046 if (!Src.isInt())
17047 return Error(E);
17048 APSInt AlignedVal =
17049 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
17050 Src.getInt().isUnsigned());
17051 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
17052 return Success(AlignedVal, E);
17053 }
17054 case Builtin::BI__builtin_align_down: {
17055 APValue Src;
17056 APSInt Alignment;
17057 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
17058 return false;
17059 if (!Src.isInt())
17060 return Error(E);
17061 APSInt AlignedVal =
17062 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
17063 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
17064 return Success(AlignedVal, E);
17065 }
17066
17067 case Builtin::BI__builtin_bitreverseg:
17068 case Builtin::BI__builtin_bitreverse8:
17069 case Builtin::BI__builtin_bitreverse16:
17070 case Builtin::BI__builtin_bitreverse32:
17071 case Builtin::BI__builtin_bitreverse64:
17072 case Builtin::BI__builtin_elementwise_bitreverse: {
17073 APSInt Val;
17074 if (!EvaluateInteger(E->getArg(0), Val, Info))
17075 return false;
17076
17077 return Success(Val.reverseBits(), E);
17078 }
17079 case Builtin::BI__builtin_bswapg:
17080 case Builtin::BI__builtin_bswap16:
17081 case Builtin::BI__builtin_bswap32:
17082 case Builtin::BI__builtin_bswap64:
17083 case Builtin::BIstdc_memreverse8u8:
17084 case Builtin::BIstdc_memreverse8u16:
17085 case Builtin::BIstdc_memreverse8u32:
17086 case Builtin::BIstdc_memreverse8u64: {
17087 APSInt Val;
17088 if (!EvaluateInteger(E->getArg(0), Val, Info))
17089 return false;
17090 if (Val.getBitWidth() == 8 || Val.getBitWidth() == 1)
17091 return Success(Val, E);
17092
17093 return Success(Val.byteSwap(), E);
17094 }
17095
17096 case Builtin::BI__builtin_classify_type:
17097 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
17098
17099 case Builtin::BI__builtin_clrsb:
17100 case Builtin::BI__builtin_clrsbl:
17101 case Builtin::BI__builtin_clrsbll: {
17102 APSInt Val;
17103 if (!EvaluateInteger(E->getArg(0), Val, Info))
17104 return false;
17105
17106 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
17107 }
17108
17109 case Builtin::BI__builtin_clz:
17110 case Builtin::BI__builtin_clzl:
17111 case Builtin::BI__builtin_clzll:
17112 case Builtin::BI__builtin_clzs:
17113 case Builtin::BI__builtin_clzg:
17114 case Builtin::BI__builtin_elementwise_clzg:
17115 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
17116 case Builtin::BI__lzcnt:
17117 case Builtin::BI__lzcnt64: {
17118 APSInt Val;
17119 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
17120 APValue Vec;
17121 if (!EvaluateVector(E->getArg(0), Vec, Info))
17122 return false;
17123 Val = ConvertBoolVectorToInt(Vec);
17124 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
17125 return false;
17126 }
17127
17128 std::optional<APSInt> Fallback;
17129 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
17130 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
17131 E->getNumArgs() > 1) {
17132 APSInt FallbackTemp;
17133 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
17134 return false;
17135 Fallback = FallbackTemp;
17136 }
17137
17138 if (!Val) {
17139 if (Fallback)
17140 return Success(*Fallback, E);
17141
17142 // When the argument is 0, the result of GCC builtins is undefined,
17143 // whereas for Microsoft intrinsics, the result is the bit-width of the
17144 // argument.
17145 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
17146 BuiltinOp != Builtin::BI__lzcnt &&
17147 BuiltinOp != Builtin::BI__lzcnt64;
17148
17149 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
17150 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
17151 << /*IsTrailing=*/false;
17152 }
17153
17154 if (ZeroIsUndefined)
17155 return Error(E);
17156 }
17157
17158 return Success(Val.countl_zero(), E);
17159 }
17160
17161 case Builtin::BI__builtin_constant_p: {
17162 const Expr *Arg = E->getArg(0);
17163 if (EvaluateBuiltinConstantP(Info, Arg))
17164 return Success(true, E);
17165 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
17166 // Outside a constant context, eagerly evaluate to false in the presence
17167 // of side-effects in order to avoid -Wunsequenced false-positives in
17168 // a branch on __builtin_constant_p(expr).
17169 return Success(false, E);
17170 }
17171 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
17172 return false;
17173 }
17174
17175 case Builtin::BI__noop:
17176 // __noop always evaluates successfully and returns 0.
17177 return Success(0, E);
17178
17179 case Builtin::BI__builtin_is_constant_evaluated: {
17180 const auto *Callee = Info.CurrentCall->getCallee();
17181 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
17182 (Info.CallStackDepth == 1 ||
17183 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
17184 Callee->getIdentifier() &&
17185 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
17186 // FIXME: Find a better way to avoid duplicated diagnostics.
17187 if (Info.EvalStatus.Diag)
17188 Info.report((Info.CallStackDepth == 1)
17189 ? E->getExprLoc()
17190 : Info.CurrentCall->getCallRange().getBegin(),
17191 diag::warn_is_constant_evaluated_always_true_constexpr)
17192 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
17193 : "std::is_constant_evaluated");
17194 }
17195
17196 return Success(Info.InConstantContext, E);
17197 }
17198
17199 case Builtin::BI__builtin_is_within_lifetime:
17200 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
17201 return Success(*result, E);
17202 return false;
17203
17204 case Builtin::BI__builtin_ctz:
17205 case Builtin::BI__builtin_ctzl:
17206 case Builtin::BI__builtin_ctzll:
17207 case Builtin::BI__builtin_ctzs:
17208 case Builtin::BI__builtin_ctzg:
17209 case Builtin::BI__builtin_elementwise_ctzg: {
17210 APSInt Val;
17211 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
17212 APValue Vec;
17213 if (!EvaluateVector(E->getArg(0), Vec, Info))
17214 return false;
17215 Val = ConvertBoolVectorToInt(Vec);
17216 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
17217 return false;
17218 }
17219
17220 std::optional<APSInt> Fallback;
17221 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
17222 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
17223 E->getNumArgs() > 1) {
17224 APSInt FallbackTemp;
17225 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
17226 return false;
17227 Fallback = FallbackTemp;
17228 }
17229
17230 if (!Val) {
17231 if (Fallback)
17232 return Success(*Fallback, E);
17233
17234 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
17235 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
17236 << /*IsTrailing=*/true;
17237 }
17238 return Error(E);
17239 }
17240
17241 return Success(Val.countr_zero(), E);
17242 }
17243
17244 case Builtin::BI__builtin_eh_return_data_regno: {
17245 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
17246 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
17247 return Success(Operand, E);
17248 }
17249
17250 case Builtin::BI__builtin_elementwise_abs: {
17251 APSInt Val;
17252 if (!EvaluateInteger(E->getArg(0), Val, Info))
17253 return false;
17254
17255 return Success(Val.abs(), E);
17256 }
17257
17258 case Builtin::BI__builtin_expect:
17259 case Builtin::BI__builtin_expect_with_probability:
17260 return Visit(E->getArg(0));
17261
17262 case Builtin::BI__builtin_ptrauth_string_discriminator: {
17263 const auto *Literal =
17265 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
17266 return Success(Result, E);
17267 }
17268
17269 case Builtin::BI__builtin_infer_alloc_token: {
17270 // If we fail to infer a type, this fails to be a constant expression; this
17271 // can be checked with __builtin_constant_p(...).
17272 QualType AllocType = infer_alloc::inferPossibleType(E, Info.Ctx, nullptr);
17273 if (AllocType.isNull())
17274 return Error(
17275 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
17276 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, Info.Ctx);
17277 if (!ATMD)
17278 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
17279 auto Mode =
17280 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
17281 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
17282 auto MaxTokensOpt = Info.getLangOpts().AllocTokenMax;
17283 uint64_t MaxTokens =
17284 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
17285 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
17286 if (!MaybeToken)
17287 return Error(E, diag::note_constexpr_infer_alloc_token_stateful_mode);
17288 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
17289 }
17290
17291 case Builtin::BI__builtin_ffs:
17292 case Builtin::BI__builtin_ffsl:
17293 case Builtin::BI__builtin_ffsll: {
17294 APSInt Val;
17295 if (!EvaluateInteger(E->getArg(0), Val, Info))
17296 return false;
17297
17298 unsigned N = Val.countr_zero();
17299 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
17300 }
17301
17302 case Builtin::BI__builtin_fpclassify: {
17303 APFloat Val(0.0);
17304 if (!EvaluateFloat(E->getArg(5), Val, Info))
17305 return false;
17306 unsigned Arg;
17307 switch (Val.getCategory()) {
17308 case APFloat::fcNaN: Arg = 0; break;
17309 case APFloat::fcInfinity: Arg = 1; break;
17310 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
17311 case APFloat::fcZero: Arg = 4; break;
17312 }
17313 return Visit(E->getArg(Arg));
17314 }
17315
17316 case Builtin::BI__builtin_isinf_sign: {
17317 APFloat Val(0.0);
17318 return EvaluateFloat(E->getArg(0), Val, Info) &&
17319 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
17320 }
17321
17322 case Builtin::BI__builtin_isinf: {
17323 APFloat Val(0.0);
17324 return EvaluateFloat(E->getArg(0), Val, Info) &&
17325 Success(Val.isInfinity() ? 1 : 0, E);
17326 }
17327
17328 case Builtin::BI__builtin_isfinite: {
17329 APFloat Val(0.0);
17330 return EvaluateFloat(E->getArg(0), Val, Info) &&
17331 Success(Val.isFinite() ? 1 : 0, E);
17332 }
17333
17334 case Builtin::BI__builtin_isnan: {
17335 APFloat Val(0.0);
17336 return EvaluateFloat(E->getArg(0), Val, Info) &&
17337 Success(Val.isNaN() ? 1 : 0, E);
17338 }
17339
17340 case Builtin::BI__builtin_isnormal: {
17341 APFloat Val(0.0);
17342 return EvaluateFloat(E->getArg(0), Val, Info) &&
17343 Success(Val.isNormal() ? 1 : 0, E);
17344 }
17345
17346 case Builtin::BI__builtin_issubnormal: {
17347 APFloat Val(0.0);
17348 return EvaluateFloat(E->getArg(0), Val, Info) &&
17349 Success(Val.isDenormal() ? 1 : 0, E);
17350 }
17351
17352 case Builtin::BI__builtin_iszero: {
17353 APFloat Val(0.0);
17354 return EvaluateFloat(E->getArg(0), Val, Info) &&
17355 Success(Val.isZero() ? 1 : 0, E);
17356 }
17357
17358 case Builtin::BI__builtin_signbit:
17359 case Builtin::BI__builtin_signbitf:
17360 case Builtin::BI__builtin_signbitl: {
17361 APFloat Val(0.0);
17362 return EvaluateFloat(E->getArg(0), Val, Info) &&
17363 Success(Val.isNegative() ? 1 : 0, E);
17364 }
17365
17366 case Builtin::BI__builtin_isgreater:
17367 case Builtin::BI__builtin_isgreaterequal:
17368 case Builtin::BI__builtin_isless:
17369 case Builtin::BI__builtin_islessequal:
17370 case Builtin::BI__builtin_islessgreater:
17371 case Builtin::BI__builtin_isunordered: {
17372 APFloat LHS(0.0);
17373 APFloat RHS(0.0);
17374 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
17375 !EvaluateFloat(E->getArg(1), RHS, Info))
17376 return false;
17377
17378 return Success(
17379 [&] {
17380 switch (BuiltinOp) {
17381 case Builtin::BI__builtin_isgreater:
17382 return LHS > RHS;
17383 case Builtin::BI__builtin_isgreaterequal:
17384 return LHS >= RHS;
17385 case Builtin::BI__builtin_isless:
17386 return LHS < RHS;
17387 case Builtin::BI__builtin_islessequal:
17388 return LHS <= RHS;
17389 case Builtin::BI__builtin_islessgreater: {
17390 APFloat::cmpResult cmp = LHS.compare(RHS);
17391 return cmp == APFloat::cmpResult::cmpLessThan ||
17392 cmp == APFloat::cmpResult::cmpGreaterThan;
17393 }
17394 case Builtin::BI__builtin_isunordered:
17395 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
17396 default:
17397 llvm_unreachable("Unexpected builtin ID: Should be a floating "
17398 "point comparison function");
17399 }
17400 }()
17401 ? 1
17402 : 0,
17403 E);
17404 }
17405
17406 case Builtin::BI__builtin_issignaling: {
17407 APFloat Val(0.0);
17408 return EvaluateFloat(E->getArg(0), Val, Info) &&
17409 Success(Val.isSignaling() ? 1 : 0, E);
17410 }
17411
17412 case Builtin::BI__builtin_isfpclass: {
17413 APSInt MaskVal;
17414 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
17415 return false;
17416 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
17417 APFloat Val(0.0);
17418 return EvaluateFloat(E->getArg(0), Val, Info) &&
17419 Success((Val.classify() & Test) ? 1 : 0, E);
17420 }
17421
17422 case Builtin::BI__builtin_parity:
17423 case Builtin::BI__builtin_parityl:
17424 case Builtin::BI__builtin_parityll: {
17425 APSInt Val;
17426 if (!EvaluateInteger(E->getArg(0), Val, Info))
17427 return false;
17428
17429 return Success(Val.popcount() % 2, E);
17430 }
17431
17432 case Builtin::BI__builtin_abs:
17433 case Builtin::BI__builtin_labs:
17434 case Builtin::BI__builtin_llabs: {
17435 APSInt Val;
17436 if (!EvaluateInteger(E->getArg(0), Val, Info))
17437 return false;
17438 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
17439 /*IsUnsigned=*/false))
17440 return false;
17441 if (Val.isNegative())
17442 Val.negate();
17443 return Success(Val, E);
17444 }
17445
17446 case Builtin::BI__builtin_popcount:
17447 case Builtin::BI__builtin_popcountl:
17448 case Builtin::BI__builtin_popcountll:
17449 case Builtin::BI__builtin_popcountg:
17450 case Builtin::BI__builtin_elementwise_popcount:
17451 case Builtin::BI__popcnt16: // Microsoft variants of popcount
17452 case Builtin::BI__popcnt:
17453 case Builtin::BI__popcnt64: {
17454 APSInt Val;
17455 if (E->getArg(0)->getType()->isExtVectorBoolType()) {
17456 APValue Vec;
17457 if (!EvaluateVector(E->getArg(0), Vec, Info))
17458 return false;
17459 Val = ConvertBoolVectorToInt(Vec);
17460 } else if (!EvaluateInteger(E->getArg(0), Val, Info)) {
17461 return false;
17462 }
17463
17464 return Success(Val.popcount(), E);
17465 }
17466
17467 case Builtin::BI__builtin_rotateleft8:
17468 case Builtin::BI__builtin_rotateleft16:
17469 case Builtin::BI__builtin_rotateleft32:
17470 case Builtin::BI__builtin_rotateleft64:
17471 case Builtin::BI__builtin_rotateright8:
17472 case Builtin::BI__builtin_rotateright16:
17473 case Builtin::BI__builtin_rotateright32:
17474 case Builtin::BI__builtin_rotateright64:
17475 case Builtin::BI__builtin_stdc_rotate_left:
17476 case Builtin::BI__builtin_stdc_rotate_right:
17477 case Builtin::BIstdc_rotate_left_uc:
17478 case Builtin::BIstdc_rotate_left_us:
17479 case Builtin::BIstdc_rotate_left_ui:
17480 case Builtin::BIstdc_rotate_left_ul:
17481 case Builtin::BIstdc_rotate_left_ull:
17482 case Builtin::BIstdc_rotate_right_uc:
17483 case Builtin::BIstdc_rotate_right_us:
17484 case Builtin::BIstdc_rotate_right_ui:
17485 case Builtin::BIstdc_rotate_right_ul:
17486 case Builtin::BIstdc_rotate_right_ull:
17487 case Builtin::BI_rotl8: // Microsoft variants of rotate left
17488 case Builtin::BI_rotl16:
17489 case Builtin::BI_rotl:
17490 case Builtin::BI_lrotl:
17491 case Builtin::BI_rotl64:
17492 case Builtin::BI_rotr8: // Microsoft variants of rotate right
17493 case Builtin::BI_rotr16:
17494 case Builtin::BI_rotr:
17495 case Builtin::BI_lrotr:
17496 case Builtin::BI_rotr64: {
17497 APSInt Value, Amount;
17498 if (!EvaluateInteger(E->getArg(0), Value, Info) ||
17499 !EvaluateInteger(E->getArg(1), Amount, Info))
17500 return false;
17501
17502 Amount = NormalizeRotateAmount(Value, Amount);
17503
17504 switch (BuiltinOp) {
17505 case Builtin::BI__builtin_rotateright8:
17506 case Builtin::BI__builtin_rotateright16:
17507 case Builtin::BI__builtin_rotateright32:
17508 case Builtin::BI__builtin_rotateright64:
17509 case Builtin::BI__builtin_stdc_rotate_right:
17510 case Builtin::BIstdc_rotate_right_uc:
17511 case Builtin::BIstdc_rotate_right_us:
17512 case Builtin::BIstdc_rotate_right_ui:
17513 case Builtin::BIstdc_rotate_right_ul:
17514 case Builtin::BIstdc_rotate_right_ull:
17515 case Builtin::BI_rotr8:
17516 case Builtin::BI_rotr16:
17517 case Builtin::BI_rotr:
17518 case Builtin::BI_lrotr:
17519 case Builtin::BI_rotr64:
17520 return Success(
17521 APSInt(Value.rotr(Amount.getZExtValue()), Value.isUnsigned()), E);
17522 default:
17523 return Success(
17524 APSInt(Value.rotl(Amount.getZExtValue()), Value.isUnsigned()), E);
17525 }
17526 }
17527
17528 case Builtin::BIstdc_leading_zeros_uc:
17529 case Builtin::BIstdc_leading_zeros_us:
17530 case Builtin::BIstdc_leading_zeros_ui:
17531 case Builtin::BIstdc_leading_zeros_ul:
17532 case Builtin::BIstdc_leading_zeros_ull:
17533 case Builtin::BIstdc_leading_ones_uc:
17534 case Builtin::BIstdc_leading_ones_us:
17535 case Builtin::BIstdc_leading_ones_ui:
17536 case Builtin::BIstdc_leading_ones_ul:
17537 case Builtin::BIstdc_leading_ones_ull:
17538 case Builtin::BIstdc_trailing_zeros_uc:
17539 case Builtin::BIstdc_trailing_zeros_us:
17540 case Builtin::BIstdc_trailing_zeros_ui:
17541 case Builtin::BIstdc_trailing_zeros_ul:
17542 case Builtin::BIstdc_trailing_zeros_ull:
17543 case Builtin::BIstdc_trailing_ones_uc:
17544 case Builtin::BIstdc_trailing_ones_us:
17545 case Builtin::BIstdc_trailing_ones_ui:
17546 case Builtin::BIstdc_trailing_ones_ul:
17547 case Builtin::BIstdc_trailing_ones_ull:
17548 case Builtin::BIstdc_first_leading_zero_uc:
17549 case Builtin::BIstdc_first_leading_zero_us:
17550 case Builtin::BIstdc_first_leading_zero_ui:
17551 case Builtin::BIstdc_first_leading_zero_ul:
17552 case Builtin::BIstdc_first_leading_zero_ull:
17553 case Builtin::BIstdc_first_leading_one_uc:
17554 case Builtin::BIstdc_first_leading_one_us:
17555 case Builtin::BIstdc_first_leading_one_ui:
17556 case Builtin::BIstdc_first_leading_one_ul:
17557 case Builtin::BIstdc_first_leading_one_ull:
17558 case Builtin::BIstdc_first_trailing_zero_uc:
17559 case Builtin::BIstdc_first_trailing_zero_us:
17560 case Builtin::BIstdc_first_trailing_zero_ui:
17561 case Builtin::BIstdc_first_trailing_zero_ul:
17562 case Builtin::BIstdc_first_trailing_zero_ull:
17563 case Builtin::BIstdc_first_trailing_one_uc:
17564 case Builtin::BIstdc_first_trailing_one_us:
17565 case Builtin::BIstdc_first_trailing_one_ui:
17566 case Builtin::BIstdc_first_trailing_one_ul:
17567 case Builtin::BIstdc_first_trailing_one_ull:
17568 case Builtin::BIstdc_count_zeros_uc:
17569 case Builtin::BIstdc_count_zeros_us:
17570 case Builtin::BIstdc_count_zeros_ui:
17571 case Builtin::BIstdc_count_zeros_ul:
17572 case Builtin::BIstdc_count_zeros_ull:
17573 case Builtin::BIstdc_count_ones_uc:
17574 case Builtin::BIstdc_count_ones_us:
17575 case Builtin::BIstdc_count_ones_ui:
17576 case Builtin::BIstdc_count_ones_ul:
17577 case Builtin::BIstdc_count_ones_ull:
17578 case Builtin::BIstdc_has_single_bit_uc:
17579 case Builtin::BIstdc_has_single_bit_us:
17580 case Builtin::BIstdc_has_single_bit_ui:
17581 case Builtin::BIstdc_has_single_bit_ul:
17582 case Builtin::BIstdc_has_single_bit_ull:
17583 case Builtin::BIstdc_bit_width_uc:
17584 case Builtin::BIstdc_bit_width_us:
17585 case Builtin::BIstdc_bit_width_ui:
17586 case Builtin::BIstdc_bit_width_ul:
17587 case Builtin::BIstdc_bit_width_ull:
17588 case Builtin::BIstdc_bit_floor_uc:
17589 case Builtin::BIstdc_bit_floor_us:
17590 case Builtin::BIstdc_bit_floor_ui:
17591 case Builtin::BIstdc_bit_floor_ul:
17592 case Builtin::BIstdc_bit_floor_ull:
17593 case Builtin::BIstdc_bit_ceil_uc:
17594 case Builtin::BIstdc_bit_ceil_us:
17595 case Builtin::BIstdc_bit_ceil_ui:
17596 case Builtin::BIstdc_bit_ceil_ul:
17597 case Builtin::BIstdc_bit_ceil_ull:
17598 case Builtin::BI__builtin_stdc_leading_zeros:
17599 case Builtin::BI__builtin_stdc_leading_ones:
17600 case Builtin::BI__builtin_stdc_trailing_zeros:
17601 case Builtin::BI__builtin_stdc_trailing_ones:
17602 case Builtin::BI__builtin_stdc_first_leading_zero:
17603 case Builtin::BI__builtin_stdc_first_leading_one:
17604 case Builtin::BI__builtin_stdc_first_trailing_zero:
17605 case Builtin::BI__builtin_stdc_first_trailing_one:
17606 case Builtin::BI__builtin_stdc_count_zeros:
17607 case Builtin::BI__builtin_stdc_count_ones:
17608 case Builtin::BI__builtin_stdc_has_single_bit:
17609 case Builtin::BI__builtin_stdc_bit_width:
17610 case Builtin::BI__builtin_stdc_bit_floor:
17611 case Builtin::BI__builtin_stdc_bit_ceil: {
17612 APSInt Val;
17613 if (!EvaluateInteger(E->getArg(0), Val, Info))
17614 return false;
17615
17616 unsigned BitWidth = Val.getBitWidth();
17617 const unsigned ResBitWidth = Info.Ctx.getIntWidth(E->getType());
17618
17619 switch (BuiltinOp) {
17620 case Builtin::BIstdc_leading_zeros_uc:
17621 case Builtin::BIstdc_leading_zeros_us:
17622 case Builtin::BIstdc_leading_zeros_ui:
17623 case Builtin::BIstdc_leading_zeros_ul:
17624 case Builtin::BIstdc_leading_zeros_ull:
17625 case Builtin::BI__builtin_stdc_leading_zeros:
17626 return Success(APInt(ResBitWidth, Val.countl_zero()), E);
17627 case Builtin::BIstdc_leading_ones_uc:
17628 case Builtin::BIstdc_leading_ones_us:
17629 case Builtin::BIstdc_leading_ones_ui:
17630 case Builtin::BIstdc_leading_ones_ul:
17631 case Builtin::BIstdc_leading_ones_ull:
17632 case Builtin::BI__builtin_stdc_leading_ones:
17633 return Success(APInt(ResBitWidth, Val.countl_one()), E);
17634 case Builtin::BIstdc_trailing_zeros_uc:
17635 case Builtin::BIstdc_trailing_zeros_us:
17636 case Builtin::BIstdc_trailing_zeros_ui:
17637 case Builtin::BIstdc_trailing_zeros_ul:
17638 case Builtin::BIstdc_trailing_zeros_ull:
17639 case Builtin::BI__builtin_stdc_trailing_zeros:
17640 return Success(APInt(ResBitWidth, Val.countr_zero()), E);
17641 case Builtin::BIstdc_trailing_ones_uc:
17642 case Builtin::BIstdc_trailing_ones_us:
17643 case Builtin::BIstdc_trailing_ones_ui:
17644 case Builtin::BIstdc_trailing_ones_ul:
17645 case Builtin::BIstdc_trailing_ones_ull:
17646 case Builtin::BI__builtin_stdc_trailing_ones:
17647 return Success(APInt(ResBitWidth, Val.countr_one()), E);
17648 case Builtin::BIstdc_first_leading_zero_uc:
17649 case Builtin::BIstdc_first_leading_zero_us:
17650 case Builtin::BIstdc_first_leading_zero_ui:
17651 case Builtin::BIstdc_first_leading_zero_ul:
17652 case Builtin::BIstdc_first_leading_zero_ull:
17653 case Builtin::BI__builtin_stdc_first_leading_zero:
17654 return Success(
17655 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countl_one() + 1), E);
17656 case Builtin::BIstdc_first_leading_one_uc:
17657 case Builtin::BIstdc_first_leading_one_us:
17658 case Builtin::BIstdc_first_leading_one_ui:
17659 case Builtin::BIstdc_first_leading_one_ul:
17660 case Builtin::BIstdc_first_leading_one_ull:
17661 case Builtin::BI__builtin_stdc_first_leading_one:
17662 return Success(
17663 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countl_zero() + 1), E);
17664 case Builtin::BIstdc_first_trailing_zero_uc:
17665 case Builtin::BIstdc_first_trailing_zero_us:
17666 case Builtin::BIstdc_first_trailing_zero_ui:
17667 case Builtin::BIstdc_first_trailing_zero_ul:
17668 case Builtin::BIstdc_first_trailing_zero_ull:
17669 case Builtin::BI__builtin_stdc_first_trailing_zero:
17670 return Success(
17671 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countr_one() + 1), E);
17672 case Builtin::BIstdc_first_trailing_one_uc:
17673 case Builtin::BIstdc_first_trailing_one_us:
17674 case Builtin::BIstdc_first_trailing_one_ui:
17675 case Builtin::BIstdc_first_trailing_one_ul:
17676 case Builtin::BIstdc_first_trailing_one_ull:
17677 case Builtin::BI__builtin_stdc_first_trailing_one:
17678 return Success(
17679 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countr_zero() + 1), E);
17680 case Builtin::BIstdc_count_zeros_uc:
17681 case Builtin::BIstdc_count_zeros_us:
17682 case Builtin::BIstdc_count_zeros_ui:
17683 case Builtin::BIstdc_count_zeros_ul:
17684 case Builtin::BIstdc_count_zeros_ull:
17685 case Builtin::BI__builtin_stdc_count_zeros: {
17686 APInt Cnt(ResBitWidth, BitWidth - Val.popcount());
17687 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
17688 }
17689 case Builtin::BIstdc_count_ones_uc:
17690 case Builtin::BIstdc_count_ones_us:
17691 case Builtin::BIstdc_count_ones_ui:
17692 case Builtin::BIstdc_count_ones_ul:
17693 case Builtin::BIstdc_count_ones_ull:
17694 case Builtin::BI__builtin_stdc_count_ones: {
17695 APInt Cnt(ResBitWidth, Val.popcount());
17696 return Success(APSInt(Cnt, /*IsUnsigned*/ true), E);
17697 }
17698 case Builtin::BIstdc_has_single_bit_uc:
17699 case Builtin::BIstdc_has_single_bit_us:
17700 case Builtin::BIstdc_has_single_bit_ui:
17701 case Builtin::BIstdc_has_single_bit_ul:
17702 case Builtin::BIstdc_has_single_bit_ull:
17703 case Builtin::BI__builtin_stdc_has_single_bit: {
17704 APInt Res(ResBitWidth, Val.popcount() == 1 ? 1 : 0);
17705 return Success(APSInt(Res, /*IsUnsigned*/ true), E);
17706 }
17707 case Builtin::BIstdc_bit_width_uc:
17708 case Builtin::BIstdc_bit_width_us:
17709 case Builtin::BIstdc_bit_width_ui:
17710 case Builtin::BIstdc_bit_width_ul:
17711 case Builtin::BIstdc_bit_width_ull:
17712 case Builtin::BI__builtin_stdc_bit_width:
17713 return Success(APInt(ResBitWidth, BitWidth - Val.countl_zero()), E);
17714 case Builtin::BIstdc_bit_floor_uc:
17715 case Builtin::BIstdc_bit_floor_us:
17716 case Builtin::BIstdc_bit_floor_ui:
17717 case Builtin::BIstdc_bit_floor_ul:
17718 case Builtin::BIstdc_bit_floor_ull:
17719 case Builtin::BI__builtin_stdc_bit_floor: {
17720 if (Val.isZero())
17721 return Success(APInt(BitWidth, 0), E);
17722 unsigned Exp = BitWidth - Val.countl_zero() - 1;
17723 return Success(
17724 APSInt(APInt::getOneBitSet(BitWidth, Exp), /*IsUnsigned*/ true), E);
17725 }
17726 case Builtin::BIstdc_bit_ceil_uc:
17727 case Builtin::BIstdc_bit_ceil_us:
17728 case Builtin::BIstdc_bit_ceil_ui:
17729 case Builtin::BIstdc_bit_ceil_ul:
17730 case Builtin::BIstdc_bit_ceil_ull:
17731 case Builtin::BI__builtin_stdc_bit_ceil: {
17732 if (Val.ule(1))
17733 return Success(APSInt(APInt(BitWidth, 1), /*IsUnsigned*/ true), E);
17734 APInt ValMinusOne = Val - 1;
17735 unsigned LZ = ValMinusOne.countl_zero();
17736 if (LZ == 0)
17737 return Success(APSInt(APInt(BitWidth, 0), /*IsUnsigned*/ true),
17738 E); // overflows; wrap to 0
17739 APInt Result = APInt::getOneBitSet(BitWidth, BitWidth - LZ);
17740 return Success(APSInt(Result, /*IsUnsigned*/ true), E);
17741 }
17742 default:
17743 llvm_unreachable("Unknown stdc builtin");
17744 }
17745 }
17746
17747 case Builtin::BI__builtin_elementwise_add_sat: {
17748 APSInt LHS, RHS;
17749 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17750 !EvaluateInteger(E->getArg(1), RHS, Info))
17751 return false;
17752
17753 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
17754 return Success(APSInt(Result, !LHS.isSigned()), E);
17755 }
17756 case Builtin::BI__builtin_elementwise_sub_sat: {
17757 APSInt LHS, RHS;
17758 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17759 !EvaluateInteger(E->getArg(1), RHS, Info))
17760 return false;
17761
17762 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
17763 return Success(APSInt(Result, !LHS.isSigned()), E);
17764 }
17765 case Builtin::BI__builtin_elementwise_max: {
17766 APSInt LHS, RHS;
17767 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17768 !EvaluateInteger(E->getArg(1), RHS, Info))
17769 return false;
17770
17771 APInt Result = std::max(LHS, RHS);
17772 return Success(APSInt(Result, !LHS.isSigned()), E);
17773 }
17774 case Builtin::BI__builtin_elementwise_min: {
17775 APSInt LHS, RHS;
17776 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17777 !EvaluateInteger(E->getArg(1), RHS, Info))
17778 return false;
17779
17780 APInt Result = std::min(LHS, RHS);
17781 return Success(APSInt(Result, !LHS.isSigned()), E);
17782 }
17783 case Builtin::BI__builtin_elementwise_clmul: {
17784 APSInt LHS, RHS;
17785 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
17786 !EvaluateInteger(E->getArg(1), RHS, Info))
17787 return false;
17788
17789 APInt Result = llvm::APIntOps::clmul(LHS, RHS);
17790 return Success(APSInt(Result, LHS.isUnsigned()), E);
17791 }
17792 case Builtin::BI__builtin_elementwise_fshl:
17793 case Builtin::BI__builtin_elementwise_fshr: {
17794 APSInt Hi, Lo, Shift;
17795 if (!EvaluateInteger(E->getArg(0), Hi, Info) ||
17796 !EvaluateInteger(E->getArg(1), Lo, Info) ||
17797 !EvaluateInteger(E->getArg(2), Shift, Info))
17798 return false;
17799
17800 switch (BuiltinOp) {
17801 case Builtin::BI__builtin_elementwise_fshl: {
17802 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
17803 return Success(Result, E);
17804 }
17805 case Builtin::BI__builtin_elementwise_fshr: {
17806 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
17807 return Success(Result, E);
17808 }
17809 }
17810 llvm_unreachable("Fully covered switch above");
17811 }
17812 case Builtin::BIstrlen:
17813 case Builtin::BIwcslen:
17814 // A call to strlen is not a constant expression.
17815 if (Info.getLangOpts().CPlusPlus11)
17816 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17817 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17818 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17819 else
17820 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17821 [[fallthrough]];
17822 case Builtin::BI__builtin_strlen:
17823 case Builtin::BI__builtin_wcslen: {
17824 // As an extension, we support __builtin_strlen() as a constant expression,
17825 // and support folding strlen() to a constant.
17826 if (std::optional<uint64_t> StrLen =
17827 EvaluateBuiltinStrLen(E->getArg(0), Info))
17828 return Success(*StrLen, E);
17829 return false;
17830 }
17831
17832 case Builtin::BIstrcmp:
17833 case Builtin::BIwcscmp:
17834 case Builtin::BIstrncmp:
17835 case Builtin::BIwcsncmp:
17836 case Builtin::BImemcmp:
17837 case Builtin::BIbcmp:
17838 case Builtin::BIwmemcmp:
17839 // A call to strlen is not a constant expression.
17840 if (Info.getLangOpts().CPlusPlus11)
17841 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
17842 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
17843 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
17844 else
17845 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
17846 [[fallthrough]];
17847 case Builtin::BI__builtin_strcmp:
17848 case Builtin::BI__builtin_wcscmp:
17849 case Builtin::BI__builtin_strncmp:
17850 case Builtin::BI__builtin_wcsncmp:
17851 case Builtin::BI__builtin_memcmp:
17852 case Builtin::BI__builtin_bcmp:
17853 case Builtin::BI__builtin_wmemcmp: {
17854 LValue String1, String2;
17855 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
17856 !EvaluatePointer(E->getArg(1), String2, Info))
17857 return false;
17858
17859 uint64_t MaxLength = uint64_t(-1);
17860 if (BuiltinOp != Builtin::BIstrcmp &&
17861 BuiltinOp != Builtin::BIwcscmp &&
17862 BuiltinOp != Builtin::BI__builtin_strcmp &&
17863 BuiltinOp != Builtin::BI__builtin_wcscmp) {
17864 APSInt N;
17865 if (!EvaluateInteger(E->getArg(2), N, Info))
17866 return false;
17867 MaxLength = N.getZExtValue();
17868 }
17869
17870 // Empty substrings compare equal by definition.
17871 if (MaxLength == 0u)
17872 return Success(0, E);
17873
17874 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17875 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
17876 String1.Designator.Invalid || String2.Designator.Invalid)
17877 return false;
17878
17879 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
17880 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
17881
17882 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
17883 BuiltinOp == Builtin::BIbcmp ||
17884 BuiltinOp == Builtin::BI__builtin_memcmp ||
17885 BuiltinOp == Builtin::BI__builtin_bcmp;
17886
17887 assert(IsRawByte ||
17888 (Info.Ctx.hasSameUnqualifiedType(
17889 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
17890 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
17891
17892 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
17893 // 'char8_t', but no other types.
17894 if (IsRawByte &&
17895 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
17896 // FIXME: Consider using our bit_cast implementation to support this.
17897 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
17898 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
17899 << CharTy2;
17900 return false;
17901 }
17902
17903 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
17904 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
17905 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
17906 Char1.isInt() && Char2.isInt();
17907 };
17908 const auto &AdvanceElems = [&] {
17909 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
17910 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
17911 };
17912
17913 bool StopAtNull =
17914 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
17915 BuiltinOp != Builtin::BIwmemcmp &&
17916 BuiltinOp != Builtin::BI__builtin_memcmp &&
17917 BuiltinOp != Builtin::BI__builtin_bcmp &&
17918 BuiltinOp != Builtin::BI__builtin_wmemcmp);
17919 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
17920 BuiltinOp == Builtin::BIwcsncmp ||
17921 BuiltinOp == Builtin::BIwmemcmp ||
17922 BuiltinOp == Builtin::BI__builtin_wcscmp ||
17923 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
17924 BuiltinOp == Builtin::BI__builtin_wmemcmp;
17925
17926 for (; MaxLength; --MaxLength) {
17927 APValue Char1, Char2;
17928 if (!ReadCurElems(Char1, Char2))
17929 return false;
17930 if (Char1.getInt().ne(Char2.getInt())) {
17931 if (IsWide) // wmemcmp compares with wchar_t signedness.
17932 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
17933 // memcmp always compares unsigned chars.
17934 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
17935 }
17936 if (StopAtNull && !Char1.getInt())
17937 return Success(0, E);
17938 assert(!(StopAtNull && !Char2.getInt()));
17939 if (!AdvanceElems())
17940 return false;
17941 }
17942 // We hit the strncmp / memcmp limit.
17943 return Success(0, E);
17944 }
17945
17946 case Builtin::BI__atomic_always_lock_free:
17947 case Builtin::BI__atomic_is_lock_free:
17948 case Builtin::BI__c11_atomic_is_lock_free: {
17949 APSInt SizeVal;
17950 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
17951 return false;
17952
17953 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
17954 // of two less than or equal to the maximum inline atomic width, we know it
17955 // is lock-free. If the size isn't a power of two, or greater than the
17956 // maximum alignment where we promote atomics, we know it is not lock-free
17957 // (at least not in the sense of atomic_is_lock_free). Otherwise,
17958 // the answer can only be determined at runtime; for example, 16-byte
17959 // atomics have lock-free implementations on some, but not all,
17960 // x86-64 processors.
17961
17962 // Check power-of-two.
17963 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
17964 if (Size.isPowerOfTwo()) {
17965 // Check against inlining width.
17966 unsigned InlineWidthBits =
17967 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
17968 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
17969 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
17970 Size == CharUnits::One())
17971 return Success(1, E);
17972
17973 // If the pointer argument can be evaluated to a compile-time constant
17974 // integer (or nullptr), check if that value is appropriately aligned.
17975 const Expr *PtrArg = E->getArg(1);
17976 Expr::EvalResult ExprResult;
17977 APSInt IntResult;
17978 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
17979 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
17980 Info.Ctx) &&
17981 IntResult.isAligned(Size.getAsAlign()))
17982 return Success(1, E);
17983
17984 // Otherwise, check if the type's alignment against Size.
17985 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
17986 // Drop the potential implicit-cast to 'const volatile void*', getting
17987 // the underlying type.
17988 if (ICE->getCastKind() == CK_BitCast)
17989 PtrArg = ICE->getSubExpr();
17990 }
17991
17992 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
17993 QualType PointeeType = PtrTy->getPointeeType();
17994 if (!PointeeType->isIncompleteType() &&
17995 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
17996 // OK, we will inline operations on this object.
17997 return Success(1, E);
17998 }
17999 }
18000 }
18001 }
18002
18003 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
18004 Success(0, E) : Error(E);
18005 }
18006 case Builtin::BI__builtin_addcb:
18007 case Builtin::BI__builtin_addcs:
18008 case Builtin::BI__builtin_addc:
18009 case Builtin::BI__builtin_addcl:
18010 case Builtin::BI__builtin_addcll:
18011 case Builtin::BI__builtin_subcb:
18012 case Builtin::BI__builtin_subcs:
18013 case Builtin::BI__builtin_subc:
18014 case Builtin::BI__builtin_subcl:
18015 case Builtin::BI__builtin_subcll: {
18016 LValue CarryOutLValue;
18017 APSInt LHS, RHS, CarryIn, CarryOut, Result;
18018 QualType ResultType = E->getArg(0)->getType();
18019 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
18020 !EvaluateInteger(E->getArg(1), RHS, Info) ||
18021 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
18022 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
18023 return false;
18024 // Copy the number of bits and sign.
18025 Result = LHS;
18026 CarryOut = LHS;
18027
18028 bool FirstOverflowed = false;
18029 bool SecondOverflowed = false;
18030 switch (BuiltinOp) {
18031 default:
18032 llvm_unreachable("Invalid value for BuiltinOp");
18033 case Builtin::BI__builtin_addcb:
18034 case Builtin::BI__builtin_addcs:
18035 case Builtin::BI__builtin_addc:
18036 case Builtin::BI__builtin_addcl:
18037 case Builtin::BI__builtin_addcll:
18038 Result =
18039 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
18040 break;
18041 case Builtin::BI__builtin_subcb:
18042 case Builtin::BI__builtin_subcs:
18043 case Builtin::BI__builtin_subc:
18044 case Builtin::BI__builtin_subcl:
18045 case Builtin::BI__builtin_subcll:
18046 Result =
18047 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
18048 break;
18049 }
18050
18051 // It is possible for both overflows to happen but CGBuiltin uses an OR so
18052 // this is consistent.
18053 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
18054 APValue APV{CarryOut};
18055 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
18056 return false;
18057 return Success(Result, E);
18058 }
18059 case Builtin::BI__builtin_add_overflow:
18060 case Builtin::BI__builtin_sub_overflow:
18061 case Builtin::BI__builtin_mul_overflow:
18062 case Builtin::BI__builtin_sadd_overflow:
18063 case Builtin::BI__builtin_uadd_overflow:
18064 case Builtin::BI__builtin_uaddl_overflow:
18065 case Builtin::BI__builtin_uaddll_overflow:
18066 case Builtin::BI__builtin_usub_overflow:
18067 case Builtin::BI__builtin_usubl_overflow:
18068 case Builtin::BI__builtin_usubll_overflow:
18069 case Builtin::BI__builtin_umul_overflow:
18070 case Builtin::BI__builtin_umull_overflow:
18071 case Builtin::BI__builtin_umulll_overflow:
18072 case Builtin::BI__builtin_saddl_overflow:
18073 case Builtin::BI__builtin_saddll_overflow:
18074 case Builtin::BI__builtin_ssub_overflow:
18075 case Builtin::BI__builtin_ssubl_overflow:
18076 case Builtin::BI__builtin_ssubll_overflow:
18077 case Builtin::BI__builtin_smul_overflow:
18078 case Builtin::BI__builtin_smull_overflow:
18079 case Builtin::BI__builtin_smulll_overflow: {
18080 LValue ResultLValue;
18081 APSInt LHS, RHS;
18082
18083 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
18084 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
18085 !EvaluateInteger(E->getArg(1), RHS, Info) ||
18086 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
18087 return false;
18088
18089 APSInt Result;
18090 bool DidOverflow = false;
18091
18092 // If the types don't have to match, enlarge all 3 to the largest of them.
18093 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
18094 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
18095 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
18096 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
18098 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
18100 uint64_t LHSSize = LHS.getBitWidth();
18101 uint64_t RHSSize = RHS.getBitWidth();
18102 uint64_t ResultSize = Info.Ctx.getIntWidth(ResultType);
18103 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
18104
18105 // Add an additional bit if the signedness isn't uniformly agreed to. We
18106 // could do this ONLY if there is a signed and an unsigned that both have
18107 // MaxBits, but the code to check that is pretty nasty. The issue will be
18108 // caught in the shrink-to-result later anyway.
18109 if (IsSigned && !AllSigned)
18110 ++MaxBits;
18111
18112 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
18113 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
18114 Result = APSInt(MaxBits, !IsSigned);
18115 }
18116
18117 // Find largest int.
18118 switch (BuiltinOp) {
18119 default:
18120 llvm_unreachable("Invalid value for BuiltinOp");
18121 case Builtin::BI__builtin_add_overflow:
18122 case Builtin::BI__builtin_sadd_overflow:
18123 case Builtin::BI__builtin_saddl_overflow:
18124 case Builtin::BI__builtin_saddll_overflow:
18125 case Builtin::BI__builtin_uadd_overflow:
18126 case Builtin::BI__builtin_uaddl_overflow:
18127 case Builtin::BI__builtin_uaddll_overflow:
18128 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
18129 : LHS.uadd_ov(RHS, DidOverflow);
18130 break;
18131 case Builtin::BI__builtin_sub_overflow:
18132 case Builtin::BI__builtin_ssub_overflow:
18133 case Builtin::BI__builtin_ssubl_overflow:
18134 case Builtin::BI__builtin_ssubll_overflow:
18135 case Builtin::BI__builtin_usub_overflow:
18136 case Builtin::BI__builtin_usubl_overflow:
18137 case Builtin::BI__builtin_usubll_overflow:
18138 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
18139 : LHS.usub_ov(RHS, DidOverflow);
18140 break;
18141 case Builtin::BI__builtin_mul_overflow:
18142 case Builtin::BI__builtin_smul_overflow:
18143 case Builtin::BI__builtin_smull_overflow:
18144 case Builtin::BI__builtin_smulll_overflow:
18145 case Builtin::BI__builtin_umul_overflow:
18146 case Builtin::BI__builtin_umull_overflow:
18147 case Builtin::BI__builtin_umulll_overflow:
18148 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
18149 : LHS.umul_ov(RHS, DidOverflow);
18150 break;
18151 }
18152
18153 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
18154 // since it will give us the behavior of a TruncOrSelf in the case where
18155 // its parameter <= its size. We previously set Result to be at least the
18156 // integer width of the result, so getIntWidth(ResultType) <=
18157 // Result.BitWidth will work exactly like TruncOrSelf.
18158 APSInt Temp = Result.extOrTrunc(Info.Ctx.getIntWidth(ResultType));
18159 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
18160
18161 // In the case where multiple sizes are allowed, truncate and see if
18162 // the values are the same.
18163 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
18164 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
18165 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
18166 if (!APSInt::isSameValue(Temp, Result))
18167 DidOverflow = true;
18168 }
18169 Result = Temp;
18170
18171 APValue APV{Result};
18172 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
18173 return false;
18174 return Success(DidOverflow, E);
18175 }
18176
18177 case Builtin::BI__builtin_reduce_add:
18178 case Builtin::BI__builtin_reduce_mul:
18179 case Builtin::BI__builtin_reduce_and:
18180 case Builtin::BI__builtin_reduce_or:
18181 case Builtin::BI__builtin_reduce_xor:
18182 case Builtin::BI__builtin_reduce_min:
18183 case Builtin::BI__builtin_reduce_max: {
18184 APValue Source;
18185 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
18186 return false;
18187
18188 unsigned SourceLen = Source.getVectorLength();
18189 APSInt Reduced = Source.getVectorElt(0).getInt();
18190 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
18191 switch (BuiltinOp) {
18192 default:
18193 return false;
18194 case Builtin::BI__builtin_reduce_add: {
18196 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
18197 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
18198 return false;
18199 break;
18200 }
18201 case Builtin::BI__builtin_reduce_mul: {
18203 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
18204 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
18205 return false;
18206 break;
18207 }
18208 case Builtin::BI__builtin_reduce_and: {
18209 Reduced &= Source.getVectorElt(EltNum).getInt();
18210 break;
18211 }
18212 case Builtin::BI__builtin_reduce_or: {
18213 Reduced |= Source.getVectorElt(EltNum).getInt();
18214 break;
18215 }
18216 case Builtin::BI__builtin_reduce_xor: {
18217 Reduced ^= Source.getVectorElt(EltNum).getInt();
18218 break;
18219 }
18220 case Builtin::BI__builtin_reduce_min: {
18221 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
18222 break;
18223 }
18224 case Builtin::BI__builtin_reduce_max: {
18225 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
18226 break;
18227 }
18228 }
18229 }
18230
18231 return Success(Reduced, E);
18232 }
18233
18234 case clang::X86::BI__builtin_ia32_addcarryx_u32:
18235 case clang::X86::BI__builtin_ia32_addcarryx_u64:
18236 case clang::X86::BI__builtin_ia32_subborrow_u32:
18237 case clang::X86::BI__builtin_ia32_subborrow_u64: {
18238 LValue ResultLValue;
18239 APSInt CarryIn, LHS, RHS;
18240 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
18241 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
18242 !EvaluateInteger(E->getArg(1), LHS, Info) ||
18243 !EvaluateInteger(E->getArg(2), RHS, Info) ||
18244 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
18245 return false;
18246
18247 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
18248 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
18249
18250 unsigned BitWidth = LHS.getBitWidth();
18251 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
18252 APInt ExResult =
18253 IsAdd
18254 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
18255 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
18256
18257 APInt Result = ExResult.extractBits(BitWidth, 0);
18258 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
18259
18260 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
18261 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
18262 return false;
18263 return Success(CarryOut, E);
18264 }
18265
18266 case clang::X86::BI__builtin_ia32_movmskps:
18267 case clang::X86::BI__builtin_ia32_movmskpd:
18268 case clang::X86::BI__builtin_ia32_pmovmskb128:
18269 case clang::X86::BI__builtin_ia32_pmovmskb256:
18270 case clang::X86::BI__builtin_ia32_movmskps256:
18271 case clang::X86::BI__builtin_ia32_movmskpd256: {
18272 APValue Source;
18273 if (!Evaluate(Source, Info, E->getArg(0)))
18274 return false;
18275 unsigned SourceLen = Source.getVectorLength();
18276 const VectorType *VT = E->getArg(0)->getType()->castAs<VectorType>();
18277 QualType ElemQT = VT->getElementType();
18278 unsigned ResultLen = Info.Ctx.getTypeSize(
18279 E->getCallReturnType(Info.Ctx)); // Always 32-bit integer.
18280 APInt Result(ResultLen, 0);
18281
18282 for (unsigned I = 0; I != SourceLen; ++I) {
18283 APInt Elem;
18284 if (ElemQT->isIntegerType()) {
18285 Elem = Source.getVectorElt(I).getInt();
18286 } else if (ElemQT->isRealFloatingType()) {
18287 Elem = Source.getVectorElt(I).getFloat().bitcastToAPInt();
18288 } else {
18289 return false;
18290 }
18291 Result.setBitVal(I, Elem.isNegative());
18292 }
18293 return Success(Result, E);
18294 }
18295
18296 case clang::X86::BI__builtin_ia32_bextr_u32:
18297 case clang::X86::BI__builtin_ia32_bextr_u64:
18298 case clang::X86::BI__builtin_ia32_bextri_u32:
18299 case clang::X86::BI__builtin_ia32_bextri_u64: {
18300 APSInt Val, Idx;
18301 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18302 !EvaluateInteger(E->getArg(1), Idx, Info))
18303 return false;
18304
18305 unsigned BitWidth = Val.getBitWidth();
18306 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
18307 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
18308 Length = Length > BitWidth ? BitWidth : Length;
18309
18310 // Handle out of bounds cases.
18311 if (Length == 0 || Shift >= BitWidth)
18312 return Success(0, E);
18313
18314 uint64_t Result = Val.getZExtValue() >> Shift;
18315 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
18316 return Success(Result, E);
18317 }
18318
18319 case clang::X86::BI__builtin_ia32_bzhi_si:
18320 case clang::X86::BI__builtin_ia32_bzhi_di: {
18321 APSInt Val, Idx;
18322 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18323 !EvaluateInteger(E->getArg(1), Idx, Info))
18324 return false;
18325
18326 unsigned BitWidth = Val.getBitWidth();
18327 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
18328 if (Index < BitWidth)
18329 Val.clearHighBits(BitWidth - Index);
18330 return Success(Val, E);
18331 }
18332
18333 case clang::X86::BI__builtin_ia32_ktestcqi:
18334 case clang::X86::BI__builtin_ia32_ktestchi:
18335 case clang::X86::BI__builtin_ia32_ktestcsi:
18336 case clang::X86::BI__builtin_ia32_ktestcdi: {
18337 APSInt A, B;
18338 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18339 !EvaluateInteger(E->getArg(1), B, Info))
18340 return false;
18341
18342 return Success((~A & B) == 0, E);
18343 }
18344
18345 case clang::X86::BI__builtin_ia32_ktestzqi:
18346 case clang::X86::BI__builtin_ia32_ktestzhi:
18347 case clang::X86::BI__builtin_ia32_ktestzsi:
18348 case clang::X86::BI__builtin_ia32_ktestzdi: {
18349 APSInt A, B;
18350 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18351 !EvaluateInteger(E->getArg(1), B, Info))
18352 return false;
18353
18354 return Success((A & B) == 0, E);
18355 }
18356
18357 case clang::X86::BI__builtin_ia32_kortestcqi:
18358 case clang::X86::BI__builtin_ia32_kortestchi:
18359 case clang::X86::BI__builtin_ia32_kortestcsi:
18360 case clang::X86::BI__builtin_ia32_kortestcdi: {
18361 APSInt A, B;
18362 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18363 !EvaluateInteger(E->getArg(1), B, Info))
18364 return false;
18365
18366 return Success(~(A | B) == 0, E);
18367 }
18368
18369 case clang::X86::BI__builtin_ia32_kortestzqi:
18370 case clang::X86::BI__builtin_ia32_kortestzhi:
18371 case clang::X86::BI__builtin_ia32_kortestzsi:
18372 case clang::X86::BI__builtin_ia32_kortestzdi: {
18373 APSInt A, B;
18374 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18375 !EvaluateInteger(E->getArg(1), B, Info))
18376 return false;
18377
18378 return Success((A | B) == 0, E);
18379 }
18380
18381 case clang::X86::BI__builtin_ia32_kunpckhi:
18382 case clang::X86::BI__builtin_ia32_kunpckdi:
18383 case clang::X86::BI__builtin_ia32_kunpcksi: {
18384 APSInt A, B;
18385 if (!EvaluateInteger(E->getArg(0), A, Info) ||
18386 !EvaluateInteger(E->getArg(1), B, Info))
18387 return false;
18388
18389 // Generic kunpack: extract lower half of each operand and concatenate
18390 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
18391 unsigned BW = A.getBitWidth();
18392 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
18393 return Success(Result, E);
18394 }
18395
18396 case clang::X86::BI__builtin_ia32_lzcnt_u16:
18397 case clang::X86::BI__builtin_ia32_lzcnt_u32:
18398 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
18399 APSInt Val;
18400 if (!EvaluateInteger(E->getArg(0), Val, Info))
18401 return false;
18402 return Success(Val.countLeadingZeros(), E);
18403 }
18404
18405 case clang::X86::BI__builtin_ia32_tzcnt_u16:
18406 case clang::X86::BI__builtin_ia32_tzcnt_u32:
18407 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
18408 APSInt Val;
18409 if (!EvaluateInteger(E->getArg(0), Val, Info))
18410 return false;
18411 return Success(Val.countTrailingZeros(), E);
18412 }
18413
18414 case clang::X86::BI__builtin_ia32_pdep_si:
18415 case clang::X86::BI__builtin_ia32_pdep_di:
18416 case Builtin::BI__builtin_elementwise_pdep: {
18417 APSInt Val, Msk;
18418 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18419 !EvaluateInteger(E->getArg(1), Msk, Info))
18420 return false;
18421 return Success(llvm::APIntOps::pdep(Val, Msk), E);
18422 }
18423
18424 case clang::X86::BI__builtin_ia32_pext_si:
18425 case clang::X86::BI__builtin_ia32_pext_di:
18426 case Builtin::BI__builtin_elementwise_pext: {
18427 APSInt Val, Msk;
18428 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
18429 !EvaluateInteger(E->getArg(1), Msk, Info))
18430 return false;
18431 return Success(llvm::APIntOps::pext(Val, Msk), E);
18432 }
18433 case X86::BI__builtin_ia32_ptestz128:
18434 case X86::BI__builtin_ia32_ptestz256:
18435 case X86::BI__builtin_ia32_vtestzps:
18436 case X86::BI__builtin_ia32_vtestzps256:
18437 case X86::BI__builtin_ia32_vtestzpd:
18438 case X86::BI__builtin_ia32_vtestzpd256: {
18439 return EvalTestOp(
18440 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
18441 }
18442 case X86::BI__builtin_ia32_ptestc128:
18443 case X86::BI__builtin_ia32_ptestc256:
18444 case X86::BI__builtin_ia32_vtestcps:
18445 case X86::BI__builtin_ia32_vtestcps256:
18446 case X86::BI__builtin_ia32_vtestcpd:
18447 case X86::BI__builtin_ia32_vtestcpd256: {
18448 return EvalTestOp(
18449 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
18450 }
18451 case X86::BI__builtin_ia32_ptestnzc128:
18452 case X86::BI__builtin_ia32_ptestnzc256:
18453 case X86::BI__builtin_ia32_vtestnzcps:
18454 case X86::BI__builtin_ia32_vtestnzcps256:
18455 case X86::BI__builtin_ia32_vtestnzcpd:
18456 case X86::BI__builtin_ia32_vtestnzcpd256: {
18457 return EvalTestOp([](const APInt &A, const APInt &B) {
18458 return ((A & B) != 0) && ((~A & B) != 0);
18459 });
18460 }
18461 case X86::BI__builtin_ia32_kandqi:
18462 case X86::BI__builtin_ia32_kandhi:
18463 case X86::BI__builtin_ia32_kandsi:
18464 case X86::BI__builtin_ia32_kanddi: {
18465 return HandleMaskBinOp(
18466 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
18467 }
18468
18469 case X86::BI__builtin_ia32_kandnqi:
18470 case X86::BI__builtin_ia32_kandnhi:
18471 case X86::BI__builtin_ia32_kandnsi:
18472 case X86::BI__builtin_ia32_kandndi: {
18473 return HandleMaskBinOp(
18474 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
18475 }
18476
18477 case X86::BI__builtin_ia32_korqi:
18478 case X86::BI__builtin_ia32_korhi:
18479 case X86::BI__builtin_ia32_korsi:
18480 case X86::BI__builtin_ia32_kordi: {
18481 return HandleMaskBinOp(
18482 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
18483 }
18484
18485 case X86::BI__builtin_ia32_kxnorqi:
18486 case X86::BI__builtin_ia32_kxnorhi:
18487 case X86::BI__builtin_ia32_kxnorsi:
18488 case X86::BI__builtin_ia32_kxnordi: {
18489 return HandleMaskBinOp(
18490 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
18491 }
18492
18493 case X86::BI__builtin_ia32_kxorqi:
18494 case X86::BI__builtin_ia32_kxorhi:
18495 case X86::BI__builtin_ia32_kxorsi:
18496 case X86::BI__builtin_ia32_kxordi: {
18497 return HandleMaskBinOp(
18498 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
18499 }
18500
18501 case X86::BI__builtin_ia32_knotqi:
18502 case X86::BI__builtin_ia32_knothi:
18503 case X86::BI__builtin_ia32_knotsi:
18504 case X86::BI__builtin_ia32_knotdi: {
18505 APSInt Val;
18506 if (!EvaluateInteger(E->getArg(0), Val, Info))
18507 return false;
18508 APSInt Result = ~Val;
18509 return Success(APValue(Result), E);
18510 }
18511
18512 case X86::BI__builtin_ia32_kaddqi:
18513 case X86::BI__builtin_ia32_kaddhi:
18514 case X86::BI__builtin_ia32_kaddsi:
18515 case X86::BI__builtin_ia32_kadddi: {
18516 return HandleMaskBinOp(
18517 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
18518 }
18519
18520 case X86::BI__builtin_ia32_kmovb:
18521 case X86::BI__builtin_ia32_kmovw:
18522 case X86::BI__builtin_ia32_kmovd:
18523 case X86::BI__builtin_ia32_kmovq: {
18524 APSInt Val;
18525 if (!EvaluateInteger(E->getArg(0), Val, Info))
18526 return false;
18527 return Success(Val, E);
18528 }
18529
18530 case X86::BI__builtin_ia32_kshiftliqi:
18531 case X86::BI__builtin_ia32_kshiftlihi:
18532 case X86::BI__builtin_ia32_kshiftlisi:
18533 case X86::BI__builtin_ia32_kshiftlidi: {
18534 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
18535 unsigned Amt = RHS.getZExtValue() & 0xFF;
18536 if (Amt >= LHS.getBitWidth())
18537 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18538 return APSInt(LHS.shl(Amt), LHS.isUnsigned());
18539 });
18540 }
18541
18542 case X86::BI__builtin_ia32_kshiftriqi:
18543 case X86::BI__builtin_ia32_kshiftrihi:
18544 case X86::BI__builtin_ia32_kshiftrisi:
18545 case X86::BI__builtin_ia32_kshiftridi: {
18546 return HandleMaskBinOp([](const APSInt &LHS, const APSInt &RHS) {
18547 unsigned Amt = RHS.getZExtValue() & 0xFF;
18548 if (Amt >= LHS.getBitWidth())
18549 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18550 return APSInt(LHS.lshr(Amt), LHS.isUnsigned());
18551 });
18552 }
18553
18554 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
18555 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
18556 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
18557 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
18558 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
18559 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
18560 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
18561 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
18562 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
18563 APValue Vec;
18564 APSInt IdxAPS;
18565 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
18566 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
18567 return false;
18568 unsigned N = Vec.getVectorLength();
18569 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
18570 return Success(Vec.getVectorElt(Idx).getInt(), E);
18571 }
18572
18573 case clang::X86::BI__builtin_ia32_cvtb2mask128:
18574 case clang::X86::BI__builtin_ia32_cvtb2mask256:
18575 case clang::X86::BI__builtin_ia32_cvtb2mask512:
18576 case clang::X86::BI__builtin_ia32_cvtw2mask128:
18577 case clang::X86::BI__builtin_ia32_cvtw2mask256:
18578 case clang::X86::BI__builtin_ia32_cvtw2mask512:
18579 case clang::X86::BI__builtin_ia32_cvtd2mask128:
18580 case clang::X86::BI__builtin_ia32_cvtd2mask256:
18581 case clang::X86::BI__builtin_ia32_cvtd2mask512:
18582 case clang::X86::BI__builtin_ia32_cvtq2mask128:
18583 case clang::X86::BI__builtin_ia32_cvtq2mask256:
18584 case clang::X86::BI__builtin_ia32_cvtq2mask512: {
18585 assert(E->getNumArgs() == 1);
18586 APValue Vec;
18587 if (!EvaluateVector(E->getArg(0), Vec, Info))
18588 return false;
18589
18590 unsigned VectorLen = Vec.getVectorLength();
18591 unsigned RetWidth = Info.Ctx.getIntWidth(E->getType());
18592 llvm::APInt Bits(RetWidth, 0);
18593
18594 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
18595 const APSInt &A = Vec.getVectorElt(ElemNum).getInt();
18596 unsigned MSB = A[A.getBitWidth() - 1];
18597 Bits.setBitVal(ElemNum, MSB);
18598 }
18599
18600 APSInt RetMask(Bits, /*isUnsigned=*/true);
18601 return Success(APValue(RetMask), E);
18602 }
18603
18604 case clang::X86::BI__builtin_ia32_cmpb128_mask:
18605 case clang::X86::BI__builtin_ia32_cmpw128_mask:
18606 case clang::X86::BI__builtin_ia32_cmpd128_mask:
18607 case clang::X86::BI__builtin_ia32_cmpq128_mask:
18608 case clang::X86::BI__builtin_ia32_cmpb256_mask:
18609 case clang::X86::BI__builtin_ia32_cmpw256_mask:
18610 case clang::X86::BI__builtin_ia32_cmpd256_mask:
18611 case clang::X86::BI__builtin_ia32_cmpq256_mask:
18612 case clang::X86::BI__builtin_ia32_cmpb512_mask:
18613 case clang::X86::BI__builtin_ia32_cmpw512_mask:
18614 case clang::X86::BI__builtin_ia32_cmpd512_mask:
18615 case clang::X86::BI__builtin_ia32_cmpq512_mask:
18616 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
18617 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
18618 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
18619 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
18620 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
18621 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
18622 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
18623 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
18624 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
18625 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
18626 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
18627 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
18628 assert(E->getNumArgs() == 4);
18629
18630 bool IsUnsigned =
18631 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
18632 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpw512_mask);
18633
18634 APValue LHS, RHS;
18635 APSInt Mask, Opcode;
18636 if (!EvaluateVector(E->getArg(0), LHS, Info) ||
18637 !EvaluateVector(E->getArg(1), RHS, Info) ||
18638 !EvaluateInteger(E->getArg(2), Opcode, Info) ||
18639 !EvaluateInteger(E->getArg(3), Mask, Info))
18640 return false;
18641
18642 assert(LHS.getVectorLength() == RHS.getVectorLength());
18643
18644 unsigned VectorLen = LHS.getVectorLength();
18645 unsigned RetWidth = Mask.getBitWidth();
18646
18647 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
18648
18649 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
18650 const APSInt &A = LHS.getVectorElt(ElemNum).getInt();
18651 const APSInt &B = RHS.getVectorElt(ElemNum).getInt();
18652 bool Result = false;
18653
18654 switch (Opcode.getExtValue() & 0x7) {
18655 case 0: // _MM_CMPINT_EQ
18656 Result = (A == B);
18657 break;
18658 case 1: // _MM_CMPINT_LT
18659 Result = IsUnsigned ? A.ult(B) : A.slt(B);
18660 break;
18661 case 2: // _MM_CMPINT_LE
18662 Result = IsUnsigned ? A.ule(B) : A.sle(B);
18663 break;
18664 case 3: // _MM_CMPINT_FALSE
18665 Result = false;
18666 break;
18667 case 4: // _MM_CMPINT_NE
18668 Result = (A != B);
18669 break;
18670 case 5: // _MM_CMPINT_NLT (>=)
18671 Result = IsUnsigned ? A.uge(B) : A.sge(B);
18672 break;
18673 case 6: // _MM_CMPINT_NLE (>)
18674 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
18675 break;
18676 case 7: // _MM_CMPINT_TRUE
18677 Result = true;
18678 break;
18679 }
18680
18681 RetMask.setBitVal(ElemNum, Mask[ElemNum] && Result);
18682 }
18683
18684 return Success(APValue(RetMask), E);
18685 }
18686 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
18687 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
18688 case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
18689 assert(E->getNumArgs() == 3);
18690
18691 APValue Source, ShuffleMask;
18692 APSInt ZeroMask;
18693 if (!EvaluateVector(E->getArg(0), Source, Info) ||
18694 !EvaluateVector(E->getArg(1), ShuffleMask, Info) ||
18695 !EvaluateInteger(E->getArg(2), ZeroMask, Info))
18696 return false;
18697
18698 assert(Source.getVectorLength() == ShuffleMask.getVectorLength());
18699 assert(ZeroMask.getBitWidth() == Source.getVectorLength());
18700
18701 unsigned NumBytesInQWord = 8;
18702 unsigned NumBitsInByte = 8;
18703 unsigned NumBytes = Source.getVectorLength();
18704 unsigned NumQWords = NumBytes / NumBytesInQWord;
18705 unsigned RetWidth = ZeroMask.getBitWidth();
18706 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
18707
18708 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
18709 APInt SourceQWord(64, 0);
18710 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
18711 uint64_t Byte = Source.getVectorElt(QWordId * NumBytesInQWord + ByteIdx)
18712 .getInt()
18713 .getZExtValue();
18714 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
18715 }
18716
18717 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
18718 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
18719 unsigned M =
18720 ShuffleMask.getVectorElt(SelIdx).getInt().getZExtValue() & 0x3F;
18721 if (ZeroMask[SelIdx]) {
18722 RetMask.setBitVal(SelIdx, SourceQWord[M]);
18723 }
18724 }
18725 }
18726 return Success(APValue(RetMask), E);
18727 }
18728 }
18729}
18730
18731/// Determine whether this is a pointer past the end of the complete
18732/// object referred to by the lvalue.
18734 const LValue &LV) {
18735 // A null pointer can be viewed as being "past the end" but we don't
18736 // choose to look at it that way here.
18737 if (!LV.getLValueBase())
18738 return false;
18739
18740 // If the designator is valid and refers to a subobject, we're not pointing
18741 // past the end.
18742 if (!LV.getLValueDesignator().Invalid &&
18743 !LV.getLValueDesignator().isOnePastTheEnd())
18744 return false;
18745
18746 // A pointer to an incomplete type might be past-the-end if the type's size is
18747 // zero. We cannot tell because the type is incomplete.
18748 QualType Ty = getType(LV.getLValueBase());
18749 if (Ty->isIncompleteType())
18750 return true;
18751
18752 // Can't be past the end of an invalid object.
18753 if (LV.getLValueDesignator().Invalid)
18754 return false;
18755
18756 // We're a past-the-end pointer if we point to the byte after the object,
18757 // no matter what our type or path is.
18758 auto Size = Ctx.getTypeSizeInChars(Ty);
18759 return LV.getLValueOffset() == Size;
18760}
18761
18762namespace {
18763
18764/// Data recursive integer evaluator of certain binary operators.
18765///
18766/// We use a data recursive algorithm for binary operators so that we are able
18767/// to handle extreme cases of chained binary operators without causing stack
18768/// overflow.
18769class DataRecursiveIntBinOpEvaluator {
18770 struct EvalResult {
18771 APValue Val;
18772 bool Failed = false;
18773
18774 EvalResult() = default;
18775
18776 void swap(EvalResult &RHS) {
18777 Val.swap(RHS.Val);
18778 Failed = RHS.Failed;
18779 RHS.Failed = false;
18780 }
18781 };
18782
18783 struct Job {
18784 const Expr *E;
18785 EvalResult LHSResult; // meaningful only for binary operator expression.
18786 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
18787
18788 Job() = default;
18789 Job(Job &&) = default;
18790
18791 void startSpeculativeEval(EvalInfo &Info) {
18792 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
18793 }
18794
18795 private:
18796 SpeculativeEvaluationRAII SpecEvalRAII;
18797 };
18798
18799 SmallVector<Job, 16> Queue;
18800
18801 IntExprEvaluator &IntEval;
18802 EvalInfo &Info;
18803 APValue &FinalResult;
18804
18805public:
18806 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
18807 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
18808
18809 /// True if \param E is a binary operator that we are going to handle
18810 /// data recursively.
18811 /// We handle binary operators that are comma, logical, or that have operands
18812 /// with integral or enumeration type.
18813 static bool shouldEnqueue(const BinaryOperator *E) {
18814 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
18818 }
18819
18820 bool Traverse(const BinaryOperator *E) {
18821 enqueue(E);
18822 EvalResult PrevResult;
18823 while (!Queue.empty())
18824 process(PrevResult);
18825
18826 if (PrevResult.Failed) return false;
18827
18828 FinalResult.swap(PrevResult.Val);
18829 return true;
18830 }
18831
18832private:
18833 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
18834 return IntEval.Success(Value, E, Result);
18835 }
18836 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
18837 return IntEval.Success(Value, E, Result);
18838 }
18839 bool Error(const Expr *E) {
18840 return IntEval.Error(E);
18841 }
18842 bool Error(const Expr *E, diag::kind D) {
18843 return IntEval.Error(E, D);
18844 }
18845
18846 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
18847 return Info.CCEDiag(E, D);
18848 }
18849
18850 // Returns true if visiting the RHS is necessary, false otherwise.
18851 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18852 bool &SuppressRHSDiags);
18853
18854 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18855 const BinaryOperator *E, APValue &Result);
18856
18857 void EvaluateExpr(const Expr *E, EvalResult &Result) {
18858 Result.Failed = !Evaluate(Result.Val, Info, E);
18859 if (Result.Failed)
18860 Result.Val = APValue();
18861 }
18862
18863 void process(EvalResult &Result);
18864
18865 void enqueue(const Expr *E) {
18866 E = E->IgnoreParens();
18867 Queue.resize(Queue.size()+1);
18868 Queue.back().E = E;
18869 Queue.back().Kind = Job::AnyExprKind;
18870 }
18871};
18872
18873}
18874
18875bool DataRecursiveIntBinOpEvaluator::
18876 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
18877 bool &SuppressRHSDiags) {
18878 if (E->getOpcode() == BO_Comma) {
18879 // Ignore LHS but note if we could not evaluate it.
18880 if (LHSResult.Failed)
18881 return Info.noteSideEffect();
18882 return true;
18883 }
18884
18885 if (E->isLogicalOp()) {
18886 bool LHSAsBool;
18887 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
18888 // We were able to evaluate the LHS, see if we can get away with not
18889 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
18890 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
18891 Success(LHSAsBool, E, LHSResult.Val);
18892 return false; // Ignore RHS
18893 }
18894 } else {
18895 LHSResult.Failed = true;
18896
18897 // Since we weren't able to evaluate the left hand side, it
18898 // might have had side effects.
18899 if (!Info.noteSideEffect())
18900 return false;
18901
18902 // We can't evaluate the LHS; however, sometimes the result
18903 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18904 // Don't ignore RHS and suppress diagnostics from this arm.
18905 SuppressRHSDiags = true;
18906 }
18907
18908 return true;
18909 }
18910
18911 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18913
18914 if (LHSResult.Failed && !Info.noteFailure())
18915 return false; // Ignore RHS;
18916
18917 return true;
18918}
18919
18920static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
18921 bool IsSub) {
18922 // Compute the new offset in the appropriate width, wrapping at 64 bits.
18923 // FIXME: When compiling for a 32-bit target, we should use 32-bit
18924 // offsets.
18925 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
18926 CharUnits &Offset = LVal.getLValueOffset();
18927 uint64_t Offset64 = Offset.getQuantity();
18928 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
18929 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
18930 : Offset64 + Index64);
18931}
18932
18933bool DataRecursiveIntBinOpEvaluator::
18934 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
18935 const BinaryOperator *E, APValue &Result) {
18936 if (E->getOpcode() == BO_Comma) {
18937 if (RHSResult.Failed)
18938 return false;
18939 Result = RHSResult.Val;
18940 return true;
18941 }
18942
18943 if (E->isLogicalOp()) {
18944 bool lhsResult, rhsResult;
18945 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
18946 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
18947
18948 if (LHSIsOK) {
18949 if (RHSIsOK) {
18950 if (E->getOpcode() == BO_LOr)
18951 return Success(lhsResult || rhsResult, E, Result);
18952 else
18953 return Success(lhsResult && rhsResult, E, Result);
18954 }
18955 } else {
18956 if (RHSIsOK) {
18957 // We can't evaluate the LHS; however, sometimes the result
18958 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
18959 if (rhsResult == (E->getOpcode() == BO_LOr))
18960 return Success(rhsResult, E, Result);
18961 }
18962 }
18963
18964 return false;
18965 }
18966
18967 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
18969
18970 if (LHSResult.Failed || RHSResult.Failed)
18971 return false;
18972
18973 const APValue &LHSVal = LHSResult.Val;
18974 const APValue &RHSVal = RHSResult.Val;
18975
18976 // Handle cases like (unsigned long)&a + 4.
18977 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
18978 Result = LHSVal;
18979 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
18980 return true;
18981 }
18982
18983 // Handle cases like 4 + (unsigned long)&a
18984 if (E->getOpcode() == BO_Add &&
18985 RHSVal.isLValue() && LHSVal.isInt()) {
18986 Result = RHSVal;
18987 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
18988 return true;
18989 }
18990
18991 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
18992 // Handle (intptr_t)&&A - (intptr_t)&&B.
18993 if (!LHSVal.getLValueOffset().isZero() ||
18994 !RHSVal.getLValueOffset().isZero())
18995 return false;
18996 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
18997 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
18998 if (!LHSExpr || !RHSExpr)
18999 return false;
19000 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
19001 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
19002 if (!LHSAddrExpr || !RHSAddrExpr)
19003 return false;
19004 // Make sure both labels come from the same function.
19005 if (LHSAddrExpr->getLabel()->getDeclContext() !=
19006 RHSAddrExpr->getLabel()->getDeclContext())
19007 return false;
19008 Result = APValue(LHSAddrExpr, RHSAddrExpr);
19009 return true;
19010 }
19011
19012 // All the remaining cases expect both operands to be an integer
19013 if (!LHSVal.isInt() || !RHSVal.isInt())
19014 return Error(E);
19015
19016 // Set up the width and signedness manually, in case it can't be deduced
19017 // from the operation we're performing.
19018 // FIXME: Don't do this in the cases where we can deduce it.
19019 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
19021 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
19022 RHSVal.getInt(), Value))
19023 return false;
19024 return Success(Value, E, Result);
19025}
19026
19027void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
19028 Job &job = Queue.back();
19029
19030 switch (job.Kind) {
19031 case Job::AnyExprKind: {
19032 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
19033 if (shouldEnqueue(Bop)) {
19034 job.Kind = Job::BinOpKind;
19035 enqueue(Bop->getLHS());
19036 return;
19037 }
19038 }
19039
19040 EvaluateExpr(job.E, Result);
19041 Queue.pop_back();
19042 return;
19043 }
19044
19045 case Job::BinOpKind: {
19046 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
19047 bool SuppressRHSDiags = false;
19048 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
19049 Queue.pop_back();
19050 return;
19051 }
19052 if (SuppressRHSDiags)
19053 job.startSpeculativeEval(Info);
19054 job.LHSResult.swap(Result);
19055 job.Kind = Job::BinOpVisitedLHSKind;
19056 enqueue(Bop->getRHS());
19057 return;
19058 }
19059
19060 case Job::BinOpVisitedLHSKind: {
19061 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
19062 EvalResult RHS;
19063 RHS.swap(Result);
19064 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
19065 Queue.pop_back();
19066 return;
19067 }
19068 }
19069
19070 llvm_unreachable("Invalid Job::Kind!");
19071}
19072
19073namespace {
19074enum class CmpResult {
19075 Unequal,
19076 Less,
19077 Equal,
19078 Greater,
19079 Unordered,
19080};
19081}
19082
19083template <class SuccessCB, class AfterCB>
19084static bool
19086 SuccessCB &&Success, AfterCB &&DoAfter) {
19087 assert(!E->isValueDependent());
19088 assert(E->isComparisonOp() && "expected comparison operator");
19089 assert((E->getOpcode() == BO_Cmp ||
19091 "unsupported binary expression evaluation");
19092 auto Error = [&](const Expr *E) {
19093 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
19094 return false;
19095 };
19096
19097 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
19098 bool IsEquality = E->isEqualityOp();
19099
19100 QualType LHSTy = E->getLHS()->getType();
19101 QualType RHSTy = E->getRHS()->getType();
19102
19103 if (LHSTy->isIntegralOrEnumerationType() &&
19104 RHSTy->isIntegralOrEnumerationType()) {
19105 APSInt LHS, RHS;
19106 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
19107 if (!LHSOK && !Info.noteFailure())
19108 return false;
19109 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
19110 return false;
19111 if (LHS < RHS)
19112 return Success(CmpResult::Less, E);
19113 if (LHS > RHS)
19114 return Success(CmpResult::Greater, E);
19115 return Success(CmpResult::Equal, E);
19116 }
19117
19118 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
19119 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
19120 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
19121
19122 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
19123 if (!LHSOK && !Info.noteFailure())
19124 return false;
19125 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
19126 return false;
19127 if (LHSFX < RHSFX)
19128 return Success(CmpResult::Less, E);
19129 if (LHSFX > RHSFX)
19130 return Success(CmpResult::Greater, E);
19131 return Success(CmpResult::Equal, E);
19132 }
19133
19134 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
19135 ComplexValue LHS, RHS;
19136 bool LHSOK;
19137 if (E->isAssignmentOp()) {
19138 LValue LV;
19139 EvaluateLValue(E->getLHS(), LV, Info);
19140 LHSOK = false;
19141 } else if (LHSTy->isRealFloatingType()) {
19142 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
19143 if (LHSOK) {
19144 LHS.makeComplexFloat();
19145 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
19146 }
19147 } else {
19148 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
19149 }
19150 if (!LHSOK && !Info.noteFailure())
19151 return false;
19152
19153 if (E->getRHS()->getType()->isRealFloatingType()) {
19154 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
19155 return false;
19156 RHS.makeComplexFloat();
19157 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
19158 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
19159 return false;
19160
19161 if (LHS.isComplexFloat()) {
19162 APFloat::cmpResult CR_r =
19163 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
19164 APFloat::cmpResult CR_i =
19165 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
19166 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
19167 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
19168 } else {
19169 assert(IsEquality && "invalid complex comparison");
19170 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
19171 LHS.getComplexIntImag() == RHS.getComplexIntImag();
19172 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
19173 }
19174 }
19175
19176 if (LHSTy->isRealFloatingType() &&
19177 RHSTy->isRealFloatingType()) {
19178 APFloat RHS(0.0), LHS(0.0);
19179
19180 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
19181 if (!LHSOK && !Info.noteFailure())
19182 return false;
19183
19184 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
19185 return false;
19186
19187 assert(E->isComparisonOp() && "Invalid binary operator!");
19188 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
19189 if (!Info.InConstantContext &&
19190 APFloatCmpResult == APFloat::cmpUnordered &&
19191 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
19192 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
19193 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
19194 return false;
19195 }
19196 auto GetCmpRes = [&]() {
19197 switch (APFloatCmpResult) {
19198 case APFloat::cmpEqual:
19199 return CmpResult::Equal;
19200 case APFloat::cmpLessThan:
19201 return CmpResult::Less;
19202 case APFloat::cmpGreaterThan:
19203 return CmpResult::Greater;
19204 case APFloat::cmpUnordered:
19205 return CmpResult::Unordered;
19206 }
19207 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
19208 };
19209 return Success(GetCmpRes(), E);
19210 }
19211
19212 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
19213 LValue LHSValue, RHSValue;
19214
19215 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
19216 if (!LHSOK && !Info.noteFailure())
19217 return false;
19218
19219 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19220 return false;
19221
19222 // Reject differing bases from the normal codepath; we special-case
19223 // comparisons to null.
19224 if (!HasSameBase(LHSValue, RHSValue)) {
19225 // Bail out early if we're checking potential constant expression.
19226 // Otherwise, prefer to diagnose other issues.
19227 if (Info.checkingPotentialConstantExpression() &&
19228 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
19229 return false;
19230 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
19231 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
19232 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
19233 Info.FFDiag(E, DiagID)
19234 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
19235 return false;
19236 };
19237 // Inequalities and subtractions between unrelated pointers have
19238 // unspecified or undefined behavior.
19239 if (!IsEquality)
19240 return DiagComparison(
19241 diag::note_constexpr_pointer_comparison_unspecified);
19242 // A constant address may compare equal to the address of a symbol.
19243 // The one exception is that address of an object cannot compare equal
19244 // to a null pointer constant.
19245 // TODO: Should we restrict this to actual null pointers, and exclude the
19246 // case of zero cast to pointer type?
19247 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
19248 (!RHSValue.Base && !RHSValue.Offset.isZero()))
19249 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
19250 !RHSValue.Base);
19251 // C++2c [intro.object]/10:
19252 // Two objects [...] may have the same address if [...] they are both
19253 // potentially non-unique objects.
19254 // C++2c [intro.object]/9:
19255 // An object is potentially non-unique if it is a string literal object,
19256 // the backing array of an initializer list, or a subobject thereof.
19257 //
19258 // This makes the comparison result unspecified, so it's not a constant
19259 // expression.
19260 //
19261 // TODO: Do we need to handle the initializer list case here?
19262 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
19263 return DiagComparison(diag::note_constexpr_literal_comparison);
19264 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
19265 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
19266 !IsOpaqueConstantCall(LHSValue));
19267 // We can't tell whether weak symbols will end up pointing to the same
19268 // object.
19269 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
19270 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
19271 !IsWeakLValue(LHSValue));
19272 // We can't compare the address of the start of one object with the
19273 // past-the-end address of another object, per C++ DR1652.
19274 if (LHSValue.Base && LHSValue.Offset.isZero() &&
19275 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
19276 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
19277 true);
19278 if (RHSValue.Base && RHSValue.Offset.isZero() &&
19279 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
19280 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
19281 false);
19282 // We can't tell whether an object is at the same address as another
19283 // zero sized object.
19284 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
19285 (LHSValue.Base && isZeroSized(RHSValue)))
19286 return DiagComparison(
19287 diag::note_constexpr_pointer_comparison_zero_sized);
19288 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
19289 return DiagComparison(
19290 diag::note_constexpr_pointer_comparison_unspecified);
19291 // FIXME: Verify both variables are live.
19292 return Success(CmpResult::Unequal, E);
19293 }
19294
19295 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
19296 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
19297
19298 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
19299 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
19300
19301 // C++11 [expr.rel]p2:
19302 // - If two pointers point to non-static data members of the same object,
19303 // or to subobjects or array elements fo such members, recursively, the
19304 // pointer to the later declared member compares greater provided the
19305 // two members have the same access control and provided their class is
19306 // not a union.
19307 // [...]
19308 // - Otherwise pointer comparisons are unspecified.
19309 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
19310 bool WasArrayIndex;
19311 unsigned Mismatch = FindDesignatorMismatch(
19312 LHSValue.Base.isNull() ? QualType()
19313 : getType(LHSValue.Base).getNonReferenceType(),
19314 LHSDesignator, RHSDesignator, WasArrayIndex);
19315 // At the point where the designators diverge, the comparison has a
19316 // specified value if:
19317 // - we are comparing array indices
19318 // - we are comparing fields of a union, or fields with the same access
19319 // Otherwise, the result is unspecified and thus the comparison is not a
19320 // constant expression.
19321 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
19322 Mismatch < RHSDesignator.Entries.size()) {
19323 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
19324 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
19325 if (!LF && !RF)
19326 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
19327 else if (!LF)
19328 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
19329 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
19330 << RF->getParent() << RF;
19331 else if (!RF)
19332 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
19333 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
19334 << LF->getParent() << LF;
19335 else if (!LF->getParent()->isUnion() &&
19336 LF->getAccess() != RF->getAccess())
19337 Info.CCEDiag(E,
19338 diag::note_constexpr_pointer_comparison_differing_access)
19339 << LF << LF->getAccess() << RF << RF->getAccess()
19340 << LF->getParent();
19341 }
19342 }
19343
19344 // The comparison here must be unsigned, and performed with the same
19345 // width as the pointer.
19346 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
19347 uint64_t CompareLHS = LHSOffset.getQuantity();
19348 uint64_t CompareRHS = RHSOffset.getQuantity();
19349 assert(PtrSize <= 64 && "Unexpected pointer width");
19350 uint64_t Mask = ~0ULL >> (64 - PtrSize);
19351 CompareLHS &= Mask;
19352 CompareRHS &= Mask;
19353
19354 // If there is a base and this is a relational operator, we can only
19355 // compare pointers within the object in question; otherwise, the result
19356 // depends on where the object is located in memory.
19357 if (!LHSValue.Base.isNull() && IsRelational) {
19358 QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
19359 if (BaseTy->isIncompleteType())
19360 return Error(E);
19361 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
19362 uint64_t OffsetLimit = Size.getQuantity();
19363 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
19364 return Error(E);
19365 }
19366
19367 if (CompareLHS < CompareRHS)
19368 return Success(CmpResult::Less, E);
19369 if (CompareLHS > CompareRHS)
19370 return Success(CmpResult::Greater, E);
19371 return Success(CmpResult::Equal, E);
19372 }
19373
19374 if (LHSTy->isMemberPointerType()) {
19375 assert(IsEquality && "unexpected member pointer operation");
19376 assert(RHSTy->isMemberPointerType() && "invalid comparison");
19377
19378 MemberPtr LHSValue, RHSValue;
19379
19380 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
19381 if (!LHSOK && !Info.noteFailure())
19382 return false;
19383
19384 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19385 return false;
19386
19387 // If either operand is a pointer to a weak function, the comparison is not
19388 // constant.
19389 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
19390 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
19391 << LHSValue.getDecl();
19392 return false;
19393 }
19394 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
19395 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
19396 << RHSValue.getDecl();
19397 return false;
19398 }
19399
19400 // C++11 [expr.eq]p2:
19401 // If both operands are null, they compare equal. Otherwise if only one is
19402 // null, they compare unequal.
19403 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
19404 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
19405 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
19406 }
19407
19408 // Otherwise if either is a pointer to a virtual member function, the
19409 // result is unspecified.
19410 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
19411 if (MD->isVirtual())
19412 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
19413 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
19414 if (MD->isVirtual())
19415 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
19416
19417 // Otherwise they compare equal if and only if they would refer to the
19418 // same member of the same most derived object or the same subobject if
19419 // they were dereferenced with a hypothetical object of the associated
19420 // class type.
19421 bool Equal = LHSValue == RHSValue;
19422 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
19423 }
19424
19425 if (LHSTy->isNullPtrType()) {
19426 assert(E->isComparisonOp() && "unexpected nullptr operation");
19427 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
19428 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
19429 // are compared, the result is true of the operator is <=, >= or ==, and
19430 // false otherwise.
19431 LValue Res;
19432 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
19433 !EvaluatePointer(E->getRHS(), Res, Info))
19434 return false;
19435 return Success(CmpResult::Equal, E);
19436 }
19437
19438 return DoAfter();
19439}
19440
19441bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
19442 if (!CheckLiteralType(Info, E))
19443 return false;
19444
19445 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
19447 switch (CR) {
19448 case CmpResult::Unequal:
19449 llvm_unreachable("should never produce Unequal for three-way comparison");
19450 case CmpResult::Less:
19451 CCR = ComparisonCategoryResult::Less;
19452 break;
19453 case CmpResult::Equal:
19454 CCR = ComparisonCategoryResult::Equal;
19455 break;
19456 case CmpResult::Greater:
19457 CCR = ComparisonCategoryResult::Greater;
19458 break;
19459 case CmpResult::Unordered:
19460 CCR = ComparisonCategoryResult::Unordered;
19461 break;
19462 }
19463 // Evaluation succeeded. Lookup the information for the comparison category
19464 // type and fetch the VarDecl for the result.
19465 const ComparisonCategoryInfo &CmpInfo =
19466 Info.Ctx.CompCategories.getInfoForType(E->getType());
19467 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
19468 // Check and evaluate the result as a constant expression.
19469 LValue LV;
19470 LV.set(VD);
19471 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
19472 return false;
19473 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
19474 ConstantExprKind::Normal);
19475 };
19476 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
19477 return ExprEvaluatorBaseTy::VisitBinCmp(E);
19478 });
19479}
19480
19481bool RecordExprEvaluator::VisitCXXParenListInitExpr(
19482 const CXXParenListInitExpr *E) {
19483 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
19484}
19485
19486bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
19487 // We don't support assignment in C. C++ assignments don't get here because
19488 // assignment is an lvalue in C++.
19489 if (E->isAssignmentOp()) {
19490 Error(E);
19491 if (!Info.noteFailure())
19492 return false;
19493 }
19494
19495 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
19496 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
19497
19498 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
19500 "DataRecursiveIntBinOpEvaluator should have handled integral types");
19501
19502 if (E->isComparisonOp()) {
19503 // Evaluate builtin binary comparisons by evaluating them as three-way
19504 // comparisons and then translating the result.
19505 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
19506 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
19507 "should only produce Unequal for equality comparisons");
19508 bool IsEqual = CR == CmpResult::Equal,
19509 IsLess = CR == CmpResult::Less,
19510 IsGreater = CR == CmpResult::Greater;
19511 auto Op = E->getOpcode();
19512 switch (Op) {
19513 default:
19514 llvm_unreachable("unsupported binary operator");
19515 case BO_EQ:
19516 case BO_NE:
19517 return Success(IsEqual == (Op == BO_EQ), E);
19518 case BO_LT:
19519 return Success(IsLess, E);
19520 case BO_GT:
19521 return Success(IsGreater, E);
19522 case BO_LE:
19523 return Success(IsEqual || IsLess, E);
19524 case BO_GE:
19525 return Success(IsEqual || IsGreater, E);
19526 }
19527 };
19528 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
19529 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19530 });
19531 }
19532
19533 QualType LHSTy = E->getLHS()->getType();
19534 QualType RHSTy = E->getRHS()->getType();
19535
19536 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
19537 E->getOpcode() == BO_Sub) {
19538 LValue LHSValue, RHSValue;
19539
19540 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
19541 if (!LHSOK && !Info.noteFailure())
19542 return false;
19543
19544 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
19545 return false;
19546
19547 // Reject differing bases from the normal codepath; we special-case
19548 // comparisons to null.
19549 if (!HasSameBase(LHSValue, RHSValue)) {
19550 if (Info.checkingPotentialConstantExpression() &&
19551 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
19552 return false;
19553
19554 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
19555 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
19556
19557 auto DiagArith = [&](unsigned DiagID) {
19558 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
19559 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
19560 Info.FFDiag(E, DiagID) << LHS << RHS;
19561 if (LHSExpr && LHSExpr == RHSExpr)
19562 Info.Note(LHSExpr->getExprLoc(),
19563 diag::note_constexpr_repeated_literal_eval)
19564 << LHSExpr->getSourceRange();
19565 return false;
19566 };
19567
19568 if (!LHSExpr || !RHSExpr)
19569 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
19570
19571 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
19572 return DiagArith(diag::note_constexpr_literal_arith);
19573
19574 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
19575 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
19576 if (!LHSAddrExpr || !RHSAddrExpr)
19577 return Error(E);
19578 // Make sure both labels come from the same function.
19579 if (LHSAddrExpr->getLabel()->getDeclContext() !=
19580 RHSAddrExpr->getLabel()->getDeclContext())
19581 return Error(E);
19582 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
19583 }
19584 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
19585 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
19586
19587 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
19588 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
19589
19590 // C++11 [expr.add]p6:
19591 // Unless both pointers point to elements of the same array object, or
19592 // one past the last element of the array object, the behavior is
19593 // undefined.
19594 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
19595 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
19596 RHSDesignator))
19597 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
19598
19599 QualType Type = E->getLHS()->getType();
19600 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
19601
19602 CharUnits ElementSize;
19603 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
19604 return false;
19605
19606 // As an extension, a type may have zero size (empty struct or union in
19607 // C, array of zero length). Pointer subtraction in such cases has
19608 // undefined behavior, so is not constant.
19609 if (ElementSize.isZero()) {
19610 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
19611 << ElementType;
19612 return false;
19613 }
19614
19615 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
19616 // and produce incorrect results when it overflows. Such behavior
19617 // appears to be non-conforming, but is common, so perhaps we should
19618 // assume the standard intended for such cases to be undefined behavior
19619 // and check for them.
19620
19621 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
19622 // overflow in the final conversion to ptrdiff_t.
19623 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
19624 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
19625 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
19626 false);
19627 APSInt TrueResult = (LHS - RHS) / ElemSize;
19628 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
19629
19630 if (Result.extend(65) != TrueResult &&
19631 !HandleOverflow(Info, E, TrueResult, E->getType()))
19632 return false;
19633 return Success(Result, E);
19634 }
19635
19636 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
19637}
19638
19639/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
19640/// a result as the expression's type.
19641bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
19642 const UnaryExprOrTypeTraitExpr *E) {
19643 switch(E->getKind()) {
19644 case UETT_PreferredAlignOf:
19645 case UETT_AlignOf: {
19646 if (E->isArgumentType())
19647 return Success(
19648 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
19649 else
19650 return Success(
19651 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
19652 }
19653
19654 case UETT_PtrAuthTypeDiscriminator: {
19655 if (E->getArgumentType()->isDependentType())
19656 return false;
19657 return Success(
19658 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
19659 }
19660 case UETT_VecStep: {
19661 QualType Ty = E->getTypeOfArgument();
19662
19663 if (Ty->isVectorType()) {
19664 unsigned n = Ty->castAs<VectorType>()->getNumElements();
19665
19666 // The vec_step built-in functions that take a 3-component
19667 // vector return 4. (OpenCL 1.1 spec 6.11.12)
19668 if (n == 3)
19669 n = 4;
19670
19671 return Success(n, E);
19672 } else
19673 return Success(1, E);
19674 }
19675
19676 case UETT_DataSizeOf:
19677 case UETT_SizeOf: {
19678 QualType SrcTy = E->getTypeOfArgument();
19679 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
19680 // the result is the size of the referenced type."
19681 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
19682 SrcTy = Ref->getPointeeType();
19683
19684 CharUnits Sizeof;
19685 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
19686 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
19687 : SizeOfType::SizeOf)) {
19688 return false;
19689 }
19690 return Success(Sizeof, E);
19691 }
19692 case UETT_OpenMPRequiredSimdAlign:
19693 assert(E->isArgumentType());
19694 return Success(
19695 Info.Ctx.toCharUnitsFromBits(
19696 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
19697 .getQuantity(),
19698 E);
19699 case UETT_VectorElements: {
19700 QualType Ty = E->getTypeOfArgument();
19701 // If the vector has a fixed size, we can determine the number of elements
19702 // at compile time.
19703 if (const auto *VT = Ty->getAs<VectorType>())
19704 return Success(VT->getNumElements(), E);
19705
19706 assert(Ty->isSizelessVectorType());
19707 if (Info.InConstantContext)
19708 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
19709 << E->getSourceRange();
19710
19711 return false;
19712 }
19713 case UETT_CountOf: {
19714 QualType Ty = E->getTypeOfArgument();
19715 assert(Ty->isArrayType());
19716
19717 // We don't need to worry about array element qualifiers, so getting the
19718 // unsafe array type is fine.
19719 if (const auto *CAT =
19720 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
19721 return Success(CAT->getSize(), E);
19722 }
19723
19724 assert(!Ty->isConstantSizeType());
19725
19726 // If it's a variable-length array type, we need to check whether it is a
19727 // multidimensional array. If so, we need to check the size expression of
19728 // the VLA to see if it's a constant size. If so, we can return that value.
19729 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
19730 assert(VAT);
19731 if (VAT->getElementType()->isArrayType()) {
19732 // Variable array size expression could be missing (e.g. int a[*][10]) In
19733 // that case, it can't be a constant expression.
19734 if (!VAT->getSizeExpr()) {
19735 Info.FFDiag(E->getBeginLoc());
19736 return false;
19737 }
19738
19739 std::optional<APSInt> Res =
19740 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
19741 if (Res) {
19742 // The resulting value always has type size_t, so we need to make the
19743 // returned APInt have the correct sign and bit-width.
19744 APInt Val{
19745 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
19746 Res->getZExtValue()};
19747 return Success(Val, E);
19748 }
19749 }
19750
19751 // Definitely a variable-length type, which is not an ICE.
19752 // FIXME: Better diagnostic.
19753 Info.FFDiag(E->getBeginLoc());
19754 return false;
19755 }
19756 }
19757
19758 llvm_unreachable("unknown expr/type trait");
19759}
19760
19761bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
19762 Info.Ctx.recordOffsetOfEvaluation(OOE);
19763 CharUnits Result;
19764 unsigned n = OOE->getNumComponents();
19765 if (n == 0)
19766 return Error(OOE);
19767 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
19768 for (unsigned i = 0; i != n; ++i) {
19769 OffsetOfNode ON = OOE->getComponent(i);
19770 switch (ON.getKind()) {
19771 case OffsetOfNode::Array: {
19772 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
19773 APSInt IdxResult;
19774 if (!EvaluateInteger(Idx, IdxResult, Info))
19775 return false;
19776 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
19777 if (!AT)
19778 return Error(OOE);
19779 CurrentType = AT->getElementType();
19780 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
19781 // Reject negative indices, indices too large to fit in int64_t,
19782 // and overflow in the offset computation.
19783 if (IdxResult.isNegative() || IdxResult.getActiveBits() > 63)
19784 return Error(OOE);
19785 int64_t IdxVal = IdxResult.getExtValue();
19786 int64_t ElemSize = ElementSize.getQuantity();
19787 if (IdxVal != 0 &&
19788 ElemSize > std::numeric_limits<int64_t>::max() / IdxVal)
19789 return Error(OOE, diag::note_constexpr_offsetof_overflow);
19790 int64_t Offset = IdxVal * ElemSize;
19791 if (Result.getQuantity() > std::numeric_limits<int64_t>::max() - Offset)
19792 return Error(OOE, diag::note_constexpr_offsetof_overflow);
19794 break;
19795 }
19796
19797 case OffsetOfNode::Field: {
19798 FieldDecl *MemberDecl = ON.getField();
19799 const auto *RD = CurrentType->getAsRecordDecl();
19800 if (!RD)
19801 return Error(OOE);
19802 if (RD->isInvalidDecl()) return false;
19803 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
19804 unsigned i = MemberDecl->getFieldIndex();
19805 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
19806 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
19807 CurrentType = MemberDecl->getType().getNonReferenceType();
19808 break;
19809 }
19810
19812 llvm_unreachable("dependent __builtin_offsetof");
19813
19814 case OffsetOfNode::Base: {
19815 CXXBaseSpecifier *BaseSpec = ON.getBase();
19816 if (BaseSpec->isVirtual())
19817 return Error(OOE);
19818
19819 // Find the layout of the class whose base we are looking into.
19820 const auto *RD = CurrentType->getAsCXXRecordDecl();
19821 if (!RD)
19822 return Error(OOE);
19823 if (RD->isInvalidDecl()) return false;
19824 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
19825
19826 // Find the base class itself.
19827 CurrentType = BaseSpec->getType();
19828 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
19829 if (!BaseRD)
19830 return Error(OOE);
19831
19832 // Add the offset to the base.
19833 Result += RL.getBaseClassOffset(BaseRD);
19834 break;
19835 }
19836 }
19837 }
19838 return Success(Result, OOE);
19839}
19840
19841bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
19842 switch (E->getOpcode()) {
19843 default:
19844 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
19845 // See C99 6.6p3.
19846 return Error(E);
19847 case UO_Extension:
19848 // FIXME: Should extension allow i-c-e extension expressions in its scope?
19849 // If so, we could clear the diagnostic ID.
19850 return Visit(E->getSubExpr());
19851 case UO_Plus:
19852 // The result is just the value.
19853 return Visit(E->getSubExpr());
19854 case UO_Minus: {
19855 if (!Visit(E->getSubExpr()))
19856 return false;
19857 if (!Result.isInt()) return Error(E);
19858 const APSInt &Value = Result.getInt();
19859 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
19860 !E->getType().isWrapType()) {
19861 if (Info.checkingForUndefinedBehavior())
19862 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
19863 diag::warn_integer_constant_overflow)
19864 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
19865 /*UpperCase=*/true, /*InsertSeparators=*/true)
19866 << E->getType() << E->getSourceRange();
19867
19868 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
19869 E->getType()))
19870 return false;
19871 }
19872 return Success(-Value, E);
19873 }
19874 case UO_Not: {
19875 if (!Visit(E->getSubExpr()))
19876 return false;
19877 if (!Result.isInt()) return Error(E);
19878 return Success(~Result.getInt(), E);
19879 }
19880 case UO_LNot: {
19881 bool bres;
19882 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
19883 return false;
19884 return Success(!bres, E);
19885 }
19886 }
19887}
19888
19889/// HandleCast - This is used to evaluate implicit or explicit casts where the
19890/// result type is integer.
19891bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
19892 const Expr *SubExpr = E->getSubExpr();
19893 QualType DestType = E->getType();
19894 QualType SrcType = SubExpr->getType();
19895
19896 switch (E->getCastKind()) {
19897 case CK_BaseToDerived:
19898 case CK_DerivedToBase:
19899 case CK_UncheckedDerivedToBase:
19900 case CK_Dynamic:
19901 case CK_ToUnion:
19902 case CK_ArrayToPointerDecay:
19903 case CK_FunctionToPointerDecay:
19904 case CK_NullToPointer:
19905 case CK_NullToMemberPointer:
19906 case CK_BaseToDerivedMemberPointer:
19907 case CK_DerivedToBaseMemberPointer:
19908 case CK_ReinterpretMemberPointer:
19909 case CK_ConstructorConversion:
19910 case CK_IntegralToPointer:
19911 case CK_ToVoid:
19912 case CK_VectorSplat:
19913 case CK_IntegralToFloating:
19914 case CK_FloatingCast:
19915 case CK_CPointerToObjCPointerCast:
19916 case CK_BlockPointerToObjCPointerCast:
19917 case CK_AnyPointerToBlockPointerCast:
19918 case CK_ObjCObjectLValueCast:
19919 case CK_FloatingRealToComplex:
19920 case CK_FloatingComplexToReal:
19921 case CK_FloatingComplexCast:
19922 case CK_FloatingComplexToIntegralComplex:
19923 case CK_IntegralRealToComplex:
19924 case CK_IntegralComplexCast:
19925 case CK_IntegralComplexToFloatingComplex:
19926 case CK_BuiltinFnToFnPtr:
19927 case CK_ZeroToOCLOpaqueType:
19928 case CK_NonAtomicToAtomic:
19929 case CK_AddressSpaceConversion:
19930 case CK_IntToOCLSampler:
19931 case CK_FloatingToFixedPoint:
19932 case CK_FixedPointToFloating:
19933 case CK_FixedPointCast:
19934 case CK_IntegralToFixedPoint:
19935 case CK_MatrixCast:
19936 case CK_HLSLAggregateSplatCast:
19937 llvm_unreachable("invalid cast kind for integral value");
19938
19939 case CK_BitCast:
19940 case CK_Dependent:
19941 case CK_LValueBitCast:
19942 case CK_ARCProduceObject:
19943 case CK_ARCConsumeObject:
19944 case CK_ARCReclaimReturnedObject:
19945 case CK_ARCExtendBlockObject:
19946 case CK_CopyAndAutoreleaseBlockObject:
19947 return Error(E);
19948
19949 case CK_UserDefinedConversion:
19950 case CK_LValueToRValue:
19951 case CK_AtomicToNonAtomic:
19952 case CK_NoOp:
19953 case CK_LValueToRValueBitCast:
19954 case CK_HLSLArrayRValue:
19955 return ExprEvaluatorBaseTy::VisitCastExpr(E);
19956
19957 case CK_MemberPointerToBoolean:
19958 case CK_PointerToBoolean:
19959 case CK_IntegralToBoolean:
19960 case CK_FloatingToBoolean:
19961 case CK_BooleanToSignedIntegral:
19962 case CK_FloatingComplexToBoolean:
19963 case CK_IntegralComplexToBoolean: {
19964 bool BoolResult;
19965 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
19966 return false;
19967 uint64_t IntResult = BoolResult;
19968 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
19969 IntResult = (uint64_t)-1;
19970 return Success(IntResult, E);
19971 }
19972
19973 case CK_FixedPointToIntegral: {
19974 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
19975 if (!EvaluateFixedPoint(SubExpr, Src, Info))
19976 return false;
19977 bool Overflowed;
19978 llvm::APSInt Result = Src.convertToInt(
19979 Info.Ctx.getIntWidth(DestType),
19980 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
19981 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
19982 return false;
19983 return Success(Result, E);
19984 }
19985
19986 case CK_FixedPointToBoolean: {
19987 // Unsigned padding does not affect this.
19988 APValue Val;
19989 if (!Evaluate(Val, Info, SubExpr))
19990 return false;
19991 return Success(Val.getFixedPoint().getBoolValue(), E);
19992 }
19993
19994 case CK_IntegralCast: {
19995 if (!Visit(SubExpr))
19996 return false;
19997
19998 if (!Result.isInt()) {
19999 // Allow casts of address-of-label differences if they are no-ops
20000 // or narrowing, if the result is at least 32 bits wide.
20001 // (The narrowing case isn't actually guaranteed to
20002 // be constant-evaluatable except in some narrow cases which are hard
20003 // to detect here. We let it through on the assumption the user knows
20004 // what they are doing.)
20005 if (Result.isAddrLabelDiff()) {
20006 unsigned DestBits = Info.Ctx.getTypeSize(DestType);
20007 return DestBits >= 32 && DestBits <= Info.Ctx.getTypeSize(SrcType);
20008 }
20009 // Only allow casts of lvalues if they are lossless.
20010 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
20011 }
20012
20013 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->isEnumeralType()) {
20014 const auto *ED = DestType->getAsEnumDecl();
20015 // Check that the value is within the range of the enumeration values.
20016 //
20017 // This corressponds to [expr.static.cast]p10 which says:
20018 // A value of integral or enumeration type can be explicitly converted
20019 // to a complete enumeration type ... If the enumeration type does not
20020 // have a fixed underlying type, the value is unchanged if the original
20021 // value is within the range of the enumeration values ([dcl.enum]), and
20022 // otherwise, the behavior is undefined.
20023 //
20024 // This was resolved as part of DR2338 which has CD5 status.
20025 if (!ED->isFixed()) {
20026 llvm::APInt Min;
20027 llvm::APInt Max;
20028
20029 ED->getValueRange(Max, Min);
20030 --Max;
20031
20032 if (ED->getNumNegativeBits() &&
20033 (Max.slt(Result.getInt().getSExtValue()) ||
20034 Min.sgt(Result.getInt().getSExtValue())))
20035 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
20036 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
20037 << Max.getSExtValue() << ED;
20038 else if (!ED->getNumNegativeBits() &&
20039 Max.ult(Result.getInt().getZExtValue()))
20040 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
20041 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
20042 << Max.getZExtValue() << ED;
20043 }
20044 }
20045
20046 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
20047 Result.getInt()), E);
20048 }
20049
20050 case CK_PointerToIntegral: {
20051 CCEDiag(E, diag::note_constexpr_invalid_cast)
20052 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
20053 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
20054
20055 LValue LV;
20056 if (!EvaluatePointer(SubExpr, LV, Info))
20057 return false;
20058
20059 if (LV.getLValueBase()) {
20060 // Only allow based lvalue casts if they are lossless.
20061 // FIXME: Allow a larger integer size than the pointer size, and allow
20062 // narrowing back down to pointer width in subsequent integral casts.
20063 // FIXME: Check integer type's active bits, not its type size.
20064 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
20065 return Error(E);
20066
20067 LV.Designator.setInvalid();
20068 LV.moveInto(Result);
20069 return true;
20070 }
20071
20072 APSInt AsInt;
20073 APValue V;
20074 LV.moveInto(V);
20075 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
20076 llvm_unreachable("Can't cast this!");
20077
20078 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
20079 }
20080
20081 case CK_IntegralComplexToReal: {
20082 ComplexValue C;
20083 if (!EvaluateComplex(SubExpr, C, Info))
20084 return false;
20085 return Success(C.getComplexIntReal(), E);
20086 }
20087
20088 case CK_FloatingToIntegral: {
20089 APFloat F(0.0);
20090 if (!EvaluateFloat(SubExpr, F, Info))
20091 return false;
20092
20093 APSInt Value;
20094 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
20095 return false;
20096 return Success(Value, E);
20097 }
20098 case CK_HLSLVectorTruncation: {
20099 APValue Val;
20100 if (!EvaluateVector(SubExpr, Val, Info))
20101 return Error(E);
20102 return Success(Val.getVectorElt(0), E);
20103 }
20104 case CK_HLSLMatrixTruncation: {
20105 APValue Val;
20106 if (!EvaluateMatrix(SubExpr, Val, Info))
20107 return Error(E);
20108 return Success(Val.getMatrixElt(0, 0), E);
20109 }
20110 case CK_HLSLElementwiseCast: {
20111 SmallVector<APValue> SrcVals;
20112 SmallVector<QualType> SrcTypes;
20113
20114 if (!hlslElementwiseCastHelper(Info, SubExpr, DestType, SrcVals, SrcTypes))
20115 return false;
20116
20117 // cast our single element
20118 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
20119 APValue ResultVal;
20120 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], DestType, SrcVals[0],
20121 ResultVal))
20122 return false;
20123 return Success(ResultVal, E);
20124 }
20125 }
20126
20127 llvm_unreachable("unknown cast resulting in integral value");
20128}
20129
20130bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
20131 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20132 ComplexValue LV;
20133 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
20134 return false;
20135 if (!LV.isComplexInt())
20136 return Error(E);
20137 return Success(LV.getComplexIntReal(), E);
20138 }
20139
20140 return Visit(E->getSubExpr());
20141}
20142
20143bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
20144 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
20145 ComplexValue LV;
20146 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
20147 return false;
20148 if (!LV.isComplexInt())
20149 return Error(E);
20150 return Success(LV.getComplexIntImag(), E);
20151 }
20152
20153 VisitIgnoredValue(E->getSubExpr());
20154 return Success(0, E);
20155}
20156
20157bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
20158 return Success(E->getPackLength(), E);
20159}
20160
20161bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
20162 return Success(E->getValue(), E);
20163}
20164
20165bool IntExprEvaluator::VisitConceptSpecializationExpr(
20166 const ConceptSpecializationExpr *E) {
20167 return Success(E->isSatisfied(), E);
20168}
20169
20170bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
20171 return Success(E->isSatisfied(), E);
20172}
20173
20174bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20175 switch (E->getOpcode()) {
20176 default:
20177 // Invalid unary operators
20178 return Error(E);
20179 case UO_Plus:
20180 // The result is just the value.
20181 return Visit(E->getSubExpr());
20182 case UO_Minus: {
20183 if (!Visit(E->getSubExpr())) return false;
20184 if (!Result.isFixedPoint())
20185 return Error(E);
20186 bool Overflowed;
20187 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
20188 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
20189 return false;
20190 return Success(Negated, E);
20191 }
20192 case UO_LNot: {
20193 bool bres;
20194 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
20195 return false;
20196 return Success(!bres, E);
20197 }
20198 }
20199}
20200
20201bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
20202 const Expr *SubExpr = E->getSubExpr();
20203 QualType DestType = E->getType();
20204 assert(DestType->isFixedPointType() &&
20205 "Expected destination type to be a fixed point type");
20206 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
20207
20208 switch (E->getCastKind()) {
20209 case CK_FixedPointCast: {
20210 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
20211 if (!EvaluateFixedPoint(SubExpr, Src, Info))
20212 return false;
20213 bool Overflowed;
20214 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
20215 if (Overflowed) {
20216 if (Info.checkingForUndefinedBehavior())
20217 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20218 diag::warn_fixedpoint_constant_overflow)
20219 << Result.toString() << E->getType();
20220 if (!HandleOverflow(Info, E, Result, E->getType()))
20221 return false;
20222 }
20223 return Success(Result, E);
20224 }
20225 case CK_IntegralToFixedPoint: {
20226 APSInt Src;
20227 if (!EvaluateInteger(SubExpr, Src, Info))
20228 return false;
20229
20230 bool Overflowed;
20231 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
20232 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
20233
20234 if (Overflowed) {
20235 if (Info.checkingForUndefinedBehavior())
20236 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20237 diag::warn_fixedpoint_constant_overflow)
20238 << IntResult.toString() << E->getType();
20239 if (!HandleOverflow(Info, E, IntResult, E->getType()))
20240 return false;
20241 }
20242
20243 return Success(IntResult, E);
20244 }
20245 case CK_FloatingToFixedPoint: {
20246 APFloat Src(0.0);
20247 if (!EvaluateFloat(SubExpr, Src, Info))
20248 return false;
20249
20250 bool Overflowed;
20251 APFixedPoint Result = APFixedPoint::getFromFloatValue(
20252 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
20253
20254 if (Overflowed) {
20255 if (Info.checkingForUndefinedBehavior())
20256 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20257 diag::warn_fixedpoint_constant_overflow)
20258 << Result.toString() << E->getType();
20259 if (!HandleOverflow(Info, E, Result, E->getType()))
20260 return false;
20261 }
20262
20263 return Success(Result, E);
20264 }
20265 case CK_NoOp:
20266 case CK_LValueToRValue:
20267 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20268 default:
20269 return Error(E);
20270 }
20271}
20272
20273bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20274 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20275 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20276
20277 const Expr *LHS = E->getLHS();
20278 const Expr *RHS = E->getRHS();
20279 FixedPointSemantics ResultFXSema =
20280 Info.Ctx.getFixedPointSemantics(E->getType());
20281
20282 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
20283 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
20284 return false;
20285 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
20286 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
20287 return false;
20288
20289 bool OpOverflow = false, ConversionOverflow = false;
20290 APFixedPoint Result(LHSFX.getSemantics());
20291 switch (E->getOpcode()) {
20292 case BO_Add: {
20293 Result = LHSFX.add(RHSFX, &OpOverflow)
20294 .convert(ResultFXSema, &ConversionOverflow);
20295 break;
20296 }
20297 case BO_Sub: {
20298 Result = LHSFX.sub(RHSFX, &OpOverflow)
20299 .convert(ResultFXSema, &ConversionOverflow);
20300 break;
20301 }
20302 case BO_Mul: {
20303 Result = LHSFX.mul(RHSFX, &OpOverflow)
20304 .convert(ResultFXSema, &ConversionOverflow);
20305 break;
20306 }
20307 case BO_Div: {
20308 if (RHSFX.getValue() == 0) {
20309 Info.FFDiag(E, diag::note_expr_divide_by_zero);
20310 return false;
20311 }
20312 Result = LHSFX.div(RHSFX, &OpOverflow)
20313 .convert(ResultFXSema, &ConversionOverflow);
20314 break;
20315 }
20316 case BO_Shl:
20317 case BO_Shr: {
20318 FixedPointSemantics LHSSema = LHSFX.getSemantics();
20319 llvm::APSInt RHSVal = RHSFX.getValue();
20320
20321 unsigned ShiftBW =
20322 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
20323 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
20324 // Embedded-C 4.1.6.2.2:
20325 // The right operand must be nonnegative and less than the total number
20326 // of (nonpadding) bits of the fixed-point operand ...
20327 if (RHSVal.isNegative())
20328 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
20329 else if (Amt != RHSVal)
20330 Info.CCEDiag(E, diag::note_constexpr_large_shift)
20331 << RHSVal << E->getType() << ShiftBW;
20332
20333 if (E->getOpcode() == BO_Shl)
20334 Result = LHSFX.shl(Amt, &OpOverflow);
20335 else
20336 Result = LHSFX.shr(Amt, &OpOverflow);
20337 break;
20338 }
20339 default:
20340 return false;
20341 }
20342 if (OpOverflow || ConversionOverflow) {
20343 if (Info.checkingForUndefinedBehavior())
20344 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
20345 diag::warn_fixedpoint_constant_overflow)
20346 << Result.toString() << E->getType();
20347 if (!HandleOverflow(Info, E, Result, E->getType()))
20348 return false;
20349 }
20350 return Success(Result, E);
20351}
20352
20353//===----------------------------------------------------------------------===//
20354// Float Evaluation
20355//===----------------------------------------------------------------------===//
20356
20357namespace {
20358class FloatExprEvaluator
20359 : public ExprEvaluatorBase<FloatExprEvaluator> {
20360 APFloat &Result;
20361public:
20362 FloatExprEvaluator(EvalInfo &info, APFloat &result)
20363 : ExprEvaluatorBaseTy(info), Result(result) {}
20364
20365 bool Success(const APValue &V, const Expr *e) {
20366 Result = V.getFloat();
20367 return true;
20368 }
20369
20370 bool ZeroInitialization(const Expr *E) {
20371 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
20372 return true;
20373 }
20374
20375 bool VisitCallExpr(const CallExpr *E);
20376
20377 bool VisitUnaryOperator(const UnaryOperator *E);
20378 bool VisitBinaryOperator(const BinaryOperator *E);
20379 bool VisitFloatingLiteral(const FloatingLiteral *E);
20380 bool VisitCastExpr(const CastExpr *E);
20381
20382 bool VisitUnaryReal(const UnaryOperator *E);
20383 bool VisitUnaryImag(const UnaryOperator *E);
20384
20385 // FIXME: Missing: array subscript of vector, member of vector
20386};
20387} // end anonymous namespace
20388
20389static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
20390 assert(!E->isValueDependent());
20391 assert(E->isPRValue() && E->getType()->isRealFloatingType());
20392 return FloatExprEvaluator(Info, Result).Visit(E);
20393}
20394
20395static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
20396 QualType ResultTy,
20397 const Expr *Arg,
20398 bool SNaN,
20399 llvm::APFloat &Result) {
20400 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
20401 if (!S || !S->isOrdinary())
20402 return false;
20403
20404 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
20405
20406 llvm::APInt fill;
20407
20408 // Treat empty strings as if they were zero.
20409 if (S->getString().empty())
20410 fill = llvm::APInt(32, 0);
20411 else if (S->getString().getAsInteger(0, fill))
20412 return false;
20413
20414 if (Context.getTargetInfo().isNan2008()) {
20415 if (SNaN)
20416 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
20417 else
20418 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
20419 } else {
20420 // Prior to IEEE 754-2008, architectures were allowed to choose whether
20421 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
20422 // a different encoding to what became a standard in 2008, and for pre-
20423 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
20424 // sNaN. This is now known as "legacy NaN" encoding.
20425 if (SNaN)
20426 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
20427 else
20428 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
20429 }
20430
20431 return true;
20432}
20433
20434bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
20435 if (!IsConstantEvaluatedBuiltinCall(E))
20436 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20437
20438 unsigned BuiltinOp = ConvertBuiltinIDToX86BuiltinID(Info.Ctx, E);
20439
20440 switch (BuiltinOp) {
20441 default:
20442 return false;
20443
20444 case Builtin::BI__builtin_huge_val:
20445 case Builtin::BI__builtin_huge_valf:
20446 case Builtin::BI__builtin_huge_vall:
20447 case Builtin::BI__builtin_huge_valf16:
20448 case Builtin::BI__builtin_huge_valf128:
20449 case Builtin::BI__builtin_inf:
20450 case Builtin::BI__builtin_inff:
20451 case Builtin::BI__builtin_infl:
20452 case Builtin::BI__builtin_inff16:
20453 case Builtin::BI__builtin_inff128: {
20454 const llvm::fltSemantics &Sem =
20455 Info.Ctx.getFloatTypeSemantics(E->getType());
20456 Result = llvm::APFloat::getInf(Sem);
20457 return true;
20458 }
20459
20460 case Builtin::BI__builtin_nans:
20461 case Builtin::BI__builtin_nansf:
20462 case Builtin::BI__builtin_nansl:
20463 case Builtin::BI__builtin_nansf16:
20464 case Builtin::BI__builtin_nansf128:
20465 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
20466 true, Result))
20467 return Error(E);
20468 return true;
20469
20470 case Builtin::BI__builtin_nan:
20471 case Builtin::BI__builtin_nanf:
20472 case Builtin::BI__builtin_nanl:
20473 case Builtin::BI__builtin_nanf16:
20474 case Builtin::BI__builtin_nanf128:
20475 // If this is __builtin_nan() turn this into a nan, otherwise we
20476 // can't constant fold it.
20477 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
20478 false, Result))
20479 return Error(E);
20480 return true;
20481
20482 case Builtin::BI__builtin_elementwise_abs:
20483 case Builtin::BI__builtin_fabs:
20484 case Builtin::BI__builtin_fabsf:
20485 case Builtin::BI__builtin_fabsl:
20486 case Builtin::BI__builtin_fabsf128:
20487 // The C standard says "fabs raises no floating-point exceptions,
20488 // even if x is a signaling NaN. The returned value is independent of
20489 // the current rounding direction mode." Therefore constant folding can
20490 // proceed without regard to the floating point settings.
20491 // Reference, WG14 N2478 F.10.4.3
20492 if (!EvaluateFloat(E->getArg(0), Result, Info))
20493 return false;
20494
20495 if (Result.isNegative())
20496 Result.changeSign();
20497 return true;
20498
20499 case Builtin::BI__arithmetic_fence:
20500 return EvaluateFloat(E->getArg(0), Result, Info);
20501
20502 // FIXME: Builtin::BI__builtin_powi
20503 // FIXME: Builtin::BI__builtin_powif
20504 // FIXME: Builtin::BI__builtin_powil
20505
20506 case Builtin::BI__builtin_copysign:
20507 case Builtin::BI__builtin_copysignf:
20508 case Builtin::BI__builtin_copysignl:
20509 case Builtin::BI__builtin_copysignf128: {
20510 APFloat RHS(0.);
20511 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20512 !EvaluateFloat(E->getArg(1), RHS, Info))
20513 return false;
20514 Result.copySign(RHS);
20515 return true;
20516 }
20517
20518 case Builtin::BI__builtin_fmax:
20519 case Builtin::BI__builtin_fmaxf:
20520 case Builtin::BI__builtin_fmaxl:
20521 case Builtin::BI__builtin_fmaxf16:
20522 case Builtin::BI__builtin_fmaxf128: {
20523 APFloat RHS(0.);
20524 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20525 !EvaluateFloat(E->getArg(1), RHS, Info))
20526 return false;
20527 Result = maxnum(Result, RHS);
20528 return true;
20529 }
20530
20531 case Builtin::BI__builtin_fmin:
20532 case Builtin::BI__builtin_fminf:
20533 case Builtin::BI__builtin_fminl:
20534 case Builtin::BI__builtin_fminf16:
20535 case Builtin::BI__builtin_fminf128: {
20536 APFloat RHS(0.);
20537 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20538 !EvaluateFloat(E->getArg(1), RHS, Info))
20539 return false;
20540 Result = minnum(Result, RHS);
20541 return true;
20542 }
20543
20544 case Builtin::BI__builtin_fmaximum_num:
20545 case Builtin::BI__builtin_fmaximum_numf:
20546 case Builtin::BI__builtin_fmaximum_numl:
20547 case Builtin::BI__builtin_fmaximum_numf16:
20548 case Builtin::BI__builtin_fmaximum_numf128: {
20549 APFloat RHS(0.);
20550 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20551 !EvaluateFloat(E->getArg(1), RHS, Info))
20552 return false;
20553 Result = maximumnum(Result, RHS);
20554 return true;
20555 }
20556
20557 case Builtin::BI__builtin_fminimum_num:
20558 case Builtin::BI__builtin_fminimum_numf:
20559 case Builtin::BI__builtin_fminimum_numl:
20560 case Builtin::BI__builtin_fminimum_numf16:
20561 case Builtin::BI__builtin_fminimum_numf128: {
20562 APFloat RHS(0.);
20563 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20564 !EvaluateFloat(E->getArg(1), RHS, Info))
20565 return false;
20566 Result = minimumnum(Result, RHS);
20567 return true;
20568 }
20569
20570 case Builtin::BI__builtin_elementwise_fma: {
20571 if (!E->getArg(0)->isPRValue() || !E->getArg(1)->isPRValue() ||
20572 !E->getArg(2)->isPRValue()) {
20573 return false;
20574 }
20575 APFloat SourceY(0.), SourceZ(0.);
20576 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
20577 !EvaluateFloat(E->getArg(1), SourceY, Info) ||
20578 !EvaluateFloat(E->getArg(2), SourceZ, Info))
20579 return false;
20580 llvm::RoundingMode RM = getActiveRoundingMode(getEvalInfo(), E);
20581 (void)Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
20582 return true;
20583 }
20584
20585 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
20586 APValue Vec;
20587 APSInt IdxAPS;
20588 if (!EvaluateVector(E->getArg(0), Vec, Info) ||
20589 !EvaluateInteger(E->getArg(1), IdxAPS, Info))
20590 return false;
20591 unsigned N = Vec.getVectorLength();
20592 unsigned Idx = static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
20593 return Success(Vec.getVectorElt(Idx), E);
20594 }
20595 }
20596}
20597
20598bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
20599 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20600 ComplexValue CV;
20601 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
20602 return false;
20603 Result = CV.FloatReal;
20604 return true;
20605 }
20606
20607 return Visit(E->getSubExpr());
20608}
20609
20610bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
20611 if (E->getSubExpr()->getType()->isAnyComplexType()) {
20612 ComplexValue CV;
20613 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
20614 return false;
20615 Result = CV.FloatImag;
20616 return true;
20617 }
20618
20619 VisitIgnoredValue(E->getSubExpr());
20620 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
20621 Result = llvm::APFloat::getZero(Sem);
20622 return true;
20623}
20624
20625bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
20626 switch (E->getOpcode()) {
20627 default: return Error(E);
20628 case UO_Plus:
20629 return EvaluateFloat(E->getSubExpr(), Result, Info);
20630 case UO_Minus:
20631 // In C standard, WG14 N2478 F.3 p4
20632 // "the unary - raises no floating point exceptions,
20633 // even if the operand is signalling."
20634 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
20635 return false;
20636 Result.changeSign();
20637 return true;
20638 }
20639}
20640
20641bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
20642 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
20643 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20644
20645 APFloat RHS(0.0);
20646 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
20647 if (!LHSOK && !Info.noteFailure())
20648 return false;
20649 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
20650 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
20651}
20652
20653bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
20654 Result = E->getValue();
20655 return true;
20656}
20657
20658bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
20659 const Expr* SubExpr = E->getSubExpr();
20660
20661 switch (E->getCastKind()) {
20662 default:
20663 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20664
20665 case CK_HLSLAggregateSplatCast:
20666 llvm_unreachable("invalid cast kind for floating value");
20667
20668 case CK_IntegralToFloating: {
20669 APSInt IntResult;
20670 const FPOptions FPO = E->getFPFeaturesInEffect(
20671 Info.Ctx.getLangOpts());
20672 return EvaluateInteger(SubExpr, IntResult, Info) &&
20673 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
20674 IntResult, E->getType(), Result);
20675 }
20676
20677 case CK_FixedPointToFloating: {
20678 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
20679 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
20680 return false;
20681 Result =
20682 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
20683 return true;
20684 }
20685
20686 case CK_FloatingCast: {
20687 if (!Visit(SubExpr))
20688 return false;
20689 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
20690 Result);
20691 }
20692
20693 case CK_FloatingComplexToReal: {
20694 ComplexValue V;
20695 if (!EvaluateComplex(SubExpr, V, Info))
20696 return false;
20697 Result = V.getComplexFloatReal();
20698 return true;
20699 }
20700 case CK_HLSLVectorTruncation: {
20701 APValue Val;
20702 if (!EvaluateVector(SubExpr, Val, Info))
20703 return Error(E);
20704 return Success(Val.getVectorElt(0), E);
20705 }
20706 case CK_HLSLMatrixTruncation: {
20707 APValue Val;
20708 if (!EvaluateMatrix(SubExpr, Val, Info))
20709 return Error(E);
20710 return Success(Val.getMatrixElt(0, 0), E);
20711 }
20712 case CK_HLSLElementwiseCast: {
20713 SmallVector<APValue> SrcVals;
20714 SmallVector<QualType> SrcTypes;
20715
20716 if (!hlslElementwiseCastHelper(Info, SubExpr, E->getType(), SrcVals,
20717 SrcTypes))
20718 return false;
20719 APValue Val;
20720
20721 // cast our single element
20722 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
20723 APValue ResultVal;
20724 if (!handleScalarCast(Info, FPO, E, SrcTypes[0], E->getType(), SrcVals[0],
20725 ResultVal))
20726 return false;
20727 return Success(ResultVal, E);
20728 }
20729 }
20730}
20731
20732//===----------------------------------------------------------------------===//
20733// Complex Evaluation (for float and integer)
20734//===----------------------------------------------------------------------===//
20735
20736namespace {
20737class ComplexExprEvaluator
20738 : public ExprEvaluatorBase<ComplexExprEvaluator> {
20739 ComplexValue &Result;
20740
20741public:
20742 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
20743 : ExprEvaluatorBaseTy(info), Result(Result) {}
20744
20745 bool Success(const APValue &V, const Expr *e) {
20746 Result.setFrom(V);
20747 return true;
20748 }
20749
20750 bool ZeroInitialization(const Expr *E);
20751
20752 //===--------------------------------------------------------------------===//
20753 // Visitor Methods
20754 //===--------------------------------------------------------------------===//
20755
20756 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
20757 bool VisitCastExpr(const CastExpr *E);
20758 bool VisitBinaryOperator(const BinaryOperator *E);
20759 bool VisitUnaryOperator(const UnaryOperator *E);
20760 bool VisitInitListExpr(const InitListExpr *E);
20761 bool VisitCallExpr(const CallExpr *E);
20762};
20763} // end anonymous namespace
20764
20765static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
20766 EvalInfo &Info) {
20767 assert(!E->isValueDependent());
20768 assert(E->isPRValue() && E->getType()->isAnyComplexType());
20769 return ComplexExprEvaluator(Info, Result).Visit(E);
20770}
20771
20772bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
20773 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
20774 if (ElemTy->isRealFloatingType()) {
20775 Result.makeComplexFloat();
20776 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
20777 Result.FloatReal = Zero;
20778 Result.FloatImag = Zero;
20779 } else {
20780 Result.makeComplexInt();
20781 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
20782 Result.IntReal = Zero;
20783 Result.IntImag = Zero;
20784 }
20785 return true;
20786}
20787
20788bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
20789 const Expr* SubExpr = E->getSubExpr();
20790
20791 if (SubExpr->getType()->isRealFloatingType()) {
20792 Result.makeComplexFloat();
20793 APFloat &Imag = Result.FloatImag;
20794 if (!EvaluateFloat(SubExpr, Imag, Info))
20795 return false;
20796
20797 Result.FloatReal = APFloat(Imag.getSemantics());
20798 return true;
20799 } else {
20800 assert(SubExpr->getType()->isIntegerType() &&
20801 "Unexpected imaginary literal.");
20802
20803 Result.makeComplexInt();
20804 APSInt &Imag = Result.IntImag;
20805 if (!EvaluateInteger(SubExpr, Imag, Info))
20806 return false;
20807
20808 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
20809 return true;
20810 }
20811}
20812
20813bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
20814
20815 switch (E->getCastKind()) {
20816 case CK_BitCast:
20817 case CK_BaseToDerived:
20818 case CK_DerivedToBase:
20819 case CK_UncheckedDerivedToBase:
20820 case CK_Dynamic:
20821 case CK_ToUnion:
20822 case CK_ArrayToPointerDecay:
20823 case CK_FunctionToPointerDecay:
20824 case CK_NullToPointer:
20825 case CK_NullToMemberPointer:
20826 case CK_BaseToDerivedMemberPointer:
20827 case CK_DerivedToBaseMemberPointer:
20828 case CK_MemberPointerToBoolean:
20829 case CK_ReinterpretMemberPointer:
20830 case CK_ConstructorConversion:
20831 case CK_IntegralToPointer:
20832 case CK_PointerToIntegral:
20833 case CK_PointerToBoolean:
20834 case CK_ToVoid:
20835 case CK_VectorSplat:
20836 case CK_IntegralCast:
20837 case CK_BooleanToSignedIntegral:
20838 case CK_IntegralToBoolean:
20839 case CK_IntegralToFloating:
20840 case CK_FloatingToIntegral:
20841 case CK_FloatingToBoolean:
20842 case CK_FloatingCast:
20843 case CK_CPointerToObjCPointerCast:
20844 case CK_BlockPointerToObjCPointerCast:
20845 case CK_AnyPointerToBlockPointerCast:
20846 case CK_ObjCObjectLValueCast:
20847 case CK_FloatingComplexToReal:
20848 case CK_FloatingComplexToBoolean:
20849 case CK_IntegralComplexToReal:
20850 case CK_IntegralComplexToBoolean:
20851 case CK_ARCProduceObject:
20852 case CK_ARCConsumeObject:
20853 case CK_ARCReclaimReturnedObject:
20854 case CK_ARCExtendBlockObject:
20855 case CK_CopyAndAutoreleaseBlockObject:
20856 case CK_BuiltinFnToFnPtr:
20857 case CK_ZeroToOCLOpaqueType:
20858 case CK_NonAtomicToAtomic:
20859 case CK_AddressSpaceConversion:
20860 case CK_IntToOCLSampler:
20861 case CK_FloatingToFixedPoint:
20862 case CK_FixedPointToFloating:
20863 case CK_FixedPointCast:
20864 case CK_FixedPointToBoolean:
20865 case CK_FixedPointToIntegral:
20866 case CK_IntegralToFixedPoint:
20867 case CK_MatrixCast:
20868 case CK_HLSLVectorTruncation:
20869 case CK_HLSLMatrixTruncation:
20870 case CK_HLSLElementwiseCast:
20871 case CK_HLSLAggregateSplatCast:
20872 llvm_unreachable("invalid cast kind for complex value");
20873
20874 case CK_LValueToRValue:
20875 case CK_AtomicToNonAtomic:
20876 case CK_NoOp:
20877 case CK_LValueToRValueBitCast:
20878 case CK_HLSLArrayRValue:
20879 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20880
20881 case CK_Dependent:
20882 case CK_LValueBitCast:
20883 case CK_UserDefinedConversion:
20884 return Error(E);
20885
20886 case CK_FloatingRealToComplex: {
20887 APFloat &Real = Result.FloatReal;
20888 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
20889 return false;
20890
20891 Result.makeComplexFloat();
20892 Result.FloatImag = APFloat(Real.getSemantics());
20893 return true;
20894 }
20895
20896 case CK_FloatingComplexCast: {
20897 if (!Visit(E->getSubExpr()))
20898 return false;
20899
20900 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20901 QualType From
20902 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20903
20904 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
20905 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
20906 }
20907
20908 case CK_FloatingComplexToIntegralComplex: {
20909 if (!Visit(E->getSubExpr()))
20910 return false;
20911
20912 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20913 QualType From
20914 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20915 Result.makeComplexInt();
20916 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
20917 To, Result.IntReal) &&
20918 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
20919 To, Result.IntImag);
20920 }
20921
20922 case CK_IntegralRealToComplex: {
20923 APSInt &Real = Result.IntReal;
20924 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
20925 return false;
20926
20927 Result.makeComplexInt();
20928 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
20929 return true;
20930 }
20931
20932 case CK_IntegralComplexCast: {
20933 if (!Visit(E->getSubExpr()))
20934 return false;
20935
20936 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20937 QualType From
20938 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20939
20940 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
20941 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
20942 return true;
20943 }
20944
20945 case CK_IntegralComplexToFloatingComplex: {
20946 if (!Visit(E->getSubExpr()))
20947 return false;
20948
20949 const FPOptions FPO = E->getFPFeaturesInEffect(
20950 Info.Ctx.getLangOpts());
20951 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
20952 QualType From
20953 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
20954 Result.makeComplexFloat();
20955 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
20956 To, Result.FloatReal) &&
20957 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
20958 To, Result.FloatImag);
20959 }
20960 }
20961
20962 llvm_unreachable("unknown cast resulting in complex value");
20963}
20964
20966 // Lookup Table for Multiplicative Inverse in GF(2^8)
20967 const uint8_t GFInv[256] = {
20968 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0,
20969 0xb0, 0xe1, 0xe5, 0xc7, 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f,
20970 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2, 0x3a, 0x6e, 0x5a, 0xf1,
20971 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,
20972 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f,
20973 0x77, 0xbb, 0x59, 0x19, 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69,
20974 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09, 0xed, 0x5c, 0x05, 0xca,
20975 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,
20976 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf,
20977 0x33, 0x93, 0x21, 0x3b, 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c,
20978 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82, 0x83, 0x7e, 0x7f, 0x80,
20979 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,
20980 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88,
20981 0xf9, 0xdc, 0x89, 0x9a, 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48,
20982 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62, 0x0c, 0xe0, 0x1f, 0xef,
20983 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,
20984 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04,
20985 0x1b, 0xfc, 0xac, 0xe6, 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea,
20986 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b, 0xb1, 0x0d, 0xd6, 0xeb,
20987 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,
20988 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0,
20989 0xcd, 0x1a, 0x41, 0x1c};
20990
20991 return GFInv[Byte];
20992}
20993
20994uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm,
20995 bool Inverse) {
20996 unsigned NumBitsInByte = 8;
20997 // Computing the affine transformation
20998 uint8_t RetByte = 0;
20999 for (uint32_t BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
21000 uint8_t AByte =
21001 AQword.lshr((7 - static_cast<int32_t>(BitIdx)) * NumBitsInByte)
21002 .getLoBits(8)
21003 .getZExtValue();
21004 uint8_t Product;
21005 if (Inverse) {
21006 Product = AByte & GFNIMultiplicativeInverse(XByte);
21007 } else {
21008 Product = AByte & XByte;
21009 }
21010 uint8_t Parity = 0;
21011
21012 // Dot product in GF(2) uses XOR instead of addition
21013 for (unsigned PBitIdx = 0; PBitIdx != NumBitsInByte; ++PBitIdx) {
21014 Parity = Parity ^ ((Product >> PBitIdx) & 0x1);
21015 }
21016
21017 uint8_t Temp = Imm[BitIdx] ? 1 : 0;
21018 RetByte |= (Temp ^ Parity) << BitIdx;
21019 }
21020 return RetByte;
21021}
21022
21024 // Multiplying two polynomials of degree 7
21025 // Polynomial of degree 7
21026 // x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
21027 uint16_t TWord = 0;
21028 unsigned NumBitsInByte = 8;
21029 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
21030 if ((BByte >> BitIdx) & 0x1) {
21031 TWord = TWord ^ (AByte << BitIdx);
21032 }
21033 }
21034
21035 // When multiplying two polynomials of degree 7
21036 // results in a polynomial of degree 14
21037 // so the result has to be reduced to 7
21038 // Reduction polynomial is x^8 + x^4 + x^3 + x + 1 i.e. 0x11B
21039 for (int32_t BitIdx = 14; BitIdx > 7; --BitIdx) {
21040 if ((TWord >> BitIdx) & 0x1) {
21041 TWord = TWord ^ (0x11B << (BitIdx - 8));
21042 }
21043 }
21044 return (TWord & 0xFF);
21045}
21046
21047void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
21048 APFloat &ResR, APFloat &ResI) {
21049 // This is an implementation of complex multiplication according to the
21050 // constraints laid out in C11 Annex G. The implementation uses the
21051 // following naming scheme:
21052 // (a + ib) * (c + id)
21053
21054 APFloat AC = A * C;
21055 APFloat BD = B * D;
21056 APFloat AD = A * D;
21057 APFloat BC = B * C;
21058 ResR = AC - BD;
21059 ResI = AD + BC;
21060 if (ResR.isNaN() && ResI.isNaN()) {
21061 bool Recalc = false;
21062 if (A.isInfinity() || B.isInfinity()) {
21063 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
21064 A);
21065 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
21066 B);
21067 if (C.isNaN())
21068 C = APFloat::copySign(APFloat(C.getSemantics()), C);
21069 if (D.isNaN())
21070 D = APFloat::copySign(APFloat(D.getSemantics()), D);
21071 Recalc = true;
21072 }
21073 if (C.isInfinity() || D.isInfinity()) {
21074 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
21075 C);
21076 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
21077 D);
21078 if (A.isNaN())
21079 A = APFloat::copySign(APFloat(A.getSemantics()), A);
21080 if (B.isNaN())
21081 B = APFloat::copySign(APFloat(B.getSemantics()), B);
21082 Recalc = true;
21083 }
21084 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
21085 BC.isInfinity())) {
21086 if (A.isNaN())
21087 A = APFloat::copySign(APFloat(A.getSemantics()), A);
21088 if (B.isNaN())
21089 B = APFloat::copySign(APFloat(B.getSemantics()), B);
21090 if (C.isNaN())
21091 C = APFloat::copySign(APFloat(C.getSemantics()), C);
21092 if (D.isNaN())
21093 D = APFloat::copySign(APFloat(D.getSemantics()), D);
21094 Recalc = true;
21095 }
21096 if (Recalc) {
21097 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
21098 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
21099 }
21100 }
21101}
21102
21103void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
21104 APFloat &ResR, APFloat &ResI) {
21105 // This is an implementation of complex division according to the
21106 // constraints laid out in C11 Annex G. The implementation uses the
21107 // following naming scheme:
21108 // (a + ib) / (c + id)
21109
21110 int DenomLogB = 0;
21111 APFloat MaxCD = maxnum(abs(C), abs(D));
21112 if (MaxCD.isFinite()) {
21113 DenomLogB = ilogb(MaxCD);
21114 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
21115 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
21116 }
21117 APFloat Denom = C * C + D * D;
21118 ResR =
21119 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
21120 ResI =
21121 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
21122 if (ResR.isNaN() && ResI.isNaN()) {
21123 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
21124 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
21125 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
21126 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
21127 D.isFinite()) {
21128 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
21129 A);
21130 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
21131 B);
21132 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
21133 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
21134 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
21135 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
21136 C);
21137 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
21138 D);
21139 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
21140 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
21141 }
21142 }
21143}
21144
21146 // Normalize shift amount to [0, BitWidth) range to match runtime behavior
21147 APSInt NormAmt = Amount;
21148 unsigned BitWidth = Value.getBitWidth();
21149 unsigned AmtBitWidth = NormAmt.getBitWidth();
21150 if (BitWidth == 1) {
21151 // Rotating a 1-bit value is always a no-op
21152 NormAmt = APSInt(APInt(AmtBitWidth, 0), NormAmt.isUnsigned());
21153 } else if (BitWidth == 2) {
21154 // For 2-bit values: rotation amount is 0 or 1 based on
21155 // whether the amount is even or odd. We can't use srem here because
21156 // the divisor (2) would be misinterpreted as -2 in 2-bit signed arithmetic.
21157 NormAmt =
21158 APSInt(APInt(AmtBitWidth, NormAmt[0] ? 1 : 0), NormAmt.isUnsigned());
21159 } else {
21160 APInt Divisor;
21161 if (AmtBitWidth > BitWidth) {
21162 Divisor = llvm::APInt(AmtBitWidth, BitWidth);
21163 } else {
21164 Divisor = llvm::APInt(BitWidth, BitWidth);
21165 if (AmtBitWidth < BitWidth) {
21166 NormAmt = NormAmt.extend(BitWidth);
21167 }
21168 }
21169
21170 // Normalize to [0, BitWidth)
21171 if (NormAmt.isSigned()) {
21172 NormAmt = APSInt(NormAmt.srem(Divisor), /*isUnsigned=*/false);
21173 if (NormAmt.isNegative()) {
21174 APSInt SignedDivisor(Divisor, /*isUnsigned=*/false);
21175 NormAmt += SignedDivisor;
21176 }
21177 } else {
21178 NormAmt = APSInt(NormAmt.urem(Divisor), /*isUnsigned=*/true);
21179 }
21180 }
21181
21182 return NormAmt;
21183}
21184
21185bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
21186 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
21187 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
21188
21189 // Track whether the LHS or RHS is real at the type system level. When this is
21190 // the case we can simplify our evaluation strategy.
21191 bool LHSReal = false, RHSReal = false;
21192
21193 bool LHSOK;
21194 if (E->getLHS()->getType()->isRealFloatingType()) {
21195 LHSReal = true;
21196 APFloat &Real = Result.FloatReal;
21197 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
21198 if (LHSOK) {
21199 Result.makeComplexFloat();
21200 Result.FloatImag = APFloat(Real.getSemantics());
21201 }
21202 } else {
21203 LHSOK = Visit(E->getLHS());
21204 }
21205 if (!LHSOK && !Info.noteFailure())
21206 return false;
21207
21208 ComplexValue RHS;
21209 if (E->getRHS()->getType()->isRealFloatingType()) {
21210 RHSReal = true;
21211 APFloat &Real = RHS.FloatReal;
21212 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
21213 return false;
21214 RHS.makeComplexFloat();
21215 RHS.FloatImag = APFloat(Real.getSemantics());
21216 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
21217 return false;
21218
21219 assert(!(LHSReal && RHSReal) &&
21220 "Cannot have both operands of a complex operation be real.");
21221 switch (E->getOpcode()) {
21222 default: return Error(E);
21223 case BO_Add:
21224 if (Result.isComplexFloat()) {
21225 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
21226 APFloat::rmNearestTiesToEven);
21227 if (LHSReal)
21228 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
21229 else if (!RHSReal)
21230 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
21231 APFloat::rmNearestTiesToEven);
21232 } else {
21233 Result.getComplexIntReal() += RHS.getComplexIntReal();
21234 Result.getComplexIntImag() += RHS.getComplexIntImag();
21235 }
21236 break;
21237 case BO_Sub:
21238 if (Result.isComplexFloat()) {
21239 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
21240 APFloat::rmNearestTiesToEven);
21241 if (LHSReal) {
21242 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
21243 Result.getComplexFloatImag().changeSign();
21244 } else if (!RHSReal) {
21245 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
21246 APFloat::rmNearestTiesToEven);
21247 }
21248 } else {
21249 Result.getComplexIntReal() -= RHS.getComplexIntReal();
21250 Result.getComplexIntImag() -= RHS.getComplexIntImag();
21251 }
21252 break;
21253 case BO_Mul:
21254 if (Result.isComplexFloat()) {
21255 // This is an implementation of complex multiplication according to the
21256 // constraints laid out in C11 Annex G. The implementation uses the
21257 // following naming scheme:
21258 // (a + ib) * (c + id)
21259 ComplexValue LHS = Result;
21260 APFloat &A = LHS.getComplexFloatReal();
21261 APFloat &B = LHS.getComplexFloatImag();
21262 APFloat &C = RHS.getComplexFloatReal();
21263 APFloat &D = RHS.getComplexFloatImag();
21264 APFloat &ResR = Result.getComplexFloatReal();
21265 APFloat &ResI = Result.getComplexFloatImag();
21266 if (LHSReal) {
21267 assert(!RHSReal && "Cannot have two real operands for a complex op!");
21268 ResR = A;
21269 ResI = A;
21270 // ResR = A * C;
21271 // ResI = A * D;
21272 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
21273 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
21274 return false;
21275 } else if (RHSReal) {
21276 // ResR = C * A;
21277 // ResI = C * B;
21278 ResR = C;
21279 ResI = C;
21280 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
21281 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
21282 return false;
21283 } else {
21284 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
21285 }
21286 } else {
21287 ComplexValue LHS = Result;
21288 Result.getComplexIntReal() =
21289 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
21290 LHS.getComplexIntImag() * RHS.getComplexIntImag());
21291 Result.getComplexIntImag() =
21292 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
21293 LHS.getComplexIntImag() * RHS.getComplexIntReal());
21294 }
21295 break;
21296 case BO_Div:
21297 if (Result.isComplexFloat()) {
21298 // This is an implementation of complex division according to the
21299 // constraints laid out in C11 Annex G. The implementation uses the
21300 // following naming scheme:
21301 // (a + ib) / (c + id)
21302 ComplexValue LHS = Result;
21303 APFloat &A = LHS.getComplexFloatReal();
21304 APFloat &B = LHS.getComplexFloatImag();
21305 APFloat &C = RHS.getComplexFloatReal();
21306 APFloat &D = RHS.getComplexFloatImag();
21307 APFloat &ResR = Result.getComplexFloatReal();
21308 APFloat &ResI = Result.getComplexFloatImag();
21309 if (RHSReal) {
21310 ResR = A;
21311 ResI = B;
21312 // ResR = A / C;
21313 // ResI = B / C;
21314 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
21315 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
21316 return false;
21317 } else {
21318 if (LHSReal) {
21319 // No real optimizations we can do here, stub out with zero.
21320 B = APFloat::getZero(A.getSemantics());
21321 }
21322 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
21323 }
21324 } else {
21325 ComplexValue LHS = Result;
21326 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
21327 RHS.getComplexIntImag() * RHS.getComplexIntImag();
21328 if (Den.isZero())
21329 return Error(E, diag::note_expr_divide_by_zero);
21330
21331 Result.getComplexIntReal() =
21332 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
21333 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
21334 Result.getComplexIntImag() =
21335 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
21336 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
21337 }
21338 break;
21339 }
21340
21341 return true;
21342}
21343
21344bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
21345 // Get the operand value into 'Result'.
21346 if (!Visit(E->getSubExpr()))
21347 return false;
21348
21349 switch (E->getOpcode()) {
21350 default:
21351 return Error(E);
21352 case UO_Extension:
21353 return true;
21354 case UO_Plus:
21355 // The result is always just the subexpr.
21356 return true;
21357 case UO_Minus:
21358 if (Result.isComplexFloat()) {
21359 Result.getComplexFloatReal().changeSign();
21360 Result.getComplexFloatImag().changeSign();
21361 }
21362 else {
21363 Result.getComplexIntReal() = -Result.getComplexIntReal();
21364 Result.getComplexIntImag() = -Result.getComplexIntImag();
21365 }
21366 return true;
21367 case UO_Not:
21368 if (Result.isComplexFloat())
21369 Result.getComplexFloatImag().changeSign();
21370 else
21371 Result.getComplexIntImag() = -Result.getComplexIntImag();
21372 return true;
21373 }
21374}
21375
21376bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
21377 if (E->getNumInits() == 2) {
21378 if (E->getType()->isComplexType()) {
21379 Result.makeComplexFloat();
21380 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
21381 return false;
21382 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
21383 return false;
21384 } else {
21385 Result.makeComplexInt();
21386 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
21387 return false;
21388 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
21389 return false;
21390 }
21391 return true;
21392 }
21393 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
21394}
21395
21396bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
21397 if (!IsConstantEvaluatedBuiltinCall(E))
21398 return ExprEvaluatorBaseTy::VisitCallExpr(E);
21399
21400 switch (E->getBuiltinCallee()) {
21401 case Builtin::BI__builtin_complex:
21402 Result.makeComplexFloat();
21403 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
21404 return false;
21405 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
21406 return false;
21407 return true;
21408
21409 default:
21410 return false;
21411 }
21412}
21413
21414//===----------------------------------------------------------------------===//
21415// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
21416// implicit conversion.
21417//===----------------------------------------------------------------------===//
21418
21419namespace {
21420class AtomicExprEvaluator :
21421 public ExprEvaluatorBase<AtomicExprEvaluator> {
21422 const LValue *This;
21423 APValue &Result;
21424public:
21425 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
21426 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
21427
21428 bool Success(const APValue &V, const Expr *E) {
21429 Result = V;
21430 return true;
21431 }
21432
21433 bool ZeroInitialization(const Expr *E) {
21434 ImplicitValueInitExpr VIE(
21435 E->getType()->castAs<AtomicType>()->getValueType());
21436 // For atomic-qualified class (and array) types in C++, initialize the
21437 // _Atomic-wrapped subobject directly, in-place.
21438 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
21439 : Evaluate(Result, Info, &VIE);
21440 }
21441
21442 bool VisitCastExpr(const CastExpr *E) {
21443 switch (E->getCastKind()) {
21444 default:
21445 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21446 case CK_NullToPointer:
21447 VisitIgnoredValue(E->getSubExpr());
21448 return ZeroInitialization(E);
21449 case CK_NonAtomicToAtomic:
21450 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
21451 : Evaluate(Result, Info, E->getSubExpr());
21452 }
21453 }
21454};
21455} // end anonymous namespace
21456
21457static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
21458 EvalInfo &Info) {
21459 assert(!E->isValueDependent());
21460 assert(E->isPRValue() && E->getType()->isAtomicType());
21461 return AtomicExprEvaluator(Info, This, Result).Visit(E);
21462}
21463
21464//===----------------------------------------------------------------------===//
21465// Void expression evaluation, primarily for a cast to void on the LHS of a
21466// comma operator
21467//===----------------------------------------------------------------------===//
21468
21469namespace {
21470class VoidExprEvaluator
21471 : public ExprEvaluatorBase<VoidExprEvaluator> {
21472public:
21473 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
21474
21475 bool Success(const APValue &V, const Expr *e) { return true; }
21476
21477 bool ZeroInitialization(const Expr *E) { return true; }
21478
21479 bool VisitCastExpr(const CastExpr *E) {
21480 switch (E->getCastKind()) {
21481 default:
21482 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21483 case CK_ToVoid:
21484 VisitIgnoredValue(E->getSubExpr());
21485 return true;
21486 }
21487 }
21488
21489 bool VisitCallExpr(const CallExpr *E) {
21490 if (!IsConstantEvaluatedBuiltinCall(E))
21491 return ExprEvaluatorBaseTy::VisitCallExpr(E);
21492
21493 switch (E->getBuiltinCallee()) {
21494 case Builtin::BI__assume:
21495 case Builtin::BI__builtin_assume:
21496 // The argument is not evaluated!
21497 return true;
21498
21499 case Builtin::BI__builtin_operator_delete:
21500 return HandleOperatorDeleteCall(Info, E);
21501
21502 default:
21503 return false;
21504 }
21505 }
21506
21507 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
21508};
21509} // end anonymous namespace
21510
21511bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
21512 // We cannot speculatively evaluate a delete expression.
21513 if (Info.SpeculativeEvaluationDepth)
21514 return false;
21515
21516 FunctionDecl *OperatorDelete = E->getOperatorDelete();
21517 if (!OperatorDelete
21518 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
21519 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
21520 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
21521 return false;
21522 }
21523
21524 const Expr *Arg = E->getArgument();
21525
21526 LValue Pointer;
21527 if (!EvaluatePointer(Arg, Pointer, Info))
21528 return false;
21529 if (Pointer.Designator.Invalid)
21530 return false;
21531
21532 // Deleting a null pointer has no effect.
21533 if (Pointer.isNullPointer()) {
21534 // This is the only case where we need to produce an extension warning:
21535 // the only other way we can succeed is if we find a dynamic allocation,
21536 // and we will have warned when we allocated it in that case.
21537 if (!Info.getLangOpts().CPlusPlus20)
21538 Info.CCEDiag(E, diag::note_constexpr_new);
21539 return true;
21540 }
21541
21542 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
21543 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
21544 if (!Alloc)
21545 return false;
21546 QualType AllocType = Pointer.Base.getDynamicAllocType();
21547
21548 // For the non-array case, the designator must be empty if the static type
21549 // does not have a virtual destructor.
21550 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
21552 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
21553 << Arg->getType()->getPointeeType() << AllocType;
21554 return false;
21555 }
21556
21557 // For a class type with a virtual destructor, the selected operator delete
21558 // is the one looked up when building the destructor.
21559 if (!E->isArrayForm() && !E->isGlobalDelete()) {
21560 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
21561 if (VirtualDelete &&
21562 !VirtualDelete
21563 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
21564 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
21565 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
21566 return false;
21567 }
21568 }
21569
21570 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
21571 (*Alloc)->Value, AllocType))
21572 return false;
21573
21574 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
21575 // The element was already erased. This means the destructor call also
21576 // deleted the object.
21577 // FIXME: This probably results in undefined behavior before we get this
21578 // far, and should be diagnosed elsewhere first.
21579 Info.FFDiag(E, diag::note_constexpr_double_delete);
21580 return false;
21581 }
21582
21583 return true;
21584}
21585
21586static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
21587 assert(!E->isValueDependent());
21588 assert(E->isPRValue() && E->getType()->isVoidType());
21589 return VoidExprEvaluator(Info).Visit(E);
21590}
21591
21592//===----------------------------------------------------------------------===//
21593// Top level Expr::EvaluateAsRValue method.
21594//===----------------------------------------------------------------------===//
21595
21596static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
21597 assert(!E->isValueDependent());
21598 // In C, function designators are not lvalues, but we evaluate them as if they
21599 // are.
21600 QualType T = E->getType();
21601 if (E->isGLValue() || T->isFunctionType()) {
21602 LValue LV;
21603 if (!EvaluateLValue(E, LV, Info))
21604 return false;
21605 LV.moveInto(Result);
21606 } else if (T->isVectorType()) {
21607 if (!EvaluateVector(E, Result, Info))
21608 return false;
21609 } else if (T->isConstantMatrixType()) {
21610 if (!EvaluateMatrix(E, Result, Info))
21611 return false;
21612 } else if (T->isIntegralOrEnumerationType()) {
21613 if (!IntExprEvaluator(Info, Result).Visit(E))
21614 return false;
21615 } else if (T->hasPointerRepresentation()) {
21616 LValue LV;
21617 if (!EvaluatePointer(E, LV, Info))
21618 return false;
21619 LV.moveInto(Result);
21620 } else if (T->isRealFloatingType()) {
21621 llvm::APFloat F(0.0);
21622 if (!EvaluateFloat(E, F, Info))
21623 return false;
21624 Result = APValue(F);
21625 } else if (T->isAnyComplexType()) {
21626 ComplexValue C;
21627 if (!EvaluateComplex(E, C, Info))
21628 return false;
21629 C.moveInto(Result);
21630 } else if (T->isFixedPointType()) {
21631 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
21632 } else if (T->isMemberPointerType()) {
21633 MemberPtr P;
21634 if (!EvaluateMemberPointer(E, P, Info))
21635 return false;
21636 P.moveInto(Result);
21637 return true;
21638 } else if (T->isArrayType()) {
21639 LValue LV;
21640 APValue &Value =
21641 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
21642 if (!EvaluateArray(E, LV, Value, Info))
21643 return false;
21644 Result = Value;
21645 } else if (T->isRecordType()) {
21646 LValue LV;
21647 APValue &Value =
21648 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
21649 if (!EvaluateRecord(E, LV, Value, Info))
21650 return false;
21651 Result = Value;
21652 } else if (T->isVoidType()) {
21653 if (!Info.getLangOpts().CPlusPlus11)
21654 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
21655 << E->getType();
21656 if (!EvaluateVoid(E, Info))
21657 return false;
21658 } else if (T->isAtomicType()) {
21659 QualType Unqual = T.getAtomicUnqualifiedType();
21660 if (Unqual->isArrayType() || Unqual->isRecordType()) {
21661 LValue LV;
21662 APValue &Value = Info.CurrentCall->createTemporary(
21663 E, Unqual, ScopeKind::FullExpression, LV);
21664 if (!EvaluateAtomic(E, &LV, Value, Info))
21665 return false;
21666 Result = Value;
21667 } else {
21668 if (!EvaluateAtomic(E, nullptr, Result, Info))
21669 return false;
21670 }
21671 } else if (Info.getLangOpts().CPlusPlus11) {
21672 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
21673 return false;
21674 } else {
21675 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
21676 return false;
21677 }
21678
21679 return true;
21680}
21681
21682/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
21683/// cases, the in-place evaluation is essential, since later initializers for
21684/// an object can indirectly refer to subobjects which were initialized earlier.
21685static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
21686 const Expr *E, bool AllowNonLiteralTypes) {
21687 assert(!E->isValueDependent());
21688
21689 // Normally expressions passed to EvaluateInPlace have a type, but not when
21690 // a VarDecl initializer is evaluated before the untyped ParenListExpr is
21691 // replaced with a CXXConstructExpr. This can happen in LLDB.
21692 if (E->getType().isNull())
21693 return false;
21694
21695 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
21696 return false;
21697
21698 if (E->isPRValue()) {
21699 // Evaluate arrays and record types in-place, so that later initializers can
21700 // refer to earlier-initialized members of the object.
21701 QualType T = E->getType();
21702 if (T->isArrayType())
21703 return EvaluateArray(E, This, Result, Info);
21704 else if (T->isRecordType())
21705 return EvaluateRecord(E, This, Result, Info);
21706 else if (T->isAtomicType()) {
21707 QualType Unqual = T.getAtomicUnqualifiedType();
21708 if (Unqual->isArrayType() || Unqual->isRecordType())
21709 return EvaluateAtomic(E, &This, Result, Info);
21710 }
21711 }
21712
21713 // For any other type, in-place evaluation is unimportant.
21714 return Evaluate(Result, Info, E);
21715}
21716
21717/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
21718/// lvalue-to-rvalue cast if it is an lvalue.
21719static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
21720 assert(!E->isValueDependent());
21721
21722 if (E->getType().isNull())
21723 return false;
21724
21725 if (!CheckLiteralType(Info, E))
21726 return false;
21727
21728 if (Info.EnableNewConstInterp) {
21729 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
21730 return false;
21731 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
21732 ConstantExprKind::Normal);
21733 }
21734
21735 if (!::Evaluate(Result, Info, E))
21736 return false;
21737
21738 // Implicit lvalue-to-rvalue cast.
21739 if (E->isGLValue()) {
21740 LValue LV;
21741 LV.setFrom(Info.Ctx, Result);
21742 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
21743 return false;
21744 }
21745
21746 // Check this core constant expression is a constant expression.
21747 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
21748 ConstantExprKind::Normal) &&
21749 CheckMemoryLeaks(Info);
21750}
21751
21752static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result,
21753 const ASTContext &Ctx, bool &IsConst) {
21754 // Fast-path evaluations of integer literals, since we sometimes see files
21755 // containing vast quantities of these.
21756 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
21757 Result =
21758 APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
21759 IsConst = true;
21760 return true;
21761 }
21762
21763 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
21764 Result = APValue(APSInt(APInt(1, L->getValue())));
21765 IsConst = true;
21766 return true;
21767 }
21768
21769 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
21770 Result = APValue(FL->getValue());
21771 IsConst = true;
21772 return true;
21773 }
21774
21775 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
21776 Result = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
21777 IsConst = true;
21778 return true;
21779 }
21780
21781 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
21782 if (CE->hasAPValueResult()) {
21783 APValue APV = CE->getAPValueResult();
21784 if (!APV.isLValue()) {
21785 Result = std::move(APV);
21786 IsConst = true;
21787 return true;
21788 }
21789 }
21790
21791 // The SubExpr is usually just an IntegerLiteral.
21792 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
21793 }
21794
21795 // This case should be rare, but we need to check it before we check on
21796 // the type below.
21797 if (Exp->getType().isNull()) {
21798 IsConst = false;
21799 return true;
21800 }
21801
21802 return false;
21803}
21804
21807 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
21808 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
21809}
21810
21812 const ASTContext &Ctx, EvalInfo &Info) {
21813 assert(!E->isValueDependent());
21814 bool IsConst;
21815 if (FastEvaluateAsRValue(E, Result.Val, Ctx, IsConst))
21816 return IsConst;
21817
21818 return EvaluateAsRValue(Info, E, Result.Val);
21819}
21820
21822 const ASTContext &Ctx,
21823 Expr::SideEffectsKind AllowSideEffects,
21824 EvalInfo &Info) {
21825 assert(!E->isValueDependent());
21827 return false;
21828
21829 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
21830 !ExprResult.Val.isInt() ||
21831 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21832 return false;
21833
21834 return true;
21835}
21836
21838 const ASTContext &Ctx,
21839 Expr::SideEffectsKind AllowSideEffects,
21840 EvalInfo &Info) {
21841 assert(!E->isValueDependent());
21842 if (!E->getType()->isFixedPointType())
21843 return false;
21844
21845 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
21846 return false;
21847
21848 if (!ExprResult.Val.isFixedPoint() ||
21849 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21850 return false;
21851
21852 return true;
21853}
21854
21855/// EvaluateAsRValue - Return true if this is a constant which we can fold using
21856/// any crazy technique (that has nothing to do with language standards) that
21857/// we want to. If this function returns true, it returns the folded constant
21858/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
21859/// will be applied to the result.
21861 bool InConstantContext) const {
21862 assert(!isValueDependent() &&
21863 "Expression evaluator can't be called on a dependent expression.");
21864 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
21865 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21866 Info.InConstantContext = InConstantContext;
21867 return ::EvaluateAsRValue(this, Result, Ctx, Info);
21868}
21869
21871 bool InConstantContext) const {
21872 assert(!isValueDependent() &&
21873 "Expression evaluator can't be called on a dependent expression.");
21874 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
21875 EvalResult Scratch;
21876 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
21877 HandleConversionToBool(Scratch.Val, Result);
21878}
21879
21881 SideEffectsKind AllowSideEffects,
21882 bool InConstantContext) const {
21883 assert(!isValueDependent() &&
21884 "Expression evaluator can't be called on a dependent expression.");
21885 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
21886 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21887 Info.InConstantContext = InConstantContext;
21888 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
21889}
21890
21892 SideEffectsKind AllowSideEffects,
21893 bool InConstantContext) const {
21894 assert(!isValueDependent() &&
21895 "Expression evaluator can't be called on a dependent expression.");
21896 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
21897 EvalInfo Info(Ctx, Result, EvaluationMode::IgnoreSideEffects);
21898 Info.InConstantContext = InConstantContext;
21899 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
21900}
21901
21902bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
21903 SideEffectsKind AllowSideEffects,
21904 bool InConstantContext) const {
21905 assert(!isValueDependent() &&
21906 "Expression evaluator can't be called on a dependent expression.");
21907
21908 if (!getType()->isRealFloatingType())
21909 return false;
21910
21911 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
21913 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
21914 !ExprResult.Val.isFloat() ||
21915 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
21916 return false;
21917
21918 Result = ExprResult.Val.getFloat();
21919 return true;
21920}
21921
21923 bool InConstantContext) const {
21924 assert(!isValueDependent() &&
21925 "Expression evaluator can't be called on a dependent expression.");
21926
21927 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
21928 EvalInfo Info(Ctx, Result, EvaluationMode::ConstantFold);
21929 Info.InConstantContext = InConstantContext;
21930 LValue LV;
21931 CheckedTemporaries CheckedTemps;
21932
21933 if (Info.EnableNewConstInterp) {
21934 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val,
21935 ConstantExprKind::Normal))
21936 return false;
21937
21938 LV.setFrom(Ctx, Result.Val);
21940 Info, getExprLoc(), Ctx.getLValueReferenceType(getType()), LV,
21941 ConstantExprKind::Normal, CheckedTemps);
21942 }
21943
21944 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
21945 Result.HasSideEffects ||
21948 ConstantExprKind::Normal, CheckedTemps))
21949 return false;
21950
21951 LV.moveInto(Result.Val);
21952 return true;
21953}
21954
21956 APValue DestroyedValue, QualType Type,
21957 SourceLocation Loc, Expr::EvalStatus &EStatus,
21958 bool IsConstantDestruction) {
21959 EvalInfo Info(Ctx, EStatus,
21960 IsConstantDestruction ? EvaluationMode::ConstantExpression
21962 Info.setEvaluatingDecl(Base, DestroyedValue,
21963 EvalInfo::EvaluatingDeclKind::Dtor);
21964 Info.InConstantContext = IsConstantDestruction;
21965
21966 LValue LVal;
21967 LVal.set(Base);
21968
21969 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
21970 EStatus.HasSideEffects)
21971 return false;
21972
21973 if (!Info.discardCleanups())
21974 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
21975
21976 return true;
21977}
21978
21980 ConstantExprKind Kind) const {
21981 assert(!isValueDependent() &&
21982 "Expression evaluator can't be called on a dependent expression.");
21983 bool IsConst;
21984 if (FastEvaluateAsRValue(this, Result.Val, Ctx, IsConst) &&
21985 Result.Val.hasValue())
21986 return true;
21987
21988 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
21990 EvalInfo Info(Ctx, Result, EM);
21991 Info.InConstantContext = true;
21992
21993 if (Info.EnableNewConstInterp) {
21994 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
21995 return false;
21996 return CheckConstantExpression(Info, getExprLoc(),
21997 getStorageType(Ctx, this), Result.Val, Kind);
21998 }
21999
22000 // The type of the object we're initializing is 'const T' for a class NTTP.
22001 QualType T = getType();
22002 if (Kind == ConstantExprKind::ClassTemplateArgument)
22003 T.addConst();
22004
22005 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
22006 // represent the result of the evaluation. CheckConstantExpression ensures
22007 // this doesn't escape.
22008 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
22009 APValue::LValueBase Base(&BaseMTE);
22010 Info.setEvaluatingDecl(Base, Result.Val);
22011
22012 LValue LVal;
22013 LVal.set(Base);
22014 // C++23 [intro.execution]/p5
22015 // A full-expression is [...] a constant-expression
22016 // So we need to make sure temporary objects are destroyed after having
22017 // evaluating the expression (per C++23 [class.temporary]/p4).
22018 FullExpressionRAII Scope(Info);
22019 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
22020 Result.HasSideEffects || !Scope.destroy())
22021 return false;
22022
22023 if (!Info.discardCleanups())
22024 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
22025
22026 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
22027 Result.Val, Kind))
22028 return false;
22029 if (!CheckMemoryLeaks(Info))
22030 return false;
22031
22032 // If this is a class template argument, it's required to have constant
22033 // destruction too.
22034 if (Kind == ConstantExprKind::ClassTemplateArgument &&
22036 true) ||
22037 Result.HasSideEffects)) {
22038 // FIXME: Prefix a note to indicate that the problem is lack of constant
22039 // destruction.
22040 return false;
22041 }
22042
22043 return true;
22044}
22045
22047 Expr::EvalResult &EStatus,
22048 bool IsConstantInitialization) const {
22049 assert(!isValueDependent() &&
22050 "Expression evaluator can't be called on a dependent expression.");
22051 assert(VD && "Need a valid VarDecl");
22052
22053 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
22054 std::string Name;
22055 llvm::raw_string_ostream OS(Name);
22056 VD->printQualifiedName(OS);
22057 return Name;
22058 });
22059
22060 EvalInfo Info(Ctx, EStatus,
22061 (IsConstantInitialization &&
22062 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
22065 Info.setEvaluatingDecl(VD, EStatus.Val);
22066 Info.InConstantContext = IsConstantInitialization;
22067
22068 SourceLocation DeclLoc = VD->getLocation();
22069 QualType DeclTy = VD->getType();
22070
22071 if (Info.EnableNewConstInterp) {
22072 auto &InterpCtx = Ctx.getInterpContext();
22073 if (!InterpCtx.evaluateAsInitializer(Info, VD, this, EStatus.Val))
22074 return false;
22075
22076 return CheckConstantExpression(Info, DeclLoc, DeclTy, EStatus.Val,
22077 ConstantExprKind::Normal);
22078 } else {
22079 LValue LVal;
22080 LVal.set(VD);
22081
22082 {
22083 // C++23 [intro.execution]/p5
22084 // A full-expression is ... an init-declarator ([dcl.decl]) or a
22085 // mem-initializer.
22086 // So we need to make sure temporary objects are destroyed after having
22087 // evaluated the expression (per C++23 [class.temporary]/p4).
22088 //
22089 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
22090 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
22091 // outermost FullExpr, such as ExprWithCleanups.
22092 FullExpressionRAII Scope(Info);
22093 if (!EvaluateInPlace(EStatus.Val, Info, LVal, this,
22094 /*AllowNonLiteralTypes=*/true) ||
22095 EStatus.HasSideEffects)
22096 return false;
22097 }
22098
22099 // At this point, any lifetime-extended temporaries are completely
22100 // initialized.
22101 Info.performLifetimeExtension();
22102
22103 if (!Info.discardCleanups())
22104 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
22105 }
22106
22107 return CheckConstantExpression(Info, DeclLoc, DeclTy, EStatus.Val,
22108 ConstantExprKind::Normal) &&
22109 CheckMemoryLeaks(Info);
22110}
22111
22114 // This function is only meaningful for records and arrays of records.
22115 QualType VarTy = getType();
22116 if (VarTy->isArrayType()) {
22117 QualType ElemTy = getASTContext().getBaseElementType(VarTy);
22118 if (!ElemTy->isRecordType()) {
22119 ensureEvaluatedStmt()->HasConstantDestruction = true;
22120 return true;
22121 }
22122 } else if (!VarTy->isRecordType()) {
22123 ensureEvaluatedStmt()->HasConstantDestruction = true;
22124 return true;
22125 }
22126
22127 Expr::EvalStatus EStatus;
22128 EStatus.Diag = &Notes;
22129
22130 // Only treat the destruction as constant destruction if we formally have
22131 // constant initialization (or are usable in a constant expression).
22132 bool IsConstantDestruction = hasConstantInitialization();
22133 ASTContext &Ctx = getASTContext();
22134
22135 // Make a copy of the value for the destructor to mutate, if we know it.
22136 // Otherwise, treat the value as default-initialized; if the destructor works
22137 // anyway, then the destruction is constant (and must be essentially empty).
22138 APValue DestroyedValue;
22139 if (getEvaluatedValue())
22140 DestroyedValue = *getEvaluatedValue();
22141 else if (!handleDefaultInitValue(VarTy, DestroyedValue))
22142 return false;
22143
22144 if (Ctx.getLangOpts().EnableNewConstInterp) {
22145 EvalInfo Info(Ctx, EStatus,
22146 IsConstantDestruction ? EvaluationMode::ConstantExpression
22148 Info.InConstantContext = IsConstantDestruction;
22149 if (!Ctx.getInterpContext().evaluateDestruction(Info, this,
22150 std::move(DestroyedValue)))
22151 return false;
22152 ensureEvaluatedStmt()->HasConstantDestruction = true;
22153 return true;
22154 }
22155
22156 if (!EvaluateDestruction(Ctx, this, std::move(DestroyedValue), VarTy,
22157 getLocation(), EStatus, IsConstantDestruction) ||
22158 EStatus.HasSideEffects)
22159 return false;
22160
22161 ensureEvaluatedStmt()->HasConstantDestruction = true;
22162 return true;
22163}
22164
22165/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
22166/// constant folded, but discard the result.
22168 assert(!isValueDependent() &&
22169 "Expression evaluator can't be called on a dependent expression.");
22170
22172 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
22174}
22175
22176APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
22177 assert(!isValueDependent() &&
22178 "Expression evaluator can't be called on a dependent expression.");
22179
22180 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
22181 EvalResult EVResult;
22182 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
22183 Info.InConstantContext = true;
22184
22185 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
22186 (void)Result;
22187 assert(Result && "Could not evaluate expression");
22188 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22189
22190 return EVResult.Val.getInt();
22191}
22192
22195 assert(!isValueDependent() &&
22196 "Expression evaluator can't be called on a dependent expression.");
22197
22198 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
22199 EvalResult EVResult;
22200 EVResult.Diag = Diag;
22201 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
22202 Info.InConstantContext = true;
22203 Info.CheckingForUndefinedBehavior = true;
22204
22205 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
22206 (void)Result;
22207 assert(Result && "Could not evaluate expression");
22208 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
22209
22210 return EVResult.Val.getInt();
22211}
22212
22214 assert(!isValueDependent() &&
22215 "Expression evaluator can't be called on a dependent expression.");
22216
22217 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
22218 bool IsConst;
22219 EvalResult EVResult;
22220 if (!FastEvaluateAsRValue(this, EVResult.Val, Ctx, IsConst)) {
22221 EvalInfo Info(Ctx, EVResult, EvaluationMode::IgnoreSideEffects);
22222 Info.CheckingForUndefinedBehavior = true;
22223 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
22224 }
22225}
22226
22228 assert(Val.isLValue());
22229 return IsGlobalLValue(Val.getLValueBase());
22230}
22231
22232/// isIntegerConstantExpr - this recursive routine will test if an expression is
22233/// an integer constant expression.
22234
22235/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
22236/// comma, etc
22237
22238// CheckICE - This function does the fundamental ICE checking: the returned
22239// ICEDiag contains an ICEKind indicating whether the expression is an ICE.
22240//
22241// Note that to reduce code duplication, this helper does no evaluation
22242// itself; the caller checks whether the expression is evaluatable, and
22243// in the rare cases where CheckICE actually cares about the evaluated
22244// value, it calls into Evaluate.
22245
22246namespace {
22247
22248enum ICEKind {
22249 /// This expression is an ICE.
22250 IK_ICE,
22251 /// This expression is not an ICE, but if it isn't evaluated, it's
22252 /// a legal subexpression for an ICE. This return value is used to handle
22253 /// the comma operator in C99 mode, and non-constant subexpressions.
22254 IK_ICEIfUnevaluated,
22255 /// This expression is not an ICE, and is not a legal subexpression for one.
22256 IK_NotICE
22257};
22258
22259struct ICEDiag {
22260 ICEKind Kind;
22261 SourceLocation Loc;
22262
22263 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
22264};
22265
22266}
22267
22268static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
22269
22270static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
22271
22272static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
22273 Expr::EvalResult EVResult;
22274 Expr::EvalStatus Status;
22275 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22276
22277 Info.InConstantContext = true;
22278 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
22279 !EVResult.Val.isInt())
22280 return ICEDiag(IK_NotICE, E->getBeginLoc());
22281
22282 return NoDiag();
22283}
22284
22285static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
22286 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
22288 return ICEDiag(IK_NotICE, E->getBeginLoc());
22289
22290 switch (E->getStmtClass()) {
22291#define ABSTRACT_STMT(Node)
22292#define STMT(Node, Base) case Expr::Node##Class:
22293#define EXPR(Node, Base)
22294#include "clang/AST/StmtNodes.inc"
22295 case Expr::PredefinedExprClass:
22296 case Expr::FloatingLiteralClass:
22297 case Expr::ImaginaryLiteralClass:
22298 case Expr::StringLiteralClass:
22299 case Expr::ArraySubscriptExprClass:
22300 case Expr::MatrixSingleSubscriptExprClass:
22301 case Expr::MatrixSubscriptExprClass:
22302 case Expr::ArraySectionExprClass:
22303 case Expr::OMPArrayShapingExprClass:
22304 case Expr::OMPIteratorExprClass:
22305 case Expr::CompoundAssignOperatorClass:
22306 case Expr::CompoundLiteralExprClass:
22307 case Expr::ExtVectorElementExprClass:
22308 case Expr::MatrixElementExprClass:
22309 case Expr::DesignatedInitExprClass:
22310 case Expr::ArrayInitLoopExprClass:
22311 case Expr::ArrayInitIndexExprClass:
22312 case Expr::NoInitExprClass:
22313 case Expr::DesignatedInitUpdateExprClass:
22314 case Expr::ImplicitValueInitExprClass:
22315 case Expr::ParenListExprClass:
22316 case Expr::VAArgExprClass:
22317 case Expr::AddrLabelExprClass:
22318 case Expr::StmtExprClass:
22319 case Expr::CXXMemberCallExprClass:
22320 case Expr::CUDAKernelCallExprClass:
22321 case Expr::CXXAddrspaceCastExprClass:
22322 case Expr::CXXDynamicCastExprClass:
22323 case Expr::CXXTypeidExprClass:
22324 case Expr::CXXUuidofExprClass:
22325 case Expr::MSPropertyRefExprClass:
22326 case Expr::MSPropertySubscriptExprClass:
22327 case Expr::CXXNullPtrLiteralExprClass:
22328 case Expr::UserDefinedLiteralClass:
22329 case Expr::CXXThisExprClass:
22330 case Expr::CXXThrowExprClass:
22331 case Expr::CXXNewExprClass:
22332 case Expr::CXXDeleteExprClass:
22333 case Expr::CXXPseudoDestructorExprClass:
22334 case Expr::UnresolvedLookupExprClass:
22335 case Expr::RecoveryExprClass:
22336 case Expr::DependentScopeDeclRefExprClass:
22337 case Expr::CXXConstructExprClass:
22338 case Expr::CXXInheritedCtorInitExprClass:
22339 case Expr::CXXStdInitializerListExprClass:
22340 case Expr::CXXBindTemporaryExprClass:
22341 case Expr::ExprWithCleanupsClass:
22342 case Expr::CXXTemporaryObjectExprClass:
22343 case Expr::CXXUnresolvedConstructExprClass:
22344 case Expr::CXXDependentScopeMemberExprClass:
22345 case Expr::UnresolvedMemberExprClass:
22346 case Expr::ObjCStringLiteralClass:
22347 case Expr::ObjCBoxedExprClass:
22348 case Expr::ObjCArrayLiteralClass:
22349 case Expr::ObjCDictionaryLiteralClass:
22350 case Expr::ObjCEncodeExprClass:
22351 case Expr::ObjCMessageExprClass:
22352 case Expr::ObjCSelectorExprClass:
22353 case Expr::ObjCProtocolExprClass:
22354 case Expr::ObjCIvarRefExprClass:
22355 case Expr::ObjCPropertyRefExprClass:
22356 case Expr::ObjCSubscriptRefExprClass:
22357 case Expr::ObjCIsaExprClass:
22358 case Expr::ObjCAvailabilityCheckExprClass:
22359 case Expr::ShuffleVectorExprClass:
22360 case Expr::ConvertVectorExprClass:
22361 case Expr::BlockExprClass:
22362 case Expr::NoStmtClass:
22363 case Expr::OpaqueValueExprClass:
22364 case Expr::PackExpansionExprClass:
22365 case Expr::SubstNonTypeTemplateParmPackExprClass:
22366 case Expr::FunctionParmPackExprClass:
22367 case Expr::AsTypeExprClass:
22368 case Expr::ObjCIndirectCopyRestoreExprClass:
22369 case Expr::MaterializeTemporaryExprClass:
22370 case Expr::PseudoObjectExprClass:
22371 case Expr::AtomicExprClass:
22372 case Expr::LambdaExprClass:
22373 case Expr::CXXFoldExprClass:
22374 case Expr::CoawaitExprClass:
22375 case Expr::DependentCoawaitExprClass:
22376 case Expr::CoyieldExprClass:
22377 case Expr::SYCLUniqueStableNameExprClass:
22378 case Expr::CXXParenListInitExprClass:
22379 case Expr::HLSLOutArgExprClass:
22380 case Expr::CXXExpansionSelectExprClass:
22381 return ICEDiag(IK_NotICE, E->getBeginLoc());
22382
22383 case Expr::MemberExprClass: {
22384 if (Ctx.getLangOpts().C23) {
22385 const Expr *ME = E->IgnoreParenImpCasts();
22386 while (const auto *M = dyn_cast<MemberExpr>(ME)) {
22387 if (M->isArrow())
22388 return ICEDiag(IK_NotICE, E->getBeginLoc());
22389 ME = M->getBase()->IgnoreParenImpCasts();
22390 }
22391 const auto *DRE = dyn_cast<DeclRefExpr>(ME);
22392 if (DRE) {
22393 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
22394 VD && VD->isConstexpr())
22395 return CheckEvalInICE(E, Ctx);
22396 }
22397 }
22398 return ICEDiag(IK_NotICE, E->getBeginLoc());
22399 }
22400
22401 case Expr::InitListExprClass: {
22402 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
22403 // form "T x = { a };" is equivalent to "T x = a;".
22404 // Unless we're initializing a reference, T is a scalar as it is known to be
22405 // of integral or enumeration type.
22406 if (E->isPRValue())
22407 if (cast<InitListExpr>(E)->getNumInits() == 1)
22408 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
22409 return ICEDiag(IK_NotICE, E->getBeginLoc());
22410 }
22411
22412 case Expr::SizeOfPackExprClass:
22413 case Expr::GNUNullExprClass:
22414 case Expr::SourceLocExprClass:
22415 case Expr::EmbedExprClass:
22416 case Expr::OpenACCAsteriskSizeExprClass:
22417 return NoDiag();
22418
22419 case Expr::PackIndexingExprClass:
22420 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
22421
22422 case Expr::SubstNonTypeTemplateParmExprClass:
22423 return
22424 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
22425
22426 case Expr::ConstantExprClass:
22427 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
22428
22429 case Expr::ParenExprClass:
22430 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
22431 case Expr::GenericSelectionExprClass:
22432 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
22433 case Expr::IntegerLiteralClass:
22434 case Expr::FixedPointLiteralClass:
22435 case Expr::CharacterLiteralClass:
22436 case Expr::ObjCBoolLiteralExprClass:
22437 case Expr::CXXBoolLiteralExprClass:
22438 case Expr::CXXScalarValueInitExprClass:
22439 case Expr::TypeTraitExprClass:
22440 case Expr::ConceptSpecializationExprClass:
22441 case Expr::RequiresExprClass:
22442 case Expr::ArrayTypeTraitExprClass:
22443 case Expr::ExpressionTraitExprClass:
22444 case Expr::CXXNoexceptExprClass:
22445 case Expr::CXXReflectExprClass:
22446 return NoDiag();
22447 case Expr::CallExprClass:
22448 case Expr::CXXOperatorCallExprClass: {
22449 // C99 6.6/3 allows function calls within unevaluated subexpressions of
22450 // constant expressions, but they can never be ICEs because an ICE cannot
22451 // contain an operand of (pointer to) function type.
22452 const CallExpr *CE = cast<CallExpr>(E);
22453 if (CE->getBuiltinCallee())
22454 return CheckEvalInICE(E, Ctx);
22455 return ICEDiag(IK_NotICE, E->getBeginLoc());
22456 }
22457 case Expr::CXXRewrittenBinaryOperatorClass:
22458 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
22459 Ctx);
22460 case Expr::DeclRefExprClass: {
22461 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
22462 if (isa<EnumConstantDecl>(D))
22463 return NoDiag();
22464
22465 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
22466 // integer variables in constant expressions:
22467 //
22468 // C++ 7.1.5.1p2
22469 // A variable of non-volatile const-qualified integral or enumeration
22470 // type initialized by an ICE can be used in ICEs.
22471 //
22472 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
22473 // that mode, use of reference variables should not be allowed.
22474 const VarDecl *VD = dyn_cast<VarDecl>(D);
22475 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
22476 !VD->getType()->isReferenceType())
22477 return NoDiag();
22478
22479 return ICEDiag(IK_NotICE, E->getBeginLoc());
22480 }
22481 case Expr::UnaryOperatorClass: {
22482 const UnaryOperator *Exp = cast<UnaryOperator>(E);
22483 switch (Exp->getOpcode()) {
22484 case UO_PostInc:
22485 case UO_PostDec:
22486 case UO_PreInc:
22487 case UO_PreDec:
22488 case UO_AddrOf:
22489 case UO_Deref:
22490 case UO_Coawait:
22491 // C99 6.6/3 allows increment and decrement within unevaluated
22492 // subexpressions of constant expressions, but they can never be ICEs
22493 // because an ICE cannot contain an lvalue operand.
22494 return ICEDiag(IK_NotICE, E->getBeginLoc());
22495 case UO_Extension:
22496 case UO_LNot:
22497 case UO_Plus:
22498 case UO_Minus:
22499 case UO_Not:
22500 case UO_Real:
22501 case UO_Imag:
22502 return CheckICE(Exp->getSubExpr(), Ctx);
22503 }
22504 llvm_unreachable("invalid unary operator class");
22505 }
22506 case Expr::OffsetOfExprClass: {
22507 // Note that per C99, offsetof must be an ICE. And AFAIK, using
22508 // EvaluateAsRValue matches the proposed gcc behavior for cases like
22509 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
22510 // compliance: we should warn earlier for offsetof expressions with
22511 // array subscripts that aren't ICEs, and if the array subscripts
22512 // are ICEs, the value of the offsetof must be an integer constant.
22513 return CheckEvalInICE(E, Ctx);
22514 }
22515 case Expr::UnaryExprOrTypeTraitExprClass: {
22517 if ((Exp->getKind() == UETT_SizeOf) &&
22519 return ICEDiag(IK_NotICE, E->getBeginLoc());
22520 if (Exp->getKind() == UETT_CountOf) {
22521 QualType ArgTy = Exp->getTypeOfArgument();
22522 if (ArgTy->isVariableArrayType()) {
22523 // We need to look whether the array is multidimensional. If it is,
22524 // then we want to check the size expression manually to see whether
22525 // it is an ICE or not.
22526 const auto *VAT = Ctx.getAsVariableArrayType(ArgTy);
22527 if (VAT->getElementType()->isArrayType())
22528 // Variable array size expression could be missing (e.g. int a[*][10])
22529 // In that case, it can't be a constant expression.
22530 return VAT->getSizeExpr() ? CheckICE(VAT->getSizeExpr(), Ctx)
22531 : ICEDiag(IK_NotICE, E->getBeginLoc());
22532
22533 // Otherwise, this is a regular VLA, which is definitely not an ICE.
22534 return ICEDiag(IK_NotICE, E->getBeginLoc());
22535 }
22536 }
22537 return NoDiag();
22538 }
22539 case Expr::BinaryOperatorClass: {
22540 const BinaryOperator *Exp = cast<BinaryOperator>(E);
22541 switch (Exp->getOpcode()) {
22542 case BO_PtrMemD:
22543 case BO_PtrMemI:
22544 case BO_Assign:
22545 case BO_MulAssign:
22546 case BO_DivAssign:
22547 case BO_RemAssign:
22548 case BO_AddAssign:
22549 case BO_SubAssign:
22550 case BO_ShlAssign:
22551 case BO_ShrAssign:
22552 case BO_AndAssign:
22553 case BO_XorAssign:
22554 case BO_OrAssign:
22555 // C99 6.6/3 allows assignments within unevaluated subexpressions of
22556 // constant expressions, but they can never be ICEs because an ICE cannot
22557 // contain an lvalue operand.
22558 return ICEDiag(IK_NotICE, E->getBeginLoc());
22559
22560 case BO_Mul:
22561 case BO_Div:
22562 case BO_Rem:
22563 case BO_Add:
22564 case BO_Sub:
22565 case BO_Shl:
22566 case BO_Shr:
22567 case BO_LT:
22568 case BO_GT:
22569 case BO_LE:
22570 case BO_GE:
22571 case BO_EQ:
22572 case BO_NE:
22573 case BO_And:
22574 case BO_Xor:
22575 case BO_Or:
22576 case BO_Comma:
22577 case BO_Cmp: {
22578 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
22579 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
22580 if (Exp->getOpcode() == BO_Div ||
22581 Exp->getOpcode() == BO_Rem) {
22582 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
22583 // we don't evaluate one.
22584 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
22585 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
22586 if (REval == 0)
22587 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22588 if (REval.isSigned() && REval.isAllOnes()) {
22589 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
22590 if (LEval.isMinSignedValue())
22591 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22592 }
22593 }
22594 }
22595 if (Exp->getOpcode() == BO_Comma) {
22596 if (Ctx.getLangOpts().C99) {
22597 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
22598 // if it isn't evaluated.
22599 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
22600 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
22601 } else {
22602 // In both C89 and C++, commas in ICEs are illegal.
22603 return ICEDiag(IK_NotICE, E->getBeginLoc());
22604 }
22605 }
22606 return Worst(LHSResult, RHSResult);
22607 }
22608 case BO_LAnd:
22609 case BO_LOr: {
22610 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
22611 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
22612 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
22613 // Rare case where the RHS has a comma "side-effect"; we need
22614 // to actually check the condition to see whether the side
22615 // with the comma is evaluated.
22616 if ((Exp->getOpcode() == BO_LAnd) !=
22617 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
22618 return RHSResult;
22619 return NoDiag();
22620 }
22621
22622 return Worst(LHSResult, RHSResult);
22623 }
22624 }
22625 llvm_unreachable("invalid binary operator kind");
22626 }
22627 case Expr::ImplicitCastExprClass:
22628 case Expr::CStyleCastExprClass:
22629 case Expr::CXXFunctionalCastExprClass:
22630 case Expr::CXXStaticCastExprClass:
22631 case Expr::CXXReinterpretCastExprClass:
22632 case Expr::CXXConstCastExprClass:
22633 case Expr::ObjCBridgedCastExprClass: {
22634 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
22635 if (isa<ExplicitCastExpr>(E)) {
22636 if (const FloatingLiteral *FL
22637 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
22638 unsigned DestWidth = Ctx.getIntWidth(E->getType());
22639 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
22640 APSInt IgnoredVal(DestWidth, !DestSigned);
22641 bool Ignored;
22642 // If the value does not fit in the destination type, the behavior is
22643 // undefined, so we are not required to treat it as a constant
22644 // expression.
22645 if (FL->getValue().convertToInteger(IgnoredVal,
22646 llvm::APFloat::rmTowardZero,
22647 &Ignored) & APFloat::opInvalidOp)
22648 return ICEDiag(IK_NotICE, E->getBeginLoc());
22649 return NoDiag();
22650 }
22651 }
22652 switch (cast<CastExpr>(E)->getCastKind()) {
22653 case CK_LValueToRValue:
22654 case CK_AtomicToNonAtomic:
22655 case CK_NonAtomicToAtomic:
22656 case CK_NoOp:
22657 case CK_IntegralToBoolean:
22658 case CK_IntegralCast:
22659 return CheckICE(SubExpr, Ctx);
22660 default:
22661 return ICEDiag(IK_NotICE, E->getBeginLoc());
22662 }
22663 }
22664 case Expr::BinaryConditionalOperatorClass: {
22666 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
22667 if (CommonResult.Kind == IK_NotICE) return CommonResult;
22668 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
22669 if (FalseResult.Kind == IK_NotICE) return FalseResult;
22670 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
22671 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
22672 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
22673 return FalseResult;
22674 }
22675 case Expr::ConditionalOperatorClass: {
22677 // If the condition (ignoring parens) is a __builtin_constant_p call,
22678 // then only the true side is actually considered in an integer constant
22679 // expression, and it is fully evaluated. This is an important GNU
22680 // extension. See GCC PR38377 for discussion.
22681 if (const CallExpr *CallCE
22682 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
22683 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
22684 return CheckEvalInICE(E, Ctx);
22685 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
22686 if (CondResult.Kind == IK_NotICE)
22687 return CondResult;
22688
22689 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
22690 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
22691
22692 if (TrueResult.Kind == IK_NotICE)
22693 return TrueResult;
22694 if (FalseResult.Kind == IK_NotICE)
22695 return FalseResult;
22696 if (CondResult.Kind == IK_ICEIfUnevaluated)
22697 return CondResult;
22698 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
22699 return NoDiag();
22700 // Rare case where the diagnostics depend on which side is evaluated
22701 // Note that if we get here, CondResult is 0, and at least one of
22702 // TrueResult and FalseResult is non-zero.
22703 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
22704 return FalseResult;
22705 return TrueResult;
22706 }
22707 case Expr::CXXDefaultArgExprClass:
22708 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
22709 case Expr::CXXDefaultInitExprClass:
22710 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
22711 case Expr::ChooseExprClass: {
22712 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
22713 }
22714 case Expr::BuiltinBitCastExprClass: {
22715 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
22716 return ICEDiag(IK_NotICE, E->getBeginLoc());
22717 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
22718 }
22719 }
22720
22721 llvm_unreachable("Invalid StmtClass!");
22722}
22723
22724/// Evaluate an expression as a C++11 integral constant expression.
22726 const Expr *E,
22727 llvm::APSInt *Value) {
22729 return false;
22730
22732 if (!E->isCXX11ConstantExpr(Ctx, &Result))
22733 return false;
22734
22735 if (!Result.isInt())
22736 return false;
22737
22738 if (Value) *Value = Result.getInt();
22739 return true;
22740}
22741
22743 assert(!isValueDependent() &&
22744 "Expression evaluator can't be called on a dependent expression.");
22745
22746 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
22747
22748 if (Ctx.getLangOpts().CPlusPlus11)
22749 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr);
22750
22751 ICEDiag D = CheckICE(this, Ctx);
22752 if (D.Kind != IK_ICE)
22753 return false;
22754 return true;
22755}
22756
22757std::optional<llvm::APSInt>
22759 if (isValueDependent()) {
22760 // Expression evaluator can't succeed on a dependent expression.
22761 return std::nullopt;
22762 }
22763
22764 if (Ctx.getLangOpts().CPlusPlus11) {
22765 APSInt Value;
22767 return Value;
22768 return std::nullopt;
22769 }
22770
22771 if (!isIntegerConstantExpr(Ctx))
22772 return std::nullopt;
22773
22774 // The only possible side-effects here are due to UB discovered in the
22775 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
22776 // required to treat the expression as an ICE, so we produce the folded
22777 // value.
22779 Expr::EvalStatus Status;
22780 EvalInfo Info(Ctx, Status, EvaluationMode::IgnoreSideEffects);
22781 Info.InConstantContext = true;
22782
22783 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
22784 llvm_unreachable("ICE cannot be evaluated!");
22785
22786 return ExprResult.Val.getInt();
22787}
22788
22790 assert(!isValueDependent() &&
22791 "Expression evaluator can't be called on a dependent expression.");
22792
22793 return CheckICE(this, Ctx).Kind == IK_ICE;
22794}
22795
22797 assert(!isValueDependent() &&
22798 "Expression evaluator can't be called on a dependent expression.");
22799
22800 // We support this checking in C++98 mode in order to diagnose compatibility
22801 // issues.
22802 assert(Ctx.getLangOpts().CPlusPlus);
22803
22804 bool IsConst;
22805 APValue Scratch;
22806 if (FastEvaluateAsRValue(this, Scratch, Ctx, IsConst) && Scratch.hasValue()) {
22807 if (Result)
22808 *Result = std::move(Scratch);
22809 return true;
22810 }
22811
22812 // Build evaluation settings.
22813 Expr::EvalStatus Status;
22814 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
22815
22816 bool IsConstExpr =
22817 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
22818 // NOTE: We don't produce a diagnostic for this, but the callers that
22819 // call us on arbitrary full-expressions should generally not care.
22820 Info.discardCleanups() && !Status.HasSideEffects;
22821
22822 return IsConstExpr && !Status.DiagEmitted;
22823}
22824
22826 const FunctionDecl *Callee,
22828 const Expr *This) const {
22829 assert(!isValueDependent() &&
22830 "Expression evaluator can't be called on a dependent expression.");
22831
22832 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
22833 std::string Name;
22834 llvm::raw_string_ostream OS(Name);
22835 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
22836 /*Qualified=*/true);
22837 return Name;
22838 });
22839
22840 Expr::EvalStatus Status;
22841 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpressionUnevaluated);
22842 Info.InConstantContext = true;
22843
22844 if (Info.EnableNewConstInterp) {
22845 if (std::optional<bool> BoolResult =
22846 Info.Ctx.getInterpContext().evaluateWithSubstitution(
22847 Info, Callee, Args, This, this)) {
22848 Value = APValue(APSInt(APInt(1, static_cast<uint64_t>(*BoolResult))));
22849 return true;
22850 }
22851 return false;
22852 }
22853
22854 LValue ThisVal;
22855 const LValue *ThisPtr = nullptr;
22856 if (This) {
22857#ifndef NDEBUG
22858 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
22859 assert(MD && "Don't provide `this` for non-methods.");
22860 assert(MD->isImplicitObjectMemberFunction() &&
22861 "Don't provide `this` for methods without an implicit object.");
22862#endif
22863 if (!This->isValueDependent() &&
22864 EvaluateObjectArgument(Info, This, ThisVal) &&
22865 !Info.EvalStatus.HasSideEffects)
22866 ThisPtr = &ThisVal;
22867
22868 // Ignore any side-effects from a failed evaluation. This is safe because
22869 // they can't interfere with any other argument evaluation.
22870 Info.EvalStatus.HasSideEffects = false;
22871 }
22872
22873 CallRef Call = Info.CurrentCall->createCall(Callee);
22874 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
22875 I != E; ++I) {
22876 unsigned Idx = I - Args.begin();
22877 if (Idx >= Callee->getNumParams())
22878 break;
22879 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
22880 if ((*I)->isValueDependent() ||
22881 !EvaluateCallArg(PVD, *I, Call, Info) ||
22882 Info.EvalStatus.HasSideEffects) {
22883 // If evaluation fails, throw away the argument entirely.
22884 if (APValue *Slot = Info.getParamSlot(Call, PVD))
22885 *Slot = APValue();
22886 }
22887
22888 // Ignore any side-effects from a failed evaluation. This is safe because
22889 // they can't interfere with any other argument evaluation.
22890 Info.EvalStatus.HasSideEffects = false;
22891 }
22892
22893 // Parameter cleanups happen in the caller and are not part of this
22894 // evaluation.
22895 Info.discardCleanups();
22896 Info.EvalStatus.HasSideEffects = false;
22897
22898 // Build fake call to Callee.
22899 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
22900 Call);
22901 // FIXME: Missing ExprWithCleanups in enable_if conditions?
22902 FullExpressionRAII Scope(Info);
22903 return Evaluate(Value, Info, this) && Scope.destroy() &&
22904 !Info.EvalStatus.HasSideEffects;
22905}
22906
22909 PartialDiagnosticAt> &Diags) {
22910 // FIXME: It would be useful to check constexpr function templates, but at the
22911 // moment the constant expression evaluator cannot cope with the non-rigorous
22912 // ASTs which we build for dependent expressions.
22913 if (FD->isDependentContext())
22914 return true;
22915
22916 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
22917 std::string Name;
22918 llvm::raw_string_ostream OS(Name);
22920 /*Qualified=*/true);
22921 return Name;
22922 });
22923
22924 Expr::EvalStatus Status;
22925 Status.Diag = &Diags;
22926
22927 EvalInfo Info(FD->getASTContext(), Status,
22929 Info.InConstantContext = true;
22930 Info.CheckingPotentialConstantExpression = true;
22931
22932 // The constexpr VM attempts to compile all methods to bytecode here.
22933 if (Info.EnableNewConstInterp) {
22934 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
22935 return Diags.empty();
22936 }
22937
22938 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
22939 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
22940
22941 // Fabricate an arbitrary expression on the stack and pretend that it
22942 // is a temporary being used as the 'this' pointer.
22943 LValue This;
22944 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getCanonicalTagType(RD)
22945 : Info.Ctx.IntTy);
22946 This.set({&VIE, Info.CurrentCall->Index});
22947
22949
22950 APValue Scratch;
22951 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
22952 // Evaluate the call as a constant initializer, to allow the construction
22953 // of objects of non-literal types.
22954 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
22955 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
22956 } else {
22957 SourceLocation Loc = FD->getLocation();
22959 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
22960 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
22961 /*ResultSlot=*/nullptr);
22962 }
22963
22964 return Diags.empty();
22965}
22966
22968 const FunctionDecl *FD,
22970 PartialDiagnosticAt> &Diags) {
22971 assert(!E->isValueDependent() &&
22972 "Expression evaluator can't be called on a dependent expression.");
22973
22974 Expr::EvalStatus Status;
22975 Status.Diag = &Diags;
22976
22977 EvalInfo Info(FD->getASTContext(), Status,
22979 Info.InConstantContext = true;
22980 Info.CheckingPotentialConstantExpression = true;
22981
22982 if (Info.EnableNewConstInterp) {
22983 Info.Ctx.getInterpContext().isPotentialConstantExprUnevaluated(Info, E, FD);
22984 return Diags.empty();
22985 }
22986
22987 // Fabricate a call stack frame to give the arguments a plausible cover story.
22988 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
22989 /*CallExpr=*/nullptr, CallRef());
22990
22991 APValue ResultScratch;
22992 Evaluate(ResultScratch, Info, E);
22993 return Diags.empty();
22994}
22995
22996std::optional<uint64_t> Expr::tryEvaluateObjectSize(const ASTContext &Ctx,
22997 unsigned Type) const {
22998 if (!getType()->isPointerType())
22999 return std::nullopt;
23000
23001 Expr::EvalStatus Status;
23002 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
23003 if (Info.EnableNewConstInterp)
23004 return Info.Ctx.getInterpContext().tryEvaluateObjectSize(Info, this, Type);
23005 return tryEvaluateBuiltinObjectSize(this, Type, Info);
23006}
23007
23008static std::optional<uint64_t>
23009EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
23010 std::string *StringResult) {
23011 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
23012 return std::nullopt;
23013
23014 LValue String;
23015
23016 if (!EvaluatePointer(E, String, Info))
23017 return std::nullopt;
23018
23019 QualType CharTy = E->getType()->getPointeeType();
23020
23021 // Fast path: if it's a string literal, search the string value.
23022 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
23023 String.getLValueBase().dyn_cast<const Expr *>())) {
23024 StringRef Str = S->getBytes();
23025 int64_t Off = String.Offset.getQuantity();
23026 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
23027 S->getCharByteWidth() == 1 &&
23028 // FIXME: Add fast-path for wchar_t too.
23029 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
23030 Str = Str.substr(Off);
23031
23032 StringRef::size_type Pos = Str.find(0);
23033 if (Pos != StringRef::npos)
23034 Str = Str.substr(0, Pos);
23035
23036 if (StringResult)
23037 *StringResult = Str;
23038 return Str.size();
23039 }
23040
23041 // Fall through to slow path.
23042 }
23043
23044 // Slow path: scan the bytes of the string looking for the terminating 0.
23045 for (uint64_t Strlen = 0; /**/; ++Strlen) {
23046 APValue Char;
23047 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
23048 !Char.isInt())
23049 return std::nullopt;
23050 if (!Char.getInt())
23051 return Strlen;
23052 else if (StringResult)
23053 StringResult->push_back(Char.getInt().getExtValue());
23054 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
23055 return std::nullopt;
23056 }
23057}
23058
23059std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
23060 Expr::EvalStatus Status;
23061 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
23062 std::string StringResult;
23063
23064 if (Info.EnableNewConstInterp) {
23065 if (!Info.Ctx.getInterpContext().evaluateString(Info, this, StringResult))
23066 return std::nullopt;
23067 return StringResult;
23068 }
23069
23070 if (EvaluateBuiltinStrLen(this, Info, &StringResult))
23071 return StringResult;
23072 return std::nullopt;
23073}
23074
23075template <typename T>
23077 const Expr *SizeExpression,
23078 const Expr *PtrExpression,
23079 ASTContext &Ctx,
23080 Expr::EvalResult &Status) {
23081 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantExpression);
23082 Info.InConstantContext = true;
23083
23084 if (Info.EnableNewConstInterp)
23085 return Info.Ctx.getInterpContext().evaluateCharRange(Info, SizeExpression,
23086 PtrExpression, Result);
23087
23088 LValue String;
23089 FullExpressionRAII Scope(Info);
23090 APSInt SizeValue;
23091 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
23092 return false;
23093
23094 uint64_t Size = SizeValue.getZExtValue();
23095
23096 // FIXME: better protect against invalid or excessive sizes
23097 if constexpr (std::is_same_v<APValue, T>)
23098 Result = APValue(APValue::UninitArray{}, Size, Size);
23099 else {
23100 if (Size < Result.max_size())
23101 Result.reserve(Size);
23102 }
23103 if (!::EvaluatePointer(PtrExpression, String, Info))
23104 return false;
23105
23106 QualType CharTy = PtrExpression->getType()->getPointeeType();
23107 for (uint64_t I = 0; I < Size; ++I) {
23108 APValue Char;
23109 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
23110 Char))
23111 return false;
23112
23113 if constexpr (std::is_same_v<APValue, T>) {
23114 Result.getArrayInitializedElt(I) = std::move(Char);
23115 } else {
23116 APSInt C = Char.getInt();
23117
23118 assert(C.getBitWidth() <= 8 &&
23119 "string element not representable in char");
23120
23121 Result.push_back(static_cast<char>(C.getExtValue()));
23122 }
23123
23124 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
23125 return false;
23126 }
23127
23128 return Scope.destroy() && CheckMemoryLeaks(Info);
23129}
23130
23132 const Expr *SizeExpression,
23133 const Expr *PtrExpression, ASTContext &Ctx,
23134 EvalResult &Status) const {
23135 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
23136 PtrExpression, Ctx, Status);
23137}
23138
23140 const Expr *SizeExpression,
23141 const Expr *PtrExpression, ASTContext &Ctx,
23142 EvalResult &Status) const {
23143 return EvaluateCharRangeAsStringImpl(this, Result, SizeExpression,
23144 PtrExpression, Ctx, Status);
23145}
23146
23147std::optional<uint64_t> Expr::tryEvaluateStrLen(const ASTContext &Ctx) const {
23148 Expr::EvalStatus Status;
23149 EvalInfo Info(Ctx, Status, EvaluationMode::ConstantFold);
23150
23151 if (Info.EnableNewConstInterp)
23152 return Info.Ctx.getInterpContext().evaluateStrlen(Info, this);
23153 return EvaluateBuiltinStrLen(this, Info);
23154}
23155
23156namespace {
23157struct IsWithinLifetimeHandler {
23158 EvalInfo &Info;
23159 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
23160 using result_type = std::optional<bool>;
23161 std::optional<bool> failed() { return std::nullopt; }
23162 template <typename T>
23163 std::optional<bool> found(T &Subobj, QualType SubobjType,
23165 return true;
23166 }
23167 template <typename T>
23168 std::optional<bool> found(T &Subobj, QualType SubobjType) {
23169 return true;
23170 }
23171};
23172
23173std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
23174 const CallExpr *E) {
23175 EvalInfo &Info = IEE.Info;
23176 // Sometimes this is called during some sorts of constant folding / early
23177 // evaluation. These are meant for non-constant expressions and are not
23178 // necessary since this consteval builtin will never be evaluated at runtime.
23179 // Just fail to evaluate when not in a constant context.
23180 if (!Info.InConstantContext)
23181 return std::nullopt;
23182 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
23183 const Expr *Arg = E->getArg(0);
23184 if (Arg->isValueDependent())
23185 return std::nullopt;
23186 LValue Val;
23187 if (!EvaluatePointer(Arg, Val, Info))
23188 return std::nullopt;
23189
23190 if (Val.allowConstexprUnknown())
23191 return true;
23192
23193 auto Error = [&](int Diag) {
23194 bool CalledFromStd = false;
23195 const auto *Callee = Info.CurrentCall->getCallee();
23196 if (Callee && Callee->isInStdNamespace()) {
23197 const IdentifierInfo *Identifier = Callee->getIdentifier();
23198 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
23199 }
23200 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
23201 : E->getExprLoc(),
23202 diag::err_invalid_is_within_lifetime)
23203 << (CalledFromStd ? "std::is_within_lifetime"
23204 : "__builtin_is_within_lifetime")
23205 << Diag;
23206 return std::nullopt;
23207 };
23208 // C++2c [meta.const.eval]p4:
23209 // During the evaluation of an expression E as a core constant expression, a
23210 // call to this function is ill-formed unless p points to an object that is
23211 // usable in constant expressions or whose complete object's lifetime began
23212 // within E.
23213
23214 // Make sure it points to an object
23215 // nullptr does not point to an object
23216 if (Val.isNullPointer() || Val.getLValueBase().isNull())
23217 return Error(0);
23218 QualType T = Val.getLValueBase().getType();
23219 assert(!T->isFunctionType() &&
23220 "Pointers to functions should have been typed as function pointers "
23221 "which would have been rejected earlier");
23222 assert(T->isObjectType());
23223 // Hypothetical array element is not an object
23224 if (Val.getLValueDesignator().isOnePastTheEnd())
23225 return Error(1);
23226 assert(Val.getLValueDesignator().isValidSubobject() &&
23227 "Unchecked case for valid subobject");
23228 // All other ill-formed values should have failed EvaluatePointer, so the
23229 // object should be a pointer to an object that is usable in a constant
23230 // expression or whose complete lifetime began within the expression
23231 CompleteObject CO =
23232 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
23233 // The lifetime hasn't begun yet if we are still evaluating the
23234 // initializer ([basic.life]p(1.2))
23235 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
23236 return Error(2);
23237
23238 if (!CO)
23239 return false;
23240 IsWithinLifetimeHandler handler{Info};
23241 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
23242}
23243} // 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 bool CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind, const FieldDecl *SubobjectDecl, CheckedTemporaries &CheckedTemps, bool IsCompleteClass=true)
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 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 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 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 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 HandleLValueDirectVirtualBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
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 HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T, bool IsCompleteClass=true)
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 HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result, bool IsCompleteClass=true)
Perform zero-initialization on an object of non-union class type. C++11 [dcl.init]p5: To zero-initial...
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 HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result, bool IsCompleteClass=true)
Evaluate a constructor call.
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 bool handleDefaultInitValue(QualType T, APValue &Result, bool IsCompleteClass=true)
Get the value to use for a default-initialized object of type T.
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 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:637
const LValueBase getLValueBase() const
Definition APValue.cpp:1020
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:629
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition APValue.cpp:474
APSInt & getInt()
Definition APValue.h:511
APValue & getStructField(unsigned i)
Definition APValue.h:674
unsigned getMatrixNumColumns() const
Definition APValue.h:602
const FieldDecl * getUnionField() const
Definition APValue.h:695
bool isVector() const
Definition APValue.h:494
APSInt & getComplexIntImag()
Definition APValue.h:549
bool isAbsent() const
Definition APValue.h:484
bool isComplexInt() const
Definition APValue.h:491
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:482
APValue & getStructVirtualBase(unsigned i)
Definition APValue.h:679
unsigned getArrayInitializedElts() const
Definition APValue.h:648
static APValue IndeterminateValue()
Definition APValue.h:453
bool isFloat() const
Definition APValue.h:489
unsigned getStructNumBases() const
Definition APValue.h:657
APFixedPoint & getFixedPoint()
Definition APValue.h:533
bool hasValue() const
Definition APValue.h:486
bool hasLValuePath() const
Definition APValue.cpp:1035
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1103
APValue & getUnionValue()
Definition APValue.h:699
CharUnits & getLValueOffset()
Definition APValue.cpp:1030
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:711
bool isComplexFloat() const
Definition APValue.h:492
APValue & getVectorElt(unsigned I)
Definition APValue.h:585
APValue & getArrayFiller()
Definition APValue.h:640
unsigned getVectorLength() const
Definition APValue.h:593
bool isLValue() const
Definition APValue.h:493
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition APValue.cpp:1096
bool isIndeterminate() const
Definition APValue.h:485
unsigned getMatrixNumRows() const
Definition APValue.h:598
bool isInt() const
Definition APValue.h:488
unsigned getArraySize() const
Definition APValue.h:652
bool allowConstexprUnknown() const
Definition APValue.h:330
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:993
bool isFixedPoint() const
Definition APValue.h:490
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:609
@ 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:497
APSInt & getComplexIntReal()
Definition APValue.h:541
APFloat & getComplexFloatImag()
Definition APValue.h:565
APFloat & getComplexFloatReal()
Definition APValue.h:557
APFloat & getFloat()
Definition APValue.h:525
APValue & getStructBase(unsigned i)
Definition APValue.h:669
bool isMatrix() const
Definition APValue.h:495
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:3047
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3821
QualType getElementType() const
Definition TypeBase.h:3833
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8288
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:1518
bool getValue() const
Definition ExprCXX.h:743
Represents a call to a C++ constructor.
Definition ExprCXX.h:1551
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1620
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1694
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1653
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1614
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1691
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:3049
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:2668
bool isArrayForm() const
Definition ExprCXX.h:2655
bool isGlobalDelete() const
Definition ExprCXX.h:2654
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:1791
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:2719
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:2726
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2870
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:2751
bool isStatic() const
Definition DeclCXX.cpp:2417
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2895
bool isArray() const
Definition ExprCXX.h:2467
QualType getAllocatedType() const
Definition ExprCXX.h:2437
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:2472
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2506
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2497
SourceRange getSourceRange() const
Definition ExprCXX.h:2613
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2462
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2536
bool getValue() const
Definition ExprCXX.h:4331
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5180
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:1681
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:1792
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
base_class_range vbases()
Definition DeclCXX.h:625
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:2129
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
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:307
bool isImplicit() const
Definition ExprCXX.h:1180
bool isTypeOperand() const
Definition ExprCXX.h:887
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:898
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:1117
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:3603
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:1929
Expr * getLHS()
Definition Stmt.h:2012
Expr * getRHS()
Definition Stmt.h:2024
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:3340
QualType getElementType() const
Definition TypeBase.h:3350
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:5705
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:1749
bool body_empty() const
Definition Stmt.h:1793
Stmt *const * const_body_iterator
Definition Stmt.h:1821
body_iterator body_end()
Definition Stmt.h:1814
body_range body()
Definition Stmt.h:1812
body_iterator body_begin()
Definition Stmt.h:1813
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:3859
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition TypeBase.h:3922
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:3948
bool isZeroSize() const
Return true if the size is zero.
Definition TypeBase.h:3929
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3955
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3915
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3935
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:4486
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:1640
decl_range decls()
Definition Stmt.h:1688
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:2841
Stmt * getBody()
Definition Stmt.h:2866
Expr * getCond()
Definition Stmt.h:2859
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:3106
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:4001
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3101
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:3097
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:3699
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:3264
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:4448
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4561
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:4752
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:2897
Stmt * getInit()
Definition Stmt.h:2912
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2941
Expr * getInc()
Definition Stmt.h:2940
Expr * getCond()
Definition Stmt.h:2939
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:3259
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4185
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4173
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3845
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:4309
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:3406
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:3104
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:2268
Stmt * getThen()
Definition Stmt.h:2357
Stmt * getInit()
Definition Stmt.h:2418
bool isNonNegatedConsteval() const
Definition Stmt.h:2453
Expr * getCond()
Definition Stmt.h:2345
Stmt * getElse()
Definition Stmt.h:2366
bool isConsteval() const
Definition Stmt.h:2448
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:2473
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition Expr.cpp:2459
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:2109
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2097
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:4919
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4944
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4936
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:4952
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:1690
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:4638
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:3393
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:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8573
QualType withConst() const
Definition TypeBase.h:1175
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1172
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8489
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8529
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:8674
QualType getCanonicalType() const
Definition TypeBase.h:8541
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8583
void removeLocalVolatile()
Definition TypeBase.h:8605
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition TypeBase.h:1180
void removeLocalConst()
Definition TypeBase.h:8597
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8562
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8535
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:5275
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:4514
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:2291
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:85
@ NoStmtClass
Definition Stmt.h:88
StmtClass getStmtClass() const
Definition Stmt.h:1502
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
bool isOrdinary() const
Definition Expr.h:1922
unsigned getCharByteWidth() const
Definition Expr.h:1916
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1902
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2518
Expr * getCond()
Definition Stmt.h:2581
Stmt * getBody()
Definition Stmt.h:2593
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2598
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2649
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3862
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4899
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:8471
bool getBoolValue() const
Definition ExprCXX.h:2950
const APValue & getAPValue() const
Definition ExprCXX.h:2955
bool isStoredAsBoolean() const
Definition ExprCXX.h:2946
The base class of the type hierarchy.
Definition TypeBase.h:1876
bool isVoidType() const
Definition TypeBase.h:9092
bool isBooleanType() const
Definition TypeBase.h:9229
bool isFunctionReferenceType() const
Definition TypeBase.h:8800
bool isMFloat8Type() const
Definition TypeBase.h:9117
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:8833
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:9395
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:8829
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:8825
bool isFunctionPointerType() const
Definition TypeBase.h:8793
bool isCountAttributedType() const
Definition Type.cpp:778
bool isConstantMatrixType() const
Definition TypeBase.h:8893
bool isPointerType() const
Definition TypeBase.h:8726
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9136
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9386
bool isReferenceType() const
Definition TypeBase.h:8750
bool isEnumeralType() const
Definition TypeBase.h:8857
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:8837
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:9214
bool isExtVectorBoolType() const
Definition TypeBase.h:8873
bool isMemberDataPointerType() const
Definition TypeBase.h:8818
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9061
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2847
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8861
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9152
bool isMemberPointerType() const
Definition TypeBase.h:8807
bool isAtomicType() const
Definition TypeBase.h:8918
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:9372
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2571
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:8722
bool isVectorType() const
Definition TypeBase.h:8865
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:2993
bool isAnyPointerType() const
Definition TypeBase.h:8734
TypeClass getTypeClass() const
Definition TypeBase.h:2446
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9319
bool isNullPtrType() const
Definition TypeBase.h:9129
bool isRecordType() const
Definition TypeBase.h:8853
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:9263
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:5581
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:2379
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition Decl.cpp:2620
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:2612
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition Decl.cpp:2840
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2632
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2347
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:2467
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition Decl.cpp:2538
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:2556
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:2356
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:2509
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:4079
Represents a GCC generic vector type.
Definition TypeBase.h:4274
unsigned getNumElements() const
Definition TypeBase.h:4289
QualType getElementType() const
Definition TypeBase.h:4288
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2706
Expr * getCond()
Definition Stmt.h:2758
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2770
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:436
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1511
llvm::FixedPointSemantics FixedPointSemantics
Definition Interp.h:57
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3167
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:3871
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:5770
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
};
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:906
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
const FunctionProtoType * T
@ 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:6016
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