clang 19.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 "ExprConstShared.h"
36#include "Interp/Context.h"
37#include "Interp/Frame.h"
38#include "Interp/State.h"
39#include "clang/AST/APValue.h"
42#include "clang/AST/ASTLambda.h"
43#include "clang/AST/Attr.h"
45#include "clang/AST/CharUnits.h"
47#include "clang/AST/Expr.h"
48#include "clang/AST/OSLog.h"
52#include "clang/AST/TypeLoc.h"
56#include "llvm/ADT/APFixedPoint.h"
57#include "llvm/ADT/SmallBitVector.h"
58#include "llvm/ADT/StringExtras.h"
59#include "llvm/Support/Debug.h"
60#include "llvm/Support/SaveAndRestore.h"
61#include "llvm/Support/TimeProfiler.h"
62#include "llvm/Support/raw_ostream.h"
63#include <cstring>
64#include <functional>
65#include <optional>
66
67#define DEBUG_TYPE "exprconstant"
68
69using namespace clang;
70using llvm::APFixedPoint;
71using llvm::APInt;
72using llvm::APSInt;
73using llvm::APFloat;
74using llvm::FixedPointSemantics;
75
76namespace {
77 struct LValue;
78 class CallStackFrame;
79 class EvalInfo;
80
81 using SourceLocExprScopeGuard =
83
84 static QualType getType(APValue::LValueBase B) {
85 return B.getType();
86 }
87
88 /// Get an LValue path entry, which is known to not be an array index, as a
89 /// field declaration.
90 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
91 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
92 }
93 /// Get an LValue path entry, which is known to not be an array index, as a
94 /// base class declaration.
95 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
96 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
97 }
98 /// Determine whether this LValue path entry for a base class names a virtual
99 /// base class.
100 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
101 return E.getAsBaseOrMember().getInt();
102 }
103
104 /// Given an expression, determine the type used to store the result of
105 /// evaluating that expression.
106 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
107 if (E->isPRValue())
108 return E->getType();
109 return Ctx.getLValueReferenceType(E->getType());
110 }
111
112 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
113 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
114 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
115 return DirectCallee->getAttr<AllocSizeAttr>();
116 if (const Decl *IndirectCallee = CE->getCalleeDecl())
117 return IndirectCallee->getAttr<AllocSizeAttr>();
118 return nullptr;
119 }
120
121 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
122 /// This will look through a single cast.
123 ///
124 /// Returns null if we couldn't unwrap a function with alloc_size.
125 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
126 if (!E->getType()->isPointerType())
127 return nullptr;
128
129 E = E->IgnoreParens();
130 // If we're doing a variable assignment from e.g. malloc(N), there will
131 // probably be a cast of some kind. In exotic cases, we might also see a
132 // top-level ExprWithCleanups. Ignore them either way.
133 if (const auto *FE = dyn_cast<FullExpr>(E))
134 E = FE->getSubExpr()->IgnoreParens();
135
136 if (const auto *Cast = dyn_cast<CastExpr>(E))
137 E = Cast->getSubExpr()->IgnoreParens();
138
139 if (const auto *CE = dyn_cast<CallExpr>(E))
140 return getAllocSizeAttr(CE) ? CE : nullptr;
141 return nullptr;
142 }
143
144 /// Determines whether or not the given Base contains a call to a function
145 /// with the alloc_size attribute.
146 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
147 const auto *E = Base.dyn_cast<const Expr *>();
148 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
149 }
150
151 /// Determines whether the given kind of constant expression is only ever
152 /// used for name mangling. If so, it's permitted to reference things that we
153 /// can't generate code for (in particular, dllimported functions).
154 static bool isForManglingOnly(ConstantExprKind Kind) {
155 switch (Kind) {
156 case ConstantExprKind::Normal:
157 case ConstantExprKind::ClassTemplateArgument:
158 case ConstantExprKind::ImmediateInvocation:
159 // Note that non-type template arguments of class type are emitted as
160 // template parameter objects.
161 return false;
162
163 case ConstantExprKind::NonClassTemplateArgument:
164 return true;
165 }
166 llvm_unreachable("unknown ConstantExprKind");
167 }
168
169 static bool isTemplateArgument(ConstantExprKind Kind) {
170 switch (Kind) {
171 case ConstantExprKind::Normal:
172 case ConstantExprKind::ImmediateInvocation:
173 return false;
174
175 case ConstantExprKind::ClassTemplateArgument:
176 case ConstantExprKind::NonClassTemplateArgument:
177 return true;
178 }
179 llvm_unreachable("unknown ConstantExprKind");
180 }
181
182 /// The bound to claim that an array of unknown bound has.
183 /// The value in MostDerivedArraySize is undefined in this case. So, set it
184 /// to an arbitrary value that's likely to loudly break things if it's used.
185 static const uint64_t AssumedSizeForUnsizedArray =
186 std::numeric_limits<uint64_t>::max() / 2;
187
188 /// Determines if an LValue with the given LValueBase will have an unsized
189 /// array in its designator.
190 /// Find the path length and type of the most-derived subobject in the given
191 /// path, and find the size of the containing array, if any.
192 static unsigned
193 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
195 uint64_t &ArraySize, QualType &Type, bool &IsArray,
196 bool &FirstEntryIsUnsizedArray) {
197 // This only accepts LValueBases from APValues, and APValues don't support
198 // arrays that lack size info.
199 assert(!isBaseAnAllocSizeCall(Base) &&
200 "Unsized arrays shouldn't appear here");
201 unsigned MostDerivedLength = 0;
202 Type = getType(Base);
203
204 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
205 if (Type->isArrayType()) {
206 const ArrayType *AT = Ctx.getAsArrayType(Type);
207 Type = AT->getElementType();
208 MostDerivedLength = I + 1;
209 IsArray = true;
210
211 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
212 ArraySize = CAT->getZExtSize();
213 } else {
214 assert(I == 0 && "unexpected unsized array designator");
215 FirstEntryIsUnsizedArray = true;
216 ArraySize = AssumedSizeForUnsizedArray;
217 }
218 } else if (Type->isAnyComplexType()) {
219 const ComplexType *CT = Type->castAs<ComplexType>();
220 Type = CT->getElementType();
221 ArraySize = 2;
222 MostDerivedLength = I + 1;
223 IsArray = true;
224 } else if (const FieldDecl *FD = getAsField(Path[I])) {
225 Type = FD->getType();
226 ArraySize = 0;
227 MostDerivedLength = I + 1;
228 IsArray = false;
229 } else {
230 // Path[I] describes a base class.
231 ArraySize = 0;
232 IsArray = false;
233 }
234 }
235 return MostDerivedLength;
236 }
237
238 /// A path from a glvalue to a subobject of that glvalue.
239 struct SubobjectDesignator {
240 /// True if the subobject was named in a manner not supported by C++11. Such
241 /// lvalues can still be folded, but they are not core constant expressions
242 /// and we cannot perform lvalue-to-rvalue conversions on them.
243 LLVM_PREFERRED_TYPE(bool)
244 unsigned Invalid : 1;
245
246 /// Is this a pointer one past the end of an object?
247 LLVM_PREFERRED_TYPE(bool)
248 unsigned IsOnePastTheEnd : 1;
249
250 /// Indicator of whether the first entry is an unsized array.
251 LLVM_PREFERRED_TYPE(bool)
252 unsigned FirstEntryIsAnUnsizedArray : 1;
253
254 /// Indicator of whether the most-derived object is an array element.
255 LLVM_PREFERRED_TYPE(bool)
256 unsigned MostDerivedIsArrayElement : 1;
257
258 /// The length of the path to the most-derived object of which this is a
259 /// subobject.
260 unsigned MostDerivedPathLength : 28;
261
262 /// The size of the array of which the most-derived object is an element.
263 /// This will always be 0 if the most-derived object is not an array
264 /// element. 0 is not an indicator of whether or not the most-derived object
265 /// is an array, however, because 0-length arrays are allowed.
266 ///
267 /// If the current array is an unsized array, the value of this is
268 /// undefined.
269 uint64_t MostDerivedArraySize;
270
271 /// The type of the most derived object referred to by this address.
272 QualType MostDerivedType;
273
274 typedef APValue::LValuePathEntry PathEntry;
275
276 /// The entries on the path from the glvalue to the designated subobject.
278
279 SubobjectDesignator() : Invalid(true) {}
280
281 explicit SubobjectDesignator(QualType T)
282 : Invalid(false), IsOnePastTheEnd(false),
283 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
284 MostDerivedPathLength(0), MostDerivedArraySize(0),
285 MostDerivedType(T) {}
286
287 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
288 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
289 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
290 MostDerivedPathLength(0), MostDerivedArraySize(0) {
291 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
292 if (!Invalid) {
293 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
294 ArrayRef<PathEntry> VEntries = V.getLValuePath();
295 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
296 if (V.getLValueBase()) {
297 bool IsArray = false;
298 bool FirstIsUnsizedArray = false;
299 MostDerivedPathLength = findMostDerivedSubobject(
300 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
301 MostDerivedType, IsArray, FirstIsUnsizedArray);
302 MostDerivedIsArrayElement = IsArray;
303 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
304 }
305 }
306 }
307
308 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
309 unsigned NewLength) {
310 if (Invalid)
311 return;
312
313 assert(Base && "cannot truncate path for null pointer");
314 assert(NewLength <= Entries.size() && "not a truncation");
315
316 if (NewLength == Entries.size())
317 return;
318 Entries.resize(NewLength);
319
320 bool IsArray = false;
321 bool FirstIsUnsizedArray = false;
322 MostDerivedPathLength = findMostDerivedSubobject(
323 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
324 FirstIsUnsizedArray);
325 MostDerivedIsArrayElement = IsArray;
326 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
327 }
328
329 void setInvalid() {
330 Invalid = true;
331 Entries.clear();
332 }
333
334 /// Determine whether the most derived subobject is an array without a
335 /// known bound.
336 bool isMostDerivedAnUnsizedArray() const {
337 assert(!Invalid && "Calling this makes no sense on invalid designators");
338 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
339 }
340
341 /// Determine what the most derived array's size is. Results in an assertion
342 /// failure if the most derived array lacks a size.
343 uint64_t getMostDerivedArraySize() const {
344 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
345 return MostDerivedArraySize;
346 }
347
348 /// Determine whether this is a one-past-the-end pointer.
349 bool isOnePastTheEnd() const {
350 assert(!Invalid);
351 if (IsOnePastTheEnd)
352 return true;
353 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
354 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
355 MostDerivedArraySize)
356 return true;
357 return false;
358 }
359
360 /// Get the range of valid index adjustments in the form
361 /// {maximum value that can be subtracted from this pointer,
362 /// maximum value that can be added to this pointer}
363 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
364 if (Invalid || isMostDerivedAnUnsizedArray())
365 return {0, 0};
366
367 // [expr.add]p4: For the purposes of these operators, a pointer to a
368 // nonarray object behaves the same as a pointer to the first element of
369 // an array of length one with the type of the object as its element type.
370 bool IsArray = MostDerivedPathLength == Entries.size() &&
371 MostDerivedIsArrayElement;
372 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
373 : (uint64_t)IsOnePastTheEnd;
374 uint64_t ArraySize =
375 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
376 return {ArrayIndex, ArraySize - ArrayIndex};
377 }
378
379 /// Check that this refers to a valid subobject.
380 bool isValidSubobject() const {
381 if (Invalid)
382 return false;
383 return !isOnePastTheEnd();
384 }
385 /// Check that this refers to a valid subobject, and if not, produce a
386 /// relevant diagnostic and set the designator as invalid.
387 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
388
389 /// Get the type of the designated object.
390 QualType getType(ASTContext &Ctx) const {
391 assert(!Invalid && "invalid designator has no subobject type");
392 return MostDerivedPathLength == Entries.size()
393 ? MostDerivedType
394 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
395 }
396
397 /// Update this designator to refer to the first element within this array.
398 void addArrayUnchecked(const ConstantArrayType *CAT) {
399 Entries.push_back(PathEntry::ArrayIndex(0));
400
401 // This is a most-derived object.
402 MostDerivedType = CAT->getElementType();
403 MostDerivedIsArrayElement = true;
404 MostDerivedArraySize = CAT->getZExtSize();
405 MostDerivedPathLength = Entries.size();
406 }
407 /// Update this designator to refer to the first element within the array of
408 /// elements of type T. This is an array of unknown size.
409 void addUnsizedArrayUnchecked(QualType ElemTy) {
410 Entries.push_back(PathEntry::ArrayIndex(0));
411
412 MostDerivedType = ElemTy;
413 MostDerivedIsArrayElement = true;
414 // The value in MostDerivedArraySize is undefined in this case. So, set it
415 // to an arbitrary value that's likely to loudly break things if it's
416 // used.
417 MostDerivedArraySize = AssumedSizeForUnsizedArray;
418 MostDerivedPathLength = Entries.size();
419 }
420 /// Update this designator to refer to the given base or member of this
421 /// object.
422 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
423 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
424
425 // If this isn't a base class, it's a new most-derived object.
426 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
427 MostDerivedType = FD->getType();
428 MostDerivedIsArrayElement = false;
429 MostDerivedArraySize = 0;
430 MostDerivedPathLength = Entries.size();
431 }
432 }
433 /// Update this designator to refer to the given complex component.
434 void addComplexUnchecked(QualType EltTy, bool Imag) {
435 Entries.push_back(PathEntry::ArrayIndex(Imag));
436
437 // This is technically a most-derived object, though in practice this
438 // is unlikely to matter.
439 MostDerivedType = EltTy;
440 MostDerivedIsArrayElement = true;
441 MostDerivedArraySize = 2;
442 MostDerivedPathLength = Entries.size();
443 }
444 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
445 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
446 const APSInt &N);
447 /// Add N to the address of this subobject.
448 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
449 if (Invalid || !N) return;
450 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
451 if (isMostDerivedAnUnsizedArray()) {
452 diagnoseUnsizedArrayPointerArithmetic(Info, E);
453 // Can't verify -- trust that the user is doing the right thing (or if
454 // not, trust that the caller will catch the bad behavior).
455 // FIXME: Should we reject if this overflows, at least?
456 Entries.back() = PathEntry::ArrayIndex(
457 Entries.back().getAsArrayIndex() + TruncatedN);
458 return;
459 }
460
461 // [expr.add]p4: For the purposes of these operators, a pointer to a
462 // nonarray object behaves the same as a pointer to the first element of
463 // an array of length one with the type of the object as its element type.
464 bool IsArray = MostDerivedPathLength == Entries.size() &&
465 MostDerivedIsArrayElement;
466 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
467 : (uint64_t)IsOnePastTheEnd;
468 uint64_t ArraySize =
469 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
470
471 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
472 // Calculate the actual index in a wide enough type, so we can include
473 // it in the note.
474 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
475 (llvm::APInt&)N += ArrayIndex;
476 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
477 diagnosePointerArithmetic(Info, E, N);
478 setInvalid();
479 return;
480 }
481
482 ArrayIndex += TruncatedN;
483 assert(ArrayIndex <= ArraySize &&
484 "bounds check succeeded for out-of-bounds index");
485
486 if (IsArray)
487 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
488 else
489 IsOnePastTheEnd = (ArrayIndex != 0);
490 }
491 };
492
493 /// A scope at the end of which an object can need to be destroyed.
494 enum class ScopeKind {
495 Block,
496 FullExpression,
497 Call
498 };
499
500 /// A reference to a particular call and its arguments.
501 struct CallRef {
502 CallRef() : OrigCallee(), CallIndex(0), Version() {}
503 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
504 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
505
506 explicit operator bool() const { return OrigCallee; }
507
508 /// Get the parameter that the caller initialized, corresponding to the
509 /// given parameter in the callee.
510 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
511 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
512 : PVD;
513 }
514
515 /// The callee at the point where the arguments were evaluated. This might
516 /// be different from the actual callee (a different redeclaration, or a
517 /// virtual override), but this function's parameters are the ones that
518 /// appear in the parameter map.
519 const FunctionDecl *OrigCallee;
520 /// The call index of the frame that holds the argument values.
521 unsigned CallIndex;
522 /// The version of the parameters corresponding to this call.
523 unsigned Version;
524 };
525
526 /// A stack frame in the constexpr call stack.
527 class CallStackFrame : public interp::Frame {
528 public:
529 EvalInfo &Info;
530
531 /// Parent - The caller of this stack frame.
532 CallStackFrame *Caller;
533
534 /// Callee - The function which was called.
535 const FunctionDecl *Callee;
536
537 /// This - The binding for the this pointer in this call, if any.
538 const LValue *This;
539
540 /// CallExpr - The syntactical structure of member function calls
541 const Expr *CallExpr;
542
543 /// Information on how to find the arguments to this call. Our arguments
544 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
545 /// key and this value as the version.
546 CallRef Arguments;
547
548 /// Source location information about the default argument or default
549 /// initializer expression we're evaluating, if any.
550 CurrentSourceLocExprScope CurSourceLocExprScope;
551
552 // Note that we intentionally use std::map here so that references to
553 // values are stable.
554 typedef std::pair<const void *, unsigned> MapKeyTy;
555 typedef std::map<MapKeyTy, APValue> MapTy;
556 /// Temporaries - Temporary lvalues materialized within this stack frame.
557 MapTy Temporaries;
558
559 /// CallRange - The source range of the call expression for this call.
560 SourceRange CallRange;
561
562 /// Index - The call index of this call.
563 unsigned Index;
564
565 /// The stack of integers for tracking version numbers for temporaries.
566 SmallVector<unsigned, 2> TempVersionStack = {1};
567 unsigned CurTempVersion = TempVersionStack.back();
568
569 unsigned getTempVersion() const { return TempVersionStack.back(); }
570
571 void pushTempVersion() {
572 TempVersionStack.push_back(++CurTempVersion);
573 }
574
575 void popTempVersion() {
576 TempVersionStack.pop_back();
577 }
578
579 CallRef createCall(const FunctionDecl *Callee) {
580 return {Callee, Index, ++CurTempVersion};
581 }
582
583 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
584 // on the overall stack usage of deeply-recursing constexpr evaluations.
585 // (We should cache this map rather than recomputing it repeatedly.)
586 // But let's try this and see how it goes; we can look into caching the map
587 // as a later change.
588
589 /// LambdaCaptureFields - Mapping from captured variables/this to
590 /// corresponding data members in the closure class.
591 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
592 FieldDecl *LambdaThisCaptureField = nullptr;
593
594 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
595 const FunctionDecl *Callee, const LValue *This,
596 const Expr *CallExpr, CallRef Arguments);
597 ~CallStackFrame();
598
599 // Return the temporary for Key whose version number is Version.
600 APValue *getTemporary(const void *Key, unsigned Version) {
601 MapKeyTy KV(Key, Version);
602 auto LB = Temporaries.lower_bound(KV);
603 if (LB != Temporaries.end() && LB->first == KV)
604 return &LB->second;
605 return nullptr;
606 }
607
608 // Return the current temporary for Key in the map.
609 APValue *getCurrentTemporary(const void *Key) {
610 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
611 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
612 return &std::prev(UB)->second;
613 return nullptr;
614 }
615
616 // Return the version number of the current temporary for Key.
617 unsigned getCurrentTemporaryVersion(const void *Key) const {
618 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
619 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
620 return std::prev(UB)->first.second;
621 return 0;
622 }
623
624 /// Allocate storage for an object of type T in this stack frame.
625 /// Populates LV with a handle to the created object. Key identifies
626 /// the temporary within the stack frame, and must not be reused without
627 /// bumping the temporary version number.
628 template<typename KeyT>
629 APValue &createTemporary(const KeyT *Key, QualType T,
630 ScopeKind Scope, LValue &LV);
631
632 /// Allocate storage for a parameter of a function call made in this frame.
633 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
634
635 void describe(llvm::raw_ostream &OS) const override;
636
637 Frame *getCaller() const override { return Caller; }
638 SourceRange getCallRange() const override { return CallRange; }
639 const FunctionDecl *getCallee() const override { return Callee; }
640
641 bool isStdFunction() const {
642 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
643 if (DC->isStdNamespace())
644 return true;
645 return false;
646 }
647
648 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
649 /// permitted. See MSConstexprDocs for description of permitted contexts.
650 bool CanEvalMSConstexpr = false;
651
652 private:
653 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
654 ScopeKind Scope);
655 };
656
657 /// Temporarily override 'this'.
658 class ThisOverrideRAII {
659 public:
660 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
661 : Frame(Frame), OldThis(Frame.This) {
662 if (Enable)
663 Frame.This = NewThis;
664 }
665 ~ThisOverrideRAII() {
666 Frame.This = OldThis;
667 }
668 private:
669 CallStackFrame &Frame;
670 const LValue *OldThis;
671 };
672
673 // A shorthand time trace scope struct, prints source range, for example
674 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
675 class ExprTimeTraceScope {
676 public:
677 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
678 : TimeScope(Name, [E, &Ctx] {
679 return E->getSourceRange().printToString(Ctx.getSourceManager());
680 }) {}
681
682 private:
683 llvm::TimeTraceScope TimeScope;
684 };
685
686 /// RAII object used to change the current ability of
687 /// [[msvc::constexpr]] evaulation.
688 struct MSConstexprContextRAII {
689 CallStackFrame &Frame;
690 bool OldValue;
691 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
692 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
693 Frame.CanEvalMSConstexpr = Value;
694 }
695
696 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
697 };
698}
699
700static bool HandleDestruction(EvalInfo &Info, const Expr *E,
701 const LValue &This, QualType ThisType);
702static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
704 QualType T);
705
706namespace {
707 /// A cleanup, and a flag indicating whether it is lifetime-extended.
708 class Cleanup {
709 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
711 QualType T;
712
713 public:
714 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
715 ScopeKind Scope)
716 : Value(Val, Scope), Base(Base), T(T) {}
717
718 /// Determine whether this cleanup should be performed at the end of the
719 /// given kind of scope.
720 bool isDestroyedAtEndOf(ScopeKind K) const {
721 return (int)Value.getInt() >= (int)K;
722 }
723 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
724 if (RunDestructors) {
726 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
727 Loc = VD->getLocation();
728 else if (const Expr *E = Base.dyn_cast<const Expr*>())
729 Loc = E->getExprLoc();
730 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
731 }
732 *Value.getPointer() = APValue();
733 return true;
734 }
735
736 bool hasSideEffect() {
737 return T.isDestructedType();
738 }
739 };
740
741 /// A reference to an object whose construction we are currently evaluating.
742 struct ObjectUnderConstruction {
745 friend bool operator==(const ObjectUnderConstruction &LHS,
746 const ObjectUnderConstruction &RHS) {
747 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
748 }
749 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
750 return llvm::hash_combine(Obj.Base, Obj.Path);
751 }
752 };
753 enum class ConstructionPhase {
754 None,
755 Bases,
756 AfterBases,
757 AfterFields,
758 Destroying,
759 DestroyingBases
760 };
761}
762
763namespace llvm {
764template<> struct DenseMapInfo<ObjectUnderConstruction> {
765 using Base = DenseMapInfo<APValue::LValueBase>;
766 static ObjectUnderConstruction getEmptyKey() {
767 return {Base::getEmptyKey(), {}}; }
768 static ObjectUnderConstruction getTombstoneKey() {
769 return {Base::getTombstoneKey(), {}};
770 }
771 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
772 return hash_value(Object);
773 }
774 static bool isEqual(const ObjectUnderConstruction &LHS,
775 const ObjectUnderConstruction &RHS) {
776 return LHS == RHS;
777 }
778};
779}
780
781namespace {
782 /// A dynamically-allocated heap object.
783 struct DynAlloc {
784 /// The value of this heap-allocated object.
786 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
787 /// or a CallExpr (the latter is for direct calls to operator new inside
788 /// std::allocator<T>::allocate).
789 const Expr *AllocExpr = nullptr;
790
791 enum Kind {
792 New,
793 ArrayNew,
794 StdAllocator
795 };
796
797 /// Get the kind of the allocation. This must match between allocation
798 /// and deallocation.
799 Kind getKind() const {
800 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
801 return NE->isArray() ? ArrayNew : New;
802 assert(isa<CallExpr>(AllocExpr));
803 return StdAllocator;
804 }
805 };
806
807 struct DynAllocOrder {
808 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
809 return L.getIndex() < R.getIndex();
810 }
811 };
812
813 /// EvalInfo - This is a private struct used by the evaluator to capture
814 /// information about a subexpression as it is folded. It retains information
815 /// about the AST context, but also maintains information about the folded
816 /// expression.
817 ///
818 /// If an expression could be evaluated, it is still possible it is not a C
819 /// "integer constant expression" or constant expression. If not, this struct
820 /// captures information about how and why not.
821 ///
822 /// One bit of information passed *into* the request for constant folding
823 /// indicates whether the subexpression is "evaluated" or not according to C
824 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
825 /// evaluate the expression regardless of what the RHS is, but C only allows
826 /// certain things in certain situations.
827 class EvalInfo : public interp::State {
828 public:
829 ASTContext &Ctx;
830
831 /// EvalStatus - Contains information about the evaluation.
832 Expr::EvalStatus &EvalStatus;
833
834 /// CurrentCall - The top of the constexpr call stack.
835 CallStackFrame *CurrentCall;
836
837 /// CallStackDepth - The number of calls in the call stack right now.
838 unsigned CallStackDepth;
839
840 /// NextCallIndex - The next call index to assign.
841 unsigned NextCallIndex;
842
843 /// StepsLeft - The remaining number of evaluation steps we're permitted
844 /// to perform. This is essentially a limit for the number of statements
845 /// we will evaluate.
846 unsigned StepsLeft;
847
848 /// Enable the experimental new constant interpreter. If an expression is
849 /// not supported by the interpreter, an error is triggered.
850 bool EnableNewConstInterp;
851
852 /// BottomFrame - The frame in which evaluation started. This must be
853 /// initialized after CurrentCall and CallStackDepth.
854 CallStackFrame BottomFrame;
855
856 /// A stack of values whose lifetimes end at the end of some surrounding
857 /// evaluation frame.
859
860 /// EvaluatingDecl - This is the declaration whose initializer is being
861 /// evaluated, if any.
862 APValue::LValueBase EvaluatingDecl;
863
864 enum class EvaluatingDeclKind {
865 None,
866 /// We're evaluating the construction of EvaluatingDecl.
867 Ctor,
868 /// We're evaluating the destruction of EvaluatingDecl.
869 Dtor,
870 };
871 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
872
873 /// EvaluatingDeclValue - This is the value being constructed for the
874 /// declaration whose initializer is being evaluated, if any.
875 APValue *EvaluatingDeclValue;
876
877 /// Set of objects that are currently being constructed.
878 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
879 ObjectsUnderConstruction;
880
881 /// Current heap allocations, along with the location where each was
882 /// allocated. We use std::map here because we need stable addresses
883 /// for the stored APValues.
884 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
885
886 /// The number of heap allocations performed so far in this evaluation.
887 unsigned NumHeapAllocs = 0;
888
889 struct EvaluatingConstructorRAII {
890 EvalInfo &EI;
891 ObjectUnderConstruction Object;
892 bool DidInsert;
893 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
894 bool HasBases)
895 : EI(EI), Object(Object) {
896 DidInsert =
897 EI.ObjectsUnderConstruction
898 .insert({Object, HasBases ? ConstructionPhase::Bases
899 : ConstructionPhase::AfterBases})
900 .second;
901 }
902 void finishedConstructingBases() {
903 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
904 }
905 void finishedConstructingFields() {
906 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
907 }
908 ~EvaluatingConstructorRAII() {
909 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
910 }
911 };
912
913 struct EvaluatingDestructorRAII {
914 EvalInfo &EI;
915 ObjectUnderConstruction Object;
916 bool DidInsert;
917 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
918 : EI(EI), Object(Object) {
919 DidInsert = EI.ObjectsUnderConstruction
920 .insert({Object, ConstructionPhase::Destroying})
921 .second;
922 }
923 void startedDestroyingBases() {
924 EI.ObjectsUnderConstruction[Object] =
925 ConstructionPhase::DestroyingBases;
926 }
927 ~EvaluatingDestructorRAII() {
928 if (DidInsert)
929 EI.ObjectsUnderConstruction.erase(Object);
930 }
931 };
932
933 ConstructionPhase
934 isEvaluatingCtorDtor(APValue::LValueBase Base,
936 return ObjectsUnderConstruction.lookup({Base, Path});
937 }
938
939 /// If we're currently speculatively evaluating, the outermost call stack
940 /// depth at which we can mutate state, otherwise 0.
941 unsigned SpeculativeEvaluationDepth = 0;
942
943 /// The current array initialization index, if we're performing array
944 /// initialization.
945 uint64_t ArrayInitIndex = -1;
946
947 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
948 /// notes attached to it will also be stored, otherwise they will not be.
949 bool HasActiveDiagnostic;
950
951 /// Have we emitted a diagnostic explaining why we couldn't constant
952 /// fold (not just why it's not strictly a constant expression)?
953 bool HasFoldFailureDiagnostic;
954
955 /// Whether we're checking that an expression is a potential constant
956 /// expression. If so, do not fail on constructs that could become constant
957 /// later on (such as a use of an undefined global).
958 bool CheckingPotentialConstantExpression = false;
959
960 /// Whether we're checking for an expression that has undefined behavior.
961 /// If so, we will produce warnings if we encounter an operation that is
962 /// always undefined.
963 ///
964 /// Note that we still need to evaluate the expression normally when this
965 /// is set; this is used when evaluating ICEs in C.
966 bool CheckingForUndefinedBehavior = false;
967
968 enum EvaluationMode {
969 /// Evaluate as a constant expression. Stop if we find that the expression
970 /// is not a constant expression.
971 EM_ConstantExpression,
972
973 /// Evaluate as a constant expression. Stop if we find that the expression
974 /// is not a constant expression. Some expressions can be retried in the
975 /// optimizer if we don't constant fold them here, but in an unevaluated
976 /// context we try to fold them immediately since the optimizer never
977 /// gets a chance to look at it.
978 EM_ConstantExpressionUnevaluated,
979
980 /// Fold the expression to a constant. Stop if we hit a side-effect that
981 /// we can't model.
982 EM_ConstantFold,
983
984 /// Evaluate in any way we know how. Don't worry about side-effects that
985 /// can't be modeled.
986 EM_IgnoreSideEffects,
987 } EvalMode;
988
989 /// Are we checking whether the expression is a potential constant
990 /// expression?
991 bool checkingPotentialConstantExpression() const override {
992 return CheckingPotentialConstantExpression;
993 }
994
995 /// Are we checking an expression for overflow?
996 // FIXME: We should check for any kind of undefined or suspicious behavior
997 // in such constructs, not just overflow.
998 bool checkingForUndefinedBehavior() const override {
999 return CheckingForUndefinedBehavior;
1000 }
1001
1002 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
1003 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
1004 CallStackDepth(0), NextCallIndex(1),
1005 StepsLeft(C.getLangOpts().ConstexprStepLimit),
1006 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
1007 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
1008 /*This=*/nullptr,
1009 /*CallExpr=*/nullptr, CallRef()),
1010 EvaluatingDecl((const ValueDecl *)nullptr),
1011 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
1012 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
1013
1014 ~EvalInfo() {
1015 discardCleanups();
1016 }
1017
1018 ASTContext &getCtx() const override { return Ctx; }
1019
1020 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1021 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1022 EvaluatingDecl = Base;
1023 IsEvaluatingDecl = EDK;
1024 EvaluatingDeclValue = &Value;
1025 }
1026
1027 bool CheckCallLimit(SourceLocation Loc) {
1028 // Don't perform any constexpr calls (other than the call we're checking)
1029 // when checking a potential constant expression.
1030 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1031 return false;
1032 if (NextCallIndex == 0) {
1033 // NextCallIndex has wrapped around.
1034 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1035 return false;
1036 }
1037 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1038 return true;
1039 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1040 << getLangOpts().ConstexprCallDepth;
1041 return false;
1042 }
1043
1044 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1045 uint64_t ElemCount, bool Diag) {
1046 // FIXME: GH63562
1047 // APValue stores array extents as unsigned,
1048 // so anything that is greater that unsigned would overflow when
1049 // constructing the array, we catch this here.
1050 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1051 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1052 if (Diag)
1053 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1054 return false;
1055 }
1056
1057 // FIXME: GH63562
1058 // Arrays allocate an APValue per element.
1059 // We use the number of constexpr steps as a proxy for the maximum size
1060 // of arrays to avoid exhausting the system resources, as initialization
1061 // of each element is likely to take some number of steps anyway.
1062 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1063 if (ElemCount > Limit) {
1064 if (Diag)
1065 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1066 << ElemCount << Limit;
1067 return false;
1068 }
1069 return true;
1070 }
1071
1072 std::pair<CallStackFrame *, unsigned>
1073 getCallFrameAndDepth(unsigned CallIndex) {
1074 assert(CallIndex && "no call index in getCallFrameAndDepth");
1075 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1076 // be null in this loop.
1077 unsigned Depth = CallStackDepth;
1078 CallStackFrame *Frame = CurrentCall;
1079 while (Frame->Index > CallIndex) {
1080 Frame = Frame->Caller;
1081 --Depth;
1082 }
1083 if (Frame->Index == CallIndex)
1084 return {Frame, Depth};
1085 return {nullptr, 0};
1086 }
1087
1088 bool nextStep(const Stmt *S) {
1089 if (!StepsLeft) {
1090 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1091 return false;
1092 }
1093 --StepsLeft;
1094 return true;
1095 }
1096
1097 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1098
1099 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1100 std::optional<DynAlloc *> Result;
1101 auto It = HeapAllocs.find(DA);
1102 if (It != HeapAllocs.end())
1103 Result = &It->second;
1104 return Result;
1105 }
1106
1107 /// Get the allocated storage for the given parameter of the given call.
1108 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1109 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1110 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1111 : nullptr;
1112 }
1113
1114 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1115 struct StdAllocatorCaller {
1116 unsigned FrameIndex;
1117 QualType ElemType;
1118 explicit operator bool() const { return FrameIndex != 0; };
1119 };
1120
1121 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1122 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1123 Call = Call->Caller) {
1124 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1125 if (!MD)
1126 continue;
1127 const IdentifierInfo *FnII = MD->getIdentifier();
1128 if (!FnII || !FnII->isStr(FnName))
1129 continue;
1130
1131 const auto *CTSD =
1132 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1133 if (!CTSD)
1134 continue;
1135
1136 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1137 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1138 if (CTSD->isInStdNamespace() && ClassII &&
1139 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1140 TAL[0].getKind() == TemplateArgument::Type)
1141 return {Call->Index, TAL[0].getAsType()};
1142 }
1143
1144 return {};
1145 }
1146
1147 void performLifetimeExtension() {
1148 // Disable the cleanups for lifetime-extended temporaries.
1149 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1150 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1151 });
1152 }
1153
1154 /// Throw away any remaining cleanups at the end of evaluation. If any
1155 /// cleanups would have had a side-effect, note that as an unmodeled
1156 /// side-effect and return false. Otherwise, return true.
1157 bool discardCleanups() {
1158 for (Cleanup &C : CleanupStack) {
1159 if (C.hasSideEffect() && !noteSideEffect()) {
1160 CleanupStack.clear();
1161 return false;
1162 }
1163 }
1164 CleanupStack.clear();
1165 return true;
1166 }
1167
1168 private:
1169 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1170 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1171
1172 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1173 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1174
1175 void setFoldFailureDiagnostic(bool Flag) override {
1176 HasFoldFailureDiagnostic = Flag;
1177 }
1178
1179 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1180
1181 // If we have a prior diagnostic, it will be noting that the expression
1182 // isn't a constant expression. This diagnostic is more important,
1183 // unless we require this evaluation to produce a constant expression.
1184 //
1185 // FIXME: We might want to show both diagnostics to the user in
1186 // EM_ConstantFold mode.
1187 bool hasPriorDiagnostic() override {
1188 if (!EvalStatus.Diag->empty()) {
1189 switch (EvalMode) {
1190 case EM_ConstantFold:
1191 case EM_IgnoreSideEffects:
1192 if (!HasFoldFailureDiagnostic)
1193 break;
1194 // We've already failed to fold something. Keep that diagnostic.
1195 [[fallthrough]];
1196 case EM_ConstantExpression:
1197 case EM_ConstantExpressionUnevaluated:
1198 setActiveDiagnostic(false);
1199 return true;
1200 }
1201 }
1202 return false;
1203 }
1204
1205 unsigned getCallStackDepth() override { return CallStackDepth; }
1206
1207 public:
1208 /// Should we continue evaluation after encountering a side-effect that we
1209 /// couldn't model?
1210 bool keepEvaluatingAfterSideEffect() {
1211 switch (EvalMode) {
1212 case EM_IgnoreSideEffects:
1213 return true;
1214
1215 case EM_ConstantExpression:
1216 case EM_ConstantExpressionUnevaluated:
1217 case EM_ConstantFold:
1218 // By default, assume any side effect might be valid in some other
1219 // evaluation of this expression from a different context.
1220 return checkingPotentialConstantExpression() ||
1221 checkingForUndefinedBehavior();
1222 }
1223 llvm_unreachable("Missed EvalMode case");
1224 }
1225
1226 /// Note that we have had a side-effect, and determine whether we should
1227 /// keep evaluating.
1228 bool noteSideEffect() {
1229 EvalStatus.HasSideEffects = true;
1230 return keepEvaluatingAfterSideEffect();
1231 }
1232
1233 /// Should we continue evaluation after encountering undefined behavior?
1234 bool keepEvaluatingAfterUndefinedBehavior() {
1235 switch (EvalMode) {
1236 case EM_IgnoreSideEffects:
1237 case EM_ConstantFold:
1238 return true;
1239
1240 case EM_ConstantExpression:
1241 case EM_ConstantExpressionUnevaluated:
1242 return checkingForUndefinedBehavior();
1243 }
1244 llvm_unreachable("Missed EvalMode case");
1245 }
1246
1247 /// Note that we hit something that was technically undefined behavior, but
1248 /// that we can evaluate past it (such as signed overflow or floating-point
1249 /// division by zero.)
1250 bool noteUndefinedBehavior() override {
1251 EvalStatus.HasUndefinedBehavior = true;
1252 return keepEvaluatingAfterUndefinedBehavior();
1253 }
1254
1255 /// Should we continue evaluation as much as possible after encountering a
1256 /// construct which can't be reduced to a value?
1257 bool keepEvaluatingAfterFailure() const override {
1258 if (!StepsLeft)
1259 return false;
1260
1261 switch (EvalMode) {
1262 case EM_ConstantExpression:
1263 case EM_ConstantExpressionUnevaluated:
1264 case EM_ConstantFold:
1265 case EM_IgnoreSideEffects:
1266 return checkingPotentialConstantExpression() ||
1267 checkingForUndefinedBehavior();
1268 }
1269 llvm_unreachable("Missed EvalMode case");
1270 }
1271
1272 /// Notes that we failed to evaluate an expression that other expressions
1273 /// directly depend on, and determine if we should keep evaluating. This
1274 /// should only be called if we actually intend to keep evaluating.
1275 ///
1276 /// Call noteSideEffect() instead if we may be able to ignore the value that
1277 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1278 ///
1279 /// (Foo(), 1) // use noteSideEffect
1280 /// (Foo() || true) // use noteSideEffect
1281 /// Foo() + 1 // use noteFailure
1282 [[nodiscard]] bool noteFailure() {
1283 // Failure when evaluating some expression often means there is some
1284 // subexpression whose evaluation was skipped. Therefore, (because we
1285 // don't track whether we skipped an expression when unwinding after an
1286 // evaluation failure) every evaluation failure that bubbles up from a
1287 // subexpression implies that a side-effect has potentially happened. We
1288 // skip setting the HasSideEffects flag to true until we decide to
1289 // continue evaluating after that point, which happens here.
1290 bool KeepGoing = keepEvaluatingAfterFailure();
1291 EvalStatus.HasSideEffects |= KeepGoing;
1292 return KeepGoing;
1293 }
1294
1295 class ArrayInitLoopIndex {
1296 EvalInfo &Info;
1297 uint64_t OuterIndex;
1298
1299 public:
1300 ArrayInitLoopIndex(EvalInfo &Info)
1301 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1302 Info.ArrayInitIndex = 0;
1303 }
1304 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1305
1306 operator uint64_t&() { return Info.ArrayInitIndex; }
1307 };
1308 };
1309
1310 /// Object used to treat all foldable expressions as constant expressions.
1311 struct FoldConstant {
1312 EvalInfo &Info;
1313 bool Enabled;
1314 bool HadNoPriorDiags;
1315 EvalInfo::EvaluationMode OldMode;
1316
1317 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1318 : Info(Info),
1319 Enabled(Enabled),
1320 HadNoPriorDiags(Info.EvalStatus.Diag &&
1321 Info.EvalStatus.Diag->empty() &&
1322 !Info.EvalStatus.HasSideEffects),
1323 OldMode(Info.EvalMode) {
1324 if (Enabled)
1325 Info.EvalMode = EvalInfo::EM_ConstantFold;
1326 }
1327 void keepDiagnostics() { Enabled = false; }
1328 ~FoldConstant() {
1329 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1330 !Info.EvalStatus.HasSideEffects)
1331 Info.EvalStatus.Diag->clear();
1332 Info.EvalMode = OldMode;
1333 }
1334 };
1335
1336 /// RAII object used to set the current evaluation mode to ignore
1337 /// side-effects.
1338 struct IgnoreSideEffectsRAII {
1339 EvalInfo &Info;
1340 EvalInfo::EvaluationMode OldMode;
1341 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1342 : Info(Info), OldMode(Info.EvalMode) {
1343 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1344 }
1345
1346 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1347 };
1348
1349 /// RAII object used to optionally suppress diagnostics and side-effects from
1350 /// a speculative evaluation.
1351 class SpeculativeEvaluationRAII {
1352 EvalInfo *Info = nullptr;
1353 Expr::EvalStatus OldStatus;
1354 unsigned OldSpeculativeEvaluationDepth = 0;
1355
1356 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1357 Info = Other.Info;
1358 OldStatus = Other.OldStatus;
1359 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1360 Other.Info = nullptr;
1361 }
1362
1363 void maybeRestoreState() {
1364 if (!Info)
1365 return;
1366
1367 Info->EvalStatus = OldStatus;
1368 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1369 }
1370
1371 public:
1372 SpeculativeEvaluationRAII() = default;
1373
1374 SpeculativeEvaluationRAII(
1375 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1376 : Info(&Info), OldStatus(Info.EvalStatus),
1377 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1378 Info.EvalStatus.Diag = NewDiag;
1379 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1380 }
1381
1382 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1383 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1384 moveFromAndCancel(std::move(Other));
1385 }
1386
1387 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1388 maybeRestoreState();
1389 moveFromAndCancel(std::move(Other));
1390 return *this;
1391 }
1392
1393 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1394 };
1395
1396 /// RAII object wrapping a full-expression or block scope, and handling
1397 /// the ending of the lifetime of temporaries created within it.
1398 template<ScopeKind Kind>
1399 class ScopeRAII {
1400 EvalInfo &Info;
1401 unsigned OldStackSize;
1402 public:
1403 ScopeRAII(EvalInfo &Info)
1404 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1405 // Push a new temporary version. This is needed to distinguish between
1406 // temporaries created in different iterations of a loop.
1407 Info.CurrentCall->pushTempVersion();
1408 }
1409 bool destroy(bool RunDestructors = true) {
1410 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1411 OldStackSize = -1U;
1412 return OK;
1413 }
1414 ~ScopeRAII() {
1415 if (OldStackSize != -1U)
1416 destroy(false);
1417 // Body moved to a static method to encourage the compiler to inline away
1418 // instances of this class.
1419 Info.CurrentCall->popTempVersion();
1420 }
1421 private:
1422 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1423 unsigned OldStackSize) {
1424 assert(OldStackSize <= Info.CleanupStack.size() &&
1425 "running cleanups out of order?");
1426
1427 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1428 // for a full-expression scope.
1429 bool Success = true;
1430 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1431 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1432 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1433 Success = false;
1434 break;
1435 }
1436 }
1437 }
1438
1439 // Compact any retained cleanups.
1440 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1441 if (Kind != ScopeKind::Block)
1442 NewEnd =
1443 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1444 return C.isDestroyedAtEndOf(Kind);
1445 });
1446 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1447 return Success;
1448 }
1449 };
1450 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1451 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1452 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1453}
1454
1455bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1456 CheckSubobjectKind CSK) {
1457 if (Invalid)
1458 return false;
1459 if (isOnePastTheEnd()) {
1460 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1461 << CSK;
1462 setInvalid();
1463 return false;
1464 }
1465 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1466 // must actually be at least one array element; even a VLA cannot have a
1467 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1468 return true;
1469}
1470
1471void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1472 const Expr *E) {
1473 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1474 // Do not set the designator as invalid: we can represent this situation,
1475 // and correct handling of __builtin_object_size requires us to do so.
1476}
1477
1478void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1479 const Expr *E,
1480 const APSInt &N) {
1481 // If we're complaining, we must be able to statically determine the size of
1482 // the most derived array.
1483 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1484 Info.CCEDiag(E, diag::note_constexpr_array_index)
1485 << N << /*array*/ 0
1486 << static_cast<unsigned>(getMostDerivedArraySize());
1487 else
1488 Info.CCEDiag(E, diag::note_constexpr_array_index)
1489 << N << /*non-array*/ 1;
1490 setInvalid();
1491}
1492
1493CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1494 const FunctionDecl *Callee, const LValue *This,
1495 const Expr *CallExpr, CallRef Call)
1496 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1497 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1498 Index(Info.NextCallIndex++) {
1499 Info.CurrentCall = this;
1500 ++Info.CallStackDepth;
1501}
1502
1503CallStackFrame::~CallStackFrame() {
1504 assert(Info.CurrentCall == this && "calls retired out of order");
1505 --Info.CallStackDepth;
1506 Info.CurrentCall = Caller;
1507}
1508
1509static bool isRead(AccessKinds AK) {
1510 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1511}
1512
1514 switch (AK) {
1515 case AK_Read:
1517 case AK_MemberCall:
1518 case AK_DynamicCast:
1519 case AK_TypeId:
1520 return false;
1521 case AK_Assign:
1522 case AK_Increment:
1523 case AK_Decrement:
1524 case AK_Construct:
1525 case AK_Destroy:
1526 return true;
1527 }
1528 llvm_unreachable("unknown access kind");
1529}
1530
1531static bool isAnyAccess(AccessKinds AK) {
1532 return isRead(AK) || isModification(AK);
1533}
1534
1535/// Is this an access per the C++ definition?
1537 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1538}
1539
1540/// Is this kind of axcess valid on an indeterminate object value?
1542 switch (AK) {
1543 case AK_Read:
1544 case AK_Increment:
1545 case AK_Decrement:
1546 // These need the object's value.
1547 return false;
1548
1550 case AK_Assign:
1551 case AK_Construct:
1552 case AK_Destroy:
1553 // Construction and destruction don't need the value.
1554 return true;
1555
1556 case AK_MemberCall:
1557 case AK_DynamicCast:
1558 case AK_TypeId:
1559 // These aren't really meaningful on scalars.
1560 return true;
1561 }
1562 llvm_unreachable("unknown access kind");
1563}
1564
1565namespace {
1566 struct ComplexValue {
1567 private:
1568 bool IsInt;
1569
1570 public:
1571 APSInt IntReal, IntImag;
1572 APFloat FloatReal, FloatImag;
1573
1574 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1575
1576 void makeComplexFloat() { IsInt = false; }
1577 bool isComplexFloat() const { return !IsInt; }
1578 APFloat &getComplexFloatReal() { return FloatReal; }
1579 APFloat &getComplexFloatImag() { return FloatImag; }
1580
1581 void makeComplexInt() { IsInt = true; }
1582 bool isComplexInt() const { return IsInt; }
1583 APSInt &getComplexIntReal() { return IntReal; }
1584 APSInt &getComplexIntImag() { return IntImag; }
1585
1586 void moveInto(APValue &v) const {
1587 if (isComplexFloat())
1588 v = APValue(FloatReal, FloatImag);
1589 else
1590 v = APValue(IntReal, IntImag);
1591 }
1592 void setFrom(const APValue &v) {
1593 assert(v.isComplexFloat() || v.isComplexInt());
1594 if (v.isComplexFloat()) {
1595 makeComplexFloat();
1596 FloatReal = v.getComplexFloatReal();
1597 FloatImag = v.getComplexFloatImag();
1598 } else {
1599 makeComplexInt();
1600 IntReal = v.getComplexIntReal();
1601 IntImag = v.getComplexIntImag();
1602 }
1603 }
1604 };
1605
1606 struct LValue {
1608 CharUnits Offset;
1609 SubobjectDesignator Designator;
1610 bool IsNullPtr : 1;
1611 bool InvalidBase : 1;
1612
1613 const APValue::LValueBase getLValueBase() const { return Base; }
1614 CharUnits &getLValueOffset() { return Offset; }
1615 const CharUnits &getLValueOffset() const { return Offset; }
1616 SubobjectDesignator &getLValueDesignator() { return Designator; }
1617 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1618 bool isNullPointer() const { return IsNullPtr;}
1619
1620 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1621 unsigned getLValueVersion() const { return Base.getVersion(); }
1622
1623 void moveInto(APValue &V) const {
1624 if (Designator.Invalid)
1625 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1626 else {
1627 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1628 V = APValue(Base, Offset, Designator.Entries,
1629 Designator.IsOnePastTheEnd, IsNullPtr);
1630 }
1631 }
1632 void setFrom(ASTContext &Ctx, const APValue &V) {
1633 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1634 Base = V.getLValueBase();
1635 Offset = V.getLValueOffset();
1636 InvalidBase = false;
1637 Designator = SubobjectDesignator(Ctx, V);
1638 IsNullPtr = V.isNullPointer();
1639 }
1640
1641 void set(APValue::LValueBase B, bool BInvalid = false) {
1642#ifndef NDEBUG
1643 // We only allow a few types of invalid bases. Enforce that here.
1644 if (BInvalid) {
1645 const auto *E = B.get<const Expr *>();
1646 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1647 "Unexpected type of invalid base");
1648 }
1649#endif
1650
1651 Base = B;
1652 Offset = CharUnits::fromQuantity(0);
1653 InvalidBase = BInvalid;
1654 Designator = SubobjectDesignator(getType(B));
1655 IsNullPtr = false;
1656 }
1657
1658 void setNull(ASTContext &Ctx, QualType PointerTy) {
1659 Base = (const ValueDecl *)nullptr;
1660 Offset =
1662 InvalidBase = false;
1663 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1664 IsNullPtr = true;
1665 }
1666
1667 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1668 set(B, true);
1669 }
1670
1671 std::string toString(ASTContext &Ctx, QualType T) const {
1672 APValue Printable;
1673 moveInto(Printable);
1674 return Printable.getAsString(Ctx, T);
1675 }
1676
1677 private:
1678 // Check that this LValue is not based on a null pointer. If it is, produce
1679 // a diagnostic and mark the designator as invalid.
1680 template <typename GenDiagType>
1681 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1682 if (Designator.Invalid)
1683 return false;
1684 if (IsNullPtr) {
1685 GenDiag();
1686 Designator.setInvalid();
1687 return false;
1688 }
1689 return true;
1690 }
1691
1692 public:
1693 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1694 CheckSubobjectKind CSK) {
1695 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1696 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1697 });
1698 }
1699
1700 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1701 AccessKinds AK) {
1702 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1703 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1704 });
1705 }
1706
1707 // Check this LValue refers to an object. If not, set the designator to be
1708 // invalid and emit a diagnostic.
1709 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1710 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1711 Designator.checkSubobject(Info, E, CSK);
1712 }
1713
1714 void addDecl(EvalInfo &Info, const Expr *E,
1715 const Decl *D, bool Virtual = false) {
1716 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1717 Designator.addDeclUnchecked(D, Virtual);
1718 }
1719 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1720 if (!Designator.Entries.empty()) {
1721 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1722 Designator.setInvalid();
1723 return;
1724 }
1725 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1726 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1727 Designator.FirstEntryIsAnUnsizedArray = true;
1728 Designator.addUnsizedArrayUnchecked(ElemTy);
1729 }
1730 }
1731 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1732 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1733 Designator.addArrayUnchecked(CAT);
1734 }
1735 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1736 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1737 Designator.addComplexUnchecked(EltTy, Imag);
1738 }
1739 void clearIsNullPointer() {
1740 IsNullPtr = false;
1741 }
1742 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1743 const APSInt &Index, CharUnits ElementSize) {
1744 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1745 // but we're not required to diagnose it and it's valid in C++.)
1746 if (!Index)
1747 return;
1748
1749 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1750 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1751 // offsets.
1752 uint64_t Offset64 = Offset.getQuantity();
1753 uint64_t ElemSize64 = ElementSize.getQuantity();
1754 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1755 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1756
1757 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1758 Designator.adjustIndex(Info, E, Index);
1759 clearIsNullPointer();
1760 }
1761 void adjustOffset(CharUnits N) {
1762 Offset += N;
1763 if (N.getQuantity())
1764 clearIsNullPointer();
1765 }
1766 };
1767
1768 struct MemberPtr {
1769 MemberPtr() {}
1770 explicit MemberPtr(const ValueDecl *Decl)
1771 : DeclAndIsDerivedMember(Decl, false) {}
1772
1773 /// The member or (direct or indirect) field referred to by this member
1774 /// pointer, or 0 if this is a null member pointer.
1775 const ValueDecl *getDecl() const {
1776 return DeclAndIsDerivedMember.getPointer();
1777 }
1778 /// Is this actually a member of some type derived from the relevant class?
1779 bool isDerivedMember() const {
1780 return DeclAndIsDerivedMember.getInt();
1781 }
1782 /// Get the class which the declaration actually lives in.
1783 const CXXRecordDecl *getContainingRecord() const {
1784 return cast<CXXRecordDecl>(
1785 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1786 }
1787
1788 void moveInto(APValue &V) const {
1789 V = APValue(getDecl(), isDerivedMember(), Path);
1790 }
1791 void setFrom(const APValue &V) {
1792 assert(V.isMemberPointer());
1793 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1794 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1795 Path.clear();
1796 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1797 Path.insert(Path.end(), P.begin(), P.end());
1798 }
1799
1800 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1801 /// whether the member is a member of some class derived from the class type
1802 /// of the member pointer.
1803 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1804 /// Path - The path of base/derived classes from the member declaration's
1805 /// class (exclusive) to the class type of the member pointer (inclusive).
1807
1808 /// Perform a cast towards the class of the Decl (either up or down the
1809 /// hierarchy).
1810 bool castBack(const CXXRecordDecl *Class) {
1811 assert(!Path.empty());
1812 const CXXRecordDecl *Expected;
1813 if (Path.size() >= 2)
1814 Expected = Path[Path.size() - 2];
1815 else
1816 Expected = getContainingRecord();
1817 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1818 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1819 // if B does not contain the original member and is not a base or
1820 // derived class of the class containing the original member, the result
1821 // of the cast is undefined.
1822 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1823 // (D::*). We consider that to be a language defect.
1824 return false;
1825 }
1826 Path.pop_back();
1827 return true;
1828 }
1829 /// Perform a base-to-derived member pointer cast.
1830 bool castToDerived(const CXXRecordDecl *Derived) {
1831 if (!getDecl())
1832 return true;
1833 if (!isDerivedMember()) {
1834 Path.push_back(Derived);
1835 return true;
1836 }
1837 if (!castBack(Derived))
1838 return false;
1839 if (Path.empty())
1840 DeclAndIsDerivedMember.setInt(false);
1841 return true;
1842 }
1843 /// Perform a derived-to-base member pointer cast.
1844 bool castToBase(const CXXRecordDecl *Base) {
1845 if (!getDecl())
1846 return true;
1847 if (Path.empty())
1848 DeclAndIsDerivedMember.setInt(true);
1849 if (isDerivedMember()) {
1850 Path.push_back(Base);
1851 return true;
1852 }
1853 return castBack(Base);
1854 }
1855 };
1856
1857 /// Compare two member pointers, which are assumed to be of the same type.
1858 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1859 if (!LHS.getDecl() || !RHS.getDecl())
1860 return !LHS.getDecl() && !RHS.getDecl();
1861 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1862 return false;
1863 return LHS.Path == RHS.Path;
1864 }
1865}
1866
1867static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1868static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1869 const LValue &This, const Expr *E,
1870 bool AllowNonLiteralTypes = false);
1871static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1872 bool InvalidBaseOK = false);
1873static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1874 bool InvalidBaseOK = false);
1875static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1876 EvalInfo &Info);
1877static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1878static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1879static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1880 EvalInfo &Info);
1881static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1882static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1883static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1884 EvalInfo &Info);
1885static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1886static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1887 EvalInfo &Info);
1888
1889/// Evaluate an integer or fixed point expression into an APResult.
1890static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1891 EvalInfo &Info);
1892
1893/// Evaluate only a fixed point expression into an APResult.
1894static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1895 EvalInfo &Info);
1896
1897//===----------------------------------------------------------------------===//
1898// Misc utilities
1899//===----------------------------------------------------------------------===//
1900
1901/// Negate an APSInt in place, converting it to a signed form if necessary, and
1902/// preserving its value (by extending by up to one bit as needed).
1903static void negateAsSigned(APSInt &Int) {
1904 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1905 Int = Int.extend(Int.getBitWidth() + 1);
1906 Int.setIsSigned(true);
1907 }
1908 Int = -Int;
1909}
1910
1911template<typename KeyT>
1912APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1913 ScopeKind Scope, LValue &LV) {
1914 unsigned Version = getTempVersion();
1915 APValue::LValueBase Base(Key, Index, Version);
1916 LV.set(Base);
1917 return createLocal(Base, Key, T, Scope);
1918}
1919
1920/// Allocate storage for a parameter of a function call made in this frame.
1921APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1922 LValue &LV) {
1923 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1924 APValue::LValueBase Base(PVD, Index, Args.Version);
1925 LV.set(Base);
1926 // We always destroy parameters at the end of the call, even if we'd allow
1927 // them to live to the end of the full-expression at runtime, in order to
1928 // give portable results and match other compilers.
1929 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1930}
1931
1932APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1933 QualType T, ScopeKind Scope) {
1934 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1935 unsigned Version = Base.getVersion();
1936 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1937 assert(Result.isAbsent() && "local created multiple times");
1938
1939 // If we're creating a local immediately in the operand of a speculative
1940 // evaluation, don't register a cleanup to be run outside the speculative
1941 // evaluation context, since we won't actually be able to initialize this
1942 // object.
1943 if (Index <= Info.SpeculativeEvaluationDepth) {
1944 if (T.isDestructedType())
1945 Info.noteSideEffect();
1946 } else {
1947 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1948 }
1949 return Result;
1950}
1951
1952APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1953 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1954 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1955 return nullptr;
1956 }
1957
1958 DynamicAllocLValue DA(NumHeapAllocs++);
1960 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1961 std::forward_as_tuple(DA), std::tuple<>());
1962 assert(Result.second && "reused a heap alloc index?");
1963 Result.first->second.AllocExpr = E;
1964 return &Result.first->second.Value;
1965}
1966
1967/// Produce a string describing the given constexpr call.
1968void CallStackFrame::describe(raw_ostream &Out) const {
1969 unsigned ArgIndex = 0;
1970 bool IsMemberCall =
1971 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1972 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1973
1974 if (!IsMemberCall)
1975 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1976 /*Qualified=*/false);
1977
1978 if (This && IsMemberCall) {
1979 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1980 const Expr *Object = MCE->getImplicitObjectArgument();
1981 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1982 /*Indentation=*/0);
1983 if (Object->getType()->isPointerType())
1984 Out << "->";
1985 else
1986 Out << ".";
1987 } else if (const auto *OCE =
1988 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1989 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1990 Info.Ctx.getPrintingPolicy(),
1991 /*Indentation=*/0);
1992 Out << ".";
1993 } else {
1994 APValue Val;
1995 This->moveInto(Val);
1996 Val.printPretty(
1997 Out, Info.Ctx,
1998 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1999 Out << ".";
2000 }
2001 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2002 /*Qualified=*/false);
2003 IsMemberCall = false;
2004 }
2005
2006 Out << '(';
2007
2008 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2009 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2010 if (ArgIndex > (unsigned)IsMemberCall)
2011 Out << ", ";
2012
2013 const ParmVarDecl *Param = *I;
2014 APValue *V = Info.getParamSlot(Arguments, Param);
2015 if (V)
2016 V->printPretty(Out, Info.Ctx, Param->getType());
2017 else
2018 Out << "<...>";
2019
2020 if (ArgIndex == 0 && IsMemberCall)
2021 Out << "->" << *Callee << '(';
2022 }
2023
2024 Out << ')';
2025}
2026
2027/// Evaluate an expression to see if it had side-effects, and discard its
2028/// result.
2029/// \return \c true if the caller should keep evaluating.
2030static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2031 assert(!E->isValueDependent());
2032 APValue Scratch;
2033 if (!Evaluate(Scratch, Info, E))
2034 // We don't need the value, but we might have skipped a side effect here.
2035 return Info.noteSideEffect();
2036 return true;
2037}
2038
2039/// Should this call expression be treated as a no-op?
2040static bool IsNoOpCall(const CallExpr *E) {
2041 unsigned Builtin = E->getBuiltinCallee();
2042 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2043 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2044 Builtin == Builtin::BI__builtin_function_start);
2045}
2046
2048 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2049 // constant expression of pointer type that evaluates to...
2050
2051 // ... a null pointer value, or a prvalue core constant expression of type
2052 // std::nullptr_t.
2053 if (!B)
2054 return true;
2055
2056 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2057 // ... the address of an object with static storage duration,
2058 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2059 return VD->hasGlobalStorage();
2060 if (isa<TemplateParamObjectDecl>(D))
2061 return true;
2062 // ... the address of a function,
2063 // ... the address of a GUID [MS extension],
2064 // ... the address of an unnamed global constant
2065 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2066 }
2067
2068 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2069 return true;
2070
2071 const Expr *E = B.get<const Expr*>();
2072 switch (E->getStmtClass()) {
2073 default:
2074 return false;
2075 case Expr::CompoundLiteralExprClass: {
2076 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2077 return CLE->isFileScope() && CLE->isLValue();
2078 }
2079 case Expr::MaterializeTemporaryExprClass:
2080 // A materialized temporary might have been lifetime-extended to static
2081 // storage duration.
2082 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2083 // A string literal has static storage duration.
2084 case Expr::StringLiteralClass:
2085 case Expr::PredefinedExprClass:
2086 case Expr::ObjCStringLiteralClass:
2087 case Expr::ObjCEncodeExprClass:
2088 return true;
2089 case Expr::ObjCBoxedExprClass:
2090 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2091 case Expr::CallExprClass:
2092 return IsNoOpCall(cast<CallExpr>(E));
2093 // For GCC compatibility, &&label has static storage duration.
2094 case Expr::AddrLabelExprClass:
2095 return true;
2096 // A Block literal expression may be used as the initialization value for
2097 // Block variables at global or local static scope.
2098 case Expr::BlockExprClass:
2099 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2100 // The APValue generated from a __builtin_source_location will be emitted as a
2101 // literal.
2102 case Expr::SourceLocExprClass:
2103 return true;
2104 case Expr::ImplicitValueInitExprClass:
2105 // FIXME:
2106 // We can never form an lvalue with an implicit value initialization as its
2107 // base through expression evaluation, so these only appear in one case: the
2108 // implicit variable declaration we invent when checking whether a constexpr
2109 // constructor can produce a constant expression. We must assume that such
2110 // an expression might be a global lvalue.
2111 return true;
2112 }
2113}
2114
2115static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2116 return LVal.Base.dyn_cast<const ValueDecl*>();
2117}
2118
2119static bool IsLiteralLValue(const LValue &Value) {
2120 if (Value.getLValueCallIndex())
2121 return false;
2122 const Expr *E = Value.Base.dyn_cast<const Expr*>();
2123 return E && !isa<MaterializeTemporaryExpr>(E);
2124}
2125
2126static bool IsWeakLValue(const LValue &Value) {
2128 return Decl && Decl->isWeak();
2129}
2130
2131static bool isZeroSized(const LValue &Value) {
2133 if (Decl && isa<VarDecl>(Decl)) {
2134 QualType Ty = Decl->getType();
2135 if (Ty->isArrayType())
2136 return Ty->isIncompleteType() ||
2137 Decl->getASTContext().getTypeSize(Ty) == 0;
2138 }
2139 return false;
2140}
2141
2142static bool HasSameBase(const LValue &A, const LValue &B) {
2143 if (!A.getLValueBase())
2144 return !B.getLValueBase();
2145 if (!B.getLValueBase())
2146 return false;
2147
2148 if (A.getLValueBase().getOpaqueValue() !=
2149 B.getLValueBase().getOpaqueValue())
2150 return false;
2151
2152 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2153 A.getLValueVersion() == B.getLValueVersion();
2154}
2155
2156static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2157 assert(Base && "no location for a null lvalue");
2158 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2159
2160 // For a parameter, find the corresponding call stack frame (if it still
2161 // exists), and point at the parameter of the function definition we actually
2162 // invoked.
2163 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2164 unsigned Idx = PVD->getFunctionScopeIndex();
2165 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2166 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2167 F->Arguments.Version == Base.getVersion() && F->Callee &&
2168 Idx < F->Callee->getNumParams()) {
2169 VD = F->Callee->getParamDecl(Idx);
2170 break;
2171 }
2172 }
2173 }
2174
2175 if (VD)
2176 Info.Note(VD->getLocation(), diag::note_declared_at);
2177 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2178 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2179 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2180 // FIXME: Produce a note for dangling pointers too.
2181 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2182 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2183 diag::note_constexpr_dynamic_alloc_here);
2184 }
2185
2186 // We have no information to show for a typeid(T) object.
2187}
2188
2192};
2193
2194/// Materialized temporaries that we've already checked to determine if they're
2195/// initializsed by a constant expression.
2198
2200 EvalInfo &Info, SourceLocation DiagLoc,
2201 QualType Type, const APValue &Value,
2202 ConstantExprKind Kind,
2203 const FieldDecl *SubobjectDecl,
2204 CheckedTemporaries &CheckedTemps);
2205
2206/// Check that this reference or pointer core constant expression is a valid
2207/// value for an address or reference constant expression. Return true if we
2208/// can fold this expression, whether or not it's a constant expression.
2210 QualType Type, const LValue &LVal,
2211 ConstantExprKind Kind,
2212 CheckedTemporaries &CheckedTemps) {
2213 bool IsReferenceType = Type->isReferenceType();
2214
2215 APValue::LValueBase Base = LVal.getLValueBase();
2216 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2217
2218 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2219 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2220
2221 // Additional restrictions apply in a template argument. We only enforce the
2222 // C++20 restrictions here; additional syntactic and semantic restrictions
2223 // are applied elsewhere.
2224 if (isTemplateArgument(Kind)) {
2225 int InvalidBaseKind = -1;
2226 StringRef Ident;
2227 if (Base.is<TypeInfoLValue>())
2228 InvalidBaseKind = 0;
2229 else if (isa_and_nonnull<StringLiteral>(BaseE))
2230 InvalidBaseKind = 1;
2231 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2232 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2233 InvalidBaseKind = 2;
2234 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2235 InvalidBaseKind = 3;
2236 Ident = PE->getIdentKindName();
2237 }
2238
2239 if (InvalidBaseKind != -1) {
2240 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2241 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2242 << Ident;
2243 return false;
2244 }
2245 }
2246
2247 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2248 FD && FD->isImmediateFunction()) {
2249 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2250 << !Type->isAnyPointerType();
2251 Info.Note(FD->getLocation(), diag::note_declared_at);
2252 return false;
2253 }
2254
2255 // Check that the object is a global. Note that the fake 'this' object we
2256 // manufacture when checking potential constant expressions is conservatively
2257 // assumed to be global here.
2258 if (!IsGlobalLValue(Base)) {
2259 if (Info.getLangOpts().CPlusPlus11) {
2260 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2261 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2262 << BaseVD;
2263 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2264 if (VarD && VarD->isConstexpr()) {
2265 // Non-static local constexpr variables have unintuitive semantics:
2266 // constexpr int a = 1;
2267 // constexpr const int *p = &a;
2268 // ... is invalid because the address of 'a' is not constant. Suggest
2269 // adding a 'static' in this case.
2270 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2271 << VarD
2272 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2273 } else {
2274 NoteLValueLocation(Info, Base);
2275 }
2276 } else {
2277 Info.FFDiag(Loc);
2278 }
2279 // Don't allow references to temporaries to escape.
2280 return false;
2281 }
2282 assert((Info.checkingPotentialConstantExpression() ||
2283 LVal.getLValueCallIndex() == 0) &&
2284 "have call index for global lvalue");
2285
2286 if (Base.is<DynamicAllocLValue>()) {
2287 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2288 << IsReferenceType << !Designator.Entries.empty();
2289 NoteLValueLocation(Info, Base);
2290 return false;
2291 }
2292
2293 if (BaseVD) {
2294 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2295 // Check if this is a thread-local variable.
2296 if (Var->getTLSKind())
2297 // FIXME: Diagnostic!
2298 return false;
2299
2300 // A dllimport variable never acts like a constant, unless we're
2301 // evaluating a value for use only in name mangling.
2302 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2303 // FIXME: Diagnostic!
2304 return false;
2305
2306 // In CUDA/HIP device compilation, only device side variables have
2307 // constant addresses.
2308 if (Info.getCtx().getLangOpts().CUDA &&
2309 Info.getCtx().getLangOpts().CUDAIsDevice &&
2310 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2311 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2312 !Var->hasAttr<CUDAConstantAttr>() &&
2313 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2314 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2315 Var->hasAttr<HIPManagedAttr>())
2316 return false;
2317 }
2318 }
2319 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2320 // __declspec(dllimport) must be handled very carefully:
2321 // We must never initialize an expression with the thunk in C++.
2322 // Doing otherwise would allow the same id-expression to yield
2323 // different addresses for the same function in different translation
2324 // units. However, this means that we must dynamically initialize the
2325 // expression with the contents of the import address table at runtime.
2326 //
2327 // The C language has no notion of ODR; furthermore, it has no notion of
2328 // dynamic initialization. This means that we are permitted to
2329 // perform initialization with the address of the thunk.
2330 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2331 FD->hasAttr<DLLImportAttr>())
2332 // FIXME: Diagnostic!
2333 return false;
2334 }
2335 } else if (const auto *MTE =
2336 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2337 if (CheckedTemps.insert(MTE).second) {
2338 QualType TempType = getType(Base);
2339 if (TempType.isDestructedType()) {
2340 Info.FFDiag(MTE->getExprLoc(),
2341 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2342 << TempType;
2343 return false;
2344 }
2345
2346 APValue *V = MTE->getOrCreateValue(false);
2347 assert(V && "evasluation result refers to uninitialised temporary");
2348 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2349 Info, MTE->getExprLoc(), TempType, *V, Kind,
2350 /*SubobjectDecl=*/nullptr, CheckedTemps))
2351 return false;
2352 }
2353 }
2354
2355 // Allow address constant expressions to be past-the-end pointers. This is
2356 // an extension: the standard requires them to point to an object.
2357 if (!IsReferenceType)
2358 return true;
2359
2360 // A reference constant expression must refer to an object.
2361 if (!Base) {
2362 // FIXME: diagnostic
2363 Info.CCEDiag(Loc);
2364 return true;
2365 }
2366
2367 // Does this refer one past the end of some object?
2368 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2369 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2370 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2371 NoteLValueLocation(Info, Base);
2372 }
2373
2374 return true;
2375}
2376
2377/// Member pointers are constant expressions unless they point to a
2378/// non-virtual dllimport member function.
2379static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2381 QualType Type,
2382 const APValue &Value,
2383 ConstantExprKind Kind) {
2384 const ValueDecl *Member = Value.getMemberPointerDecl();
2385 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2386 if (!FD)
2387 return true;
2388 if (FD->isImmediateFunction()) {
2389 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2390 Info.Note(FD->getLocation(), diag::note_declared_at);
2391 return false;
2392 }
2393 return isForManglingOnly(Kind) || FD->isVirtual() ||
2394 !FD->hasAttr<DLLImportAttr>();
2395}
2396
2397/// Check that this core constant expression is of literal type, and if not,
2398/// produce an appropriate diagnostic.
2399static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2400 const LValue *This = nullptr) {
2401 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2402 return true;
2403
2404 // C++1y: A constant initializer for an object o [...] may also invoke
2405 // constexpr constructors for o and its subobjects even if those objects
2406 // are of non-literal class types.
2407 //
2408 // C++11 missed this detail for aggregates, so classes like this:
2409 // struct foo_t { union { int i; volatile int j; } u; };
2410 // are not (obviously) initializable like so:
2411 // __attribute__((__require_constant_initialization__))
2412 // static const foo_t x = {{0}};
2413 // because "i" is a subobject with non-literal initialization (due to the
2414 // volatile member of the union). See:
2415 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2416 // Therefore, we use the C++1y behavior.
2417 if (This && Info.EvaluatingDecl == This->getLValueBase())
2418 return true;
2419
2420 // Prvalue constant expressions must be of literal types.
2421 if (Info.getLangOpts().CPlusPlus11)
2422 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2423 << E->getType();
2424 else
2425 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2426 return false;
2427}
2428
2430 EvalInfo &Info, SourceLocation DiagLoc,
2431 QualType Type, const APValue &Value,
2432 ConstantExprKind Kind,
2433 const FieldDecl *SubobjectDecl,
2434 CheckedTemporaries &CheckedTemps) {
2435 if (!Value.hasValue()) {
2436 if (SubobjectDecl) {
2437 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2438 << /*(name)*/ 1 << SubobjectDecl;
2439 Info.Note(SubobjectDecl->getLocation(),
2440 diag::note_constexpr_subobject_declared_here);
2441 } else {
2442 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2443 << /*of type*/ 0 << Type;
2444 }
2445 return false;
2446 }
2447
2448 // We allow _Atomic(T) to be initialized from anything that T can be
2449 // initialized from.
2450 if (const AtomicType *AT = Type->getAs<AtomicType>())
2451 Type = AT->getValueType();
2452
2453 // Core issue 1454: For a literal constant expression of array or class type,
2454 // each subobject of its value shall have been initialized by a constant
2455 // expression.
2456 if (Value.isArray()) {
2458 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2459 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2460 Value.getArrayInitializedElt(I), Kind,
2461 SubobjectDecl, CheckedTemps))
2462 return false;
2463 }
2464 if (!Value.hasArrayFiller())
2465 return true;
2466 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2467 Value.getArrayFiller(), Kind, SubobjectDecl,
2468 CheckedTemps);
2469 }
2470 if (Value.isUnion() && Value.getUnionField()) {
2471 return CheckEvaluationResult(
2472 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2473 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2474 }
2475 if (Value.isStruct()) {
2476 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2477 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2478 unsigned BaseIndex = 0;
2479 for (const CXXBaseSpecifier &BS : CD->bases()) {
2480 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2481 if (!BaseValue.hasValue()) {
2482 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2483 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2484 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2485 return false;
2486 }
2487 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2488 Kind, /*SubobjectDecl=*/nullptr,
2489 CheckedTemps))
2490 return false;
2491 ++BaseIndex;
2492 }
2493 }
2494 for (const auto *I : RD->fields()) {
2495 if (I->isUnnamedBitField())
2496 continue;
2497
2498 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2499 Value.getStructField(I->getFieldIndex()), Kind,
2500 I, CheckedTemps))
2501 return false;
2502 }
2503 }
2504
2505 if (Value.isLValue() &&
2506 CERK == CheckEvaluationResultKind::ConstantExpression) {
2507 LValue LVal;
2508 LVal.setFrom(Info.Ctx, Value);
2509 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2510 CheckedTemps);
2511 }
2512
2513 if (Value.isMemberPointer() &&
2514 CERK == CheckEvaluationResultKind::ConstantExpression)
2515 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2516
2517 // Everything else is fine.
2518 return true;
2519}
2520
2521/// Check that this core constant expression value is a valid value for a
2522/// constant expression. If not, report an appropriate diagnostic. Does not
2523/// check that the expression is of literal type.
2524static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2525 QualType Type, const APValue &Value,
2526 ConstantExprKind Kind) {
2527 // Nothing to check for a constant expression of type 'cv void'.
2528 if (Type->isVoidType())
2529 return true;
2530
2531 CheckedTemporaries CheckedTemps;
2532 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2533 Info, DiagLoc, Type, Value, Kind,
2534 /*SubobjectDecl=*/nullptr, CheckedTemps);
2535}
2536
2537/// Check that this evaluated value is fully-initialized and can be loaded by
2538/// an lvalue-to-rvalue conversion.
2539static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2540 QualType Type, const APValue &Value) {
2541 CheckedTemporaries CheckedTemps;
2542 return CheckEvaluationResult(
2543 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2544 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2545}
2546
2547/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2548/// "the allocated storage is deallocated within the evaluation".
2549static bool CheckMemoryLeaks(EvalInfo &Info) {
2550 if (!Info.HeapAllocs.empty()) {
2551 // We can still fold to a constant despite a compile-time memory leak,
2552 // so long as the heap allocation isn't referenced in the result (we check
2553 // that in CheckConstantExpression).
2554 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2555 diag::note_constexpr_memory_leak)
2556 << unsigned(Info.HeapAllocs.size() - 1);
2557 }
2558 return true;
2559}
2560
2561static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2562 // A null base expression indicates a null pointer. These are always
2563 // evaluatable, and they are false unless the offset is zero.
2564 if (!Value.getLValueBase()) {
2565 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2566 Result = !Value.getLValueOffset().isZero();
2567 return true;
2568 }
2569
2570 // We have a non-null base. These are generally known to be true, but if it's
2571 // a weak declaration it can be null at runtime.
2572 Result = true;
2573 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2574 return !Decl || !Decl->isWeak();
2575}
2576
2577static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2578 // TODO: This function should produce notes if it fails.
2579 switch (Val.getKind()) {
2580 case APValue::None:
2582 return false;
2583 case APValue::Int:
2584 Result = Val.getInt().getBoolValue();
2585 return true;
2587 Result = Val.getFixedPoint().getBoolValue();
2588 return true;
2589 case APValue::Float:
2590 Result = !Val.getFloat().isZero();
2591 return true;
2593 Result = Val.getComplexIntReal().getBoolValue() ||
2594 Val.getComplexIntImag().getBoolValue();
2595 return true;
2597 Result = !Val.getComplexFloatReal().isZero() ||
2598 !Val.getComplexFloatImag().isZero();
2599 return true;
2600 case APValue::LValue:
2601 return EvalPointerValueAsBool(Val, Result);
2603 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2604 return false;
2605 }
2606 Result = Val.getMemberPointerDecl();
2607 return true;
2608 case APValue::Vector:
2609 case APValue::Array:
2610 case APValue::Struct:
2611 case APValue::Union:
2613 return false;
2614 }
2615
2616 llvm_unreachable("unknown APValue kind");
2617}
2618
2619static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2620 EvalInfo &Info) {
2621 assert(!E->isValueDependent());
2622 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2623 APValue Val;
2624 if (!Evaluate(Val, Info, E))
2625 return false;
2626 return HandleConversionToBool(Val, Result);
2627}
2628
2629template<typename T>
2630static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2631 const T &SrcValue, QualType DestType) {
2632 Info.CCEDiag(E, diag::note_constexpr_overflow)
2633 << SrcValue << DestType;
2634 return Info.noteUndefinedBehavior();
2635}
2636
2637static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2638 QualType SrcType, const APFloat &Value,
2639 QualType DestType, APSInt &Result) {
2640 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2641 // Determine whether we are converting to unsigned or signed.
2642 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2643
2644 Result = APSInt(DestWidth, !DestSigned);
2645 bool ignored;
2646 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2647 & APFloat::opInvalidOp)
2648 return HandleOverflow(Info, E, Value, DestType);
2649 return true;
2650}
2651
2652/// Get rounding mode to use in evaluation of the specified expression.
2653///
2654/// If rounding mode is unknown at compile time, still try to evaluate the
2655/// expression. If the result is exact, it does not depend on rounding mode.
2656/// So return "tonearest" mode instead of "dynamic".
2657static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2658 llvm::RoundingMode RM =
2659 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2660 if (RM == llvm::RoundingMode::Dynamic)
2661 RM = llvm::RoundingMode::NearestTiesToEven;
2662 return RM;
2663}
2664
2665/// Check if the given evaluation result is allowed for constant evaluation.
2666static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2667 APFloat::opStatus St) {
2668 // In a constant context, assume that any dynamic rounding mode or FP
2669 // exception state matches the default floating-point environment.
2670 if (Info.InConstantContext)
2671 return true;
2672
2673 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2674 if ((St & APFloat::opInexact) &&
2675 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2676 // Inexact result means that it depends on rounding mode. If the requested
2677 // mode is dynamic, the evaluation cannot be made in compile time.
2678 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2679 return false;
2680 }
2681
2682 if ((St != APFloat::opOK) &&
2683 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2684 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2685 FPO.getAllowFEnvAccess())) {
2686 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2687 return false;
2688 }
2689
2690 if ((St & APFloat::opStatus::opInvalidOp) &&
2691 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2692 // There is no usefully definable result.
2693 Info.FFDiag(E);
2694 return false;
2695 }
2696
2697 // FIXME: if:
2698 // - evaluation triggered other FP exception, and
2699 // - exception mode is not "ignore", and
2700 // - the expression being evaluated is not a part of global variable
2701 // initializer,
2702 // the evaluation probably need to be rejected.
2703 return true;
2704}
2705
2706static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2707 QualType SrcType, QualType DestType,
2708 APFloat &Result) {
2709 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2710 isa<ConvertVectorExpr>(E)) &&
2711 "HandleFloatToFloatCast has been checked with only CastExpr, "
2712 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2713 "the new expression or address the root cause of this usage.");
2714 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2715 APFloat::opStatus St;
2716 APFloat Value = Result;
2717 bool ignored;
2718 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2719 return checkFloatingPointResult(Info, E, St);
2720}
2721
2722static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2723 QualType DestType, QualType SrcType,
2724 const APSInt &Value) {
2725 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2726 // Figure out if this is a truncate, extend or noop cast.
2727 // If the input is signed, do a sign extend, noop, or truncate.
2728 APSInt Result = Value.extOrTrunc(DestWidth);
2729 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2730 if (DestType->isBooleanType())
2731 Result = Value.getBoolValue();
2732 return Result;
2733}
2734
2735static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2736 const FPOptions FPO,
2737 QualType SrcType, const APSInt &Value,
2738 QualType DestType, APFloat &Result) {
2739 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2740 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2741 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2742 return checkFloatingPointResult(Info, E, St);
2743}
2744
2745static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2746 APValue &Value, const FieldDecl *FD) {
2747 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2748
2749 if (!Value.isInt()) {
2750 // Trying to store a pointer-cast-to-integer into a bitfield.
2751 // FIXME: In this case, we should provide the diagnostic for casting
2752 // a pointer to an integer.
2753 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2754 Info.FFDiag(E);
2755 return false;
2756 }
2757
2758 APSInt &Int = Value.getInt();
2759 unsigned OldBitWidth = Int.getBitWidth();
2760 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2761 if (NewBitWidth < OldBitWidth)
2762 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2763 return true;
2764}
2765
2766/// Perform the given integer operation, which is known to need at most BitWidth
2767/// bits, and check for overflow in the original type (if that type was not an
2768/// unsigned type).
2769template<typename Operation>
2770static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2771 const APSInt &LHS, const APSInt &RHS,
2772 unsigned BitWidth, Operation Op,
2773 APSInt &Result) {
2774 if (LHS.isUnsigned()) {
2775 Result = Op(LHS, RHS);
2776 return true;
2777 }
2778
2779 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2780 Result = Value.trunc(LHS.getBitWidth());
2781 if (Result.extend(BitWidth) != Value) {
2782 if (Info.checkingForUndefinedBehavior())
2783 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2784 diag::warn_integer_constant_overflow)
2785 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2786 /*UpperCase=*/true, /*InsertSeparators=*/true)
2787 << E->getType() << E->getSourceRange();
2788 return HandleOverflow(Info, E, Value, E->getType());
2789 }
2790 return true;
2791}
2792
2793/// Perform the given binary integer operation.
2794static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2795 const APSInt &LHS, BinaryOperatorKind Opcode,
2796 APSInt RHS, APSInt &Result) {
2797 bool HandleOverflowResult = true;
2798 switch (Opcode) {
2799 default:
2800 Info.FFDiag(E);
2801 return false;
2802 case BO_Mul:
2803 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2804 std::multiplies<APSInt>(), Result);
2805 case BO_Add:
2806 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2807 std::plus<APSInt>(), Result);
2808 case BO_Sub:
2809 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2810 std::minus<APSInt>(), Result);
2811 case BO_And: Result = LHS & RHS; return true;
2812 case BO_Xor: Result = LHS ^ RHS; return true;
2813 case BO_Or: Result = LHS | RHS; return true;
2814 case BO_Div:
2815 case BO_Rem:
2816 if (RHS == 0) {
2817 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2818 << E->getRHS()->getSourceRange();
2819 return false;
2820 }
2821 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2822 // this operation and gives the two's complement result.
2823 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2824 LHS.isMinSignedValue())
2825 HandleOverflowResult = HandleOverflow(
2826 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2827 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2828 return HandleOverflowResult;
2829 case BO_Shl: {
2830 if (Info.getLangOpts().OpenCL)
2831 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2832 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2833 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2834 RHS.isUnsigned());
2835 else if (RHS.isSigned() && RHS.isNegative()) {
2836 // During constant-folding, a negative shift is an opposite shift. Such
2837 // a shift is not a constant expression.
2838 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2839 RHS = -RHS;
2840 goto shift_right;
2841 }
2842 shift_left:
2843 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2844 // the shifted type.
2845 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2846 if (SA != RHS) {
2847 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2848 << RHS << E->getType() << LHS.getBitWidth();
2849 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2850 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2851 // operand, and must not overflow the corresponding unsigned type.
2852 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2853 // E1 x 2^E2 module 2^N.
2854 if (LHS.isNegative())
2855 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2856 else if (LHS.countl_zero() < SA)
2857 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2858 }
2859 Result = LHS << SA;
2860 return true;
2861 }
2862 case BO_Shr: {
2863 if (Info.getLangOpts().OpenCL)
2864 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2865 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2866 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2867 RHS.isUnsigned());
2868 else if (RHS.isSigned() && RHS.isNegative()) {
2869 // During constant-folding, a negative shift is an opposite shift. Such a
2870 // shift is not a constant expression.
2871 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2872 RHS = -RHS;
2873 goto shift_left;
2874 }
2875 shift_right:
2876 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2877 // shifted type.
2878 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2879 if (SA != RHS)
2880 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2881 << RHS << E->getType() << LHS.getBitWidth();
2882 Result = LHS >> SA;
2883 return true;
2884 }
2885
2886 case BO_LT: Result = LHS < RHS; return true;
2887 case BO_GT: Result = LHS > RHS; return true;
2888 case BO_LE: Result = LHS <= RHS; return true;
2889 case BO_GE: Result = LHS >= RHS; return true;
2890 case BO_EQ: Result = LHS == RHS; return true;
2891 case BO_NE: Result = LHS != RHS; return true;
2892 case BO_Cmp:
2893 llvm_unreachable("BO_Cmp should be handled elsewhere");
2894 }
2895}
2896
2897/// Perform the given binary floating-point operation, in-place, on LHS.
2898static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2899 APFloat &LHS, BinaryOperatorKind Opcode,
2900 const APFloat &RHS) {
2901 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2902 APFloat::opStatus St;
2903 switch (Opcode) {
2904 default:
2905 Info.FFDiag(E);
2906 return false;
2907 case BO_Mul:
2908 St = LHS.multiply(RHS, RM);
2909 break;
2910 case BO_Add:
2911 St = LHS.add(RHS, RM);
2912 break;
2913 case BO_Sub:
2914 St = LHS.subtract(RHS, RM);
2915 break;
2916 case BO_Div:
2917 // [expr.mul]p4:
2918 // If the second operand of / or % is zero the behavior is undefined.
2919 if (RHS.isZero())
2920 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2921 St = LHS.divide(RHS, RM);
2922 break;
2923 }
2924
2925 // [expr.pre]p4:
2926 // If during the evaluation of an expression, the result is not
2927 // mathematically defined [...], the behavior is undefined.
2928 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2929 if (LHS.isNaN()) {
2930 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2931 return Info.noteUndefinedBehavior();
2932 }
2933
2934 return checkFloatingPointResult(Info, E, St);
2935}
2936
2937static bool handleLogicalOpForVector(const APInt &LHSValue,
2938 BinaryOperatorKind Opcode,
2939 const APInt &RHSValue, APInt &Result) {
2940 bool LHS = (LHSValue != 0);
2941 bool RHS = (RHSValue != 0);
2942
2943 if (Opcode == BO_LAnd)
2944 Result = LHS && RHS;
2945 else
2946 Result = LHS || RHS;
2947 return true;
2948}
2949static bool handleLogicalOpForVector(const APFloat &LHSValue,
2950 BinaryOperatorKind Opcode,
2951 const APFloat &RHSValue, APInt &Result) {
2952 bool LHS = !LHSValue.isZero();
2953 bool RHS = !RHSValue.isZero();
2954
2955 if (Opcode == BO_LAnd)
2956 Result = LHS && RHS;
2957 else
2958 Result = LHS || RHS;
2959 return true;
2960}
2961
2962static bool handleLogicalOpForVector(const APValue &LHSValue,
2963 BinaryOperatorKind Opcode,
2964 const APValue &RHSValue, APInt &Result) {
2965 // The result is always an int type, however operands match the first.
2966 if (LHSValue.getKind() == APValue::Int)
2967 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2968 RHSValue.getInt(), Result);
2969 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2970 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2971 RHSValue.getFloat(), Result);
2972}
2973
2974template <typename APTy>
2975static bool
2977 const APTy &RHSValue, APInt &Result) {
2978 switch (Opcode) {
2979 default:
2980 llvm_unreachable("unsupported binary operator");
2981 case BO_EQ:
2982 Result = (LHSValue == RHSValue);
2983 break;
2984 case BO_NE:
2985 Result = (LHSValue != RHSValue);
2986 break;
2987 case BO_LT:
2988 Result = (LHSValue < RHSValue);
2989 break;
2990 case BO_GT:
2991 Result = (LHSValue > RHSValue);
2992 break;
2993 case BO_LE:
2994 Result = (LHSValue <= RHSValue);
2995 break;
2996 case BO_GE:
2997 Result = (LHSValue >= RHSValue);
2998 break;
2999 }
3000
3001 // The boolean operations on these vector types use an instruction that
3002 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3003 // to -1 to make sure that we produce the correct value.
3004 Result.negate();
3005
3006 return true;
3007}
3008
3009static bool handleCompareOpForVector(const APValue &LHSValue,
3010 BinaryOperatorKind Opcode,
3011 const APValue &RHSValue, APInt &Result) {
3012 // The result is always an int type, however operands match the first.
3013 if (LHSValue.getKind() == APValue::Int)
3014 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3015 RHSValue.getInt(), Result);
3016 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3017 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3018 RHSValue.getFloat(), Result);
3019}
3020
3021// Perform binary operations for vector types, in place on the LHS.
3022static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3023 BinaryOperatorKind Opcode,
3024 APValue &LHSValue,
3025 const APValue &RHSValue) {
3026 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3027 "Operation not supported on vector types");
3028
3029 const auto *VT = E->getType()->castAs<VectorType>();
3030 unsigned NumElements = VT->getNumElements();
3031 QualType EltTy = VT->getElementType();
3032
3033 // In the cases (typically C as I've observed) where we aren't evaluating
3034 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3035 // just give up.
3036 if (!LHSValue.isVector()) {
3037 assert(LHSValue.isLValue() &&
3038 "A vector result that isn't a vector OR uncalculated LValue");
3039 Info.FFDiag(E);
3040 return false;
3041 }
3042
3043 assert(LHSValue.getVectorLength() == NumElements &&
3044 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3045
3046 SmallVector<APValue, 4> ResultElements;
3047
3048 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3049 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3050 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3051
3052 if (EltTy->isIntegerType()) {
3053 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3054 EltTy->isUnsignedIntegerType()};
3055 bool Success = true;
3056
3057 if (BinaryOperator::isLogicalOp(Opcode))
3058 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3059 else if (BinaryOperator::isComparisonOp(Opcode))
3060 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3061 else
3062 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3063 RHSElt.getInt(), EltResult);
3064
3065 if (!Success) {
3066 Info.FFDiag(E);
3067 return false;
3068 }
3069 ResultElements.emplace_back(EltResult);
3070
3071 } else if (EltTy->isFloatingType()) {
3072 assert(LHSElt.getKind() == APValue::Float &&
3073 RHSElt.getKind() == APValue::Float &&
3074 "Mismatched LHS/RHS/Result Type");
3075 APFloat LHSFloat = LHSElt.getFloat();
3076
3077 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3078 RHSElt.getFloat())) {
3079 Info.FFDiag(E);
3080 return false;
3081 }
3082
3083 ResultElements.emplace_back(LHSFloat);
3084 }
3085 }
3086
3087 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3088 return true;
3089}
3090
3091/// Cast an lvalue referring to a base subobject to a derived class, by
3092/// truncating the lvalue's path to the given length.
3093static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3094 const RecordDecl *TruncatedType,
3095 unsigned TruncatedElements) {
3096 SubobjectDesignator &D = Result.Designator;
3097
3098 // Check we actually point to a derived class object.
3099 if (TruncatedElements == D.Entries.size())
3100 return true;
3101 assert(TruncatedElements >= D.MostDerivedPathLength &&
3102 "not casting to a derived class");
3103 if (!Result.checkSubobject(Info, E, CSK_Derived))
3104 return false;
3105
3106 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3107 const RecordDecl *RD = TruncatedType;
3108 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3109 if (RD->isInvalidDecl()) return false;
3110 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3111 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3112 if (isVirtualBaseClass(D.Entries[I]))
3113 Result.Offset -= Layout.getVBaseClassOffset(Base);
3114 else
3115 Result.Offset -= Layout.getBaseClassOffset(Base);
3116 RD = Base;
3117 }
3118 D.Entries.resize(TruncatedElements);
3119 return true;
3120}
3121
3122static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3123 const CXXRecordDecl *Derived,
3124 const CXXRecordDecl *Base,
3125 const ASTRecordLayout *RL = nullptr) {
3126 if (!RL) {
3127 if (Derived->isInvalidDecl()) return false;
3128 RL = &Info.Ctx.getASTRecordLayout(Derived);
3129 }
3130
3131 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3132 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3133 return true;
3134}
3135
3136static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3137 const CXXRecordDecl *DerivedDecl,
3138 const CXXBaseSpecifier *Base) {
3139 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3140
3141 if (!Base->isVirtual())
3142 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3143
3144 SubobjectDesignator &D = Obj.Designator;
3145 if (D.Invalid)
3146 return false;
3147
3148 // Extract most-derived object and corresponding type.
3149 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3150 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3151 return false;
3152
3153 // Find the virtual base class.
3154 if (DerivedDecl->isInvalidDecl()) return false;
3155 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3156 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3157 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3158 return true;
3159}
3160
3161static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3162 QualType Type, LValue &Result) {
3163 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3164 PathE = E->path_end();
3165 PathI != PathE; ++PathI) {
3166 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3167 *PathI))
3168 return false;
3169 Type = (*PathI)->getType();
3170 }
3171 return true;
3172}
3173
3174/// Cast an lvalue referring to a derived class to a known base subobject.
3175static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3176 const CXXRecordDecl *DerivedRD,
3177 const CXXRecordDecl *BaseRD) {
3178 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3179 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3180 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3181 llvm_unreachable("Class must be derived from the passed in base class!");
3182
3183 for (CXXBasePathElement &Elem : Paths.front())
3184 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3185 return false;
3186 return true;
3187}
3188
3189/// Update LVal to refer to the given field, which must be a member of the type
3190/// currently described by LVal.
3191static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3192 const FieldDecl *FD,
3193 const ASTRecordLayout *RL = nullptr) {
3194 if (!RL) {
3195 if (FD->getParent()->isInvalidDecl()) return false;
3196 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3197 }
3198
3199 unsigned I = FD->getFieldIndex();
3200 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3201 LVal.addDecl(Info, E, FD);
3202 return true;
3203}
3204
3205/// Update LVal to refer to the given indirect field.
3206static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3207 LValue &LVal,
3208 const IndirectFieldDecl *IFD) {
3209 for (const auto *C : IFD->chain())
3210 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3211 return false;
3212 return true;
3213}
3214
3215enum class SizeOfType {
3216 SizeOf,
3217 DataSizeOf,
3218};
3219
3220/// Get the size of the given type in char units.
3221static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3222 CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3223 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3224 // extension.
3225 if (Type->isVoidType() || Type->isFunctionType()) {
3226 Size = CharUnits::One();
3227 return true;
3228 }
3229
3230 if (Type->isDependentType()) {
3231 Info.FFDiag(Loc);
3232 return false;
3233 }
3234
3235 if (!Type->isConstantSizeType()) {
3236 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3237 // FIXME: Better diagnostic.
3238 Info.FFDiag(Loc);
3239 return false;
3240 }
3241
3242 if (SOT == SizeOfType::SizeOf)
3243 Size = Info.Ctx.getTypeSizeInChars(Type);
3244 else
3245 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3246 return true;
3247}
3248
3249/// Update a pointer value to model pointer arithmetic.
3250/// \param Info - Information about the ongoing evaluation.
3251/// \param E - The expression being evaluated, for diagnostic purposes.
3252/// \param LVal - The pointer value to be updated.
3253/// \param EltTy - The pointee type represented by LVal.
3254/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3255static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3256 LValue &LVal, QualType EltTy,
3257 APSInt Adjustment) {
3258 CharUnits SizeOfPointee;
3259 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3260 return false;
3261
3262 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3263 return true;
3264}
3265
3266static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3267 LValue &LVal, QualType EltTy,
3268 int64_t Adjustment) {
3269 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3270 APSInt::get(Adjustment));
3271}
3272
3273/// Update an lvalue to refer to a component of a complex number.
3274/// \param Info - Information about the ongoing evaluation.
3275/// \param LVal - The lvalue to be updated.
3276/// \param EltTy - The complex number's component type.
3277/// \param Imag - False for the real component, true for the imaginary.
3278static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3279 LValue &LVal, QualType EltTy,
3280 bool Imag) {
3281 if (Imag) {
3282 CharUnits SizeOfComponent;
3283 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3284 return false;
3285 LVal.Offset += SizeOfComponent;
3286 }
3287 LVal.addComplex(Info, E, EltTy, Imag);
3288 return true;
3289}
3290
3291/// Try to evaluate the initializer for a variable declaration.
3292///
3293/// \param Info Information about the ongoing evaluation.
3294/// \param E An expression to be used when printing diagnostics.
3295/// \param VD The variable whose initializer should be obtained.
3296/// \param Version The version of the variable within the frame.
3297/// \param Frame The frame in which the variable was created. Must be null
3298/// if this variable is not local to the evaluation.
3299/// \param Result Filled in with a pointer to the value of the variable.
3300static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3301 const VarDecl *VD, CallStackFrame *Frame,
3302 unsigned Version, APValue *&Result) {
3303 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3304
3305 // If this is a local variable, dig out its value.
3306 if (Frame) {
3307 Result = Frame->getTemporary(VD, Version);
3308 if (Result)
3309 return true;
3310
3311 if (!isa<ParmVarDecl>(VD)) {
3312 // Assume variables referenced within a lambda's call operator that were
3313 // not declared within the call operator are captures and during checking
3314 // of a potential constant expression, assume they are unknown constant
3315 // expressions.
3316 assert(isLambdaCallOperator(Frame->Callee) &&
3317 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3318 "missing value for local variable");
3319 if (Info.checkingPotentialConstantExpression())
3320 return false;
3321 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3322 // still reachable at all?
3323 Info.FFDiag(E->getBeginLoc(),
3324 diag::note_unimplemented_constexpr_lambda_feature_ast)
3325 << "captures not currently allowed";
3326 return false;
3327 }
3328 }
3329
3330 // If we're currently evaluating the initializer of this declaration, use that
3331 // in-flight value.
3332 if (Info.EvaluatingDecl == Base) {
3333 Result = Info.EvaluatingDeclValue;
3334 return true;
3335 }
3336
3337 if (isa<ParmVarDecl>(VD)) {
3338 // Assume parameters of a potential constant expression are usable in
3339 // constant expressions.
3340 if (!Info.checkingPotentialConstantExpression() ||
3341 !Info.CurrentCall->Callee ||
3342 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3343 if (Info.getLangOpts().CPlusPlus11) {
3344 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3345 << VD;
3346 NoteLValueLocation(Info, Base);
3347 } else {
3348 Info.FFDiag(E);
3349 }
3350 }
3351 return false;
3352 }
3353
3354 if (E->isValueDependent())
3355 return false;
3356
3357 // Dig out the initializer, and use the declaration which it's attached to.
3358 // FIXME: We should eventually check whether the variable has a reachable
3359 // initializing declaration.
3360 const Expr *Init = VD->getAnyInitializer(VD);
3361 if (!Init) {
3362 // Don't diagnose during potential constant expression checking; an
3363 // initializer might be added later.
3364 if (!Info.checkingPotentialConstantExpression()) {
3365 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3366 << VD;
3367 NoteLValueLocation(Info, Base);
3368 }
3369 return false;
3370 }
3371
3372 if (Init->isValueDependent()) {
3373 // The DeclRefExpr is not value-dependent, but the variable it refers to
3374 // has a value-dependent initializer. This should only happen in
3375 // constant-folding cases, where the variable is not actually of a suitable
3376 // type for use in a constant expression (otherwise the DeclRefExpr would
3377 // have been value-dependent too), so diagnose that.
3378 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3379 if (!Info.checkingPotentialConstantExpression()) {
3380 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3381 ? diag::note_constexpr_ltor_non_constexpr
3382 : diag::note_constexpr_ltor_non_integral, 1)
3383 << VD << VD->getType();
3384 NoteLValueLocation(Info, Base);
3385 }
3386 return false;
3387 }
3388
3389 // Check that we can fold the initializer. In C++, we will have already done
3390 // this in the cases where it matters for conformance.
3391 if (!VD->evaluateValue()) {
3392 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3393 NoteLValueLocation(Info, Base);
3394 return false;
3395 }
3396
3397 // Check that the variable is actually usable in constant expressions. For a
3398 // const integral variable or a reference, we might have a non-constant
3399 // initializer that we can nonetheless evaluate the initializer for. Such
3400 // variables are not usable in constant expressions. In C++98, the
3401 // initializer also syntactically needs to be an ICE.
3402 //
3403 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3404 // expressions here; doing so would regress diagnostics for things like
3405 // reading from a volatile constexpr variable.
3406 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3407 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3408 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3409 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3410 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3411 NoteLValueLocation(Info, Base);
3412 }
3413
3414 // Never use the initializer of a weak variable, not even for constant
3415 // folding. We can't be sure that this is the definition that will be used.
3416 if (VD->isWeak()) {
3417 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3418 NoteLValueLocation(Info, Base);
3419 return false;
3420 }
3421
3422 Result = VD->getEvaluatedValue();
3423 return true;
3424}
3425
3426/// Get the base index of the given base class within an APValue representing
3427/// the given derived class.
3428static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3429 const CXXRecordDecl *Base) {
3430 Base = Base->getCanonicalDecl();
3431 unsigned Index = 0;
3433 E = Derived->bases_end(); I != E; ++I, ++Index) {
3434 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3435 return Index;
3436 }
3437
3438 llvm_unreachable("base class missing from derived class's bases list");
3439}
3440
3441/// Extract the value of a character from a string literal.
3442static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3443 uint64_t Index) {
3444 assert(!isa<SourceLocExpr>(Lit) &&
3445 "SourceLocExpr should have already been converted to a StringLiteral");
3446
3447 // FIXME: Support MakeStringConstant
3448 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3449 std::string Str;
3450 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3451 assert(Index <= Str.size() && "Index too large");
3452 return APSInt::getUnsigned(Str.c_str()[Index]);
3453 }
3454
3455 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3456 Lit = PE->getFunctionName();
3457 const StringLiteral *S = cast<StringLiteral>(Lit);
3458 const ConstantArrayType *CAT =
3459 Info.Ctx.getAsConstantArrayType(S->getType());
3460 assert(CAT && "string literal isn't an array");
3461 QualType CharType = CAT->getElementType();
3462 assert(CharType->isIntegerType() && "unexpected character type");
3463 APSInt Value(Info.Ctx.getTypeSize(CharType),
3464 CharType->isUnsignedIntegerType());
3465 if (Index < S->getLength())
3466 Value = S->getCodeUnit(Index);
3467 return Value;
3468}
3469
3470// Expand a string literal into an array of characters.
3471//
3472// FIXME: This is inefficient; we should probably introduce something similar
3473// to the LLVM ConstantDataArray to make this cheaper.
3474static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3475 APValue &Result,
3476 QualType AllocType = QualType()) {
3477 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3478 AllocType.isNull() ? S->getType() : AllocType);
3479 assert(CAT && "string literal isn't an array");
3480 QualType CharType = CAT->getElementType();
3481 assert(CharType->isIntegerType() && "unexpected character type");
3482
3483 unsigned Elts = CAT->getZExtSize();
3484 Result = APValue(APValue::UninitArray(),
3485 std::min(S->getLength(), Elts), Elts);
3486 APSInt Value(Info.Ctx.getTypeSize(CharType),
3487 CharType->isUnsignedIntegerType());
3488 if (Result.hasArrayFiller())
3489 Result.getArrayFiller() = APValue(Value);
3490 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3491 Value = S->getCodeUnit(I);
3492 Result.getArrayInitializedElt(I) = APValue(Value);
3493 }
3494}
3495
3496// Expand an array so that it has more than Index filled elements.
3497static void expandArray(APValue &Array, unsigned Index) {
3498 unsigned Size = Array.getArraySize();
3499 assert(Index < Size);
3500
3501 // Always at least double the number of elements for which we store a value.
3502 unsigned OldElts = Array.getArrayInitializedElts();
3503 unsigned NewElts = std::max(Index+1, OldElts * 2);
3504 NewElts = std::min(Size, std::max(NewElts, 8u));
3505
3506 // Copy the data across.
3507 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3508 for (unsigned I = 0; I != OldElts; ++I)
3509 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3510 for (unsigned I = OldElts; I != NewElts; ++I)
3511 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3512 if (NewValue.hasArrayFiller())
3513 NewValue.getArrayFiller() = Array.getArrayFiller();
3514 Array.swap(NewValue);
3515}
3516
3517/// Determine whether a type would actually be read by an lvalue-to-rvalue
3518/// conversion. If it's of class type, we may assume that the copy operation
3519/// is trivial. Note that this is never true for a union type with fields
3520/// (because the copy always "reads" the active member) and always true for
3521/// a non-class type.
3522static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3525 return !RD || isReadByLvalueToRvalueConversion(RD);
3526}
3528 // FIXME: A trivial copy of a union copies the object representation, even if
3529 // the union is empty.
3530 if (RD->isUnion())
3531 return !RD->field_empty();
3532 if (RD->isEmpty())
3533 return false;
3534
3535 for (auto *Field : RD->fields())
3536 if (!Field->isUnnamedBitField() &&
3537 isReadByLvalueToRvalueConversion(Field->getType()))
3538 return true;
3539
3540 for (auto &BaseSpec : RD->bases())
3541 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3542 return true;
3543
3544 return false;
3545}
3546
3547/// Diagnose an attempt to read from any unreadable field within the specified
3548/// type, which might be a class type.
3549static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3550 QualType T) {
3552 if (!RD)
3553 return false;
3554
3555 if (!RD->hasMutableFields())
3556 return false;
3557
3558 for (auto *Field : RD->fields()) {
3559 // If we're actually going to read this field in some way, then it can't
3560 // be mutable. If we're in a union, then assigning to a mutable field
3561 // (even an empty one) can change the active member, so that's not OK.
3562 // FIXME: Add core issue number for the union case.
3563 if (Field->isMutable() &&
3564 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3565 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3566 Info.Note(Field->getLocation(), diag::note_declared_at);
3567 return true;
3568 }
3569
3570 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3571 return true;
3572 }
3573
3574 for (auto &BaseSpec : RD->bases())
3575 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3576 return true;
3577
3578 // All mutable fields were empty, and thus not actually read.
3579 return false;
3580}
3581
3582static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3584 bool MutableSubobject = false) {
3585 // A temporary or transient heap allocation we created.
3586 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3587 return true;
3588
3589 switch (Info.IsEvaluatingDecl) {
3590 case EvalInfo::EvaluatingDeclKind::None:
3591 return false;
3592
3593 case EvalInfo::EvaluatingDeclKind::Ctor:
3594 // The variable whose initializer we're evaluating.
3595 if (Info.EvaluatingDecl == Base)
3596 return true;
3597
3598 // A temporary lifetime-extended by the variable whose initializer we're
3599 // evaluating.
3600 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3601 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3602 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3603 return false;
3604
3605 case EvalInfo::EvaluatingDeclKind::Dtor:
3606 // C++2a [expr.const]p6:
3607 // [during constant destruction] the lifetime of a and its non-mutable
3608 // subobjects (but not its mutable subobjects) [are] considered to start
3609 // within e.
3610 if (MutableSubobject || Base != Info.EvaluatingDecl)
3611 return false;
3612 // FIXME: We can meaningfully extend this to cover non-const objects, but
3613 // we will need special handling: we should be able to access only
3614 // subobjects of such objects that are themselves declared const.
3615 QualType T = getType(Base);
3616 return T.isConstQualified() || T->isReferenceType();
3617 }
3618
3619 llvm_unreachable("unknown evaluating decl kind");
3620}
3621
3622static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3623 SourceLocation CallLoc = {}) {
3624 return Info.CheckArraySize(
3625 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3626 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3627 /*Diag=*/true);
3628}
3629
3630namespace {
3631/// A handle to a complete object (an object that is not a subobject of
3632/// another object).
3633struct CompleteObject {
3634 /// The identity of the object.
3636 /// The value of the complete object.
3637 APValue *Value;
3638 /// The type of the complete object.
3639 QualType Type;
3640
3641 CompleteObject() : Value(nullptr) {}
3643 : Base(Base), Value(Value), Type(Type) {}
3644
3645 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3646 // If this isn't a "real" access (eg, if it's just accessing the type
3647 // info), allow it. We assume the type doesn't change dynamically for
3648 // subobjects of constexpr objects (even though we'd hit UB here if it
3649 // did). FIXME: Is this right?
3650 if (!isAnyAccess(AK))
3651 return true;
3652
3653 // In C++14 onwards, it is permitted to read a mutable member whose
3654 // lifetime began within the evaluation.
3655 // FIXME: Should we also allow this in C++11?
3656 if (!Info.getLangOpts().CPlusPlus14)
3657 return false;
3658 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3659 }
3660
3661 explicit operator bool() const { return !Type.isNull(); }
3662};
3663} // end anonymous namespace
3664
3665static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3666 bool IsMutable = false) {
3667 // C++ [basic.type.qualifier]p1:
3668 // - A const object is an object of type const T or a non-mutable subobject
3669 // of a const object.
3670 if (ObjType.isConstQualified() && !IsMutable)
3671 SubobjType.addConst();
3672 // - A volatile object is an object of type const T or a subobject of a
3673 // volatile object.
3674 if (ObjType.isVolatileQualified())
3675 SubobjType.addVolatile();
3676 return SubobjType;
3677}
3678
3679/// Find the designated sub-object of an rvalue.
3680template<typename SubobjectHandler>
3681typename SubobjectHandler::result_type
3682findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3683 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3684 if (Sub.Invalid)
3685 // A diagnostic will have already been produced.
3686 return handler.failed();
3687 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3688 if (Info.getLangOpts().CPlusPlus11)
3689 Info.FFDiag(E, Sub.isOnePastTheEnd()
3690 ? diag::note_constexpr_access_past_end
3691 : diag::note_constexpr_access_unsized_array)
3692 << handler.AccessKind;
3693 else
3694 Info.FFDiag(E);
3695 return handler.failed();
3696 }
3697
3698 APValue *O = Obj.Value;
3699 QualType ObjType = Obj.Type;
3700 const FieldDecl *LastField = nullptr;
3701 const FieldDecl *VolatileField = nullptr;
3702
3703 // Walk the designator's path to find the subobject.
3704 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3705 // Reading an indeterminate value is undefined, but assigning over one is OK.
3706 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3707 (O->isIndeterminate() &&
3708 !isValidIndeterminateAccess(handler.AccessKind))) {
3709 if (!Info.checkingPotentialConstantExpression())
3710 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3711 << handler.AccessKind << O->isIndeterminate()
3712 << E->getSourceRange();
3713 return handler.failed();
3714 }
3715
3716 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3717 // const and volatile semantics are not applied on an object under
3718 // {con,de}struction.
3719 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3720 ObjType->isRecordType() &&
3721 Info.isEvaluatingCtorDtor(
3722 Obj.Base,
3723 llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3724 ConstructionPhase::None) {
3725 ObjType = Info.Ctx.getCanonicalType(ObjType);
3726 ObjType.removeLocalConst();
3727 ObjType.removeLocalVolatile();
3728 }
3729
3730 // If this is our last pass, check that the final object type is OK.
3731 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3732 // Accesses to volatile objects are prohibited.
3733 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3734 if (Info.getLangOpts().CPlusPlus) {
3735 int DiagKind;
3737 const NamedDecl *Decl = nullptr;
3738 if (VolatileField) {
3739 DiagKind = 2;
3740 Loc = VolatileField->getLocation();
3741 Decl = VolatileField;
3742 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3743 DiagKind = 1;
3744 Loc = VD->getLocation();
3745 Decl = VD;
3746 } else {
3747 DiagKind = 0;
3748 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3749 Loc = E->getExprLoc();
3750 }
3751 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3752 << handler.AccessKind << DiagKind << Decl;
3753 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3754 } else {
3755 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3756 }
3757 return handler.failed();
3758 }
3759
3760 // If we are reading an object of class type, there may still be more
3761 // things we need to check: if there are any mutable subobjects, we
3762 // cannot perform this read. (This only happens when performing a trivial
3763 // copy or assignment.)
3764 if (ObjType->isRecordType() &&
3765 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3766 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3767 return handler.failed();
3768 }
3769
3770 if (I == N) {
3771 if (!handler.found(*O, ObjType))
3772 return false;
3773
3774 // If we modified a bit-field, truncate it to the right width.
3775 if (isModification(handler.AccessKind) &&
3776 LastField && LastField->isBitField() &&
3777 !truncateBitfieldValue(Info, E, *O, LastField))
3778 return false;
3779
3780 return true;
3781 }
3782
3783 LastField = nullptr;
3784 if (ObjType->isArrayType()) {
3785 // Next subobject is an array element.
3786 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3787 assert(CAT && "vla in literal type?");
3788 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3789 if (CAT->getSize().ule(Index)) {
3790 // Note, it should not be possible to form a pointer with a valid
3791 // designator which points more than one past the end of the array.
3792 if (Info.getLangOpts().CPlusPlus11)
3793 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3794 << handler.AccessKind;
3795 else
3796 Info.FFDiag(E);
3797 return handler.failed();
3798 }
3799
3800 ObjType = CAT->getElementType();
3801
3802 if (O->getArrayInitializedElts() > Index)
3803 O = &O->getArrayInitializedElt(Index);
3804 else if (!isRead(handler.AccessKind)) {
3805 if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3806 return handler.failed();
3807
3808 expandArray(*O, Index);
3809 O = &O->getArrayInitializedElt(Index);
3810 } else
3811 O = &O->getArrayFiller();
3812 } else if (ObjType->isAnyComplexType()) {
3813 // Next subobject is a complex number.
3814 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3815 if (Index > 1) {
3816 if (Info.getLangOpts().CPlusPlus11)
3817 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3818 << handler.AccessKind;
3819 else
3820 Info.FFDiag(E);
3821 return handler.failed();
3822 }
3823
3824 ObjType = getSubobjectType(
3825 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3826
3827 assert(I == N - 1 && "extracting subobject of scalar?");
3828 if (O->isComplexInt()) {
3829 return handler.found(Index ? O->getComplexIntImag()
3830 : O->getComplexIntReal(), ObjType);
3831 } else {
3832 assert(O->isComplexFloat());
3833 return handler.found(Index ? O->getComplexFloatImag()
3834 : O->getComplexFloatReal(), ObjType);
3835 }
3836 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3837 if (Field->isMutable() &&
3838 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3839 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3840 << handler.AccessKind << Field;
3841 Info.Note(Field->getLocation(), diag::note_declared_at);
3842 return handler.failed();
3843 }
3844
3845 // Next subobject is a class, struct or union field.
3846 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3847 if (RD->isUnion()) {
3848 const FieldDecl *UnionField = O->getUnionField();
3849 if (!UnionField ||
3850 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3851 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3852 // Placement new onto an inactive union member makes it active.
3853 O->setUnion(Field, APValue());
3854 } else {
3855 // FIXME: If O->getUnionValue() is absent, report that there's no
3856 // active union member rather than reporting the prior active union
3857 // member. We'll need to fix nullptr_t to not use APValue() as its
3858 // representation first.
3859 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3860 << handler.AccessKind << Field << !UnionField << UnionField;
3861 return handler.failed();
3862 }
3863 }
3864 O = &O->getUnionValue();
3865 } else
3866 O = &O->getStructField(Field->getFieldIndex());
3867
3868 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3869 LastField = Field;
3870 if (Field->getType().isVolatileQualified())
3871 VolatileField = Field;
3872 } else {
3873 // Next subobject is a base class.
3874 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3875 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3876 O = &O->getStructBase(getBaseIndex(Derived, Base));
3877
3878 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3879 }
3880 }
3881}
3882
3883namespace {
3884struct ExtractSubobjectHandler {
3885 EvalInfo &Info;
3886 const Expr *E;
3887 APValue &Result;
3888 const AccessKinds AccessKind;
3889
3890 typedef bool result_type;
3891 bool failed() { return false; }
3892 bool found(APValue &Subobj, QualType SubobjType) {
3893 Result = Subobj;
3894 if (AccessKind == AK_ReadObjectRepresentation)
3895 return true;
3896 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3897 }
3898 bool found(APSInt &Value, QualType SubobjType) {
3899 Result = APValue(Value);
3900 return true;
3901 }
3902 bool found(APFloat &Value, QualType SubobjType) {
3903 Result = APValue(Value);
3904 return true;
3905 }
3906};
3907} // end anonymous namespace
3908
3909/// Extract the designated sub-object of an rvalue.
3910static bool extractSubobject(EvalInfo &Info, const Expr *E,
3911 const CompleteObject &Obj,
3912 const SubobjectDesignator &Sub, APValue &Result,
3913 AccessKinds AK = AK_Read) {
3914 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3915 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3916 return findSubobject(Info, E, Obj, Sub, Handler);
3917}
3918
3919namespace {
3920struct ModifySubobjectHandler {
3921 EvalInfo &Info;
3922 APValue &NewVal;
3923 const Expr *E;
3924
3925 typedef bool result_type;
3926 static const AccessKinds AccessKind = AK_Assign;
3927
3928 bool checkConst(QualType QT) {
3929 // Assigning to a const object has undefined behavior.
3930 if (QT.isConstQualified()) {
3931 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3932 return false;
3933 }
3934 return true;
3935 }
3936
3937 bool failed() { return false; }
3938 bool found(APValue &Subobj, QualType SubobjType) {
3939 if (!checkConst(SubobjType))
3940 return false;
3941 // We've been given ownership of NewVal, so just swap it in.
3942 Subobj.swap(NewVal);
3943 return true;
3944 }
3945 bool found(APSInt &Value, QualType SubobjType) {
3946 if (!checkConst(SubobjType))
3947 return false;
3948 if (!NewVal.isInt()) {
3949 // Maybe trying to write a cast pointer value into a complex?
3950 Info.FFDiag(E);
3951 return false;
3952 }
3953 Value = NewVal.getInt();
3954 return true;
3955 }
3956 bool found(APFloat &Value, QualType SubobjType) {
3957 if (!checkConst(SubobjType))
3958 return false;
3959 Value = NewVal.getFloat();
3960 return true;
3961 }
3962};
3963} // end anonymous namespace
3964
3965const AccessKinds ModifySubobjectHandler::AccessKind;
3966
3967/// Update the designated sub-object of an rvalue to the given value.
3968static bool modifySubobject(EvalInfo &Info, const Expr *E,
3969 const CompleteObject &Obj,
3970 const SubobjectDesignator &Sub,
3971 APValue &NewVal) {
3972 ModifySubobjectHandler Handler = { Info, NewVal, E };
3973 return findSubobject(Info, E, Obj, Sub, Handler);
3974}
3975
3976/// Find the position where two subobject designators diverge, or equivalently
3977/// the length of the common initial subsequence.
3978static unsigned FindDesignatorMismatch(QualType ObjType,
3979 const SubobjectDesignator &A,
3980 const SubobjectDesignator &B,
3981 bool &WasArrayIndex) {
3982 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3983 for (/**/; I != N; ++I) {
3984 if (!ObjType.isNull() &&
3985 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3986 // Next subobject is an array element.
3987 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3988 WasArrayIndex = true;
3989 return I;
3990 }
3991 if (ObjType->isAnyComplexType())
3992 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3993 else
3994 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3995 } else {
3996 if (A.Entries[I].getAsBaseOrMember() !=
3997 B.Entries[I].getAsBaseOrMember()) {
3998 WasArrayIndex = false;
3999 return I;
4000 }
4001 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4002 // Next subobject is a field.
4003 ObjType = FD->getType();
4004 else
4005 // Next subobject is a base class.
4006 ObjType = QualType();
4007 }
4008 }
4009 WasArrayIndex = false;
4010 return I;
4011}
4012
4013/// Determine whether the given subobject designators refer to elements of the
4014/// same array object.
4016 const SubobjectDesignator &A,
4017 const SubobjectDesignator &B) {
4018 if (A.Entries.size() != B.Entries.size())
4019 return false;
4020
4021 bool IsArray = A.MostDerivedIsArrayElement;
4022 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4023 // A is a subobject of the array element.
4024 return false;
4025
4026 // If A (and B) designates an array element, the last entry will be the array
4027 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4028 // of length 1' case, and the entire path must match.
4029 bool WasArrayIndex;
4030 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4031 return CommonLength >= A.Entries.size() - IsArray;
4032}
4033
4034/// Find the complete object to which an LValue refers.
4035static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4036 AccessKinds AK, const LValue &LVal,
4037 QualType LValType) {
4038 if (LVal.InvalidBase) {
4039 Info.FFDiag(E);
4040 return CompleteObject();
4041 }
4042
4043 if (!LVal.Base) {
4044 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4045 return CompleteObject();
4046 }
4047
4048 CallStackFrame *Frame = nullptr;
4049 unsigned Depth = 0;
4050 if (LVal.getLValueCallIndex()) {
4051 std::tie(Frame, Depth) =
4052 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4053 if (!Frame) {
4054 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4055 << AK << LVal.Base.is<const ValueDecl*>();
4056 NoteLValueLocation(Info, LVal.Base);
4057 return CompleteObject();
4058 }
4059 }
4060
4061 bool IsAccess = isAnyAccess(AK);
4062
4063 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4064 // is not a constant expression (even if the object is non-volatile). We also
4065 // apply this rule to C++98, in order to conform to the expected 'volatile'
4066 // semantics.
4067 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4068 if (Info.getLangOpts().CPlusPlus)
4069 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4070 << AK << LValType;
4071 else
4072 Info.FFDiag(E);
4073 return CompleteObject();
4074 }
4075
4076 // Compute value storage location and type of base object.
4077 APValue *BaseVal = nullptr;
4078 QualType BaseType = getType(LVal.Base);
4079
4080 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4081 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4082 // This is the object whose initializer we're evaluating, so its lifetime
4083 // started in the current evaluation.
4084 BaseVal = Info.EvaluatingDeclValue;
4085 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4086 // Allow reading from a GUID declaration.
4087 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4088 if (isModification(AK)) {
4089 // All the remaining cases do not permit modification of the object.
4090 Info.FFDiag(E, diag::note_constexpr_modify_global);
4091 return CompleteObject();
4092 }
4093 APValue &V = GD->getAsAPValue();
4094 if (V.isAbsent()) {
4095 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4096 << GD->getType();
4097 return CompleteObject();
4098 }
4099 return CompleteObject(LVal.Base, &V, GD->getType());
4100 }
4101
4102 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4103 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4104 if (isModification(AK)) {
4105 Info.FFDiag(E, diag::note_constexpr_modify_global);
4106 return CompleteObject();
4107 }
4108 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4109 GCD->getType());
4110 }
4111
4112 // Allow reading from template parameter objects.
4113 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4114 if (isModification(AK)) {
4115 Info.FFDiag(E, diag::note_constexpr_modify_global);
4116 return CompleteObject();
4117 }
4118 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4119 TPO->getType());
4120 }
4121
4122 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4123 // In C++11, constexpr, non-volatile variables initialized with constant
4124 // expressions are constant expressions too. Inside constexpr functions,
4125 // parameters are constant expressions even if they're non-const.
4126 // In C++1y, objects local to a constant expression (those with a Frame) are
4127 // both readable and writable inside constant expressions.
4128 // In C, such things can also be folded, although they are not ICEs.
4129 const VarDecl *VD = dyn_cast<VarDecl>(D);
4130 if (VD) {
4131 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4132 VD = VDef;
4133 }
4134 if (!VD || VD->isInvalidDecl()) {
4135 Info.FFDiag(E);
4136 return CompleteObject();
4137 }
4138
4139 bool IsConstant = BaseType.isConstant(Info.Ctx);
4140 bool ConstexprVar = false;
4141 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4142 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4143 ConstexprVar = VD->isConstexpr();
4144
4145 // Unless we're looking at a local variable or argument in a constexpr call,
4146 // the variable we're reading must be const.
4147 if (!Frame) {
4148 if (IsAccess && isa<ParmVarDecl>(VD)) {
4149 // Access of a parameter that's not associated with a frame isn't going
4150 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4151 // suitable diagnostic.
4152 } else if (Info.getLangOpts().CPlusPlus14 &&
4153 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4154 // OK, we can read and modify an object if we're in the process of
4155 // evaluating its initializer, because its lifetime began in this
4156 // evaluation.
4157 } else if (isModification(AK)) {
4158 // All the remaining cases do not permit modification of the object.
4159 Info.FFDiag(E, diag::note_constexpr_modify_global);
4160 return CompleteObject();
4161 } else if (VD->isConstexpr()) {
4162 // OK, we can read this variable.
4163 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4164 Info.FFDiag(E);
4165 return CompleteObject();
4166 } else if (BaseType->isIntegralOrEnumerationType()) {
4167 if (!IsConstant) {
4168 if (!IsAccess)
4169 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4170 if (Info.getLangOpts().CPlusPlus) {
4171 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4172 Info.Note(VD->getLocation(), diag::note_declared_at);
4173 } else {
4174 Info.FFDiag(E);
4175 }
4176 return CompleteObject();
4177 }
4178 } else if (!IsAccess) {
4179 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4180 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4181 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4182 // This variable might end up being constexpr. Don't diagnose it yet.
4183 } else if (IsConstant) {
4184 // Keep evaluating to see what we can do. In particular, we support
4185 // folding of const floating-point types, in order to make static const
4186 // data members of such types (supported as an extension) more useful.
4187 if (Info.getLangOpts().CPlusPlus) {
4188 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4189 ? diag::note_constexpr_ltor_non_constexpr
4190 : diag::note_constexpr_ltor_non_integral, 1)
4191 << VD << BaseType;
4192 Info.Note(VD->getLocation(), diag::note_declared_at);
4193 } else {
4194 Info.CCEDiag(E);
4195 }
4196 } else {
4197 // Never allow reading a non-const value.
4198 if (Info.getLangOpts().CPlusPlus) {
4199 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4200 ? diag::note_constexpr_ltor_non_constexpr
4201 : diag::note_constexpr_ltor_non_integral, 1)
4202 << VD << BaseType;
4203 Info.Note(VD->getLocation(), diag::note_declared_at);
4204 } else {
4205 Info.FFDiag(E);
4206 }
4207 return CompleteObject();
4208 }
4209 }
4210
4211 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4212 return CompleteObject();
4213 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4214 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4215 if (!Alloc) {
4216 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4217 return CompleteObject();
4218 }
4219 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4220 LVal.Base.getDynamicAllocType());
4221 } else {
4222 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4223
4224 if (!Frame) {
4225 if (const MaterializeTemporaryExpr *MTE =
4226 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4227 assert(MTE->getStorageDuration() == SD_Static &&
4228 "should have a frame for a non-global materialized temporary");
4229
4230 // C++20 [expr.const]p4: [DR2126]
4231 // An object or reference is usable in constant expressions if it is
4232 // - a temporary object of non-volatile const-qualified literal type
4233 // whose lifetime is extended to that of a variable that is usable
4234 // in constant expressions
4235 //
4236 // C++20 [expr.const]p5:
4237 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4238 // - a non-volatile glvalue that refers to an object that is usable
4239 // in constant expressions, or
4240 // - a non-volatile glvalue of literal type that refers to a
4241 // non-volatile object whose lifetime began within the evaluation
4242 // of E;
4243 //
4244 // C++11 misses the 'began within the evaluation of e' check and
4245 // instead allows all temporaries, including things like:
4246 // int &&r = 1;
4247 // int x = ++r;
4248 // constexpr int k = r;
4249 // Therefore we use the C++14-onwards rules in C++11 too.
4250 //
4251 // Note that temporaries whose lifetimes began while evaluating a
4252 // variable's constructor are not usable while evaluating the
4253 // corresponding destructor, not even if they're of const-qualified
4254 // types.
4255 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4256 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4257 if (!IsAccess)
4258 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4259 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4260 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4261 return CompleteObject();
4262 }
4263
4264 BaseVal = MTE->getOrCreateValue(false);
4265 assert(BaseVal && "got reference to unevaluated temporary");
4266 } else {
4267 if (!IsAccess)
4268 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4269 APValue Val;
4270 LVal.moveInto(Val);
4271 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4272 << AK
4273 << Val.getAsString(Info.Ctx,
4274 Info.Ctx.getLValueReferenceType(LValType));
4275 NoteLValueLocation(Info, LVal.Base);
4276 return CompleteObject();
4277 }
4278 } else {
4279 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4280 assert(BaseVal && "missing value for temporary");
4281 }
4282 }
4283
4284 // In C++14, we can't safely access any mutable state when we might be
4285 // evaluating after an unmodeled side effect. Parameters are modeled as state
4286 // in the caller, but aren't visible once the call returns, so they can be
4287 // modified in a speculatively-evaluated call.
4288 //
4289 // FIXME: Not all local state is mutable. Allow local constant subobjects
4290 // to be read here (but take care with 'mutable' fields).
4291 unsigned VisibleDepth = Depth;
4292 if (llvm::isa_and_nonnull<ParmVarDecl>(
4293 LVal.Base.dyn_cast<const ValueDecl *>()))
4294 ++VisibleDepth;
4295 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4296 Info.EvalStatus.HasSideEffects) ||
4297 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4298 return CompleteObject();
4299
4300 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4301}
4302
4303/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4304/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4305/// glvalue referred to by an entity of reference type.
4306///
4307/// \param Info - Information about the ongoing evaluation.
4308/// \param Conv - The expression for which we are performing the conversion.
4309/// Used for diagnostics.
4310/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4311/// case of a non-class type).
4312/// \param LVal - The glvalue on which we are attempting to perform this action.
4313/// \param RVal - The produced value will be placed here.
4314/// \param WantObjectRepresentation - If true, we're looking for the object
4315/// representation rather than the value, and in particular,
4316/// there is no requirement that the result be fully initialized.
4317static bool
4319 const LValue &LVal, APValue &RVal,
4320 bool WantObjectRepresentation = false) {
4321 if (LVal.Designator.Invalid)
4322 return false;
4323
4324 // Check for special cases where there is no existing APValue to look at.
4325 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4326
4327 AccessKinds AK =
4328 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4329
4330 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4331 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4332 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4333 // initializer until now for such expressions. Such an expression can't be
4334 // an ICE in C, so this only matters for fold.
4335 if (Type.isVolatileQualified()) {
4336 Info.FFDiag(Conv);
4337 return false;
4338 }
4339
4340 APValue Lit;
4341 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4342 return false;
4343
4344 // According to GCC info page:
4345 //
4346 // 6.28 Compound Literals
4347 //
4348 // As an optimization, G++ sometimes gives array compound literals longer
4349 // lifetimes: when the array either appears outside a function or has a
4350 // const-qualified type. If foo and its initializer had elements of type
4351 // char *const rather than char *, or if foo were a global variable, the
4352 // array would have static storage duration. But it is probably safest
4353 // just to avoid the use of array compound literals in C++ code.
4354 //
4355 // Obey that rule by checking constness for converted array types.
4356
4357 QualType CLETy = CLE->getType();
4358 if (CLETy->isArrayType() && !Type->isArrayType()) {
4359 if (!CLETy.isConstant(Info.Ctx)) {
4360 Info.FFDiag(Conv);
4361 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4362 return false;
4363 }
4364 }
4365
4366 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4367 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4368 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4369 // Special-case character extraction so we don't have to construct an
4370 // APValue for the whole string.
4371 assert(LVal.Designator.Entries.size() <= 1 &&
4372 "Can only read characters from string literals");
4373 if (LVal.Designator.Entries.empty()) {
4374 // Fail for now for LValue to RValue conversion of an array.
4375 // (This shouldn't show up in C/C++, but it could be triggered by a
4376 // weird EvaluateAsRValue call from a tool.)
4377 Info.FFDiag(Conv);
4378 return false;
4379 }
4380 if (LVal.Designator.isOnePastTheEnd()) {
4381 if (Info.getLangOpts().CPlusPlus11)
4382 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4383 else
4384 Info.FFDiag(Conv);
4385 return false;
4386 }
4387 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4388 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4389 return true;
4390 }
4391 }
4392
4393 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4394 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4395}
4396
4397/// Perform an assignment of Val to LVal. Takes ownership of Val.
4398static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4399 QualType LValType, APValue &Val) {
4400 if (LVal.Designator.Invalid)
4401 return false;
4402
4403 if (!Info.getLangOpts().CPlusPlus14) {
4404 Info.FFDiag(E);
4405 return false;
4406 }
4407
4408 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4409 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4410}
4411
4412namespace {
4413struct CompoundAssignSubobjectHandler {
4414 EvalInfo &Info;
4415 const CompoundAssignOperator *E;
4416 QualType PromotedLHSType;
4418 const APValue &RHS;
4419
4420 static const AccessKinds AccessKind = AK_Assign;
4421
4422 typedef bool result_type;
4423
4424 bool checkConst(QualType QT) {
4425 // Assigning to a const object has undefined behavior.
4426 if (QT.isConstQualified()) {
4427 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4428 return false;
4429 }
4430 return true;
4431 }
4432
4433 bool failed() { return false; }
4434 bool found(APValue &Subobj, QualType SubobjType) {
4435 switch (Subobj.getKind()) {
4436 case APValue::Int:
4437 return found(Subobj.getInt(), SubobjType);
4438 case APValue::Float:
4439 return found(Subobj.getFloat(), SubobjType);
4442 // FIXME: Implement complex compound assignment.
4443 Info.FFDiag(E);
4444 return false;
4445 case APValue::LValue:
4446 return foundPointer(Subobj, SubobjType);
4447 case APValue::Vector:
4448 return foundVector(Subobj, SubobjType);
4450 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4451 << /*read of=*/0 << /*uninitialized object=*/1
4452 << E->getLHS()->getSourceRange();
4453 return false;
4454 default:
4455 // FIXME: can this happen?
4456 Info.FFDiag(E);
4457 return false;
4458 }
4459 }
4460
4461 bool foundVector(APValue &Value, QualType SubobjType) {
4462 if (!checkConst(SubobjType))
4463 return false;
4464
4465 if (!SubobjType->isVectorType()) {
4466 Info.FFDiag(E);
4467 return false;
4468 }
4469 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4470 }
4471
4472 bool found(APSInt &Value, QualType SubobjType) {
4473 if (!checkConst(SubobjType))
4474 return false;
4475
4476 if (!SubobjType->isIntegerType()) {
4477 // We don't support compound assignment on integer-cast-to-pointer
4478 // values.
4479 Info.FFDiag(E);
4480 return false;
4481 }
4482
4483 if (RHS.isInt()) {
4484 APSInt LHS =
4485 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4486 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4487 return false;
4488 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4489 return true;
4490 } else if (RHS.isFloat()) {
4491 const FPOptions FPO = E->getFPFeaturesInEffect(
4492 Info.Ctx.getLangOpts());
4493 APFloat FValue(0.0);
4494 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4495 PromotedLHSType, FValue) &&
4496 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4497 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4498 Value);
4499 }
4500
4501 Info.FFDiag(E);
4502 return false;
4503 }
4504 bool found(APFloat &Value, QualType SubobjType) {
4505 return checkConst(SubobjType) &&
4506 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4507 Value) &&
4508 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4509 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4510 }
4511 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4512 if (!checkConst(SubobjType))
4513 return false;
4514
4515 QualType PointeeType;
4516 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4517 PointeeType = PT->getPointeeType();
4518
4519 if (PointeeType.isNull() || !RHS.isInt() ||
4520 (Opcode != BO_Add && Opcode != BO_Sub)) {
4521 Info.FFDiag(E);
4522 return false;
4523 }
4524
4525 APSInt Offset = RHS.getInt();
4526 if (Opcode == BO_Sub)
4527 negateAsSigned(Offset);
4528
4529 LValue LVal;
4530 LVal.setFrom(Info.Ctx, Subobj);
4531 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4532 return false;
4533 LVal.moveInto(Subobj);
4534 return true;
4535 }
4536};
4537} // end anonymous namespace
4538
4539const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4540
4541/// Perform a compound assignment of LVal <op>= RVal.
4542static bool handleCompoundAssignment(EvalInfo &Info,
4543 const CompoundAssignOperator *E,
4544 const LValue &LVal, QualType LValType,
4545 QualType PromotedLValType,
4546 BinaryOperatorKind Opcode,
4547 const APValue &RVal) {
4548 if (LVal.Designator.Invalid)
4549 return false;
4550
4551 if (!Info.getLangOpts().CPlusPlus14) {
4552 Info.FFDiag(E);
4553 return false;
4554 }
4555
4556 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4557 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4558 RVal };
4559 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4560}
4561
4562namespace {
4563struct IncDecSubobjectHandler {
4564 EvalInfo &Info;
4565 const UnaryOperator *E;
4566 AccessKinds AccessKind;
4567 APValue *Old;
4568
4569 typedef bool result_type;
4570
4571 bool checkConst(QualType QT) {
4572 // Assigning to a const object has undefined behavior.
4573 if (QT.isConstQualified()) {
4574 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4575 return false;
4576 }
4577 return true;
4578 }
4579
4580 bool failed() { return false; }
4581 bool found(APValue &Subobj, QualType SubobjType) {
4582 // Stash the old value. Also clear Old, so we don't clobber it later
4583 // if we're post-incrementing a complex.
4584 if (Old) {
4585 *Old = Subobj;
4586 Old = nullptr;
4587 }
4588
4589 switch (Subobj.getKind()) {
4590 case APValue::Int:
4591 return found(Subobj.getInt(), SubobjType);
4592 case APValue::Float:
4593 return found(Subobj.getFloat(), SubobjType);
4595 return found(Subobj.getComplexIntReal(),
4596 SubobjType->castAs<ComplexType>()->getElementType()
4597 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4599 return found(Subobj.getComplexFloatReal(),
4600 SubobjType->castAs<ComplexType>()->getElementType()
4601 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4602 case APValue::LValue:
4603 return foundPointer(Subobj, SubobjType);
4604 default:
4605 // FIXME: can this happen?
4606 Info.FFDiag(E);
4607 return false;
4608 }
4609 }
4610 bool found(APSInt &Value, QualType SubobjType) {
4611 if (!checkConst(SubobjType))
4612 return false;
4613
4614 if (!SubobjType->isIntegerType()) {
4615 // We don't support increment / decrement on integer-cast-to-pointer
4616 // values.
4617 Info.FFDiag(E);
4618 return false;
4619 }
4620
4621 if (Old) *Old = APValue(Value);
4622
4623 // bool arithmetic promotes to int, and the conversion back to bool
4624 // doesn't reduce mod 2^n, so special-case it.
4625 if (SubobjType->isBooleanType()) {
4626 if (AccessKind == AK_Increment)
4627 Value = 1;
4628 else
4629 Value = !Value;
4630 return true;
4631 }
4632
4633 bool WasNegative = Value.isNegative();
4634 if (AccessKind == AK_Increment) {
4635 ++Value;
4636
4637 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4638 APSInt ActualValue(Value, /*IsUnsigned*/true);
4639 return HandleOverflow(Info, E, ActualValue, SubobjType);
4640 }
4641 } else {
4642 --Value;
4643
4644 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4645 unsigned BitWidth = Value.getBitWidth();
4646 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4647 ActualValue.setBit(BitWidth);
4648 return HandleOverflow(Info, E, ActualValue, SubobjType);
4649 }
4650 }
4651 return true;
4652 }
4653 bool found(APFloat &Value, QualType SubobjType) {
4654 if (!checkConst(SubobjType))
4655 return false;
4656
4657 if (Old) *Old = APValue(Value);
4658
4659 APFloat One(Value.getSemantics(), 1);
4660 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4661 APFloat::opStatus St;
4662 if (AccessKind == AK_Increment)
4663 St = Value.add(One, RM);
4664 else
4665 St = Value.subtract(One, RM);
4666 return checkFloatingPointResult(Info, E, St);
4667 }
4668 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4669 if (!checkConst(SubobjType))
4670 return false;
4671
4672 QualType PointeeType;
4673 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4674 PointeeType = PT->getPointeeType();
4675 else {
4676 Info.FFDiag(E);
4677 return false;
4678 }
4679
4680 LValue LVal;
4681 LVal.setFrom(Info.Ctx, Subobj);
4682 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4683 AccessKind == AK_Increment ? 1 : -1))
4684 return false;
4685 LVal.moveInto(Subobj);
4686 return true;
4687 }
4688};
4689} // end anonymous namespace
4690
4691/// Perform an increment or decrement on LVal.
4692static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4693 QualType LValType, bool IsIncrement, APValue *Old) {
4694 if (LVal.Designator.Invalid)
4695 return false;
4696
4697 if (!Info.getLangOpts().CPlusPlus14) {
4698 Info.FFDiag(E);
4699 return false;
4700 }
4701
4702 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4703 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4704 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4705 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4706}
4707
4708/// Build an lvalue for the object argument of a member function call.
4709static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4710 LValue &This) {
4711 if (Object->getType()->isPointerType() && Object->isPRValue())
4712 return EvaluatePointer(Object, This, Info);
4713
4714 if (Object->isGLValue())
4715 return EvaluateLValue(Object, This, Info);
4716
4717 if (Object->getType()->isLiteralType(Info.Ctx))
4718 return EvaluateTemporary(Object, This, Info);
4719
4720 if (Object->getType()->isRecordType() && Object->isPRValue())
4721 return EvaluateTemporary(Object, This, Info);
4722
4723 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4724 return false;
4725}
4726
4727/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4728/// lvalue referring to the result.
4729///
4730/// \param Info - Information about the ongoing evaluation.
4731/// \param LV - An lvalue referring to the base of the member pointer.
4732/// \param RHS - The member pointer expression.
4733/// \param IncludeMember - Specifies whether the member itself is included in
4734/// the resulting LValue subobject designator. This is not possible when
4735/// creating a bound member function.
4736/// \return The field or method declaration to which the member pointer refers,
4737/// or 0 if evaluation fails.
4738static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4739 QualType LVType,
4740 LValue &LV,
4741 const Expr *RHS,
4742 bool IncludeMember = true) {
4743 MemberPtr MemPtr;
4744 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4745 return nullptr;
4746
4747 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4748 // member value, the behavior is undefined.
4749 if (!MemPtr.getDecl()) {
4750 // FIXME: Specific diagnostic.
4751 Info.FFDiag(RHS);
4752 return nullptr;
4753 }
4754
4755 if (MemPtr.isDerivedMember()) {
4756 // This is a member of some derived class. Truncate LV appropriately.
4757 // The end of the derived-to-base path for the base object must match the
4758 // derived-to-base path for the member pointer.
4759 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4760 LV.Designator.Entries.size()) {
4761 Info.FFDiag(RHS);
4762 return nullptr;
4763 }
4764 unsigned PathLengthToMember =
4765 LV.Designator.Entries.size() - MemPtr.Path.size();
4766 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4767 const CXXRecordDecl *LVDecl = getAsBaseClass(
4768 LV.Designator.Entries[PathLengthToMember + I]);
4769 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4770 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4771 Info.FFDiag(RHS);
4772 return nullptr;
4773 }
4774 }
4775
4776 // Truncate the lvalue to the appropriate derived class.
4777 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4778 PathLengthToMember))
4779 return nullptr;
4780 } else if (!MemPtr.Path.empty()) {
4781 // Extend the LValue path with the member pointer's path.
4782 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4783 MemPtr.Path.size() + IncludeMember);
4784
4785 // Walk down to the appropriate base class.
4786 if (const PointerType *PT = LVType->getAs<PointerType>())
4787 LVType = PT->getPointeeType();
4788 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4789 assert(RD && "member pointer access on non-class-type expression");
4790 // The first class in the path is that of the lvalue.
4791 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4792 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4793 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4794 return nullptr;
4795 RD = Base;
4796 }
4797 // Finally cast to the class containing the member.
4798 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4799 MemPtr.getContainingRecord()))
4800 return nullptr;
4801 }
4802
4803 // Add the member. Note that we cannot build bound member functions here.
4804 if (IncludeMember) {
4805 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4806 if (!HandleLValueMember(Info, RHS, LV, FD))
4807 return nullptr;
4808 } else if (const IndirectFieldDecl *IFD =
4809 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4810 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4811 return nullptr;
4812 } else {
4813 llvm_unreachable("can't construct reference to bound member function");
4814 }
4815 }
4816
4817 return MemPtr.getDecl();
4818}
4819
4820static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4821 const BinaryOperator *BO,
4822 LValue &LV,
4823 bool IncludeMember = true) {
4824 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4825
4826 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4827 if (Info.noteFailure()) {
4828 MemberPtr MemPtr;
4829 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4830 }
4831 return nullptr;
4832 }
4833
4834 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4835 BO->getRHS(), IncludeMember);
4836}
4837
4838/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4839/// the provided lvalue, which currently refers to the base object.
4840static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4841 LValue &Result) {
4842 SubobjectDesignator &D = Result.Designator;
4843 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4844 return false;
4845
4846 QualType TargetQT = E->getType();
4847 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4848 TargetQT = PT->getPointeeType();
4849
4850 // Check this cast lands within the final derived-to-base subobject path.
4851 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4852 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4853 << D.MostDerivedType << TargetQT;
4854 return false;
4855 }
4856
4857 // Check the type of the final cast. We don't need to check the path,
4858 // since a cast can only be formed if the path is unique.
4859 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4860 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4861 const CXXRecordDecl *FinalType;
4862 if (NewEntriesSize == D.MostDerivedPathLength)
4863 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4864 else
4865 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4866 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4867 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4868 << D.MostDerivedType << TargetQT;
4869 return false;
4870 }
4871
4872 // Truncate the lvalue to the appropriate derived class.
4873 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4874}
4875
4876/// Get the value to use for a default-initialized object of type T.
4877/// Return false if it encounters something invalid.
4879 bool Success = true;
4880
4881 // If there is already a value present don't overwrite it.
4882 if (!Result.isAbsent())
4883 return true;
4884
4885 if (auto *RD = T->getAsCXXRecordDecl()) {
4886 if (RD->isInvalidDecl()) {
4887 Result = APValue();
4888 return false;
4889 }
4890 if (RD->isUnion()) {
4891 Result = APValue((const FieldDecl *)nullptr);
4892 return true;
4893 }
4894 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4895 std::distance(RD->field_begin(), RD->field_end()));
4896
4897 unsigned Index = 0;
4898 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4899 End = RD->bases_end();
4900 I != End; ++I, ++Index)
4901 Success &=
4902 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
4903
4904 for (const auto *I : RD->fields()) {
4905 if (I->isUnnamedBitField())
4906 continue;
4908 I->getType(), Result.getStructField(I->getFieldIndex()));
4909 }
4910 return Success;
4911 }
4912
4913 if (auto *AT =
4914 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4915 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
4916 if (Result.hasArrayFiller())
4917 Success &=
4918 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4919
4920 return Success;
4921 }
4922
4923 Result = APValue::IndeterminateValue();
4924 return true;
4925}
4926
4927namespace {
4928enum EvalStmtResult {
4929 /// Evaluation failed.
4930 ESR_Failed,
4931 /// Hit a 'return' statement.
4932 ESR_Returned,
4933 /// Evaluation succeeded.
4934 ESR_Succeeded,
4935 /// Hit a 'continue' statement.
4936 ESR_Continue,
4937 /// Hit a 'break' statement.
4938 ESR_Break,
4939 /// Still scanning for 'case' or 'default' statement.
4940 ESR_CaseNotFound
4941};
4942}
4943
4944static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4945 if (VD->isInvalidDecl())
4946 return false;
4947 // We don't need to evaluate the initializer for a static local.
4948 if (!VD->hasLocalStorage())
4949 return true;
4950
4951 LValue Result;
4952 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4953 ScopeKind::Block, Result);
4954
4955 const Expr *InitE = VD->getInit();
4956 if (!InitE) {
4957 if (VD->getType()->isDependentType())
4958 return Info.noteSideEffect();
4959 return handleDefaultInitValue(VD->getType(), Val);
4960 }
4961 if (InitE->isValueDependent())
4962 return false;
4963
4964 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4965 // Wipe out any partially-computed value, to allow tracking that this
4966 // evaluation failed.
4967 Val = APValue();
4968 return false;
4969 }
4970
4971 return true;
4972}
4973
4974static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4975 bool OK = true;
4976
4977 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4978 OK &= EvaluateVarDecl(Info, VD);
4979
4980 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4981 for (auto *BD : DD->bindings())
4982 if (auto *VD = BD->getHoldingVar())
4983 OK &= EvaluateDecl(Info, VD);
4984
4985 return OK;
4986}
4987
4988static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4989 assert(E->isValueDependent());
4990 if (Info.noteSideEffect())
4991 return true;
4992 assert(E->containsErrors() && "valid value-dependent expression should never "
4993 "reach invalid code path.");
4994 return false;
4995}
4996
4997/// Evaluate a condition (either a variable declaration or an expression).
4998static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4999 const Expr *Cond, bool &Result) {
5000 if (Cond->isValueDependent())
5001 return false;
5002 FullExpressionRAII Scope(Info);
5003 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5004 return false;
5005 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5006 return false;
5007 return Scope.destroy();
5008}
5009
5010namespace {
5011/// A location where the result (returned value) of evaluating a
5012/// statement should be stored.
5013struct StmtResult {
5014 /// The APValue that should be filled in with the returned value.
5015 APValue &Value;
5016 /// The location containing the result, if any (used to support RVO).
5017 const LValue *Slot;
5018};
5019
5020struct TempVersionRAII {
5021 CallStackFrame &Frame;
5022
5023 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5024 Frame.pushTempVersion();
5025 }
5026
5027 ~TempVersionRAII() {
5028 Frame.popTempVersion();
5029 }
5030};
5031
5032}
5033
5034static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5035 const Stmt *S,
5036 const SwitchCase *SC = nullptr);
5037
5038/// Evaluate the body of a loop, and translate the result as appropriate.
5039static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5040 const Stmt *Body,
5041 const SwitchCase *Case = nullptr) {
5042 BlockScopeRAII Scope(Info);
5043
5044 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5045 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5046 ESR = ESR_Failed;
5047
5048 switch (ESR) {
5049 case ESR_Break:
5050 return ESR_Succeeded;
5051 case ESR_Succeeded:
5052 case ESR_Continue:
5053 return ESR_Continue;
5054 case ESR_Failed:
5055 case ESR_Returned:
5056 case ESR_CaseNotFound:
5057 return ESR;
5058 }
5059 llvm_unreachable("Invalid EvalStmtResult!");
5060}
5061
5062/// Evaluate a switch statement.
5063static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5064 const SwitchStmt *SS) {
5065 BlockScopeRAII Scope(Info);
5066
5067 // Evaluate the switch condition.
5068 APSInt Value;
5069 {
5070 if (const Stmt *Init = SS->getInit()) {
5071 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5072 if (ESR != ESR_Succeeded) {
5073 if (ESR != ESR_Failed && !Scope.destroy())
5074 ESR = ESR_Failed;
5075 return ESR;
5076 }
5077 }
5078
5079 FullExpressionRAII CondScope(Info);
5080 if (SS->getConditionVariable() &&
5081 !EvaluateDecl(Info, SS->getConditionVariable()))
5082 return ESR_Failed;
5083 if (SS->getCond()->isValueDependent()) {
5084 // We don't know what the value is, and which branch should jump to.
5085 EvaluateDependentExpr(SS->getCond(), Info);
5086 return ESR_Failed;
5087 }
5088 if (!EvaluateInteger(SS->getCond(), Value, Info))
5089 return ESR_Failed;
5090
5091 if (!CondScope.destroy())
5092 return ESR_Failed;
5093 }
5094
5095 // Find the switch case corresponding to the value of the condition.
5096 // FIXME: Cache this lookup.
5097 const SwitchCase *Found = nullptr;
5098 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5099 SC = SC->getNextSwitchCase()) {
5100 if (isa<DefaultStmt>(SC)) {
5101 Found = SC;
5102 continue;
5103 }
5104
5105 const CaseStmt *CS = cast<CaseStmt>(SC);
5106 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5107 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5108 : LHS;
5109 if (LHS <= Value && Value <= RHS) {
5110 Found = SC;
5111 break;
5112 }
5113 }
5114
5115 if (!Found)
5116 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5117
5118 // Search the switch body for the switch case and evaluate it from there.
5119 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5120 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5121 return ESR_Failed;
5122
5123 switch (ESR) {
5124 case ESR_Break:
5125 return ESR_Succeeded;
5126 case ESR_Succeeded:
5127 case ESR_Continue:
5128 case ESR_Failed:
5129 case ESR_Returned:
5130 return ESR;
5131 case ESR_CaseNotFound:
5132 // This can only happen if the switch case is nested within a statement
5133 // expression. We have no intention of supporting that.
5134 Info.FFDiag(Found->getBeginLoc(),
5135 diag::note_constexpr_stmt_expr_unsupported);
5136 return ESR_Failed;
5137 }
5138 llvm_unreachable("Invalid EvalStmtResult!");
5139}
5140
5141static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5142 // An expression E is a core constant expression unless the evaluation of E
5143 // would evaluate one of the following: [C++23] - a control flow that passes
5144 // through a declaration of a variable with static or thread storage duration
5145 // unless that variable is usable in constant expressions.
5146 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5147 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5148 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5149 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5150 return false;
5151 }
5152 return true;
5153}
5154
5155// Evaluate a statement.
5156static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5157 const Stmt *S, const SwitchCase *Case) {
5158 if (!Info.nextStep(S))
5159 return ESR_Failed;
5160
5161 // If we're hunting down a 'case' or 'default' label, recurse through
5162 // substatements until we hit the label.
5163 if (Case) {
5164 switch (S->getStmtClass()) {
5165 case Stmt::CompoundStmtClass:
5166 // FIXME: Precompute which substatement of a compound statement we
5167 // would jump to, and go straight there rather than performing a
5168 // linear scan each time.
5169 case Stmt::LabelStmtClass:
5170 case Stmt::AttributedStmtClass:
5171 case Stmt::DoStmtClass:
5172 break;
5173
5174 case Stmt::CaseStmtClass:
5175 case Stmt::DefaultStmtClass:
5176 if (Case == S)
5177 Case = nullptr;
5178 break;
5179
5180 case Stmt::IfStmtClass: {
5181 // FIXME: Precompute which side of an 'if' we would jump to, and go
5182 // straight there rather than scanning both sides.
5183 const IfStmt *IS = cast<IfStmt>(S);
5184
5185 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5186 // preceded by our switch label.
5187 BlockScopeRAII Scope(Info);
5188
5189 // Step into the init statement in case it brings an (uninitialized)
5190 // variable into scope.
5191 if (const Stmt *Init = IS->getInit()) {
5192 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5193 if (ESR != ESR_CaseNotFound) {
5194 assert(ESR != ESR_Succeeded);
5195 return ESR;
5196 }
5197 }
5198
5199 // Condition variable must be initialized if it exists.
5200 // FIXME: We can skip evaluating the body if there's a condition
5201 // variable, as there can't be any case labels within it.
5202 // (The same is true for 'for' statements.)
5203
5204 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5205 if (ESR == ESR_Failed)
5206 return ESR;
5207 if (ESR != ESR_CaseNotFound)
5208 return Scope.destroy() ? ESR : ESR_Failed;
5209 if (!IS->getElse())
5210 return ESR_CaseNotFound;
5211
5212 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5213 if (ESR == ESR_Failed)
5214 return ESR;
5215 if (ESR != ESR_CaseNotFound)
5216 return Scope.destroy() ? ESR : ESR_Failed;
5217 return ESR_CaseNotFound;
5218 }
5219
5220 case Stmt::WhileStmtClass: {
5221 EvalStmtResult ESR =
5222 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5223 if (ESR != ESR_Continue)
5224 return ESR;
5225 break;
5226 }
5227
5228 case Stmt::ForStmtClass: {
5229 const ForStmt *FS = cast<ForStmt>(S);
5230 BlockScopeRAII Scope(Info);
5231
5232 // Step into the init statement in case it brings an (uninitialized)
5233 // variable into scope.
5234 if (const Stmt *Init = FS->getInit()) {
5235 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5236 if (ESR != ESR_CaseNotFound) {
5237 assert(ESR != ESR_Succeeded);
5238 return ESR;
5239 }
5240 }
5241
5242 EvalStmtResult ESR =
5243 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5244 if (ESR != ESR_Continue)
5245 return ESR;
5246 if (const auto *Inc = FS->getInc()) {
5247 if (Inc->isValueDependent()) {
5248 if (!EvaluateDependentExpr(Inc, Info))
5249 return ESR_Failed;
5250 } else {
5251 FullExpressionRAII IncScope(Info);
5252 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5253 return ESR_Failed;
5254 }
5255 }
5256 break;
5257 }
5258
5259 case Stmt::DeclStmtClass: {
5260 // Start the lifetime of any uninitialized variables we encounter. They
5261 // might be used by the selected branch of the switch.
5262 const DeclStmt *DS = cast<DeclStmt>(S);
5263 for (const auto *D : DS->decls()) {
5264 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5265 if (!CheckLocalVariableDeclaration(Info, VD))
5266 return ESR_Failed;
5267 if (VD->hasLocalStorage() && !VD->getInit())
5268 if (!EvaluateVarDecl(Info, VD))
5269 return ESR_Failed;
5270 // FIXME: If the variable has initialization that can't be jumped
5271 // over, bail out of any immediately-surrounding compound-statement
5272 // too. There can't be any case labels here.
5273 }
5274 }
5275 return ESR_CaseNotFound;
5276 }
5277
5278 default:
5279 return ESR_CaseNotFound;
5280 }
5281 }
5282
5283 switch (S->getStmtClass()) {
5284 default:
5285 if (const Expr *E = dyn_cast<Expr>(S)) {
5286 if (E->isValueDependent()) {
5287 if (!EvaluateDependentExpr(E, Info))
5288 return ESR_Failed;
5289 } else {
5290 // Don't bother evaluating beyond an expression-statement which couldn't
5291 // be evaluated.
5292 // FIXME: Do we need the FullExpressionRAII object here?
5293 // VisitExprWithCleanups should create one when necessary.
5294 FullExpressionRAII Scope(Info);
5295 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5296 return ESR_Failed;
5297 }
5298 return ESR_Succeeded;
5299 }
5300
5301 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5302 return ESR_Failed;
5303
5304 case Stmt::NullStmtClass:
5305 return ESR_Succeeded;
5306
5307 case Stmt::DeclStmtClass: {
5308 const DeclStmt *DS = cast<DeclStmt>(S);
5309 for (const auto *D : DS->decls()) {
5310 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5311 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5312 return ESR_Failed;
5313 // Each declaration initialization is its own full-expression.
5314 FullExpressionRAII Scope(Info);
5315 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5316 return ESR_Failed;
5317 if (!Scope.destroy())
5318 return ESR_Failed;
5319 }
5320 return ESR_Succeeded;
5321 }
5322
5323 case Stmt::ReturnStmtClass: {
5324 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5325 FullExpressionRAII Scope(Info);
5326 if (RetExpr && RetExpr->isValueDependent()) {
5327 EvaluateDependentExpr(RetExpr, Info);
5328 // We know we returned, but we don't know what the value is.
5329 return ESR_Failed;
5330 }
5331 if (RetExpr &&
5332 !(Result.Slot
5333 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5334 : Evaluate(Result.Value, Info, RetExpr)))
5335 return ESR_Failed;
5336 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5337 }
5338
5339 case Stmt::CompoundStmtClass: {
5340 BlockScopeRAII Scope(Info);
5341
5342 const CompoundStmt *CS = cast<CompoundStmt>(S);
5343 for (const auto *BI : CS->body()) {
5344 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5345 if (ESR == ESR_Succeeded)
5346 Case = nullptr;
5347 else if (ESR != ESR_CaseNotFound) {
5348 if (ESR != ESR_Failed && !Scope.destroy())
5349 return ESR_Failed;
5350 return ESR;
5351 }
5352 }
5353 if (Case)
5354 return ESR_CaseNotFound;
5355 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5356 }
5357
5358 case Stmt::IfStmtClass: {
5359 const IfStmt *IS = cast<IfStmt>(S);
5360
5361 // Evaluate the condition, as either a var decl or as an expression.
5362 BlockScopeRAII Scope(Info);
5363 if (const Stmt *Init = IS->getInit()) {
5364 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5365 if (ESR != ESR_Succeeded) {
5366 if (ESR != ESR_Failed && !Scope.destroy())
5367 return ESR_Failed;
5368 return ESR;
5369 }
5370 }
5371 bool Cond;
5372 if (IS->isConsteval()) {
5373 Cond = IS->isNonNegatedConsteval();
5374 // If we are not in a constant context, if consteval should not evaluate
5375 // to true.
5376 if (!Info.InConstantContext)
5377 Cond = !Cond;
5378 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5379 Cond))
5380 return ESR_Failed;
5381
5382 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5383 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5384 if (ESR != ESR_Succeeded) {
5385 if (ESR != ESR_Failed && !Scope.destroy())
5386 return ESR_Failed;
5387 return ESR;
5388 }
5389 }
5390 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5391 }
5392
5393 case Stmt::WhileStmtClass: {
5394 const WhileStmt *WS = cast<WhileStmt>(S);
5395 while (true) {
5396 BlockScopeRAII Scope(Info);
5397 bool Continue;
5398 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5399 Continue))
5400 return ESR_Failed;
5401 if (!Continue)
5402 break;
5403
5404 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5405 if (ESR != ESR_Continue) {
5406 if (ESR != ESR_Failed && !Scope.destroy())
5407 return ESR_Failed;
5408 return ESR;
5409 }
5410 if (!Scope.destroy())
5411 return ESR_Failed;
5412 }
5413 return ESR_Succeeded;
5414 }
5415
5416 case Stmt::DoStmtClass: {
5417 const DoStmt *DS = cast<DoStmt>(S);
5418 bool Continue;
5419 do {
5420 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5421 if (ESR != ESR_Continue)
5422 return ESR;
5423 Case = nullptr;
5424
5425 if (DS->getCond()->isValueDependent()) {
5426 EvaluateDependentExpr(DS->getCond(), Info);
5427 // Bailout as we don't know whether to keep going or terminate the loop.
5428 return ESR_Failed;
5429 }
5430 FullExpressionRAII CondScope(Info);
5431 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5432 !CondScope.destroy())
5433 return ESR_Failed;
5434 } while (Continue);
5435 return ESR_Succeeded;
5436 }
5437
5438 case Stmt::ForStmtClass: {
5439 const ForStmt *FS = cast<ForStmt>(S);
5440 BlockScopeRAII ForScope(Info);
5441 if (FS->getInit()) {
5442 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5443 if (ESR != ESR_Succeeded) {
5444 if (ESR != ESR_Failed && !ForScope.destroy())
5445 return ESR_Failed;
5446 return ESR;
5447 }
5448 }
5449 while (true) {
5450 BlockScopeRAII IterScope(Info);
5451 bool Continue = true;
5452 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5453 FS->getCond(), Continue))
5454 return ESR_Failed;
5455 if (!Continue)
5456 break;
5457
5458 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5459 if (ESR != ESR_Continue) {
5460 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5461 return ESR_Failed;
5462 return ESR;
5463 }
5464
5465 if (const auto *Inc = FS->getInc()) {
5466 if (Inc->isValueDependent()) {
5467 if (!EvaluateDependentExpr(Inc, Info))
5468 return ESR_Failed;
5469 } else {
5470 FullExpressionRAII IncScope(Info);
5471 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5472 return ESR_Failed;
5473 }
5474 }
5475
5476 if (!IterScope.destroy())
5477 return ESR_Failed;
5478 }
5479 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5480 }
5481
5482 case Stmt::CXXForRangeStmtClass: {
5483 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5484 BlockScopeRAII Scope(Info);
5485
5486 // Evaluate the init-statement if present.
5487 if (FS->getInit()) {
5488 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5489 if (ESR != ESR_Succeeded) {
5490 if (ESR != ESR_Failed && !Scope.destroy())
5491 return ESR_Failed;
5492 return ESR;
5493 }
5494 }
5495
5496 // Initialize the __range variable.
5497 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5498 if (ESR != ESR_Succeeded) {
5499 if (ESR != ESR_Failed && !Scope.destroy())
5500 return ESR_Failed;
5501 return ESR;
5502 }
5503
5504 // In error-recovery cases it's possible to get here even if we failed to
5505 // synthesize the __begin and __end variables.
5506 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5507 return ESR_Failed;
5508
5509 // Create the __begin and __end iterators.
5510 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5511 if (ESR != ESR_Succeeded) {
5512 if (ESR != ESR_Failed && !Scope.destroy())
5513 return ESR_Failed;
5514 return ESR;
5515 }
5516 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5517 if (ESR != ESR_Succeeded) {
5518 if (ESR != ESR_Failed && !Scope.destroy())
5519 return ESR_Failed;
5520 return ESR;
5521 }
5522
5523 while (true) {
5524 // Condition: __begin != __end.
5525 {
5526 if (FS->getCond()->isValueDependent()) {
5527 EvaluateDependentExpr(FS->getCond(), Info);
5528 // We don't know whether to keep going or terminate the loop.
5529 return ESR_Failed;
5530 }
5531 bool Continue = true;
5532 FullExpressionRAII CondExpr(Info);
5533 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5534 return ESR_Failed;
5535 if (!Continue)
5536 break;
5537 }
5538
5539 // User's variable declaration, initialized by *__begin.
5540 BlockScopeRAII InnerScope(Info);
5541 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5542 if (ESR != ESR_Succeeded) {
5543 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5544 return ESR_Failed;
5545 return ESR;
5546 }
5547
5548 // Loop body.
5549 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5550 if (ESR != ESR_Continue) {
5551 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5552 return ESR_Failed;
5553 return ESR;
5554 }
5555 if (FS->getInc()->isValueDependent()) {
5556 if (!EvaluateDependentExpr(FS->getInc(), Info))
5557 return ESR_Failed;
5558 } else {
5559 // Increment: ++__begin
5560 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5561 return ESR_Failed;
5562 }
5563
5564 if (!InnerScope.destroy())
5565 return ESR_Failed;
5566 }
5567
5568 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5569 }
5570
5571 case Stmt::SwitchStmtClass:
5572 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5573
5574 case Stmt::ContinueStmtClass:
5575 return ESR_Continue;
5576
5577 case Stmt::BreakStmtClass:
5578 return ESR_Break;
5579
5580 case Stmt::LabelStmtClass:
5581 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5582
5583 case Stmt::AttributedStmtClass: {
5584 const auto *AS = cast<AttributedStmt>(S);
5585 const auto *SS = AS->getSubStmt();
5586 MSConstexprContextRAII ConstexprContext(
5587 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5588 isa<ReturnStmt>(SS));
5589
5590 auto LO = Info.getCtx().getLangOpts();
5591 if (LO.CXXAssumptions && !LO.MSVCCompat) {
5592 for (auto *Attr : AS->getAttrs()) {
5593 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
5594 if (!AA)
5595 continue;
5596
5597 auto *Assumption = AA->getAssumption();
5598 if (Assumption->isValueDependent())
5599 return ESR_Failed;
5600
5601 if (Assumption->HasSideEffects(Info.getCtx()))
5602 continue;
5603
5604 bool Value;
5605 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
5606 return ESR_Failed;
5607 if (!Value) {
5608 Info.CCEDiag(Assumption->getExprLoc(),
5609 diag::note_constexpr_assumption_failed);
5610 return ESR_Failed;
5611 }
5612 }
5613 }
5614
5615 return EvaluateStmt(Result, Info, SS, Case);
5616 }
5617
5618 case Stmt::CaseStmtClass:
5619 case Stmt::DefaultStmtClass:
5620 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5621 case Stmt::CXXTryStmtClass:
5622 // Evaluate try blocks by evaluating all sub statements.
5623 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5624 }
5625}
5626
5627/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5628/// default constructor. If so, we'll fold it whether or not it's marked as
5629/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5630/// so we need special handling.
5632 const CXXConstructorDecl *CD,
5633 bool IsValueInitialization) {
5634 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5635 return false;
5636
5637 // Value-initialization does not call a trivial default constructor, so such a
5638 // call is a core constant expression whether or not the constructor is
5639 // constexpr.
5640 if (!CD->isConstexpr() && !IsValueInitialization) {
5641 if (Info.getLangOpts().CPlusPlus11) {
5642 // FIXME: If DiagDecl is an implicitly-declared special member function,
5643 // we should be much more explicit about why it's not constexpr.
5644 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5645 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5646 Info.Note(CD->getLocation(), diag::note_declared_at);
5647 } else {
5648 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5649 }
5650 }
5651 return true;
5652}
5653
5654/// CheckConstexprFunction - Check that a function can be called in a constant
5655/// expression.
5656static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5658 const FunctionDecl *Definition,
5659 const Stmt *Body) {
5660 // Potential constant expressions can contain calls to declared, but not yet
5661 // defined, constexpr functions.
5662 if (Info.checkingPotentialConstantExpression() && !Definition &&
5663 Declaration->isConstexpr())
5664 return false;
5665
5666 // Bail out if the function declaration itself is invalid. We will
5667 // have produced a relevant diagnostic while parsing it, so just
5668 // note the problematic sub-expression.
5669 if (Declaration->isInvalidDecl()) {
5670 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5671 return false;
5672 }
5673
5674 // DR1872: An instantiated virtual constexpr function can't be called in a
5675 // constant expression (prior to C++20). We can still constant-fold such a
5676 // call.
5677 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5678 cast<CXXMethodDecl>(Declaration)->isVirtual())
5679 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5680
5681 if (Definition && Definition->isInvalidDecl()) {
5682 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5683 return false;
5684 }
5685
5686 // Can we evaluate this function call?
5687 if (Definition && Body &&
5688 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
5689 Definition->hasAttr<MSConstexprAttr>())))
5690 return true;
5691
5692 if (Info.getLangOpts().CPlusPlus11) {
5693 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5694
5695 // If this function is not constexpr because it is an inherited
5696 // non-constexpr constructor, diagnose that directly.
5697 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5698 if (CD && CD->isInheritingConstructor()) {
5699 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5700 if (!Inherited->isConstexpr())
5701 DiagDecl = CD = Inherited;
5702 }
5703
5704 // FIXME: If DiagDecl is an implicitly-declared special member function
5705 // or an inheriting constructor, we should be much more explicit about why
5706 // it's not constexpr.
5707 if (CD && CD->isInheritingConstructor())
5708 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5709 << CD->getInheritedConstructor().getConstructor()->getParent();
5710 else
5711 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5712 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5713 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5714 } else {
5715 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5716 }
5717 return false;
5718}
5719
5720namespace {
5721struct CheckDynamicTypeHandler {
5722 AccessKinds AccessKind;
5723 typedef bool result_type;
5724 bool failed() { return false; }
5725 bool found(APValue &Subobj, QualType SubobjType) { return true; }
5726 bool found(APSInt &Value, QualType SubobjType) { return true; }
5727 bool found(APFloat &Value, QualType SubobjType) { return true; }
5728};
5729} // end anonymous namespace
5730
5731/// Check that we can access the notional vptr of an object / determine its
5732/// dynamic type.
5733static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5734 AccessKinds AK, bool Polymorphic) {
5735 if (This.Designator.Invalid)
5736 return false;
5737
5738 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5739
5740 if (!Obj)
5741 return false;
5742
5743 if (!Obj.Value) {
5744 // The object is not usable in constant expressions, so we can't inspect
5745 // its value to see if it's in-lifetime or what the active union members
5746 // are. We can still check for a one-past-the-end lvalue.
5747 if (This.Designator.isOnePastTheEnd() ||
5748 This.Designator.isMostDerivedAnUnsizedArray()) {
5749 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5750 ? diag::note_constexpr_access_past_end
5751 : diag::note_constexpr_access_unsized_array)
5752 << AK;
5753 return false;
5754 } else if (Polymorphic) {
5755 // Conservatively refuse to perform a polymorphic operation if we would
5756 // not be able to read a notional 'vptr' value.
5757 APValue Val;
5758 This.moveInto(Val);
5759 QualType StarThisType =
5760 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5761 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5762 << AK << Val.getAsString(Info.Ctx, StarThisType);
5763 return false;
5764 }
5765 return true;
5766 }
5767
5768 CheckDynamicTypeHandler Handler{AK};
5769 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5770}
5771
5772/// Check that the pointee of the 'this' pointer in a member function call is
5773/// either within its lifetime or in its period of construction or destruction.
5774static bool
5776 const LValue &This,
5777 const CXXMethodDecl *NamedMember) {
5778 return checkDynamicType(
5779 Info, E, This,
5780 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5781}
5782
5784 /// The dynamic class type of the object.
5786 /// The corresponding path length in the lvalue.
5787 unsigned PathLength;
5788};
5789
5790static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5791 unsigned PathLength) {
5792 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5793 Designator.Entries.size() && "invalid path length");
5794 return (PathLength == Designator.MostDerivedPathLength)
5795 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5796 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5797}
5798
5799/// Determine the dynamic type of an object.
5800static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5801 const Expr *E,
5802 LValue &This,
5803 AccessKinds AK) {
5804 // If we don't have an lvalue denoting an object of class type, there is no
5805 // meaningful dynamic type. (We consider objects of non-class type to have no
5806 // dynamic type.)
5807 if (!checkDynamicType(Info, E, This, AK, true))
5808 return std::nullopt;
5809
5810 // Refuse to compute a dynamic type in the presence of virtual bases. This
5811 // shouldn't happen other than in constant-folding situations, since literal
5812 // types can't have virtual bases.
5813 //
5814 // Note that consumers of DynamicType assume that the type has no virtual
5815 // bases, and will need modifications if this restriction is relaxed.
5816 const CXXRecordDecl *Class =
5817 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5818 if (!Class || Class->getNumVBases()) {
5819 Info.FFDiag(E);
5820 return std::nullopt;
5821 }
5822
5823 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5824 // binary search here instead. But the overwhelmingly common case is that
5825 // we're not in the middle of a constructor, so it probably doesn't matter
5826 // in practice.
5827 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5828 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5829 PathLength <= Path.size(); ++PathLength) {
5830 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5831 Path.slice(0, PathLength))) {
5832 case ConstructionPhase::Bases:
5833 case ConstructionPhase::DestroyingBases:
5834 // We're constructing or destroying a base class. This is not the dynamic
5835 // type.
5836 break;
5837
5838 case ConstructionPhase::None:
5839 case ConstructionPhase::AfterBases:
5840 case ConstructionPhase::AfterFields:
5841 case ConstructionPhase::Destroying:
5842 // We've finished constructing the base classes and not yet started
5843 // destroying them again, so this is the dynamic type.
5844 return DynamicType{getBaseClassType(This.Designator, PathLength),
5845 PathLength};
5846 }
5847 }
5848
5849 // CWG issue 1517: we're constructing a base class of the object described by
5850 // 'This', so that object has not yet begun its period of construction and
5851 // any polymorphic operation on it results in undefined behavior.
5852 Info.FFDiag(E);
5853 return std::nullopt;
5854}
5855
5856/// Perform virtual dispatch.
5858 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5859 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5860 std::optional<DynamicType> DynType = ComputeDynamicType(
5861 Info, E, This,
5862 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5863 if (!DynType)
5864 return nullptr;
5865
5866 // Find the final overrider. It must be declared in one of the classes on the
5867 // path from the dynamic type to the static type.
5868 // FIXME: If we ever allow literal types to have virtual base classes, that
5869 // won't be true.
5870 const CXXMethodDecl *Callee = Found;
5871 unsigned PathLength = DynType->PathLength;
5872 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5873 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5874 const CXXMethodDecl *Overrider =
5876 if (Overrider) {
5877 Callee = Overrider;
5878 break;
5879 }
5880 }
5881
5882 // C++2a [class.abstract]p6:
5883 // the effect of making a virtual call to a pure virtual function [...] is
5884 // undefined
5885 if (Callee->isPureVirtual()) {
5886 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5887 Info.Note(Callee->getLocation(), diag::note_declared_at);
5888 return nullptr;
5889 }
5890
5891 // If necessary, walk the rest of the path to determine the sequence of
5892 // covariant adjustment steps to apply.
5893 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5894 Found->getReturnType())) {
5895 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5896 for (unsigned CovariantPathLength = PathLength + 1;
5897 CovariantPathLength != This.Designator.Entries.size();
5898 ++CovariantPathLength) {
5899 const CXXRecordDecl *NextClass =
5900 getBaseClassType(This.Designator, CovariantPathLength);
5901 const CXXMethodDecl *Next =
5902 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5903 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5904 Next->getReturnType(), CovariantAdjustmentPath.back()))
5905 CovariantAdjustmentPath.push_back(Next->getReturnType());
5906 }
5907 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5908 CovariantAdjustmentPath.back()))
5909 CovariantAdjustmentPath.push_back(Found->getReturnType());
5910 }
5911
5912 // Perform 'this' adjustment.
5913 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5914 return nullptr;
5915
5916 return Callee;
5917}
5918
5919/// Perform the adjustment from a value returned by a virtual function to
5920/// a value of the statically expected type, which may be a pointer or
5921/// reference to a base class of the returned type.
5922static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5923 APValue &Result,
5924 ArrayRef<QualType> Path) {
5925 assert(Result.isLValue() &&
5926 "unexpected kind of APValue for covariant return");
5927 if (Result.isNullPointer())
5928 return true;
5929
5930 LValue LVal;
5931 LVal.setFrom(Info.Ctx, Result);
5932
5933 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5934 for (unsigned I = 1; I != Path.size(); ++I) {
5935 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5936 assert(OldClass && NewClass && "unexpected kind of covariant return");
5937 if (OldClass != NewClass &&
5938 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5939 return false;
5940 OldClass = NewClass;
5941 }
5942
5943 LVal.moveInto(Result);
5944 return true;
5945}
5946
5947/// Determine whether \p Base, which is known to be a direct base class of
5948/// \p Derived, is a public base class.
5949static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5950 const CXXRecordDecl *Base) {
5951 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5952 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5953 if (BaseClass && declaresSameEntity(BaseClass, Base))
5954 return BaseSpec.getAccessSpecifier() == AS_public;
5955 }
5956 llvm_unreachable("Base is not a direct base of Derived");
5957}
5958
5959/// Apply the given dynamic cast operation on the provided lvalue.
5960///
5961/// This implements the hard case of dynamic_cast, requiring a "runtime check"
5962/// to find a suitable target subobject.
5963static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5964 LValue &Ptr) {
5965 // We can't do anything with a non-symbolic pointer value.
5966 SubobjectDesignator &D = Ptr.Designator;
5967 if (D.Invalid)
5968 return false;
5969
5970 // C++ [expr.dynamic.cast]p6:
5971 // If v is a null pointer value, the result is a null pointer value.
5972 if (Ptr.isNullPointer() && !E->isGLValue())
5973 return true;
5974
5975 // For all the other cases, we need the pointer to point to an object within
5976 // its lifetime / period of construction / destruction, and we need to know
5977 // its dynamic type.
5978 std::optional<DynamicType> DynType =
5979 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5980 if (!DynType)
5981 return false;
5982
5983 // C++ [expr.dynamic.cast]p7:
5984 // If T is "pointer to cv void", then the result is a pointer to the most
5985 // derived object
5986 if (E->getType()->isVoidPointerType())
5987 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5988
5990 assert(C && "dynamic_cast target is not void pointer nor class");
5991 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5992
5993 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5994 // C++ [expr.dynamic.cast]p9:
5995 if (!E->isGLValue()) {
5996 // The value of a failed cast to pointer type is the null pointer value
5997 // of the required result type.
5998 Ptr.setNull(Info.Ctx, E->getType());
5999 return true;
6000 }
6001
6002 // A failed cast to reference type throws [...] std::bad_cast.
6003 unsigned DiagKind;
6004 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6005 DynType->Type->isDerivedFrom(C)))
6006 DiagKind = 0;
6007 else if (!Paths || Paths->begin() == Paths->end())
6008 DiagKind = 1;
6009 else if (Paths->isAmbiguous(CQT))
6010 DiagKind = 2;
6011 else {
6012 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6013 DiagKind = 3;
6014 }
6015 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6016 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6017 << Info.Ctx.getRecordType(DynType->Type)
6018 << E->getType().getUnqualifiedType();
6019 return false;
6020 };
6021
6022 // Runtime check, phase 1:
6023 // Walk from the base subobject towards the derived object looking for the
6024 // target type.
6025 for (int PathLength = Ptr.Designator.Entries.size();
6026 PathLength >= (int)DynType->PathLength; --PathLength) {
6027 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6029 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6030 // We can only walk across public inheritance edges.
6031 if (PathLength > (int)DynType->PathLength &&
6032 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6033 Class))
6034 return RuntimeCheckFailed(nullptr);
6035 }
6036
6037 // Runtime check, phase 2:
6038 // Search the dynamic type for an unambiguous public base of type C.
6039 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6040 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6041 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6042 Paths.front().Access == AS_public) {
6043 // Downcast to the dynamic type...
6044 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6045 return false;
6046 // ... then upcast to the chosen base class subobject.
6047 for (CXXBasePathElement &Elem : Paths.front())
6048 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6049 return false;
6050 return true;
6051 }
6052
6053 // Otherwise, the runtime check fails.
6054 return RuntimeCheckFailed(&Paths);
6055}
6056
6057namespace {
6058struct StartLifetimeOfUnionMemberHandler {
6059 EvalInfo &Info;
6060 const Expr *LHSExpr;
6061 const FieldDecl *Field;
6062 bool DuringInit;
6063 bool Failed = false;
6064 static const AccessKinds AccessKind = AK_Assign;
6065
6066 typedef bool result_type;
6067 bool failed() { return Failed; }
6068 bool found(APValue &Subobj, QualType SubobjType) {
6069 // We are supposed to perform no initialization but begin the lifetime of
6070 // the object. We interpret that as meaning to do what default
6071 // initialization of the object would do if all constructors involved were
6072 // trivial:
6073 // * All base, non-variant member, and array element subobjects' lifetimes
6074 // begin
6075 // * No variant members' lifetimes begin
6076 // * All scalar subobjects whose lifetimes begin have indeterminate values
6077 assert(SubobjType->isUnionType());
6078 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6079 // This union member is already active. If it's also in-lifetime, there's
6080 // nothing to do.
6081 if (Subobj.getUnionValue().hasValue())
6082 return true;
6083 } else if (DuringInit) {
6084 // We're currently in the process of initializing a different union
6085 // member. If we carried on, that initialization would attempt to
6086 // store to an inactive union member, resulting in undefined behavior.
6087 Info.FFDiag(LHSExpr,
6088 diag::note_constexpr_union_member_change_during_init);
6089 return false;
6090 }
6091 APValue Result;
6092 Failed = !handleDefaultInitValue(Field->getType(), Result);
6093 Subobj.setUnion(Field, Result);
6094 return true;
6095 }
6096 bool found(APSInt &Value, QualType SubobjType) {
6097 llvm_unreachable("wrong value kind for union object");
6098 }
6099 bool found(APFloat &Value, QualType SubobjType) {
6100 llvm_unreachable("wrong value kind for union object");
6101 }
6102};
6103} // end anonymous namespace
6104
6105const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6106
6107/// Handle a builtin simple-assignment or a call to a trivial assignment
6108/// operator whose left-hand side might involve a union member access. If it
6109/// does, implicitly start the lifetime of any accessed union elements per
6110/// C++20 [class.union]5.
6111static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6112 const Expr *LHSExpr,
6113 const LValue &LHS) {
6114 if (LHS.InvalidBase || LHS.Designator.Invalid)
6115 return false;
6116
6118 // C++ [class.union]p5:
6119 // define the set S(E) of subexpressions of E as follows:
6120 unsigned PathLength = LHS.Designator.Entries.size();
6121 for (const Expr *E = LHSExpr; E != nullptr;) {
6122 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6123 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6124 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6125 // Note that we can't implicitly start the lifetime of a reference,
6126 // so we don't need to proceed any further if we reach one.
6127 if (!FD || FD->getType()->isReferenceType())
6128 break;
6129
6130 // ... and also contains A.B if B names a union member ...
6131 if (FD->getParent()->isUnion()) {
6132 // ... of a non-class, non-array type, or of a class type with a
6133 // trivial default constructor that is not deleted, or an array of
6134 // such types.
6135 auto *RD =
6136 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6137 if (!RD || RD->hasTrivialDefaultConstructor())
6138 UnionPathLengths.push_back({PathLength - 1, FD});
6139 }
6140
6141 E = ME->getBase();
6142 --PathLength;
6143 assert(declaresSameEntity(FD,
6144 LHS.Designator.Entries[PathLength]
6145 .getAsBaseOrMember().getPointer()));
6146
6147 // -- If E is of the form A[B] and is interpreted as a built-in array
6148 // subscripting operator, S(E) is [S(the array operand, if any)].
6149 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6150 // Step over an ArrayToPointerDecay implicit cast.
6151 auto *Base = ASE->getBase()->IgnoreImplicit();
6152 if (!Base->getType()->isArrayType())
6153 break;
6154
6155 E = Base;
6156 --PathLength;
6157
6158 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6159 // Step over a derived-to-base conversion.
6160 E = ICE->getSubExpr();
6161 if (ICE->getCastKind() == CK_NoOp)
6162 continue;
6163 if (ICE->getCastKind() != CK_DerivedToBase &&
6164 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6165 break;
6166 // Walk path backwards as we walk up from the base to the derived class.
6167 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6168 if (Elt->isVirtual()) {
6169 // A class with virtual base classes never has a trivial default
6170 // constructor, so S(E) is empty in this case.
6171 E = nullptr;
6172 break;
6173 }
6174
6175 --PathLength;
6176 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6177 LHS.Designator.Entries[PathLength]
6178 .getAsBaseOrMember().getPointer()));
6179 }
6180
6181 // -- Otherwise, S(E) is empty.
6182 } else {
6183 break;
6184 }
6185 }
6186
6187 // Common case: no unions' lifetimes are started.
6188 if (UnionPathLengths.empty())
6189 return true;
6190
6191 // if modification of X [would access an inactive union member], an object
6192 // of the type of X is implicitly created
6193 CompleteObject Obj =
6194 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6195 if (!Obj)
6196 return false;
6197 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6198 llvm::reverse(UnionPathLengths)) {
6199 // Form a designator for the union object.
6200 SubobjectDesignator D = LHS.Designator;
6201 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6202
6203 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6204 ConstructionPhase::AfterBases;
6205 StartLifetimeOfUnionMemberHandler StartLifetime{
6206 Info, LHSExpr, LengthAndField.second, DuringInit};
6207 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6208 return false;
6209 }
6210
6211 return true;
6212}
6213
6214static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6215 CallRef Call, EvalInfo &Info,
6216 bool NonNull = false) {
6217 LValue LV;
6218 // Create the parameter slot and register its destruction. For a vararg
6219 // argument, create a temporary.
6220 // FIXME: For calling conventions that destroy parameters in the callee,
6221 // should we consider performing destruction when the function returns
6222 // instead?
6223 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6224 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6225 ScopeKind::Call, LV);
6226 if (!EvaluateInPlace(V, Info, LV, Arg))
6227 return false;
6228
6229 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6230 // undefined behavior, so is non-constant.
6231 if (NonNull && V.isLValue() && V.isNullPointer()) {
6232 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6233 return false;
6234 }
6235
6236 return true;
6237}
6238
6239/// Evaluate the arguments to a function call.
6240static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6241 EvalInfo &Info, const FunctionDecl *Callee,
6242 bool RightToLeft = false) {
6243 bool Success = true;
6244 llvm::SmallBitVector ForbiddenNullArgs;
6245 if (Callee->hasAttr<NonNullAttr>()) {
6246 ForbiddenNullArgs.resize(Args.size());
6247 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6248 if (!Attr->args_size()) {
6249 ForbiddenNullArgs.set();
6250 break;
6251 } else
6252 for (auto Idx : Attr->args()) {
6253 unsigned ASTIdx = Idx.getASTIndex();
6254 if (ASTIdx >= Args.size())
6255 continue;
6256 ForbiddenNullArgs[ASTIdx] = true;
6257 }
6258 }
6259 }
6260 for (unsigned I = 0; I < Args.size(); I++) {
6261 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6262 const ParmVarDecl *PVD =
6263 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6264 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6265 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6266 // If we're checking for a potential constant expression, evaluate all
6267 // initializers even if some of them fail.
6268 if (!Info.noteFailure())
6269 return false;
6270 Success = false;
6271 }
6272 }
6273 return Success;
6274}
6275
6276/// Perform a trivial copy from Param, which is the parameter of a copy or move
6277/// constructor or assignment operator.
6278static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6279 const Expr *E, APValue &Result,
6280 bool CopyObjectRepresentation) {
6281 // Find the reference argument.
6282 CallStackFrame *Frame = Info.CurrentCall;
6283 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6284 if (!RefValue) {
6285 Info.FFDiag(E);
6286 return false;
6287 }
6288
6289 // Copy out the contents of the RHS object.
6290 LValue RefLValue;
6291 RefLValue.setFrom(Info.Ctx, *RefValue);
6293 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6294 CopyObjectRepresentation);
6295}
6296
6297/// Evaluate a function call.
6299 const FunctionDecl *Callee, const LValue *This,
6300 const Expr *E, ArrayRef<const Expr *> Args,
6301 CallRef Call, const Stmt *Body, EvalInfo &Info,
6302 APValue &Result, const LValue *ResultSlot) {
6303 if (!Info.CheckCallLimit(CallLoc))
6304 return false;
6305
6306 CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);
6307
6308 // For a trivial copy or move assignment, perform an APValue copy. This is
6309 // essential for unions, where the operations performed by the assignment
6310 // operator cannot be represented as statements.
6311 //
6312 // Skip this for non-union classes with no fields; in that case, the defaulted
6313 // copy/move does not actually read the object.
6314 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6315 if (MD && MD->isDefaulted() &&
6316 (MD->getParent()->isUnion() ||
6317 (MD->isTrivial() &&
6319 assert(This &&
6321 APValue RHSValue;
6322 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6323 MD->getParent()->isUnion()))
6324 return false;
6325 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6326 RHSValue))
6327 return false;
6328 This->moveInto(Result);
6329 return true;
6330 } else if (MD && isLambdaCallOperator(MD)) {
6331 // We're in a lambda; determine the lambda capture field maps unless we're
6332 // just constexpr checking a lambda's call operator. constexpr checking is
6333 // done before the captures have been added to the closure object (unless
6334 // we're inferring constexpr-ness), so we don't have access to them in this
6335 // case. But since we don't need the captures to constexpr check, we can
6336 // just ignore them.
6337 if (!Info.checkingPotentialConstantExpression())
6338 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6339 Frame.LambdaThisCaptureField);
6340 }
6341
6342 StmtResult Ret = {Result, ResultSlot};
6343 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6344 if (ESR == ESR_Succeeded) {
6345 if (Callee->getReturnType()->isVoidType())
6346 return true;
6347 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6348 }
6349 return ESR == ESR_Returned;
6350}
6351
6352/// Evaluate a constructor call.
6353static bool HandleConstructorCall(const Expr *E, const LValue &This,
6354 CallRef Call,
6356 EvalInfo &Info, APValue &Result) {
6357 SourceLocation CallLoc = E->getExprLoc();
6358 if (!Info.CheckCallLimit(CallLoc))
6359 return false;
6360
6361 const CXXRecordDecl *RD = Definition->getParent();
6362 if (RD->getNumVBases()) {
6363 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6364 return false;
6365 }
6366
6367 EvalInfo::EvaluatingConstructorRAII EvalObj(
6368 Info,
6369 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6370 RD->getNumBases());
6371 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6372
6373 // FIXME: Creating an APValue just to hold a nonexistent return value is
6374 // wasteful.
6375 APValue RetVal;
6376 StmtResult Ret = {RetVal, nullptr};
6377
6378 // If it's a delegating constructor, delegate.
6379 if (Definition->isDelegatingConstructor()) {
6381 if ((*I)->getInit()->isValueDependent()) {
6382 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6383 return false;
6384 } else {
6385 FullExpressionRAII InitScope(Info);
6386 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6387 !InitScope.destroy())
6388 return false;
6389 }
6390 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6391 }
6392
6393 // For a trivial copy or move constructor, perform an APValue copy. This is
6394 // essential for unions (or classes with anonymous union members), where the
6395 // operations performed by the constructor cannot be represented by
6396 // ctor-initializers.
6397 //
6398 // Skip this for empty non-union classes; we should not perform an
6399 // lvalue-to-rvalue conversion on them because their copy constructor does not
6400 // actually read them.
6401 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6402 (Definition->getParent()->isUnion() ||
6403 (Definition->isTrivial() &&
6405 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6406 Definition->getParent()->isUnion());
6407 }
6408
6409 // Reserve space for the struct members.
6410 if (!Result.hasValue()) {
6411 if (!RD->isUnion())
6412 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6413 std::distance(RD->field_begin(), RD->field_end()));
6414 else
6415 // A union starts with no active member.
6416 Result = APValue((const FieldDecl*)nullptr);
6417 }
6418
6419 if (RD->isInvalidDecl()) return false;
6420 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6421
6422 // A scope for temporaries lifetime-extended by reference members.
6423 BlockScopeRAII LifetimeExtendedScope(Info);
6424
6425 bool Success = true;
6426 unsigned BasesSeen = 0;
6427#ifndef NDEBUG
6429#endif
6431 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6432 // We might be initializing the same field again if this is an indirect
6433 // field initialization.
6434 if (FieldIt == RD->field_end() ||
6435 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6436 assert(Indirect && "fields out of order?");
6437 return;
6438 }
6439
6440 // Default-initialize any fields with no explicit initializer.
6441 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6442 assert(FieldIt != RD->field_end() && "missing field?");
6443 if (!FieldIt->isUnnamedBitField())
6445 FieldIt->getType(),
6446 Result.getStructField(FieldIt->getFieldIndex()));
6447 }
6448 ++FieldIt;
6449 };
6450 for (const auto *I : Definition->inits()) {
6451 LValue Subobject = This;
6452 LValue SubobjectParent = This;
6453 APValue *Value = &Result;
6454
6455 // Determine the subobject to initialize.
6456 FieldDecl *FD = nullptr;
6457 if (I->isBaseInitializer()) {
6458 QualType BaseType(I->getBaseClass(), 0);
6459#ifndef NDEBUG
6460 // Non-virtual base classes are initialized in the order in the class
6461 // definition. We have already checked for virtual base classes.
6462 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6463 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6464 "base class initializers not in expected order");
6465 ++BaseIt;
6466#endif
6467 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6468 BaseType->getAsCXXRecordDecl(), &Layout))
6469 return false;
6470 Value = &Result.getStructBase(BasesSeen++);
6471 } else if ((FD = I->getMember())) {
6472 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6473 return false;
6474 if (RD->isUnion()) {
6475 Result = APValue(FD);
6476 Value = &Result.getUnionValue();
6477 } else {
6478 SkipToField(FD, false);
6479 Value = &Result.getStructField(FD->getFieldIndex());
6480 }
6481 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6482 // Walk the indirect field decl's chain to find the object to initialize,
6483 // and make sure we've initialized every step along it.
6484 auto IndirectFieldChain = IFD->chain();
6485 for (auto *C : IndirectFieldChain) {
6486 FD = cast<FieldDecl>(C);
6487 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6488 // Switch the union field if it differs. This happens if we had
6489 // preceding zero-initialization, and we're now initializing a union
6490 // subobject other than the first.
6491 // FIXME: In this case, the values of the other subobjects are
6492 // specified, since zero-initialization sets all padding bits to zero.
6493 if (!Value->hasValue() ||
6494 (Value->isUnion() && Value->getUnionField() != FD)) {
6495 if (CD->isUnion())
6496 *Value = APValue(FD);
6497 else
6498 // FIXME: This immediately starts the lifetime of all members of
6499 // an anonymous struct. It would be preferable to strictly start
6500 // member lifetime in initialization order.
6501 Success &=
6502 handleDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6503 }
6504 // Store Subobject as its parent before updating it for the last element
6505 // in the chain.
6506 if (C == IndirectFieldChain.back())
6507 SubobjectParent = Subobject;
6508 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6509 return false;
6510 if (CD->isUnion())
6511 Value = &Value->getUnionValue();
6512 else {
6513 if (C == IndirectFieldChain.front() && !RD->isUnion())
6514 SkipToField(FD, true);
6515 Value = &Value->getStructField(FD->getFieldIndex());
6516 }
6517 }
6518 } else {
6519 llvm_unreachable("unknown base initializer kind");
6520 }
6521
6522 // Need to override This for implicit field initializers as in this case
6523 // This refers to innermost anonymous struct/union containing initializer,
6524 // not to currently constructed class.
6525 const Expr *Init = I->getInit();
6526 if (Init->isValueDependent()) {
6527 if (!EvaluateDependentExpr(Init, Info))
6528 return false;
6529 } else {
6530 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6531 isa<CXXDefaultInitExpr>(Init));
6532 FullExpressionRAII InitScope(Info);
6533 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6534 (FD && FD->isBitField() &&
6535 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6536 // If we're checking for a potential constant expression, evaluate all
6537 // initializers even if some of them fail.
6538 if (!Info.noteFailure())
6539 return false;
6540 Success = false;
6541 }
6542 }
6543
6544 // This is the point at which the dynamic type of the object becomes this
6545 // class type.
6546 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6547 EvalObj.finishedConstructingBases();
6548 }
6549
6550 // Default-initialize any remaining fields.
6551 if (!RD->isUnion()) {
6552 for (; FieldIt != RD->field_end(); ++FieldIt) {
6553 if (!FieldIt->isUnnamedBitField())
6555 FieldIt->getType(),
6556 Result.getStructField(FieldIt->getFieldIndex()));
6557 }
6558 }
6559
6560 EvalObj.finishedConstructingFields();
6561
6562 return Success &&
6563 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6564 LifetimeExtendedScope.destroy();
6565}
6566
6567static bool HandleConstructorCall(const Expr *E, const LValue &This,
6570 EvalInfo &Info, APValue &Result) {
6571 CallScopeRAII CallScope(Info);
6572 CallRef Call = Info.CurrentCall->createCall(Definition);
6573 if (!EvaluateArgs(Args, Call, Info, Definition))
6574 return false;
6575
6576 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6577 CallScope.destroy();
6578}
6579
6580static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6581 const LValue &This, APValue &Value,
6582 QualType T) {
6583 // Objects can only be destroyed while they're within their lifetimes.
6584 // FIXME: We have no representation for whether an object of type nullptr_t
6585 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6586 // as indeterminate instead?
6587 if (Value.isAbsent() && !T->isNullPtrType()) {
6588 APValue Printable;
6589 This.moveInto(Printable);
6590 Info.FFDiag(CallRange.getBegin(),
6591 diag::note_constexpr_destroy_out_of_lifetime)
6592 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6593 return false;
6594 }
6595
6596 // Invent an expression for location purposes.
6597 // FIXME: We shouldn't need to do this.
6598 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
6599
6600 // For arrays, destroy elements right-to-left.
6601 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6602 uint64_t Size = CAT->getZExtSize();
6603 QualType ElemT = CAT->getElementType();
6604
6605 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
6606 return false;
6607
6608 LValue ElemLV = This;
6609 ElemLV.addArray(Info, &LocE, CAT);
6610 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6611 return false;
6612
6613 // Ensure that we have actual array elements available to destroy; the
6614 // destructors might mutate the value, so we can't run them on the array
6615 // filler.
6616 if (Size && Size > Value.getArrayInitializedElts())
6617 expandArray(Value, Value.getArraySize() - 1);
6618
6619 for (; Size != 0; --Size) {
6620 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6621 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6622 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
6623 return false;
6624 }
6625
6626 // End the lifetime of this array now.
6627 Value = APValue();
6628 return true;
6629 }
6630
6631 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6632 if (!RD) {
6633 if (T.isDestructedType()) {
6634 Info.FFDiag(CallRange.getBegin(),
6635 diag::note_constexpr_unsupported_destruction)
6636 << T;
6637 return false;
6638 }
6639
6640 Value = APValue();
6641 return true;
6642 }
6643
6644 if (RD->getNumVBases()) {
6645 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
6646 return false;
6647 }
6648
6649 const CXXDestructorDecl *DD = RD->getDestructor();
6650 if (!DD && !RD->hasTrivialDestructor()) {
6651 Info.FFDiag(CallRange.getBegin());
6652 return false;
6653 }
6654
6655 if (!DD || DD->isTrivial() ||
6656 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6657 // A trivial destructor just ends the lifetime of the object. Check for
6658 // this case before checking for a body, because we might not bother
6659 // building a body for a trivial destructor. Note that it doesn't matter
6660 // whether the destructor is constexpr in this case; all trivial
6661 // destructors are constexpr.
6662 //
6663 // If an anonymous union would be destroyed, some enclosing destructor must
6664 // have been explicitly defined, and the anonymous union destruction should
6665 // have no effect.
6666 Value = APValue();
6667 return true;
6668 }
6669
6670 if (!Info.CheckCallLimit(CallRange.getBegin()))
6671 return false;
6672
6673 const FunctionDecl *Definition = nullptr;
6674 const Stmt *Body = DD->getBody(Definition);
6675
6676 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
6677 return false;
6678
6679 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
6680 CallRef());
6681
6682 // We're now in the period of destruction of this object.
6683 unsigned BasesLeft = RD->getNumBases();
6684 EvalInfo::EvaluatingDestructorRAII EvalObj(
6685 Info,
6686 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6687 if (!EvalObj.DidInsert) {
6688 // C++2a [class.dtor]p19:
6689 // the behavior is undefined if the destructor is invoked for an object
6690 // whose lifetime has ended
6691 // (Note that formally the lifetime ends when the period of destruction
6692 // begins, even though certain uses of the object remain valid until the
6693 // period of destruction ends.)
6694 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
6695 return false;
6696 }
6697
6698 // FIXME: Creating an APValue just to hold a nonexistent return value is
6699 // wasteful.
6700 APValue RetVal;
6701 StmtResult Ret = {RetVal, nullptr};
6702 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6703 return false;
6704
6705 // A union destructor does not implicitly destroy its members.
6706 if (RD->isUnion())
6707 return true;
6708
6709 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6710
6711 // We don't have a good way to iterate fields in reverse, so collect all the
6712 // fields first and then walk them backwards.
6713 SmallVector<FieldDecl*, 16> Fields(RD->fields());
6714 for (const FieldDecl *FD : llvm::reverse(Fields)) {
6715 if (FD->isUnnamedBitField())
6716 continue;
6717
6718 LValue Subobject = This;
6719 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6720 return false;
6721
6722 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6723 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6724 FD->getType()))
6725 return false;
6726 }
6727
6728 if (BasesLeft != 0)
6729 EvalObj.startedDestroyingBases();
6730
6731 // Destroy base classes in reverse order.
6732 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6733 --BasesLeft;
6734
6735 QualType BaseType = Base.getType();
6736 LValue Subobject = This;
6737 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6738 BaseType->getAsCXXRecordDecl(), &Layout))
6739 return false;
6740
6741 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6742 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6743 BaseType))
6744 return false;
6745 }
6746 assert(BasesLeft == 0 && "NumBases was wrong?");
6747
6748 // The period of destruction ends now. The object is gone.
6749 Value = APValue();
6750 return true;
6751}
6752
6753namespace {
6754struct DestroyObjectHandler {
6755 EvalInfo &Info;
6756 const Expr *E;
6757 const LValue &This;
6758 const AccessKinds AccessKind;
6759
6760 typedef bool result_type;
6761 bool failed() { return false; }
6762 bool found(APValue &Subobj, QualType SubobjType) {
6763 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
6764 SubobjType);
6765 }
6766 bool found(APSInt &Value, QualType SubobjType) {
6767 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6768 return false;
6769 }
6770 bool found(APFloat &Value, QualType SubobjType) {
6771 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6772 return false;
6773 }
6774};
6775}
6776
6777/// Perform a destructor or pseudo-destructor call on the given object, which
6778/// might in general not be a complete object.
6779static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6780 const LValue &This, QualType ThisType) {
6781 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6782 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6783 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6784}
6785
6786/// Destroy and end the lifetime of the given complete object.
6787static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6789 QualType T) {
6790 // If we've had an unmodeled side-effect, we can't rely on mutable state
6791 // (such as the object we're about to destroy) being correct.
6792 if (Info.EvalStatus.HasSideEffects)
6793 return false;
6794
6795 LValue LV;
6796 LV.set({LVBase});
6797 return HandleDestructionImpl(Info, Loc, LV, Value, T);
6798}
6799
6800/// Perform a call to 'operator new' or to `__builtin_operator_new'.
6801static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6802 LValue &Result) {
6803 if (Info.checkingPotentialConstantExpression() ||
6804 Info.SpeculativeEvaluationDepth)
6805 return false;
6806
6807 // This is permitted only within a call to std::allocator<T>::allocate.
6808 auto Caller = Info.getStdAllocatorCaller("allocate");
6809 if (!Caller) {
6810 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6811 ? diag::note_constexpr_new_untyped
6812 : diag::note_constexpr_new);
6813 return false;
6814 }
6815
6816 QualType ElemType = Caller.ElemType;
6817 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6818 Info.FFDiag(E->getExprLoc(),
6819 diag::note_constexpr_new_not_complete_object_type)
6820 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6821 return false;
6822 }
6823
6824 APSInt ByteSize;
6825 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6826 return false;
6827 bool IsNothrow = false;
6828 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6829 EvaluateIgnoredValue(Info, E->getArg(I));
6830 IsNothrow |= E->getType()->isNothrowT();
6831 }
6832
6833 CharUnits ElemSize;
6834 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6835 return false;
6836 APInt Size, Remainder;
6837 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6838 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6839 if (Remainder != 0) {
6840 // This likely indicates a bug in the implementation of 'std::allocator'.
6841 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6842 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6843 return false;
6844 }
6845
6846 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
6847 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
6848 if (IsNothrow) {
6849 Result.setNull(Info.Ctx, E->getType());
6850 return true;
6851 }
6852 return false;
6853 }
6854
6855 QualType AllocType = Info.Ctx.getConstantArrayType(
6856 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
6857 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6858 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6859 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6860 return true;
6861}
6862
6864 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6865 if (CXXDestructorDecl *DD = RD->getDestructor())
6866 return DD->isVirtual();
6867 return false;
6868}
6869
6871 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6872 if (CXXDestructorDecl *DD = RD->getDestructor())
6873 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6874 return nullptr;
6875}
6876
6877/// Check that the given object is a suitable pointer to a heap allocation that
6878/// still exists and is of the right kind for the purpose of a deletion.
6879///
6880/// On success, returns the heap allocation to deallocate. On failure, produces
6881/// a diagnostic and returns std::nullopt.
6882static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6883 const LValue &Pointer,
6884 DynAlloc::Kind DeallocKind) {
6885 auto PointerAsString = [&] {
6886 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6887 };
6888
6889 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6890 if (!DA) {
6891 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6892 << PointerAsString();
6893 if (Pointer.Base)
6894 NoteLValueLocation(Info, Pointer.Base);
6895 return std::nullopt;
6896 }
6897
6898 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6899 if (!Alloc) {
6900 Info.FFDiag(E, diag::note_constexpr_double_delete);
6901 return std::nullopt;
6902 }
6903
6904 if (DeallocKind != (*Alloc)->getKind()) {
6905 QualType AllocType = Pointer.Base.getDynamicAllocType();
6906 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6907 << DeallocKind << (*Alloc)->getKind() << AllocType;
6908 NoteLValueLocation(Info, Pointer.Base);
6909 return std::nullopt;
6910 }
6911
6912 bool Subobject = false;
6913 if (DeallocKind == DynAlloc::New) {
6914 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6915 Pointer.Designator.isOnePastTheEnd();
6916 } else {
6917 Subobject = Pointer.Designator.Entries.size() != 1 ||
6918 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6919 }
6920 if (Subobject) {
6921 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6922 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6923 return std::nullopt;
6924 }
6925
6926 return Alloc;
6927}
6928
6929// Perform a call to 'operator delete' or '__builtin_operator_delete'.
6930bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6931 if (Info.checkingPotentialConstantExpression() ||
6932 Info.SpeculativeEvaluationDepth)
6933 return false;
6934
6935 // This is permitted only within a call to std::allocator<T>::deallocate.
6936 if (!Info.getStdAllocatorCaller("deallocate")) {
6937 Info.FFDiag(E->getExprLoc());
6938 return true;
6939 }
6940
6941 LValue Pointer;
6942 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6943 return false;
6944 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6945 EvaluateIgnoredValue(Info, E->getArg(I));
6946
6947 if (Pointer.Designator.Invalid)
6948 return false;
6949
6950 // Deleting a null pointer would have no effect, but it's not permitted by
6951 // std::allocator<T>::deallocate's contract.
6952 if (Pointer.isNullPointer()) {
6953 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6954 return true;
6955 }
6956
6957 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6958 return false;
6959
6960 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6961 return true;
6962}
6963
6964//===----------------------------------------------------------------------===//
6965// Generic Evaluation
6966//===----------------------------------------------------------------------===//
6967namespace {
6968
6969class BitCastBuffer {
6970 // FIXME: We're going to need bit-level granularity when we support
6971 // bit-fields.
6972 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6973 // we don't support a host or target where that is the case. Still, we should
6974 // use a more generic type in case we ever do.
6976
6977 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6978 "Need at least 8 bit unsigned char");
6979
6980 bool TargetIsLittleEndian;
6981
6982public:
6983 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6984 : Bytes(Width.getQuantity()),
6985 TargetIsLittleEndian(TargetIsLittleEndian) {}
6986
6987 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
6988 SmallVectorImpl<unsigned char> &Output) const {
6989 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6990 // If a byte of an integer is uninitialized, then the whole integer is
6991 // uninitialized.
6992 if (!Bytes[I.getQuantity()])
6993 return false;
6994 Output.push_back(*Bytes[I.getQuantity()]);
6995 }
6996 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6997 std::reverse(Output.begin(), Output.end());
6998 return true;
6999 }
7000
7001 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7002 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7003 std::reverse(Input.begin(), Input.end());
7004
7005 size_t Index = 0;
7006 for (unsigned char Byte : Input) {
7007 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7008 Bytes[Offset.getQuantity() + Index] = Byte;
7009 ++Index;
7010 }
7011 }
7012
7013 size_t size() { return Bytes.size(); }
7014};
7015
7016/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7017/// target would represent the value at runtime.
7018class APValueToBufferConverter {
7019 EvalInfo &Info;
7020 BitCastBuffer Buffer;
7021 const CastExpr *BCE;
7022
7023 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7024 const CastExpr *BCE)
7025 : Info(Info),
7026 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7027 BCE(BCE) {}
7028
7029 bool visit(const APValue &Val, QualType Ty) {
7030 return visit(Val, Ty, CharUnits::fromQuantity(0));
7031 }
7032
7033 // Write out Val with type Ty into Buffer starting at Offset.
7034 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7035 assert((size_t)Offset.getQuantity() <= Buffer.size());
7036
7037 // As a special case, nullptr_t has an indeterminate value.
7038 if (Ty->isNullPtrType())
7039 return true;
7040
7041 // Dig through Src to find the byte at SrcOffset.
7042 switch (Val.getKind()) {
7044 case APValue::None:
7045 return true;
7046
7047 case APValue::Int:
7048 return visitInt(Val.getInt(), Ty, Offset);
7049 case APValue::Float:
7050 return visitFloat(Val.getFloat(), Ty, Offset);
7051 case APValue::Array:
7052 return visitArray(Val, Ty, Offset);
7053 case APValue::Struct:
7054 return visitRecord(Val, Ty, Offset);
7055 case APValue::Vector:
7056 return visitVector(Val, Ty, Offset);
7057
7061 // FIXME: We should support these.
7062
7063 case APValue::Union:
7066 Info.FFDiag(BCE->getBeginLoc(),
7067 diag::note_constexpr_bit_cast_unsupported_type)
7068 << Ty;
7069 return false;
7070 }
7071
7072 case APValue::LValue:
7073 llvm_unreachable("LValue subobject in bit_cast?");
7074 }
7075 llvm_unreachable("Unhandled APValue::ValueKind");
7076 }
7077
7078 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7079 const RecordDecl *RD = Ty->getAsRecordDecl();
7080 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7081
7082 // Visit the base classes.
7083 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7084 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7085 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7086 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7087
7088 if (!visitRecord(Val.getStructBase(I), BS.getType(),
7089 Layout.getBaseClassOffset(BaseDecl) + Offset))
7090 return false;
7091 }
7092 }
7093
7094 // Visit the fields.
7095 unsigned FieldIdx = 0;
7096 for (FieldDecl *FD : RD->fields()) {
7097 if (FD->isBitField()) {
7098 Info.FFDiag(BCE->getBeginLoc(),
7099 diag::note_constexpr_bit_cast_unsupported_bitfield);
7100 return false;
7101 }
7102
7103 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7104
7105 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7106 "only bit-fields can have sub-char alignment");
7107 CharUnits FieldOffset =
7108 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7109 QualType FieldTy = FD->getType();
7110 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7111 return false;
7112 ++FieldIdx;
7113 }
7114
7115 return true;
7116 }
7117
7118 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7119 const auto *CAT =
7120 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7121 if (!CAT)
7122 return false;
7123
7124 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7125 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7126 unsigned ArraySize = Val.getArraySize();
7127 // First, initialize the initialized elements.
7128 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7129 const APValue &SubObj = Val.getArrayInitializedElt(I);
7130 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7131 return false;
7132 }
7133
7134 // Next, initialize the rest of the array using the filler.
7135 if (Val.hasArrayFiller()) {
7136 const APValue &Filler = Val.getArrayFiller();
7137 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7138 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7139 return false;
7140 }
7141 }
7142
7143 return true;
7144 }
7145
7146 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7147 const VectorType *VTy = Ty->castAs<VectorType>();
7148 QualType EltTy = VTy->getElementType();
7149 unsigned NElts = VTy->getNumElements();
7150 unsigned EltSize =
7151 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7152
7153 if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7154 // The vector's size in bits is not a multiple of the target's byte size,
7155 // so its layout is unspecified. For now, we'll simply treat these cases
7156 // as unsupported (this should only be possible with OpenCL bool vectors
7157 // whose element count isn't a multiple of the byte size).
7158 Info.FFDiag(BCE->getBeginLoc(),
7159 diag::note_constexpr_bit_cast_invalid_vector)
7160 << Ty.getCanonicalType() << EltSize << NElts
7161 << Info.Ctx.getCharWidth();
7162 return false;
7163 }
7164
7165 if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7166 &APFloat::x87DoubleExtended()) {
7167 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7168 // by both clang and LLVM, so for now we won't allow bit_casts involving
7169 // it in a constexpr context.
7170 Info.FFDiag(BCE->getBeginLoc(),
7171 diag::note_constexpr_bit_cast_unsupported_type)
7172 << EltTy;
7173 return false;
7174 }
7175
7176 if (VTy->isExtVectorBoolType()) {
7177 // Special handling for OpenCL bool vectors:
7178 // Since these vectors are stored as packed bits, but we can't write
7179 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7180 // together into an appropriately sized APInt and write them all out at
7181 // once. Because we don't accept vectors where NElts * EltSize isn't a
7182 // multiple of the char size, there will be no padding space, so we don't
7183 // have to worry about writing data which should have been left
7184 // uninitialized.
7185 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7186
7187 llvm::APInt Res = llvm::APInt::getZero(NElts);
7188 for (unsigned I = 0; I < NElts; ++I) {
7189 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7190 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7191 "bool vector element must be 1-bit unsigned integer!");
7192
7193 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7194 }
7195
7196 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7197 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7198 Buffer.writeObject(Offset, Bytes);
7199 } else {
7200 // Iterate over each of the elements and write them out to the buffer at
7201 // the appropriate offset.
7202 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7203 for (unsigned I = 0; I < NElts; ++I) {
7204 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7205 return false;
7206 }
7207 }
7208
7209 return true;
7210 }
7211
7212 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7213 APSInt AdjustedVal = Val;
7214 unsigned Width = AdjustedVal.getBitWidth();
7215 if (Ty->isBooleanType()) {
7216 Width = Info.Ctx.getTypeSize(Ty);
7217 AdjustedVal = AdjustedVal.extend(Width);
7218 }
7219
7220 SmallVector<uint8_t, 8> Bytes(Width / 8);
7221 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7222 Buffer.writeObject(Offset, Bytes);
7223 return true;
7224 }
7225
7226 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7227 APSInt AsInt(Val.bitcastToAPInt());
7228 return visitInt(AsInt, Ty, Offset);
7229 }
7230
7231public:
7232 static std::optional<BitCastBuffer>
7233 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7234 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7235 APValueToBufferConverter Converter(Info, DstSize, BCE);
7236 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7237 return std::nullopt;
7238 return Converter.Buffer;
7239 }
7240};
7241
7242/// Write an BitCastBuffer into an APValue.
7243class BufferToAPValueConverter {
7244 EvalInfo &Info;
7245 const BitCastBuffer &Buffer;
7246 const CastExpr *BCE;
7247
7248 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7249 const CastExpr *BCE)
7250 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7251
7252 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7253 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7254 // Ideally this will be unreachable.
7255 std::nullopt_t unsupportedType(QualType Ty) {
7256 Info.FFDiag(BCE->getBeginLoc(),
7257 diag::note_constexpr_bit_cast_unsupported_type)
7258 << Ty;
7259 return std::nullopt;
7260 }
7261
7262 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7263 Info.FFDiag(BCE->getBeginLoc(),
7264 diag::note_constexpr_bit_cast_unrepresentable_value)
7265 << Ty << toString(Val, /*Radix=*/10);
7266 return std::nullopt;
7267 }
7268
7269 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7270 const EnumType *EnumSugar = nullptr) {
7271 if (T->isNullPtrType()) {
7272 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7273 return APValue((Expr *)nullptr,
7274 /*Offset=*/CharUnits::fromQuantity(NullValue),
7275 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7276 }
7277
7278 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7279
7280 // Work around floating point types that contain unused padding bytes. This
7281 // is really just `long double` on x86, which is the only fundamental type
7282 // with padding bytes.
7283 if (T->isRealFloatingType()) {
7284 const llvm::fltSemantics &Semantics =
7285 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7286 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7287 assert(NumBits % 8 == 0);
7288 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7289 if (NumBytes != SizeOf)
7290 SizeOf = NumBytes;
7291 }
7292
7294 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7295 // If this is std::byte or unsigned char, then its okay to store an
7296 // indeterminate value.
7297 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7298 bool IsUChar =
7299 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7300 T->isSpecificBuiltinType(BuiltinType::Char_U));
7301 if (!IsStdByte && !IsUChar) {
7302 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7303 Info.FFDiag(BCE->getExprLoc(),
7304 diag::note_constexpr_bit_cast_indet_dest)
7305 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7306 return std::nullopt;
7307 }
7308
7310 }
7311
7312 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7313 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7314
7316 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7317
7318 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7319 if (IntWidth != Val.getBitWidth()) {
7320 APSInt Truncated = Val.trunc(IntWidth);
7321 if (Truncated.extend(Val.getBitWidth()) != Val)
7322 return unrepresentableValue(QualType(T, 0), Val);
7323 Val = Truncated;
7324 }
7325
7326 return APValue(Val);
7327 }
7328
7329 if (T->isRealFloatingType()) {
7330 const llvm::fltSemantics &Semantics =
7331 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7332 return APValue(APFloat(Semantics, Val));
7333 }
7334
7335 return unsupportedType(QualType(T, 0));
7336 }
7337
7338 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7339 const RecordDecl *RD = RTy->getAsRecordDecl();
7340 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7341
7342 unsigned NumBases = 0;
7343 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7344 NumBases = CXXRD->getNumBases();
7345
7346 APValue ResultVal(APValue::UninitStruct(), NumBases,
7347 std::distance(RD->field_begin(), RD->field_end()));
7348
7349 // Visit the base classes.
7350 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7351 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7352 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7353 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7354
7355 std::optional<APValue> SubObj = visitType(
7356 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7357 if (!SubObj)
7358 return std::nullopt;
7359 ResultVal.getStructBase(I) = *SubObj;
7360 }
7361 }
7362
7363 // Visit the fields.
7364 unsigned FieldIdx = 0;
7365 for (FieldDecl *FD : RD->fields()) {
7366 // FIXME: We don't currently support bit-fields. A lot of the logic for
7367 // this is in CodeGen, so we need to factor it around.
7368 if (FD->isBitField()) {
7369 Info.FFDiag(BCE->getBeginLoc(),
7370 diag::note_constexpr_bit_cast_unsupported_bitfield);
7371 return std::nullopt;
7372 }
7373
7374 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7375 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7376
7377 CharUnits FieldOffset =
7378 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7379 Offset;
7380 QualType FieldTy = FD->getType();
7381 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7382 if (!SubObj)
7383 return std::nullopt;
7384 ResultVal.getStructField(FieldIdx) = *SubObj;
7385 ++FieldIdx;
7386 }
7387
7388 return ResultVal;
7389 }
7390
7391 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7392 QualType RepresentationType = Ty->getDecl()->getIntegerType();
7393 assert(!RepresentationType.isNull() &&
7394 "enum forward decl should be caught by Sema");
7395 const auto *AsBuiltin =
7396 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7397 // Recurse into the underlying type. Treat std::byte transparently as
7398 // unsigned char.
7399 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7400 }
7401
7402 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7403 size_t Size = Ty->getLimitedSize();
7404 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7405
7406 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7407 for (size_t I = 0; I != Size; ++I) {
7408 std::optional<APValue> ElementValue =
7409 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7410 if (!ElementValue)
7411 return std::nullopt;
7412 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7413 }
7414
7415 return ArrayValue;
7416 }
7417
7418 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7419 QualType EltTy = VTy->getElementType();
7420 unsigned NElts = VTy->getNumElements();
7421 unsigned EltSize =
7422 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7423
7424 if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7425 // The vector's size in bits is not a multiple of the target's byte size,
7426 // so its layout is unspecified. For now, we'll simply treat these cases
7427 // as unsupported (this should only be possible with OpenCL bool vectors
7428 // whose element count isn't a multiple of the byte size).
7429 Info.FFDiag(BCE->getBeginLoc(),
7430 diag::note_constexpr_bit_cast_invalid_vector)
7431 << QualType(VTy, 0) << EltSize << NElts << Info.Ctx.getCharWidth();
7432 return std::nullopt;
7433 }
7434
7435 if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7436 &APFloat::x87DoubleExtended()) {
7437 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7438 // by both clang and LLVM, so for now we won't allow bit_casts involving
7439 // it in a constexpr context.
7440 Info.FFDiag(BCE->getBeginLoc(),
7441 diag::note_constexpr_bit_cast_unsupported_type)
7442 << EltTy;
7443 return std::nullopt;
7444 }
7445
7447 Elts.reserve(NElts);
7448 if (VTy->isExtVectorBoolType()) {
7449 // Special handling for OpenCL bool vectors:
7450 // Since these vectors are stored as packed bits, but we can't read
7451 // individual bits from the BitCastBuffer, we'll buffer all of the
7452 // elements together into an appropriately sized APInt and write them all
7453 // out at once. Because we don't accept vectors where NElts * EltSize
7454 // isn't a multiple of the char size, there will be no padding space, so
7455 // we don't have to worry about reading any padding data which didn't
7456 // actually need to be accessed.
7457 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7458
7460 Bytes.reserve(NElts / 8);
7461 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7462 return std::nullopt;
7463
7464 APSInt SValInt(NElts, true);
7465 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7466
7467 for (unsigned I = 0; I < NElts; ++I) {
7468 llvm::APInt Elt =
7469 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7470 Elts.emplace_back(
7471 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7472 }
7473 } else {
7474 // Iterate over each of the elements and read them from the buffer at
7475 // the appropriate offset.
7476 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7477 for (unsigned I = 0; I < NElts; ++I) {
7478 std::optional<APValue> EltValue =
7479 visitType(EltTy, Offset + I * EltSizeChars);
7480 if (!EltValue)
7481 return std::nullopt;
7482 Elts.push_back(std::move(*EltValue));
7483 }
7484 }
7485
7486 return APValue(Elts.data(), Elts.size());
7487 }
7488
7489 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7490 return unsupportedType(QualType(Ty, 0));
7491 }
7492
7493 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7494 QualType Can = Ty.getCanonicalType();
7495
7496 switch (Can->getTypeClass()) {
7497#define TYPE(Class, Base) \
7498 case Type::Class: \
7499 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7500#define ABSTRACT_TYPE(Class, Base)
7501#define NON_CANONICAL_TYPE(Class, Base) \
7502 case Type::Class: \
7503 llvm_unreachable("non-canonical type should be impossible!");
7504#define DEPENDENT_TYPE(Class, Base) \
7505 case Type::Class: \
7506 llvm_unreachable( \
7507 "dependent types aren't supported in the constant evaluator!");
7508#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7509 case Type::Class: \
7510 llvm_unreachable("either dependent or not canonical!");
7511#include "clang/AST/TypeNodes.inc"
7512 }
7513 llvm_unreachable("Unhandled Type::TypeClass");
7514 }
7515
7516public:
7517 // Pull out a full value of type DstType.
7518 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7519 const CastExpr *BCE) {
7520 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7521 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7522 }
7523};
7524
7525static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7526 QualType Ty, EvalInfo *Info,
7527 const ASTContext &Ctx,
7528 bool CheckingDest) {
7529 Ty = Ty.getCanonicalType();
7530
7531 auto diag = [&](int Reason) {
7532 if (Info)
7533 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7534 << CheckingDest << (Reason == 4) << Reason;
7535 return false;
7536 };
7537 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7538 if (Info)
7539 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7540 << NoteTy << Construct << Ty;
7541 return false;
7542 };
7543
7544 if (Ty->isUnionType())
7545 return diag(0);
7546 if (Ty->isPointerType())
7547 return diag(1);
7548 if (Ty->isMemberPointerType())
7549 return diag(2);
7550 if (Ty.isVolatileQualified())
7551 return diag(3);
7552
7553 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7554 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7555 for (CXXBaseSpecifier &BS : CXXRD->bases())
7556 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7557 CheckingDest))
7558 return note(1, BS.getType(), BS.getBeginLoc());
7559 }
7560 for (FieldDecl *FD : Record->fields()) {
7561 if (FD->getType()->isReferenceType())
7562 return diag(4);
7563 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7564 CheckingDest))
7565 return note(0, FD->getType(), FD->getBeginLoc());
7566 }
7567 }
7568
7569 if (Ty->isArrayType() &&
7570 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7571 Info, Ctx, CheckingDest))
7572 return false;
7573
7574 return true;
7575}
7576
7577static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7578 const ASTContext &Ctx,
7579 const CastExpr *BCE) {
7580 bool DestOK = checkBitCastConstexprEligibilityType(
7581 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7582 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7583 BCE->getBeginLoc(),
7584 BCE->getSubExpr()->getType(), Info, Ctx, false);
7585 return SourceOK;
7586}
7587
7588static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7589 const APValue &SourceRValue,
7590 const CastExpr *BCE) {
7591 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7592 "no host or target supports non 8-bit chars");
7593
7594 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7595 return false;
7596
7597 // Read out SourceValue into a char buffer.
7598 std::optional<BitCastBuffer> Buffer =
7599 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7600 if (!Buffer)
7601 return false;
7602
7603 // Write out the buffer into a new APValue.
7604 std::optional<APValue> MaybeDestValue =
7605 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7606 if (!MaybeDestValue)
7607 return false;
7608
7609 DestValue = std::move(*MaybeDestValue);
7610 return true;
7611}
7612
7613static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7614 APValue &SourceValue,
7615 const CastExpr *BCE) {
7616 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7617 "no host or target supports non 8-bit chars");
7618 assert(SourceValue.isLValue() &&
7619 "LValueToRValueBitcast requires an lvalue operand!");
7620
7621 LValue SourceLValue;
7622 APValue SourceRValue;
7623 SourceLValue.setFrom(Info.Ctx, SourceValue);
7625 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7626 SourceRValue, /*WantObjectRepresentation=*/true))
7627 return false;
7628
7629 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
7630}
7631
7632template <class Derived>
7633class ExprEvaluatorBase
7634 : public ConstStmtVisitor<Derived, bool> {
7635private:
7636 Derived &getDerived() { return static_cast<Derived&>(*this); }
7637 bool DerivedSuccess(const APValue &V, const Expr *E) {
7638 return getDerived().Success(V, E);
7639 }
7640 bool DerivedZeroInitialization(const Expr *E) {
7641 return getDerived().ZeroInitialization(E);
7642 }
7643
7644 // Check whether a conditional operator with a non-constant condition is a
7645 // potential constant expression. If neither arm is a potential constant
7646 // expression, then the conditional operator is not either.
7647 template<typename ConditionalOperator>
7648 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7649 assert(Info.checkingPotentialConstantExpression());
7650
7651 // Speculatively evaluate both arms.
7653 {
7654 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7655 StmtVisitorTy::Visit(E->getFalseExpr());
7656 if (Diag.empty())
7657 return;
7658 }
7659
7660 {
7661 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7662 Diag.clear();
7663 StmtVisitorTy::Visit(E->getTrueExpr());
7664 if (Diag.empty())
7665 return;
7666 }
7667
7668 Error(E, diag::note_constexpr_conditional_never_const);
7669 }
7670
7671
7672 template<typename ConditionalOperator>
7673 bool HandleConditionalOperator(const ConditionalOperator *E) {
7674 bool BoolResult;
7675 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7676 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7677 CheckPotentialConstantConditional(E);
7678 return false;
7679 }
7680 if (Info.noteFailure()) {
7681 StmtVisitorTy::Visit(E->getTrueExpr());
7682 StmtVisitorTy::Visit(E->getFalseExpr());
7683 }
7684 return false;
7685 }
7686
7687 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7688 return StmtVisitorTy::Visit(EvalExpr);
7689 }
7690
7691protected:
7692 EvalInfo &Info;
7693 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7694 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7695
7696 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7697 return Info.CCEDiag(E, D);
7698 }
7699
7700 bool ZeroInitialization(const Expr *E) { return Error(E); }
7701
7702 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7703 unsigned BuiltinOp = E->getBuiltinCallee();
7704 return BuiltinOp != 0 &&
7705 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7706 }
7707
7708public:
7709 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7710
7711 EvalInfo &getEvalInfo() { return Info; }
7712
7713 /// Report an evaluation error. This should only be called when an error is
7714 /// first discovered. When propagating an error, just return false.
7715 bool Error(const Expr *E, diag::kind D) {
7716 Info.FFDiag(E, D) << E->getSourceRange();
7717 return false;
7718 }
7719 bool Error(const Expr *E) {
7720 return Error(E, diag::note_invalid_subexpr_in_const_expr);
7721 }
7722
7723 bool VisitStmt(const Stmt *) {
7724 llvm_unreachable("Expression evaluator should not be called on stmts");
7725 }
7726 bool VisitExpr(const Expr *E) {
7727 return Error(E);
7728 }
7729
7730 bool VisitPredefinedExpr(const PredefinedExpr *E) {
7731 return StmtVisitorTy::Visit(E->getFunctionName());
7732 }
7733 bool VisitConstantExpr(const ConstantExpr *E) {
7734 if (E->hasAPValueResult())
7735 return DerivedSuccess(E->getAPValueResult(), E);
7736
7737 return StmtVisitorTy::Visit(E->getSubExpr());
7738 }
7739
7740 bool VisitParenExpr(const ParenExpr *E)
7741 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7742 bool VisitUnaryExtension(const UnaryOperator *E)
7743 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7744 bool VisitUnaryPlus(const UnaryOperator *E)
7745 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7746 bool VisitChooseExpr(const ChooseExpr *E)
7747 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7748 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7749 { return StmtVisitorTy::Visit(E->getResultExpr()); }
7750 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7751 { return StmtVisitorTy::Visit(E->getReplacement()); }
7752 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7753 TempVersionRAII RAII(*Info.CurrentCall);
7754 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7755 return StmtVisitorTy::Visit(E->getExpr());
7756 }
7757 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7758 TempVersionRAII RAII(*Info.CurrentCall);
7759 // The initializer may not have been parsed yet, or might be erroneous.
7760 if (!E->getExpr())
7761 return Error(E);
7762 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7763 return StmtVisitorTy::Visit(E->getExpr());
7764 }
7765
7766 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7767 FullExpressionRAII Scope(Info);
7768 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7769 }
7770
7771 // Temporaries are registered when created, so we don't care about
7772 // CXXBindTemporaryExpr.
7773 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7774 return StmtVisitorTy::Visit(E->getSubExpr());
7775 }
7776
7777 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7778 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7779 return static_cast<Derived*>(this)->VisitCastExpr(E);
7780 }
7781 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7782 if (!Info.Ctx.getLangOpts().CPlusPlus20)
7783 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7784 return static_cast<Derived*>(this)->VisitCastExpr(E);
7785 }
7786 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7787 return static_cast<Derived*>(this)->VisitCastExpr(E);
7788 }
7789
7790 bool VisitBinaryOperator(const BinaryOperator *E) {
7791 switch (E->getOpcode()) {
7792 default:
7793 return Error(E);
7794
7795 case BO_Comma:
7796 VisitIgnoredValue(E->getLHS());
7797 return StmtVisitorTy::Visit(E->getRHS());
7798
7799 case BO_PtrMemD:
7800 case BO_PtrMemI: {
7801 LValue Obj;
7802 if (!HandleMemberPointerAccess(Info, E, Obj))
7803 return false;
7804 APValue Result;
7805 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7806 return false;
7807 return DerivedSuccess(Result, E);
7808 }
7809 }
7810 }
7811
7812 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7813 return StmtVisitorTy::Visit(E->getSemanticForm());
7814 }
7815
7816 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7817 // Evaluate and cache the common expression. We treat it as a temporary,
7818 // even though it's not quite the same thing.
7819 LValue CommonLV;
7820 if (!Evaluate(Info.CurrentCall->createTemporary(
7821 E->getOpaqueValue(),
7822 getStorageType(Info.Ctx, E->getOpaqueValue()),
7823 ScopeKind::FullExpression, CommonLV),
7824 Info, E->getCommon()))
7825 return false;
7826
7827 return HandleConditionalOperator(E);
7828 }
7829
7830 bool VisitConditionalOperator(const ConditionalOperator *E) {
7831 bool IsBcpCall = false;
7832 // If the condition (ignoring parens) is a __builtin_constant_p call,
7833 // the result is a constant expression if it can be folded without
7834 // side-effects. This is an important GNU extension. See GCC PR38377
7835 // for discussion.
7836 if (const CallExpr *CallCE =
7837 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7838 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7839 IsBcpCall = true;
7840
7841 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7842 // constant expression; we can't check whether it's potentially foldable.
7843 // FIXME: We should instead treat __builtin_constant_p as non-constant if
7844 // it would return 'false' in this mode.
7845 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7846 return false;
7847
7848 FoldConstant Fold(Info, IsBcpCall);
7849 if (!HandleConditionalOperator(E)) {
7850 Fold.keepDiagnostics();
7851 return false;
7852 }
7853
7854 return true;
7855 }
7856
7857 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7858 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
7859 Value && !Value->isAbsent())
7860 return DerivedSuccess(*Value, E);
7861
7862 const Expr *Source = E->getSourceExpr();
7863 if (!Source)
7864 return Error(E);
7865 if (Source == E) {
7866 assert(0 && "OpaqueValueExpr recursively refers to itself");
7867 return Error(E);
7868 }
7869 return StmtVisitorTy::Visit(Source);
7870 }
7871
7872 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7873 for (const Expr *SemE : E->semantics()) {
7874 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7875 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7876 // result expression: there could be two different LValues that would
7877 // refer to the same object in that case, and we can't model that.
7878 if (SemE == E->getResultExpr())
7879 return Error(E);
7880
7881 // Unique OVEs get evaluated if and when we encounter them when
7882 // emitting the rest of the semantic form, rather than eagerly.
7883 if (OVE->isUnique())
7884 continue;
7885
7886 LValue LV;
7887 if (!Evaluate(Info.CurrentCall->createTemporary(
7888 OVE, getStorageType(Info.Ctx, OVE),
7889 ScopeKind::FullExpression, LV),
7890 Info, OVE->getSourceExpr()))
7891 return false;
7892 } else if (SemE == E->getResultExpr()) {
7893 if (!StmtVisitorTy::Visit(SemE))
7894 return false;
7895 } else {
7896 if (!EvaluateIgnoredValue(Info, SemE))
7897 return false;
7898 }
7899 }
7900 return true;
7901 }
7902
7903 bool VisitCallExpr(const CallExpr *E) {
7904 APValue Result;
7905 if (!handleCallExpr(E, Result, nullptr))
7906 return false;
7907 return DerivedSuccess(Result, E);
7908 }
7909
7910 bool handleCallExpr(const CallExpr *E, APValue &Result,
7911 const LValue *ResultSlot) {
7912 CallScopeRAII CallScope(Info);
7913
7914 const Expr *Callee = E->getCallee()->IgnoreParens();
7915 QualType CalleeType = Callee->getType();
7916
7917 const FunctionDecl *FD = nullptr;
7918 LValue *This = nullptr, ThisVal;
7919 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7920 bool HasQualifier = false;
7921
7922 CallRef Call;
7923
7924 // Extract function decl and 'this' pointer from the callee.
7925 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7926 const CXXMethodDecl *Member = nullptr;
7927 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7928 // Explicit bound member calls, such as x.f() or p->g();
7929 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7930 return false;
7931 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7932 if (!Member)
7933 return Error(Callee);
7934 This = &ThisVal;
7935 HasQualifier = ME->hasQualifier();
7936 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7937 // Indirect bound member calls ('.*' or '->*').
7938 const ValueDecl *D =
7939 HandleMemberPointerAccess(Info, BE, ThisVal, false);
7940 if (!D)
7941 return false;
7942 Member = dyn_cast<CXXMethodDecl>(D);
7943 if (!Member)
7944 return Error(Callee);
7945 This = &ThisVal;
7946 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7947 if (!Info.getLangOpts().CPlusPlus20)
7948 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7949 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7950 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7951 } else
7952 return Error(Callee);
7953 FD = Member;
7954 } else if (CalleeType->isFunctionPointerType()) {
7955 LValue CalleeLV;
7956 if (!EvaluatePointer(Callee, CalleeLV, Info))
7957 return false;
7958
7959 if (!CalleeLV.getLValueOffset().isZero())
7960 return Error(Callee);
7961 if (CalleeLV.isNullPointer()) {
7962 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7963 << const_cast<Expr *>(Callee);
7964 return false;
7965 }
7966 FD = dyn_cast_or_null<FunctionDecl>(
7967 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7968 if (!FD)
7969 return Error(Callee);
7970 // Don't call function pointers which have been cast to some other type.
7971 // Per DR (no number yet), the caller and callee can differ in noexcept.
7972 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7973 CalleeType->getPointeeType(), FD->getType())) {
7974 return Error(E);
7975 }
7976
7977 // For an (overloaded) assignment expression, evaluate the RHS before the
7978 // LHS.
7979 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7980 if (OCE && OCE->isAssignmentOp()) {
7981 assert(Args.size() == 2 && "wrong number of arguments in assignment");
7982 Call = Info.CurrentCall->createCall(FD);
7983 bool HasThis = false;
7984 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7985 HasThis = MD->isImplicitObjectMemberFunction();
7986 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
7987 /*RightToLeft=*/true))
7988 return false;
7989 }
7990
7991 // Overloaded operator calls to member functions are represented as normal
7992 // calls with '*this' as the first argument.
7993 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7994 if (MD &&
7995 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
7996 // FIXME: When selecting an implicit conversion for an overloaded
7997 // operator delete, we sometimes try to evaluate calls to conversion
7998 // operators without a 'this' parameter!
7999 if (Args.empty())
8000 return Error(E);
8001
8002 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
8003 return false;
8004
8005 // If we are calling a static operator, the 'this' argument needs to be
8006 // ignored after being evaluated.
8007 if (MD->isInstance())
8008 This = &ThisVal;
8009
8010 // If this is syntactically a simple assignment using a trivial
8011 // assignment operator, start the lifetimes of union members as needed,
8012 // per C++20 [class.union]5.
8013 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8014 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8015 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))
8016 return false;
8017
8018 Args = Args.slice(1);
8019 } else if (MD && MD->isLambdaStaticInvoker()) {
8020 // Map the static invoker for the lambda back to the call operator.
8021 // Conveniently, we don't have to slice out the 'this' argument (as is
8022 // being done for the non-static case), since a static member function
8023 // doesn't have an implicit argument passed in.
8024 const CXXRecordDecl *ClosureClass = MD->getParent();
8025 assert(
8026 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
8027 "Number of captures must be zero for conversion to function-ptr");
8028
8029 const CXXMethodDecl *LambdaCallOp =
8030 ClosureClass->getLambdaCallOperator();
8031
8032 // Set 'FD', the function that will be called below, to the call
8033 // operator. If the closure object represents a generic lambda, find
8034 // the corresponding specialization of the call operator.
8035
8036 if (ClosureClass->isGenericLambda()) {
8037 assert(MD->isFunctionTemplateSpecialization() &&
8038 "A generic lambda's static-invoker function must be a "
8039 "template specialization");
8041 FunctionTemplateDecl *CallOpTemplate =
8042 LambdaCallOp->getDescribedFunctionTemplate();
8043 void *InsertPos = nullptr;
8044 FunctionDecl *CorrespondingCallOpSpecialization =
8045 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8046 assert(CorrespondingCallOpSpecialization &&
8047 "We must always have a function call operator specialization "
8048 "that corresponds to our static invoker specialization");
8049 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8050 FD = CorrespondingCallOpSpecialization;
8051 } else
8052 FD = LambdaCallOp;
8053 } else if (FD->isReplaceableGlobalAllocationFunction()) {
8054 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
8055 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
8056 LValue Ptr;
8057 if (!HandleOperatorNewCall(Info, E, Ptr))
8058 return false;
8059 Ptr.moveInto(Result);
8060 return CallScope.destroy();
8061 } else {
8062 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8063 }
8064 }
8065 } else
8066 return Error(E);
8067
8068 // Evaluate the arguments now if we've not already done so.
8069 if (!Call) {
8070 Call = Info.CurrentCall->createCall(FD);
8071 if (!EvaluateArgs(Args, Call, Info, FD))
8072 return false;
8073 }
8074
8075 SmallVector<QualType, 4> CovariantAdjustmentPath;
8076 if (This) {
8077 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8078 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8079 // Perform virtual dispatch, if necessary.
8080 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8081 CovariantAdjustmentPath);
8082 if (!FD)
8083 return false;
8084 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8085 // Check that the 'this' pointer points to an object of the right type.
8086 // FIXME: If this is an assignment operator call, we may need to change
8087 // the active union member before we check this.
8088 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8089 return false;
8090 }
8091 }
8092
8093 // Destructor calls are different enough that they have their own codepath.
8094 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8095 assert(This && "no 'this' pointer for destructor call");
8096 return HandleDestruction(Info, E, *This,
8097 Info.Ctx.getRecordType(DD->getParent())) &&
8098 CallScope.destroy();
8099 }
8100
8101 const FunctionDecl *Definition = nullptr;
8102 Stmt *Body = FD->getBody(Definition);
8103
8104 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8105 !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8106 Body, Info, Result, ResultSlot))
8107 return false;
8108
8109 if (!CovariantAdjustmentPath.empty() &&
8110 !HandleCovariantReturnAdjustment(Info, E, Result,
8111 CovariantAdjustmentPath))
8112 return false;
8113
8114 return CallScope.destroy();
8115 }
8116
8117 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8118 return StmtVisitorTy::Visit(E->getInitializer());
8119 }
8120 bool VisitInitListExpr(const InitListExpr *E) {
8121 if (E->getNumInits() == 0)
8122 return DerivedZeroInitialization(E);
8123 if (E->getNumInits() == 1)
8124 return StmtVisitorTy::Visit(E->getInit(0));
8125 return Error(E);
8126 }
8127 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8128 return DerivedZeroInitialization(E);
8129 }
8130 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8131 return DerivedZeroInitialization(E);
8132 }
8133 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8134 return DerivedZeroInitialization(E);
8135 }
8136
8137 /// A member expression where the object is a prvalue is itself a prvalue.
8138 bool VisitMemberExpr(const MemberExpr *E) {
8139 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8140 "missing temporary materialization conversion");
8141 assert(!E->isArrow() && "missing call to bound member function?");
8142
8143 APValue Val;
8144 if (!Evaluate(Val, Info, E->getBase()))
8145 return false;
8146
8147 QualType BaseTy = E->getBase()->getType();
8148
8149 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8150 if (!FD) return Error(E);
8151 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8152 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8153 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8154
8155 // Note: there is no lvalue base here. But this case should only ever
8156 // happen in C or in C++98, where we cannot be evaluating a constexpr
8157 // constructor, which is the only case the base matters.
8158 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8159 SubobjectDesignator Designator(BaseTy);
8160 Designator.addDeclUnchecked(FD);
8161
8162 APValue Result;
8163 return extractSubobject(Info, E, Obj, Designator, Result) &&
8164 DerivedSuccess(Result, E);
8165 }
8166
8167 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8168 APValue Val;
8169 if (!Evaluate(Val, Info, E->getBase()))
8170 return false;
8171
8172 if (Val.isVector()) {
8174 E->getEncodedElementAccess(Indices);
8175 if (Indices.size() == 1) {
8176 // Return scalar.
8177 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8178 } else {
8179 // Construct new APValue vector.
8181 for (unsigned I = 0; I < Indices.size(); ++I) {
8182 Elts.push_back(Val.getVectorElt(Indices[I]));
8183 }
8184 APValue VecResult(Elts.data(), Indices.size());
8185 return DerivedSuccess(VecResult, E);
8186 }
8187 }
8188
8189 return false;
8190 }
8191
8192 bool VisitCastExpr(const CastExpr *E) {
8193 switch (E->getCastKind()) {
8194 default:
8195 break;
8196
8197 case CK_AtomicToNonAtomic: {
8198 APValue AtomicVal;
8199 // This does not need to be done in place even for class/array types:
8200 // atomic-to-non-atomic conversion implies copying the object
8201 // representation.
8202 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8203 return false;
8204 return DerivedSuccess(AtomicVal, E);
8205 }
8206
8207 case CK_NoOp:
8208 case CK_UserDefinedConversion:
8209 return StmtVisitorTy::Visit(E->getSubExpr());
8210
8211 case CK_LValueToRValue: {
8212 LValue LVal;
8213 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8214 return false;
8215 APValue RVal;
8216 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8218 LVal, RVal))
8219 return false;
8220 return DerivedSuccess(RVal, E);
8221 }
8222 case CK_LValueToRValueBitCast: {
8223 APValue DestValue, SourceValue;
8224 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8225 return false;
8226 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8227 return false;
8228 return DerivedSuccess(DestValue, E);
8229 }
8230
8231 case CK_AddressSpaceConversion: {
8232 APValue Value;
8233 if (!Evaluate(Value, Info, E->getSubExpr()))
8234 return false;
8235 return DerivedSuccess(Value, E);
8236 }
8237 }
8238
8239 return Error(E);
8240 }
8241
8242 bool VisitUnaryPostInc(const UnaryOperator *UO) {
8243 return VisitUnaryPostIncDec(UO);
8244 }
8245 bool VisitUnaryPostDec(const UnaryOperator *UO) {
8246 return VisitUnaryPostIncDec(UO);
8247 }
8248 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8249 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8250 return Error(UO);
8251
8252 LValue LVal;
8253 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8254 return false;
8255 APValue RVal;
8256 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8257 UO->isIncrementOp(), &RVal))
8258 return false;
8259 return DerivedSuccess(RVal, UO);
8260 }
8261
8262 bool VisitStmtExpr(const StmtExpr *E) {
8263 // We will have checked the full-expressions inside the statement expression
8264 // when they were completed, and don't need to check them again now.
8265 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8266 false);
8267
8268 const CompoundStmt *CS = E->getSubStmt();
8269 if (CS->body_empty())
8270 return true;
8271
8272 BlockScopeRAII Scope(Info);
8274 BE = CS->body_end();
8275 /**/; ++BI) {
8276 if (BI + 1 == BE) {
8277 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8278 if (!FinalExpr) {
8279 Info.FFDiag((*BI)->getBeginLoc(),
8280 diag::note_constexpr_stmt_expr_unsupported);
8281 return false;
8282 }
8283 return this->Visit(FinalExpr) && Scope.destroy();
8284 }
8285
8287 StmtResult Result = { ReturnValue, nullptr };
8288 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8289 if (ESR != ESR_Succeeded) {
8290 // FIXME: If the statement-expression terminated due to 'return',
8291 // 'break', or 'continue', it would be nice to propagate that to
8292 // the outer statement evaluation rather than bailing out.
8293 if (ESR != ESR_Failed)
8294 Info.FFDiag((*BI)->getBeginLoc(),
8295 diag::note_constexpr_stmt_expr_unsupported);
8296 return false;
8297 }
8298 }
8299
8300 llvm_unreachable("Return from function from the loop above.");
8301 }
8302
8303 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8304 return StmtVisitorTy::Visit(E->getSelectedExpr());
8305 }
8306
8307 /// Visit a value which is evaluated, but whose value is ignored.
8308 void VisitIgnoredValue(const Expr *E) {
8309 EvaluateIgnoredValue(Info, E);
8310 }
8311
8312 /// Potentially visit a MemberExpr's base expression.
8313 void VisitIgnoredBaseExpression(const Expr *E) {
8314 // While MSVC doesn't evaluate the base expression, it does diagnose the
8315 // presence of side-effecting behavior.
8316 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8317 return;
8318 VisitIgnoredValue(E);
8319 }
8320};
8321
8322} // namespace
8323
8324//===----------------------------------------------------------------------===//
8325// Common base class for lvalue and temporary evaluation.
8326//===----------------------------------------------------------------------===//
8327namespace {
8328template<class Derived>
8329class LValueExprEvaluatorBase
8330 : public ExprEvaluatorBase<Derived> {
8331protected:
8332 LValue &Result;
8333 bool InvalidBaseOK;
8334 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8335 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8336
8338 Result.set(B);
8339 return true;
8340 }
8341
8342 bool evaluatePointer(const Expr *E, LValue &Result) {
8343 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8344 }
8345
8346public:
8347 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8348 : ExprEvaluatorBaseTy(Info), Result(Result),
8349 InvalidBaseOK(InvalidBaseOK) {}
8350
8351 bool Success(const APValue &V, const Expr *E) {
8352 Result.setFrom(this->Info.Ctx, V);
8353 return true;
8354 }
8355
8356 bool VisitMemberExpr(const MemberExpr *E) {
8357 // Handle non-static data members.
8358 QualType BaseTy;
8359 bool EvalOK;
8360 if (E->isArrow()) {
8361 EvalOK = evaluatePointer(E->getBase(), Result);
8362 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8363 } else if (E->getBase()->isPRValue()) {
8364 assert(E->getBase()->getType()->isRecordType());
8365 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8366 BaseTy = E->getBase()->getType();
8367 } else {
8368 EvalOK = this->Visit(E->getBase());
8369 BaseTy = E->getBase()->getType();
8370 }
8371 if (!EvalOK) {
8372 if (!InvalidBaseOK)
8373 return false;
8374 Result.setInvalid(E);
8375 return true;
8376 }
8377
8378 const ValueDecl *MD = E->getMemberDecl();
8379 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8380 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8381 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8382 (void)BaseTy;
8383 if (!HandleLValueMember(this->Info, E, Result, FD))
8384 return false;
8385 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8386 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8387 return false;
8388 } else
8389 return this->Error(E);
8390
8391 if (MD->getType()->isReferenceType()) {
8392 APValue RefValue;
8393 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8394 RefValue))
8395 return false;
8396 return Success(RefValue, E);
8397 }
8398 return true;
8399 }
8400
8401 bool VisitBinaryOperator(const BinaryOperator *E) {
8402 switch (E->getOpcode()) {
8403 default:
8404 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8405
8406 case BO_PtrMemD:
8407 case BO_PtrMemI:
8408 return HandleMemberPointerAccess(this->Info, E, Result);
8409 }
8410 }
8411
8412 bool VisitCastExpr(const CastExpr *E) {
8413 switch (E->getCastKind()) {
8414 default:
8415 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8416
8417 case CK_DerivedToBase:
8418 case CK_UncheckedDerivedToBase:
8419 if (!this->Visit(E->getSubExpr()))
8420 return false;
8421
8422 // Now figure out the necessary offset to add to the base LV to get from
8423 // the derived class to the base class.
8424 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8425 Result);
8426 }
8427 }
8428};
8429}
8430
8431//===----------------------------------------------------------------------===//
8432// LValue Evaluation
8433//
8434// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8435// function designators (in C), decl references to void objects (in C), and
8436// temporaries (if building with -Wno-address-of-temporary).
8437//
8438// LValue evaluation produces values comprising a base expression of one of the
8439// following types:
8440// - Declarations
8441// * VarDecl
8442// * FunctionDecl
8443// - Literals
8444// * CompoundLiteralExpr in C (and in global scope in C++)
8445// * StringLiteral
8446// * PredefinedExpr
8447// * ObjCStringLiteralExpr
8448// * ObjCEncodeExpr
8449// * AddrLabelExpr
8450// * BlockExpr
8451// * CallExpr for a MakeStringConstant builtin
8452// - typeid(T) expressions, as TypeInfoLValues
8453// - Locals and temporaries
8454// * MaterializeTemporaryExpr
8455// * Any Expr, with a CallIndex indicating the function in which the temporary
8456// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8457// from the AST (FIXME).
8458// * A MaterializeTemporaryExpr that has static storage duration, with no
8459// CallIndex, for a lifetime-extended temporary.
8460// * The ConstantExpr that is currently being evaluated during evaluation of an
8461// immediate invocation.
8462// plus an offset in bytes.
8463//===----------------------------------------------------------------------===//
8464namespace {
8465class LValueExprEvaluator
8466 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8467public:
8468 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8469 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8470
8471 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8472 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8473
8474 bool VisitCallExpr(const CallExpr *E);
8475 bool VisitDeclRefExpr(const DeclRefExpr *E);
8476 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8477 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8478 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8479 bool VisitMemberExpr(const MemberExpr *E);
8480 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8481 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8482 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8483 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8484 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8485 bool VisitUnaryDeref(const UnaryOperator *E);
8486 bool VisitUnaryReal(const UnaryOperator *E);
8487 bool VisitUnaryImag(const UnaryOperator *E);
8488 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8489 return VisitUnaryPreIncDec(UO);
8490 }
8491 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8492 return VisitUnaryPreIncDec(UO);
8493 }
8494 bool VisitBinAssign(const BinaryOperator *BO);
8495 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8496
8497 bool VisitCastExpr(const CastExpr *E) {
8498 switch (E->getCastKind()) {
8499 default:
8500 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8501
8502 case CK_LValueBitCast:
8503 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8504 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8505 if (!Visit(E->getSubExpr()))
8506 return false;
8507 Result.Designator.setInvalid();
8508 return true;
8509
8510 case CK_BaseToDerived:
8511 if (!Visit(E->getSubExpr()))
8512 return false;
8513 return HandleBaseToDerivedCast(Info, E, Result);
8514
8515 case CK_Dynamic:
8516 if (!Visit(E->getSubExpr()))
8517 return false;
8518 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8519 }
8520 }
8521};
8522} // end anonymous namespace
8523
8524/// Get an lvalue to a field of a lambda's closure type.
8525static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8526 const CXXMethodDecl *MD, const FieldDecl *FD,
8527 bool LValueToRValueConversion) {
8528 // Static lambda function call operators can't have captures. We already
8529 // diagnosed this, so bail out here.
8530 if (MD->isStatic()) {
8531 assert(Info.CurrentCall->This == nullptr &&
8532 "This should not be set for a static call operator");
8533 return false;
8534 }
8535
8536 // Start with 'Result' referring to the complete closure object...
8538 // Self may be passed by reference or by value.
8539 const ParmVarDecl *Self = MD->getParamDecl(0);
8540 if (Self->getType()->isReferenceType()) {
8541 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
8542 Result.setFrom(Info.Ctx, *RefValue);
8543 } else {
8544 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
8545 CallStackFrame *Frame =
8546 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
8547 .first;
8548 unsigned Version = Info.CurrentCall->Arguments.Version;
8549 Result.set({VD, Frame->Index, Version});
8550 }
8551 } else
8552 Result = *Info.CurrentCall->This;
8553
8554 // ... then update it to refer to the field of the closure object
8555 // that represents the capture.
8556 if (!HandleLValueMember(Info, E, Result, FD))
8557 return false;
8558
8559 // And if the field is of reference type (or if we captured '*this' by
8560 // reference), update 'Result' to refer to what
8561 // the field refers to.
8562 if (LValueToRValueConversion) {
8563 APValue RVal;
8564 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
8565 return false;
8566 Result.setFrom(Info.Ctx, RVal);
8567 }
8568 return true;
8569}
8570
8571/// Evaluate an expression as an lvalue. This can be legitimately called on
8572/// expressions which are not glvalues, in three cases:
8573/// * function designators in C, and
8574/// * "extern void" objects
8575/// * @selector() expressions in Objective-C
8576static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8577 bool InvalidBaseOK) {
8578 assert(!E->isValueDependent());
8579 assert(E->isGLValue() || E->getType()->isFunctionType() ||
8580 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8581 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8582}
8583
8584bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8585 const NamedDecl *D = E->getDecl();
8588 return Success(cast<ValueDecl>(D));
8589 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8590 return VisitVarDecl(E, VD);
8591 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8592 return Visit(BD->getBinding());
8593 return Error(E);
8594}
8595
8596
8597bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8598
8599 // If we are within a lambda's call operator, check whether the 'VD' referred
8600 // to within 'E' actually represents a lambda-capture that maps to a
8601 // data-member/field within the closure object, and if so, evaluate to the
8602 // field or what the field refers to.
8603 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8604 isa<DeclRefExpr>(E) &&
8605 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8606 // We don't always have a complete capture-map when checking or inferring if
8607 // the function call operator meets the requirements of a constexpr function
8608 // - but we don't need to evaluate the captures to determine constexprness
8609 // (dcl.constexpr C++17).
8610 if (Info.checkingPotentialConstantExpression())
8611 return false;
8612
8613 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8614 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
8615 return HandleLambdaCapture(Info, E, Result, MD, FD,
8616 FD->getType()->isReferenceType());
8617 }
8618 }
8619
8620 CallStackFrame *Frame = nullptr;
8621 unsigned Version = 0;
8622 if (VD->hasLocalStorage()) {
8623 // Only if a local variable was declared in the function currently being
8624 // evaluated, do we expect to be able to find its value in the current
8625 // frame. (Otherwise it was likely declared in an enclosing context and
8626 // could either have a valid evaluatable value (for e.g. a constexpr
8627 // variable) or be ill-formed (and trigger an appropriate evaluation
8628 // diagnostic)).
8629 CallStackFrame *CurrFrame = Info.CurrentCall;
8630 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8631 // Function parameters are stored in some caller's frame. (Usually the
8632 // immediate caller, but for an inherited constructor they may be more
8633 // distant.)
8634 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8635 if (CurrFrame->Arguments) {
8636 VD = CurrFrame->Arguments.getOrigParam(PVD);
8637 Frame =
8638 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8639 Version = CurrFrame->Arguments.Version;
8640 }
8641 } else {
8642 Frame = CurrFrame;
8643 Version = CurrFrame->getCurrentTemporaryVersion(VD);
8644 }
8645 }
8646 }
8647
8648 if (!VD->getType()->isReferenceType()) {
8649 if (Frame) {
8650 Result.set({VD, Frame->Index, Version});
8651 return true;
8652 }
8653 return Success(VD);
8654 }
8655
8656 if (!Info.getLangOpts().CPlusPlus11) {
8657 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8658 << VD << VD->getType();
8659 Info.Note(VD->getLocation(), diag::note_declared_at);
8660 }
8661
8662 APValue *V;
8663 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8664 return false;
8665 if (!V->hasValue()) {
8666 // FIXME: Is it possible for V to be indeterminate here? If so, we should
8667 // adjust the diagnostic to say that.
8668 if (!Info.checkingPotentialConstantExpression())
8669 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8670 return false;
8671 }
8672 return Success(*V, E);
8673}
8674
8675bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8676 if (!IsConstantEvaluatedBuiltinCall(E))
8677 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8678
8679 switch (E->getBuiltinCallee()) {
8680 default:
8681 return false;
8682 case Builtin::BIas_const:
8683 case Builtin::BIforward:
8684 case Builtin::BIforward_like:
8685 case Builtin::BImove:
8686 case Builtin::BImove_if_noexcept:
8687 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8688 return Visit(E->getArg(0));
8689 break;
8690 }
8691
8692 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8693}
8694
8695bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8696 const MaterializeTemporaryExpr *E) {
8697 // Walk through the expression to find the materialized temporary itself.
8700 const Expr *Inner =
8701 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8702
8703 // If we passed any comma operators, evaluate their LHSs.
8704 for (const Expr *E : CommaLHSs)
8705 if (!EvaluateIgnoredValue(Info, E))
8706 return false;
8707
8708 // A materialized temporary with static storage duration can appear within the
8709 // result of a constant expression evaluation, so we need to preserve its
8710 // value for use outside this evaluation.
8711 APValue *Value;
8712 if (E->getStorageDuration() == SD_Static) {
8713 if (Info.EvalMode == EvalInfo::EM_ConstantFold)
8714 return false;
8715 // FIXME: What about SD_Thread?
8716 Value = E->getOrCreateValue(true);
8717 *Value = APValue();
8718 Result.set(E);
8719 } else {
8720 Value = &Info.CurrentCall->createTemporary(
8721 E, Inner->getType(),
8722 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8723 : ScopeKind::Block,
8724 Result);
8725 }
8726
8727 QualType Type = Inner->getType();
8728
8729 // Materialize the temporary itself.
8730 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8731 *Value = APValue();
8732 return false;
8733 }
8734
8735 // Adjust our lvalue to refer to the desired subobject.
8736 for (unsigned I = Adjustments.size(); I != 0; /**/) {
8737 --I;
8738 switch (Adjustments[I].Kind) {
8740 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8741 Type, Result))
8742 return false;
8743 Type = Adjustments[I].DerivedToBase.BasePath->getType();
8744 break;
8745
8747 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8748 return false;
8749 Type = Adjustments[I].Field->getType();
8750 break;
8751
8753 if (!HandleMemberPointerAccess(this->Info, Type, Result,
8754 Adjustments[I].Ptr.RHS))
8755 return false;
8756 Type = Adjustments[I].Ptr.MPT->getPointeeType();
8757 break;
8758 }
8759 }
8760
8761 return true;
8762}
8763
8764bool
8765LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8766 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8767 "lvalue compound literal in c++?");
8768 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8769 // only see this when folding in C, so there's no standard to follow here.
8770 return Success(E);
8771}
8772
8773bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8775
8776 if (!E->isPotentiallyEvaluated()) {
8777 if (E->isTypeOperand())
8779 else
8781 } else {
8782 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8783 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8784 << E->getExprOperand()->getType()
8785 << E->getExprOperand()->getSourceRange();
8786 }
8787
8788 if (!Visit(E->getExprOperand()))
8789 return false;
8790
8791 std::optional<DynamicType> DynType =
8792 ComputeDynamicType(Info, E, Result, AK_TypeId);
8793 if (!DynType)
8794 return false;
8795
8796 TypeInfo =
8797 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8798 }
8799
8801}
8802
8803bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8804 return Success(E->getGuidDecl());
8805}
8806
8807bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8808 // Handle static data members.
8809 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8810 VisitIgnoredBaseExpression(E->getBase());
8811 return VisitVarDecl(E, VD);
8812 }
8813
8814 // Handle static member functions.
8815 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8816 if (MD->isStatic()) {
8817 VisitIgnoredBaseExpression(E->getBase());
8818 return Success(MD);
8819 }
8820 }
8821
8822 // Handle non-static data members.
8823 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8824}
8825
8826bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8827 // FIXME: Deal with vectors as array subscript bases.
8828 if (E->getBase()->getType()->isVectorType() ||
8830 return Error(E);
8831
8832 APSInt Index;
8833 bool Success = true;
8834
8835 // C++17's rules require us to evaluate the LHS first, regardless of which
8836 // side is the base.
8837 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8838 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8839 : !EvaluateInteger(SubExpr, Index, Info)) {
8840 if (!Info.noteFailure())
8841 return false;
8842 Success = false;
8843 }
8844 }
8845
8846 return Success &&
8847 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8848}
8849
8850bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8851 return evaluatePointer(E->getSubExpr(), Result);
8852}
8853
8854bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8855 if (!Visit(E->getSubExpr()))
8856 return false;
8857 // __real is a no-op on scalar lvalues.
8858 if (E->getSubExpr()->getType()->isAnyComplexType())
8859 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8860 return true;
8861}
8862
8863bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8864 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8865 "lvalue __imag__ on scalar?");
8866 if (!Visit(E->getSubExpr()))
8867 return false;
8868 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8869 return true;
8870}
8871
8872bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8873 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8874 return Error(UO);
8875
8876 if (!this->Visit(UO->getSubExpr()))
8877 return false;
8878
8879 return handleIncDec(
8880 this->Info, UO, Result, UO->getSubExpr()->getType(),
8881 UO->isIncrementOp(), nullptr);
8882}
8883
8884bool LValueExprEvaluator::VisitCompoundAssignOperator(
8885 const CompoundAssignOperator *CAO) {
8886 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8887 return Error(CAO);
8888
8889 bool Success = true;
8890
8891 // C++17 onwards require that we evaluate the RHS first.
8892 APValue RHS;
8893 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8894 if (!Info.noteFailure())
8895 return false;
8896 Success = false;
8897 }
8898
8899 // The overall lvalue result is the result of evaluating the LHS.
8900 if (!this->Visit(CAO->getLHS()) || !Success)
8901 return false;
8902
8904 this->Info, CAO,
8905 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8906 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8907}
8908
8909bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8910 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8911 return Error(E);
8912
8913 bool Success = true;
8914
8915 // C++17 onwards require that we evaluate the RHS first.
8916 APValue NewVal;
8917 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8918 if (!Info.noteFailure())
8919 return false;
8920 Success = false;
8921 }
8922
8923 if (!this->Visit(E->getLHS()) || !Success)
8924 return false;
8925
8926 if (Info.getLangOpts().CPlusPlus20 &&
8927 !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8928 return false;
8929
8930 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8931 NewVal);
8932}
8933
8934//===----------------------------------------------------------------------===//
8935// Pointer Evaluation
8936//===----------------------------------------------------------------------===//
8937
8938/// Attempts to compute the number of bytes available at the pointer
8939/// returned by a function with the alloc_size attribute. Returns true if we
8940/// were successful. Places an unsigned number into `Result`.
8941///
8942/// This expects the given CallExpr to be a call to a function with an
8943/// alloc_size attribute.
8945 const CallExpr *Call,
8946 llvm::APInt &Result) {
8947 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8948
8949 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8950 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8951 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8952 if (Call->getNumArgs() <= SizeArgNo)
8953 return false;
8954
8955 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8958 return false;
8959 Into = ExprResult.Val.getInt();
8960 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8961 return false;
8962 Into = Into.zext(BitsInSizeT);
8963 return true;
8964 };
8965
8966 APSInt SizeOfElem;
8967 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8968 return false;
8969
8970 if (!AllocSize->getNumElemsParam().isValid()) {
8971 Result = std::move(SizeOfElem);
8972 return true;
8973 }
8974
8975 APSInt NumberOfElems;
8976 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8977 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8978 return false;
8979
8980 bool Overflow;
8981 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8982 if (Overflow)
8983 return false;
8984
8985 Result = std::move(BytesAvailable);
8986 return true;
8987}
8988
8989/// Convenience function. LVal's base must be a call to an alloc_size
8990/// function.
8992 const LValue &LVal,
8993 llvm::APInt &Result) {
8994 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8995 "Can't get the size of a non alloc_size function");
8996 const auto *Base = LVal.getLValueBase().get<const Expr *>();
8997 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8998 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8999}
9000
9001/// Attempts to evaluate the given LValueBase as the result of a call to
9002/// a function with the alloc_size attribute. If it was possible to do so, this
9003/// function will return true, make Result's Base point to said function call,
9004/// and mark Result's Base as invalid.
9006 LValue &Result) {
9007 if (Base.isNull())
9008 return false;
9009
9010 // Because we do no form of static analysis, we only support const variables.
9011 //
9012 // Additionally, we can't support parameters, nor can we support static
9013 // variables (in the latter case, use-before-assign isn't UB; in the former,
9014 // we have no clue what they'll be assigned to).
9015 const auto *VD =
9016 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9017 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9018 return false;
9019
9020 const Expr *Init = VD->getAnyInitializer();
9021 if (!Init || Init->getType().isNull())
9022 return false;
9023
9024 const Expr *E = Init->IgnoreParens();
9025 if (!tryUnwrapAllocSizeCall(E))
9026 return false;
9027
9028 // Store E instead of E unwrapped so that the type of the LValue's base is
9029 // what the user wanted.
9030 Result.setInvalid(E);
9031
9032 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9033 Result.addUnsizedArray(Info, E, Pointee);
9034 return true;
9035}
9036
9037namespace {
9038class PointerExprEvaluator
9039 : public ExprEvaluatorBase<PointerExprEvaluator> {
9040 LValue &Result;
9041 bool InvalidBaseOK;
9042
9043 bool Success(const Expr *E) {
9044 Result.set(E);
9045 return true;
9046 }
9047
9048 bool evaluateLValue(const Expr *E, LValue &Result) {
9049 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9050 }
9051
9052 bool evaluatePointer(const Expr *E, LValue &Result) {
9053 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9054 }
9055
9056 bool visitNonBuiltinCallExpr(const CallExpr *E);
9057public:
9058
9059 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9060 : ExprEvaluatorBaseTy(info), Result(Result),
9061 InvalidBaseOK(InvalidBaseOK) {}
9062
9063 bool Success(const APValue &V, const Expr *E) {
9064 Result.setFrom(Info.Ctx, V);
9065 return true;
9066 }
9067 bool ZeroInitialization(const Expr *E) {
9068 Result.setNull(Info.Ctx, E->getType());
9069 return true;
9070 }
9071
9072 bool VisitBinaryOperator(const BinaryOperator *E);
9073 bool VisitCastExpr(const CastExpr* E);
9074 bool VisitUnaryAddrOf(const UnaryOperator *E);
9075 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9076 { return Success(E); }
9077 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9079 return Success(E);
9080 if (Info.noteFailure())
9081 EvaluateIgnoredValue(Info, E->getSubExpr());
9082 return Error(E);
9083 }
9084 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9085 { return Success(E); }
9086 bool VisitCallExpr(const CallExpr *E);
9087 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9088 bool VisitBlockExpr(const BlockExpr *E) {
9089 if (!E->getBlockDecl()->hasCaptures())
9090 return Success(E);
9091 return Error(E);
9092 }
9093 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9094 auto DiagnoseInvalidUseOfThis = [&] {
9095 if (Info.getLangOpts().CPlusPlus11)
9096 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9097 else
9098 Info.FFDiag(E);
9099 };
9100
9101 // Can't look at 'this' when checking a potential constant expression.
9102 if (Info.checkingPotentialConstantExpression())
9103 return false;
9104
9105 bool IsExplicitLambda =
9106 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9107 if (!IsExplicitLambda) {
9108 if (!Info.CurrentCall->This) {
9109 DiagnoseInvalidUseOfThis();
9110 return false;
9111 }
9112
9113 Result = *Info.CurrentCall->This;
9114 }
9115
9116 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9117 // Ensure we actually have captured 'this'. If something was wrong with
9118 // 'this' capture, the error would have been previously reported.
9119 // Otherwise we can be inside of a default initialization of an object
9120 // declared by lambda's body, so no need to return false.
9121 if (!Info.CurrentCall->LambdaThisCaptureField) {
9122 if (IsExplicitLambda && !Info.CurrentCall->This) {
9123 DiagnoseInvalidUseOfThis();
9124 return false;
9125 }
9126
9127 return true;
9128 }
9129
9130 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9131 return HandleLambdaCapture(
9132 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9133 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9134 }
9135 return true;
9136 }
9137
9138 bool VisitCXXNewExpr(const CXXNewExpr *E);
9139
9140 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9141 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9142 APValue LValResult = E->EvaluateInContext(
9143 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9144 Result.setFrom(Info.Ctx, LValResult);
9145 return true;
9146 }
9147
9148 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9149 std::string ResultStr = E->ComputeName(Info.Ctx);
9150
9151 QualType CharTy = Info.Ctx.CharTy.withConst();
9152 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9153 ResultStr.size() + 1);
9154 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9155 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9156
9157 StringLiteral *SL =
9158 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9159 /*Pascal*/ false, ArrayTy, E->getLocation());
9160
9161 evaluateLValue(SL, Result);
9162 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9163 return true;
9164 }
9165
9166 // FIXME: Missing: @protocol, @selector
9167};
9168} // end anonymous namespace
9169
9170static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9171 bool InvalidBaseOK) {
9172 assert(!E->isValueDependent());
9173 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9174 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9175}
9176
9177bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9178 if (E->getOpcode() != BO_Add &&
9179 E->getOpcode() != BO_Sub)
9180 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9181
9182 const Expr *PExp = E->getLHS();
9183 const Expr *IExp = E->getRHS();
9184 if (IExp->getType()->isPointerType())
9185 std::swap(PExp, IExp);
9186
9187 bool EvalPtrOK = evaluatePointer(PExp, Result);
9188 if (!EvalPtrOK && !Info.noteFailure())
9189 return false;
9190
9191 llvm::APSInt Offset;
9192 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9193 return false;
9194
9195 if (E->getOpcode() == BO_Sub)
9196 negateAsSigned(Offset);
9197
9198 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9199 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9200}
9201
9202bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9203 return evaluateLValue(E->getSubExpr(), Result);
9204}
9205
9206// Is the provided decl 'std::source_location::current'?
9208 if (!FD)
9209 return false;
9210 const IdentifierInfo *FnII = FD->getIdentifier();
9211 if (!FnII || !FnII->isStr("current"))
9212 return false;
9213
9214 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9215 if (!RD)
9216 return false;
9217
9218 const IdentifierInfo *ClassII = RD->getIdentifier();
9219 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9220}
9221
9222bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9223 const Expr *SubExpr = E->getSubExpr();
9224
9225 switch (E->getCastKind()) {
9226 default:
9227 break;
9228 case CK_BitCast:
9229 case CK_CPointerToObjCPointerCast:
9230 case CK_BlockPointerToObjCPointerCast:
9231 case CK_AnyPointerToBlockPointerCast:
9232 case CK_AddressSpaceConversion:
9233 if (!Visit(SubExpr))
9234 return false;
9235 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9236 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9237 // also static_casts, but we disallow them as a resolution to DR1312.
9238 if (!E->getType()->isVoidPointerType()) {
9239 // In some circumstances, we permit casting from void* to cv1 T*, when the
9240 // actual pointee object is actually a cv2 T.
9241 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9242 !Result.IsNullPtr;
9243 bool VoidPtrCastMaybeOK =
9244 Result.IsNullPtr ||
9245 (HasValidResult &&
9246 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9247 E->getType()->getPointeeType()));
9248 // 1. We'll allow it in std::allocator::allocate, and anything which that
9249 // calls.
9250 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9251 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9252 // We'll allow it in the body of std::source_location::current. GCC's
9253 // implementation had a parameter of type `void*`, and casts from
9254 // that back to `const __impl*` in its body.
9255 if (VoidPtrCastMaybeOK &&
9256 (Info.getStdAllocatorCaller("allocate") ||
9257 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9258 Info.getLangOpts().CPlusPlus26)) {
9259 // Permitted.
9260 } else {
9261 if (SubExpr->getType()->isVoidPointerType() &&
9262 Info.getLangOpts().CPlusPlus) {
9263 if (HasValidResult)
9264 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9265 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9266 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9267 << E->getType()->getPointeeType();
9268 else
9269 CCEDiag(E, diag::note_constexpr_invalid_cast)
9270 << 3 << SubExpr->getType();
9271 } else
9272 CCEDiag(E, diag::note_constexpr_invalid_cast)
9273 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9274 Result.Designator.setInvalid();
9275 }
9276 }
9277 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9278 ZeroInitialization(E);
9279 return true;
9280
9281 case CK_DerivedToBase:
9282 case CK_UncheckedDerivedToBase:
9283 if (!evaluatePointer(E->getSubExpr(), Result))
9284 return false;
9285 if (!Result.Base && Result.Offset.isZero())
9286 return true;
9287
9288 // Now figure out the necessary offset to add to the base LV to get from
9289 // the derived class to the base class.
9290 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9291 castAs<PointerType>()->getPointeeType(),
9292 Result);
9293
9294 case CK_BaseToDerived:
9295 if (!Visit(E->getSubExpr()))
9296 return false;
9297 if (!Result.Base && Result.Offset.isZero())
9298 return true;
9299 return HandleBaseToDerivedCast(Info, E, Result);
9300
9301 case CK_Dynamic:
9302 if (!Visit(E->getSubExpr()))
9303 return false;
9304 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9305
9306 case CK_NullToPointer:
9307 VisitIgnoredValue(E->getSubExpr());
9308 return ZeroInitialization(E);
9309
9310 case CK_IntegralToPointer: {
9311 CCEDiag(E, diag::note_constexpr_invalid_cast)
9312 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9313
9314 APValue Value;
9315 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9316 break;
9317
9318 if (Value.isInt()) {
9319 unsigned Size = Info.Ctx.getTypeSize(E->getType());
9320 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9321 Result.Base = (Expr*)nullptr;
9322 Result.InvalidBase = false;
9323 Result.Offset = CharUnits::fromQuantity(N);
9324 Result.Designator.setInvalid();
9325 Result.IsNullPtr = false;
9326 return true;
9327 } else {
9328 // Cast is of an lvalue, no need to change value.
9329 Result.setFrom(Info.Ctx, Value);
9330 return true;
9331 }
9332 }
9333
9334 case CK_ArrayToPointerDecay: {
9335 if (SubExpr->isGLValue()) {
9336 if (!evaluateLValue(SubExpr, Result))
9337 return false;
9338 } else {
9339 APValue &Value = Info.CurrentCall->createTemporary(
9340 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9341 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9342 return false;
9343 }
9344 // The result is a pointer to the first element of the array.
9345 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9346 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9347 Result.addArray(Info, E, CAT);
9348 else
9349 Result.addUnsizedArray(Info, E, AT->getElementType());
9350 return true;
9351 }
9352
9353 case CK_FunctionToPointerDecay:
9354 return evaluateLValue(SubExpr, Result);
9355
9356 case CK_LValueToRValue: {
9357 LValue LVal;
9358 if (!evaluateLValue(E->getSubExpr(), LVal))
9359 return false;
9360
9361 APValue RVal;
9362 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9364 LVal, RVal))
9365 return InvalidBaseOK &&
9366 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9367 return Success(RVal, E);
9368 }
9369 }
9370
9371 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9372}
9373
9374static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
9375 UnaryExprOrTypeTrait ExprKind) {
9376 // C++ [expr.alignof]p3:
9377 // When alignof is applied to a reference type, the result is the
9378 // alignment of the referenced type.
9379 T = T.getNonReferenceType();
9380
9381 if (T.getQualifiers().hasUnaligned())
9382 return CharUnits::One();
9383
9384 const bool AlignOfReturnsPreferred =
9385 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9386
9387 // __alignof is defined to return the preferred alignment.
9388 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9389 // as well.
9390 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9391 return Info.Ctx.toCharUnitsFromBits(
9392 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9393 // alignof and _Alignof are defined to return the ABI alignment.
9394 else if (ExprKind == UETT_AlignOf)
9395 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9396 else
9397 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9398}
9399
9400static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9401 UnaryExprOrTypeTrait ExprKind) {
9402 E = E->IgnoreParens();
9403
9404 // The kinds of expressions that we have special-case logic here for
9405 // should be kept up to date with the special checks for those
9406 // expressions in Sema.
9407
9408 // alignof decl is always accepted, even if it doesn't make sense: we default
9409 // to 1 in those cases.
9410 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9411 return Info.Ctx.getDeclAlign(DRE->getDecl(),
9412 /*RefAsPointee*/true);
9413
9414 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9415 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9416 /*RefAsPointee*/true);
9417
9418 return GetAlignOfType(Info, E->getType(), ExprKind);
9419}
9420
9421static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9422 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9423 return Info.Ctx.getDeclAlign(VD);
9424 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9425 return GetAlignOfExpr(Info, E, UETT_AlignOf);
9426 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9427}
9428
9429/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9430/// __builtin_is_aligned and __builtin_assume_aligned.
9431static bool getAlignmentArgument(const Expr *E, QualType ForType,
9432 EvalInfo &Info, APSInt &Alignment) {
9433 if (!EvaluateInteger(E, Alignment, Info))
9434 return false;
9435 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9436 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9437 return false;
9438 }
9439 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9440 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9441 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9442 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9443 << MaxValue << ForType << Alignment;
9444 return false;
9445 }
9446 // Ensure both alignment and source value have the same bit width so that we
9447 // don't assert when computing the resulting value.
9448 APSInt ExtAlignment =
9449 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9450 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9451 "Alignment should not be changed by ext/trunc");
9452 Alignment = ExtAlignment;
9453 assert(Alignment.getBitWidth() == SrcWidth);
9454 return true;
9455}
9456
9457// To be clear: this happily visits unsupported builtins. Better name welcomed.
9458bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9459 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9460 return true;
9461
9462 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9463 return false;
9464
9465 Result.setInvalid(E);
9466 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9467 Result.addUnsizedArray(Info, E, PointeeTy);
9468 return true;
9469}
9470
9471bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9472 if (!IsConstantEvaluatedBuiltinCall(E))
9473 return visitNonBuiltinCallExpr(E);
9474 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9475}
9476
9477// Determine if T is a character type for which we guarantee that
9478// sizeof(T) == 1.
9480 return T->isCharType() || T->isChar8Type();
9481}
9482
9483bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9484 unsigned BuiltinOp) {
9485 if (IsNoOpCall(E))
9486 return Success(E);
9487
9488 switch (BuiltinOp) {
9489 case Builtin::BIaddressof:
9490 case Builtin::BI__addressof:
9491 case Builtin::BI__builtin_addressof:
9492 return evaluateLValue(E->getArg(0), Result);
9493 case Builtin::BI__builtin_assume_aligned: {
9494 // We need to be very careful here because: if the pointer does not have the
9495 // asserted alignment, then the behavior is undefined, and undefined
9496 // behavior is non-constant.
9497 if (!evaluatePointer(E->getArg(0), Result))
9498 return false;
9499
9500 LValue OffsetResult(Result);
9501 APSInt Alignment;
9502 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9503 Alignment))
9504 return false;
9505 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9506
9507 if (E->getNumArgs() > 2) {
9508 APSInt Offset;
9509 if (!EvaluateInteger(E->getArg(2), Offset, Info))
9510 return false;
9511
9512 int64_t AdditionalOffset = -Offset.getZExtValue();
9513 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9514 }
9515
9516 // If there is a base object, then it must have the correct alignment.
9517 if (OffsetResult.Base) {
9518 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9519
9520 if (BaseAlignment < Align) {
9521 Result.Designator.setInvalid();
9522 // FIXME: Add support to Diagnostic for long / long long.
9523 CCEDiag(E->getArg(0),
9524 diag::note_constexpr_baa_insufficient_alignment) << 0
9525 << (unsigned)BaseAlignment.getQuantity()
9526 << (unsigned)Align.getQuantity();
9527 return false;
9528 }
9529 }
9530
9531 // The offset must also have the correct alignment.
9532 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9533 Result.Designator.setInvalid();
9534
9535 (OffsetResult.Base
9536 ? CCEDiag(E->getArg(0),
9537 diag::note_constexpr_baa_insufficient_alignment) << 1
9538 : CCEDiag(E->getArg(0),
9539 diag::note_constexpr_baa_value_insufficient_alignment))
9540 << (int)OffsetResult.Offset.getQuantity()
9541 << (unsigned)Align.getQuantity();
9542 return false;
9543 }
9544
9545 return true;
9546 }
9547 case Builtin::BI__builtin_align_up:
9548 case Builtin::BI__builtin_align_down: {
9549 if (!evaluatePointer(E->getArg(0), Result))
9550 return false;
9551 APSInt Alignment;
9552 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9553 Alignment))
9554 return false;
9555 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9556 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9557 // For align_up/align_down, we can return the same value if the alignment
9558 // is known to be greater or equal to the requested value.
9559 if (PtrAlign.getQuantity() >= Alignment)
9560 return true;
9561
9562 // The alignment could be greater than the minimum at run-time, so we cannot
9563 // infer much about the resulting pointer value. One case is possible:
9564 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9565 // can infer the correct index if the requested alignment is smaller than
9566 // the base alignment so we can perform the computation on the offset.
9567 if (BaseAlignment.getQuantity() >= Alignment) {
9568 assert(Alignment.getBitWidth() <= 64 &&
9569 "Cannot handle > 64-bit address-space");
9570 uint64_t Alignment64 = Alignment.getZExtValue();
9572 BuiltinOp == Builtin::BI__builtin_align_down
9573 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9574 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9575 Result.adjustOffset(NewOffset - Result.Offset);
9576 // TODO: diagnose out-of-bounds values/only allow for arrays?
9577 return true;
9578 }
9579 // Otherwise, we cannot constant-evaluate the result.
9580 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9581 << Alignment;
9582 return false;
9583 }
9584 case Builtin::BI__builtin_operator_new:
9585 return HandleOperatorNewCall(Info, E, Result);
9586 case Builtin::BI__builtin_launder:
9587 return evaluatePointer(E->getArg(0), Result);
9588 case Builtin::BIstrchr:
9589 case Builtin::BIwcschr:
9590 case Builtin::BImemchr:
9591 case Builtin::BIwmemchr:
9592 if (Info.getLangOpts().CPlusPlus11)
9593 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9594 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9595 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9596 else
9597 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9598 [[fallthrough]];
9599 case Builtin::BI__builtin_strchr:
9600 case Builtin::BI__builtin_wcschr:
9601 case Builtin::BI__builtin_memchr:
9602 case Builtin::BI__builtin_char_memchr:
9603 case Builtin::BI__builtin_wmemchr: {
9604 if (!Visit(E->getArg(0)))
9605 return false;
9606 APSInt Desired;
9607 if (!EvaluateInteger(E->getArg(1), Desired, Info))
9608 return false;
9609 uint64_t MaxLength = uint64_t(-1);
9610 if (BuiltinOp != Builtin::BIstrchr &&
9611 BuiltinOp != Builtin::BIwcschr &&
9612 BuiltinOp != Builtin::BI__builtin_strchr &&
9613 BuiltinOp != Builtin::BI__builtin_wcschr) {
9614 APSInt N;
9615 if (!EvaluateInteger(E->getArg(2), N, Info))
9616 return false;
9617 MaxLength = N.getZExtValue();
9618 }
9619 // We cannot find the value if there are no candidates to match against.
9620 if (MaxLength == 0u)
9621 return ZeroInitialization(E);
9622 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9623 Result.Designator.Invalid)
9624 return false;
9625 QualType CharTy = Result.Designator.getType(Info.Ctx);
9626 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9627 BuiltinOp == Builtin::BI__builtin_memchr;
9628 assert(IsRawByte ||
9629 Info.Ctx.hasSameUnqualifiedType(
9630 CharTy, E->getArg(0)->getType()->getPointeeType()));
9631 // Pointers to const void may point to objects of incomplete type.
9632 if (IsRawByte && CharTy->isIncompleteType()) {
9633 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9634 return false;
9635 }
9636 // Give up on byte-oriented matching against multibyte elements.
9637 // FIXME: We can compare the bytes in the correct order.
9638 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9639 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9640 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
9641 << CharTy;
9642 return false;
9643 }
9644 // Figure out what value we're actually looking for (after converting to
9645 // the corresponding unsigned type if necessary).
9646 uint64_t DesiredVal;
9647 bool StopAtNull = false;
9648 switch (BuiltinOp) {
9649 case Builtin::BIstrchr:
9650 case Builtin::BI__builtin_strchr:
9651 // strchr compares directly to the passed integer, and therefore
9652 // always fails if given an int that is not a char.
9653 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9654 E->getArg(1)->getType(),
9655 Desired),
9656 Desired))
9657 return ZeroInitialization(E);
9658 StopAtNull = true;
9659 [[fallthrough]];
9660 case Builtin::BImemchr:
9661 case Builtin::BI__builtin_memchr:
9662 case Builtin::BI__builtin_char_memchr:
9663 // memchr compares by converting both sides to unsigned char. That's also
9664 // correct for strchr if we get this far (to cope with plain char being
9665 // unsigned in the strchr case).
9666 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9667 break;
9668
9669 case Builtin::BIwcschr:
9670 case Builtin::BI__builtin_wcschr:
9671 StopAtNull = true;
9672 [[fallthrough]];
9673 case Builtin::BIwmemchr:
9674 case Builtin::BI__builtin_wmemchr:
9675 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9676 DesiredVal = Desired.getZExtValue();
9677 break;
9678 }
9679
9680 for (; MaxLength; --MaxLength) {
9681 APValue Char;
9682 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9683 !Char.isInt())
9684 return false;
9685 if (Char.getInt().getZExtValue() == DesiredVal)
9686 return true;
9687 if (StopAtNull && !Char.getInt())
9688 break;
9689 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9690 return false;
9691 }
9692 // Not found: return nullptr.
9693 return ZeroInitialization(E);
9694 }
9695
9696 case Builtin::BImemcpy:
9697 case Builtin::BImemmove:
9698 case Builtin::BIwmemcpy:
9699 case Builtin::BIwmemmove:
9700 if (Info.getLangOpts().CPlusPlus11)
9701 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9702 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9703 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9704 else
9705 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9706 [[fallthrough]];
9707 case Builtin::BI__builtin_memcpy:
9708 case Builtin::BI__builtin_memmove:
9709 case Builtin::BI__builtin_wmemcpy:
9710 case Builtin::BI__builtin_wmemmove: {
9711 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9712 BuiltinOp == Builtin::BIwmemmove ||
9713 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9714 BuiltinOp == Builtin::BI__builtin_wmemmove;
9715 bool Move = BuiltinOp == Builtin::BImemmove ||
9716 BuiltinOp == Builtin::BIwmemmove ||
9717 BuiltinOp == Builtin::BI__builtin_memmove ||
9718 BuiltinOp == Builtin::BI__builtin_wmemmove;
9719
9720 // The result of mem* is the first argument.
9721 if (!Visit(E->getArg(0)))
9722 return false;
9723 LValue Dest = Result;
9724
9725 LValue Src;
9726 if (!EvaluatePointer(E->getArg(1), Src, Info))
9727 return false;
9728
9729 APSInt N;
9730 if (!EvaluateInteger(E->getArg(2), N, Info))
9731 return false;
9732 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9733
9734 // If the size is zero, we treat this as always being a valid no-op.
9735 // (Even if one of the src and dest pointers is null.)
9736 if (!N)
9737 return true;
9738
9739 // Otherwise, if either of the operands is null, we can't proceed. Don't
9740 // try to determine the type of the copied objects, because there aren't
9741 // any.
9742 if (!Src.Base || !Dest.Base) {
9743 APValue Val;
9744 (!Src.Base ? Src : Dest).moveInto(Val);
9745 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9746 << Move << WChar << !!Src.Base
9747 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9748 return false;
9749 }
9750 if (Src.Designator.Invalid || Dest.Designator.Invalid)
9751 return false;
9752
9753 // We require that Src and Dest are both pointers to arrays of
9754 // trivially-copyable type. (For the wide version, the designator will be
9755 // invalid if the designated object is not a wchar_t.)
9756 QualType T = Dest.Designator.getType(Info.Ctx);
9757 QualType SrcT = Src.Designator.getType(Info.Ctx);
9758 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9759 // FIXME: Consider using our bit_cast implementation to support this.
9760 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9761 return false;
9762 }
9763 if (T->isIncompleteType()) {
9764 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9765 return false;
9766 }
9767 if (!T.isTriviallyCopyableType(Info.Ctx)) {
9768 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9769 return false;
9770 }
9771
9772 // Figure out how many T's we're copying.
9773 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9774 if (TSize == 0)
9775 return false;
9776 if (!WChar) {
9777 uint64_t Remainder;
9778 llvm::APInt OrigN = N;
9779 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9780 if (Remainder) {
9781 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9782 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9783 << (unsigned)TSize;
9784 return false;
9785 }
9786 }
9787
9788 // Check that the copying will remain within the arrays, just so that we
9789 // can give a more meaningful diagnostic. This implicitly also checks that
9790 // N fits into 64 bits.
9791 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9792 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9793 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9794 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9795 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9796 << toString(N, 10, /*Signed*/false);
9797 return false;
9798 }
9799 uint64_t NElems = N.getZExtValue();
9800 uint64_t NBytes = NElems * TSize;
9801
9802 // Check for overlap.
9803 int Direction = 1;
9804 if (HasSameBase(Src, Dest)) {
9805 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9806 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9807 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9808 // Dest is inside the source region.
9809 if (!Move) {
9810 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9811 return false;
9812 }
9813 // For memmove and friends, copy backwards.
9814 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9815 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9816 return false;
9817 Direction = -1;
9818 } else if (!Move && SrcOffset >= DestOffset &&
9819 SrcOffset - DestOffset < NBytes) {
9820 // Src is inside the destination region for memcpy: invalid.
9821 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9822 return false;
9823 }
9824 }
9825
9826 while (true) {
9827 APValue Val;
9828 // FIXME: Set WantObjectRepresentation to true if we're copying a
9829 // char-like type?
9830 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9831 !handleAssignment(Info, E, Dest, T, Val))
9832 return false;
9833 // Do not iterate past the last element; if we're copying backwards, that
9834 // might take us off the start of the array.
9835 if (--NElems == 0)
9836 return true;
9837 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9838 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9839 return false;
9840 }
9841 }
9842
9843 default:
9844 return false;
9845 }
9846}
9847
9848static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9849 APValue &Result, const InitListExpr *ILE,
9850 QualType AllocType);
9851static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9852 APValue &Result,
9853 const CXXConstructExpr *CCE,
9854 QualType AllocType);
9855
9856bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9857 if (!Info.getLangOpts().CPlusPlus20)
9858 Info.CCEDiag(E, diag::note_constexpr_new);
9859
9860 // We cannot speculatively evaluate a delete expression.
9861 if (Info.SpeculativeEvaluationDepth)
9862 return false;
9863
9864 FunctionDecl *OperatorNew = E->getOperatorNew();
9865
9866 bool IsNothrow = false;
9867 bool IsPlacement = false;
9868 if (OperatorNew->isReservedGlobalPlacementOperator() &&
9869 Info.CurrentCall->isStdFunction() && !E->isArray()) {
9870 // FIXME Support array placement new.
9871 assert(E->getNumPlacementArgs() == 1);
9872 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9873 return false;
9874 if (Result.Designator.Invalid)
9875 return false;
9876 IsPlacement = true;
9877 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9878 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9879 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9880 return false;
9881 } else if (E->getNumPlacementArgs()) {
9882 // The only new-placement list we support is of the form (std::nothrow).
9883 //
9884 // FIXME: There is no restriction on this, but it's not clear that any
9885 // other form makes any sense. We get here for cases such as:
9886 //
9887 // new (std::align_val_t{N}) X(int)
9888 //
9889 // (which should presumably be valid only if N is a multiple of
9890 // alignof(int), and in any case can't be deallocated unless N is
9891 // alignof(X) and X has new-extended alignment).
9892 if (E->getNumPlacementArgs() != 1 ||
9893 !E->getPlacementArg(0)->getType()->isNothrowT())
9894 return Error(E, diag::note_constexpr_new_placement);
9895
9896 LValue Nothrow;
9897 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9898 return false;
9899 IsNothrow = true;
9900 }
9901
9902 const Expr *Init = E->getInitializer();
9903 const InitListExpr *ResizedArrayILE = nullptr;
9904 const CXXConstructExpr *ResizedArrayCCE = nullptr;
9905 bool ValueInit = false;
9906
9907 QualType AllocType = E->getAllocatedType();
9908 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
9909 const Expr *Stripped = *ArraySize;
9910 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9911 Stripped = ICE->getSubExpr())
9912 if (ICE->getCastKind() != CK_NoOp &&
9913 ICE->getCastKind() != CK_IntegralCast)
9914 break;
9915
9916 llvm::APSInt ArrayBound;
9917 if (!EvaluateInteger(Stripped, ArrayBound, Info))
9918 return false;
9919
9920 // C++ [expr.new]p9:
9921 // The expression is erroneous if:
9922 // -- [...] its value before converting to size_t [or] applying the
9923 // second standard conversion sequence is less than zero
9924 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9925 if (IsNothrow)
9926 return ZeroInitialization(E);
9927
9928 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9929 << ArrayBound << (*ArraySize)->getSourceRange();
9930 return false;
9931 }
9932
9933 // -- its value is such that the size of the allocated object would
9934 // exceed the implementation-defined limit
9935 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
9937 Info.Ctx, AllocType, ArrayBound),
9938 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
9939 if (IsNothrow)
9940 return ZeroInitialization(E);
9941 return false;
9942 }
9943
9944 // -- the new-initializer is a braced-init-list and the number of
9945 // array elements for which initializers are provided [...]
9946 // exceeds the number of elements to initialize
9947 if (!Init) {
9948 // No initialization is performed.
9949 } else if (isa<CXXScalarValueInitExpr>(Init) ||
9950 isa<ImplicitValueInitExpr>(Init)) {
9951 ValueInit = true;
9952 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9953 ResizedArrayCCE = CCE;
9954 } else {
9955 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9956 assert(CAT && "unexpected type for array initializer");
9957
9958 unsigned Bits =
9959 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
9960 llvm::APInt InitBound = CAT->getSize().zext(Bits);
9961 llvm::APInt AllocBound = ArrayBound.zext(Bits);
9962 if (InitBound.ugt(AllocBound)) {
9963 if (IsNothrow)
9964 return ZeroInitialization(E);
9965
9966 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9967 << toString(AllocBound, 10, /*Signed=*/false)
9968 << toString(InitBound, 10, /*Signed=*/false)
9969 << (*ArraySize)->getSourceRange();
9970 return false;
9971 }
9972
9973 // If the sizes differ, we must have an initializer list, and we need
9974 // special handling for this case when we initialize.
9975 if (InitBound != AllocBound)
9976 ResizedArrayILE = cast<InitListExpr>(Init);
9977 }
9978
9979 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9980 ArraySizeModifier::Normal, 0);
9981 } else {
9982 assert(!AllocType->isArrayType() &&
9983 "array allocation with non-array new");
9984 }
9985
9986 APValue *Val;
9987 if (IsPlacement) {
9989 struct FindObjectHandler {
9990 EvalInfo &Info;
9991 const Expr *E;
9992 QualType AllocType;
9993 const AccessKinds AccessKind;
9994 APValue *Value;
9995
9996 typedef bool result_type;
9997 bool failed() { return false; }
9998 bool found(APValue &Subobj, QualType SubobjType) {
9999 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10000 // old name of the object to be used to name the new object.
10001 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
10002 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
10003 SubobjType << AllocType;
10004 return false;
10005 }
10006 Value = &Subobj;
10007 return true;
10008 }
10009 bool found(APSInt &Value, QualType SubobjType) {
10010 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10011 return false;
10012 }
10013 bool found(APFloat &Value, QualType SubobjType) {
10014 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10015 return false;
10016 }
10017 } Handler = {Info, E, AllocType, AK, nullptr};
10018
10019 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10020 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10021 return false;
10022
10023 Val = Handler.Value;
10024
10025 // [basic.life]p1:
10026 // The lifetime of an object o of type T ends when [...] the storage
10027 // which the object occupies is [...] reused by an object that is not
10028 // nested within o (6.6.2).
10029 *Val = APValue();
10030 } else {
10031 // Perform the allocation and obtain a pointer to the resulting object.
10032 Val = Info.createHeapAlloc(E, AllocType, Result);
10033 if (!Val)
10034 return false;
10035 }
10036
10037 if (ValueInit) {
10038 ImplicitValueInitExpr VIE(AllocType);
10039 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10040 return false;
10041 } else if (ResizedArrayILE) {
10042 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10043 AllocType))
10044 return false;
10045 } else if (ResizedArrayCCE) {
10046 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10047 AllocType))
10048 return false;
10049 } else if (Init) {
10050 if (!EvaluateInPlace(*Val, Info, Result, Init))
10051 return false;
10052 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10053 return false;
10054 }
10055
10056 // Array new returns a pointer to the first element, not a pointer to the
10057 // array.
10058 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10059 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10060
10061 return true;
10062}
10063//===----------------------------------------------------------------------===//
10064// Member Pointer Evaluation
10065//===----------------------------------------------------------------------===//
10066
10067namespace {
10068class MemberPointerExprEvaluator
10069 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10070 MemberPtr &Result;
10071
10072 bool Success(const ValueDecl *D) {
10073 Result = MemberPtr(D);
10074 return true;
10075 }
10076public:
10077
10078 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10079 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10080
10081 bool Success(const APValue &V, const Expr *E) {
10082 Result.setFrom(V);
10083 return true;
10084 }
10085 bool ZeroInitialization(const Expr *E) {
10086 return Success((const ValueDecl*)nullptr);
10087 }
10088
10089 bool VisitCastExpr(const CastExpr *E);
10090 bool VisitUnaryAddrOf(const UnaryOperator *E);
10091};
10092} // end anonymous namespace
10093
10094static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10095 EvalInfo &Info) {
10096 assert(!E->isValueDependent());
10097 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10098 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10099}
10100
10101bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10102 switch (E->getCastKind()) {
10103 default:
10104 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10105
10106 case CK_NullToMemberPointer:
10107 VisitIgnoredValue(E->getSubExpr());
10108 return ZeroInitialization(E);
10109
10110 case CK_BaseToDerivedMemberPointer: {
10111 if (!Visit(E->getSubExpr()))
10112 return false;
10113 if (E->path_empty())
10114 return true;
10115 // Base-to-derived member pointer casts store the path in derived-to-base
10116 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10117 // the wrong end of the derived->base arc, so stagger the path by one class.
10118 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10119 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10120 PathI != PathE; ++PathI) {
10121 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10122 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10123 if (!Result.castToDerived(Derived))
10124 return Error(E);
10125 }
10126 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
10127 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
10128 return Error(E);
10129 return true;
10130 }
10131
10132 case CK_DerivedToBaseMemberPointer:
10133 if (!Visit(E->getSubExpr()))
10134 return false;
10135 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10136 PathE = E->path_end(); PathI != PathE; ++PathI) {
10137 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10138 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10139 if (!Result.castToBase(Base))
10140 return Error(E);
10141 }
10142 return true;
10143 }
10144}
10145
10146bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10147 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10148 // member can be formed.
10149 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10150}
10151
10152//===----------------------------------------------------------------------===//
10153// Record Evaluation
10154//===----------------------------------------------------------------------===//
10155
10156namespace {
10157 class RecordExprEvaluator
10158 : public ExprEvaluatorBase<RecordExprEvaluator> {
10159 const LValue &This;
10160 APValue &Result;
10161 public:
10162
10163 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10164 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10165
10166 bool Success(const APValue &V, const Expr *E) {
10167 Result = V;
10168 return true;
10169 }
10170 bool ZeroInitialization(const Expr *E) {
10171 return ZeroInitialization(E, E->getType());
10172 }
10173 bool ZeroInitialization(const Expr *E, QualType T);
10174
10175 bool VisitCallExpr(const CallExpr *E) {
10176 return handleCallExpr(E, Result, &This);
10177 }
10178 bool VisitCastExpr(const CastExpr *E);
10179 bool VisitInitListExpr(const InitListExpr *E);
10180 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10181 return VisitCXXConstructExpr(E, E->getType());
10182 }
10183 bool VisitLambdaExpr(const LambdaExpr *E);
10184 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10185 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10186 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10187 bool VisitBinCmp(const BinaryOperator *E);
10188 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10189 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10190 ArrayRef<Expr *> Args);
10191 };
10192}
10193
10194/// Perform zero-initialization on an object of non-union class type.
10195/// C++11 [dcl.init]p5:
10196/// To zero-initialize an object or reference of type T means:
10197/// [...]
10198/// -- if T is a (possibly cv-qualified) non-union class type,
10199/// each non-static data member and each base-class subobject is
10200/// zero-initialized
10201static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10202 const RecordDecl *RD,
10203 const LValue &This, APValue &Result) {
10204 assert(!RD->isUnion() && "Expected non-union class type");
10205 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10206 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10207 std::distance(RD->field_begin(), RD->field_end()));
10208
10209 if (RD->isInvalidDecl()) return false;
10210 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10211
10212 if (CD) {
10213 unsigned Index = 0;
10215 End = CD->bases_end(); I != End; ++I, ++Index) {
10216 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10217 LValue Subobject = This;
10218 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10219 return false;
10220 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10221 Result.getStructBase(Index)))
10222 return false;
10223 }
10224 }
10225
10226 for (const auto *I : RD->fields()) {
10227 // -- if T is a reference type, no initialization is performed.
10228 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10229 continue;
10230
10231 LValue Subobject = This;
10232 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10233 return false;
10234
10235 ImplicitValueInitExpr VIE(I->getType());
10236 if (!EvaluateInPlace(
10237 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10238 return false;
10239 }
10240
10241 return true;
10242}
10243
10244bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10245 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
10246 if (RD->isInvalidDecl()) return false;
10247 if (RD->isUnion()) {
10248 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10249 // object's first non-static named data member is zero-initialized
10251 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10252 ++I;
10253 if (I == RD->field_end()) {
10254 Result = APValue((const FieldDecl*)nullptr);
10255 return true;
10256 }
10257
10258 LValue Subobject = This;
10259 if (!HandleLValueMember(Info, E, Subobject, *I))
10260 return false;
10261 Result = APValue(*I);
10262 ImplicitValueInitExpr VIE(I->getType());
10263 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10264 }
10265
10266 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10267 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10268 return false;
10269 }
10270
10271 return HandleClassZeroInitialization(Info, E, RD, This, Result);
10272}
10273
10274bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10275 switch (E->getCastKind()) {
10276 default:
10277 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10278
10279 case CK_ConstructorConversion:
10280 return Visit(E->getSubExpr());
10281
10282 case CK_DerivedToBase:
10283 case CK_UncheckedDerivedToBase: {
10284 APValue DerivedObject;
10285 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10286 return false;
10287 if (!DerivedObject.isStruct())
10288 return Error(E->getSubExpr());
10289
10290 // Derived-to-base rvalue conversion: just slice off the derived part.
10291 APValue *Value = &DerivedObject;
10292 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10293 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10294 PathE = E->path_end(); PathI != PathE; ++PathI) {
10295 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10296 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10297 Value = &Value->getStructBase(getBaseIndex(RD, Base));
10298 RD = Base;
10299 }
10300 Result = *Value;
10301 return true;
10302 }
10303 }
10304}
10305
10306bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10307 if (E->isTransparent())
10308 return Visit(E->getInit(0));
10309 return VisitCXXParenListOrInitListExpr(E, E->inits());
10310}
10311
10312bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10313 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10314 const RecordDecl *RD =
10315 ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10316 if (RD->isInvalidDecl()) return false;
10317 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10318 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10319
10320 EvalInfo::EvaluatingConstructorRAII EvalObj(
10321 Info,
10322 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10323 CXXRD && CXXRD->getNumBases());
10324
10325 if (RD->isUnion()) {
10326 const FieldDecl *Field;
10327 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10328 Field = ILE->getInitializedFieldInUnion();
10329 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10330 Field = PLIE->getInitializedFieldInUnion();
10331 } else {
10332 llvm_unreachable(
10333 "Expression is neither an init list nor a C++ paren list");
10334 }
10335
10336 Result = APValue(Field);
10337 if (!Field)
10338 return true;
10339
10340 // If the initializer list for a union does not contain any elements, the
10341 // first element of the union is value-initialized.
10342 // FIXME: The element should be initialized from an initializer list.
10343 // Is this difference ever observable for initializer lists which
10344 // we don't build?
10345 ImplicitValueInitExpr VIE(Field->getType());
10346 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10347
10348 LValue Subobject = This;
10349 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10350 return false;
10351
10352 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10353 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10354 isa<CXXDefaultInitExpr>(InitExpr));
10355
10356 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10357 if (Field->isBitField())
10358 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10359 Field);
10360 return true;
10361 }
10362
10363 return false;
10364 }
10365
10366 if (!Result.hasValue())
10367 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10368 std::distance(RD->field_begin(), RD->field_end()));
10369 unsigned ElementNo = 0;
10370 bool Success = true;
10371
10372 // Initialize base classes.
10373 if (CXXRD && CXXRD->getNumBases()) {
10374 for (const auto &Base : CXXRD->bases()) {
10375 assert(ElementNo < Args.size() && "missing init for base class");
10376 const Expr *Init = Args[ElementNo];
10377
10378 LValue Subobject = This;
10379 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10380 return false;
10381
10382 APValue &FieldVal = Result.getStructBase(ElementNo);
10383 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10384 if (!Info.noteFailure())
10385 return false;
10386 Success = false;
10387 }
10388 ++ElementNo;
10389 }
10390
10391 EvalObj.finishedConstructingBases();
10392 }
10393
10394 // Initialize members.
10395 for (const auto *Field : RD->fields()) {
10396 // Anonymous bit-fields are not considered members of the class for
10397 // purposes of aggregate initialization.
10398 if (Field->isUnnamedBitField())
10399 continue;
10400
10401 LValue Subobject = This;
10402
10403 bool HaveInit = ElementNo < Args.size();
10404
10405 // FIXME: Diagnostics here should point to the end of the initializer
10406 // list, not the start.
10407 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10408 Subobject, Field, &Layout))
10409 return false;
10410
10411 // Perform an implicit value-initialization for members beyond the end of
10412 // the initializer list.
10413 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10414 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10415
10416 if (Field->getType()->isIncompleteArrayType()) {
10417 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10418 if (!CAT->isZeroSize()) {
10419 // Bail out for now. This might sort of "work", but the rest of the
10420 // code isn't really prepared to handle it.
10421 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10422 return false;
10423 }
10424 }
10425 }
10426
10427 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10428 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10429 isa<CXXDefaultInitExpr>(Init));
10430
10431 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10432 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10433 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10434 FieldVal, Field))) {
10435 if (!Info.noteFailure())
10436 return false;
10437 Success = false;
10438 }
10439 }
10440
10441 EvalObj.finishedConstructingFields();
10442
10443 return Success;
10444}
10445
10446bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10447 QualType T) {
10448 // Note that E's type is not necessarily the type of our class here; we might
10449 // be initializing an array element instead.
10450 const CXXConstructorDecl *FD = E->getConstructor();
10451 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10452
10453 bool ZeroInit = E->requiresZeroInitialization();
10454 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10455 // If we've already performed zero-initialization, we're already done.
10456 if (Result.hasValue())
10457 return true;
10458
10459 if (ZeroInit)
10460 return ZeroInitialization(E, T);
10461
10462 return handleDefaultInitValue(T, Result);
10463 }
10464
10465 const FunctionDecl *Definition = nullptr;
10466 auto Body = FD->getBody(Definition);
10467
10468 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10469 return false;
10470
10471 // Avoid materializing a temporary for an elidable copy/move constructor.
10472 if (E->isElidable() && !ZeroInit) {
10473 // FIXME: This only handles the simplest case, where the source object
10474 // is passed directly as the first argument to the constructor.
10475 // This should also handle stepping though implicit casts and
10476 // and conversion sequences which involve two steps, with a
10477 // conversion operator followed by a converting constructor.
10478 const Expr *SrcObj = E->getArg(0);
10479 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10480 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10481 if (const MaterializeTemporaryExpr *ME =
10482 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10483 return Visit(ME->getSubExpr());
10484 }
10485
10486 if (ZeroInit && !ZeroInitialization(E, T))
10487 return false;
10488
10489 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10490 return HandleConstructorCall(E, This, Args,
10491 cast<CXXConstructorDecl>(Definition), Info,
10492 Result);
10493}
10494
10495bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10496 const CXXInheritedCtorInitExpr *E) {
10497 if (!Info.CurrentCall) {
10498 assert(Info.checkingPotentialConstantExpression());
10499 return false;
10500 }
10501
10502 const CXXConstructorDecl *FD = E->getConstructor();
10503 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10504 return false;
10505
10506 const FunctionDecl *Definition = nullptr;
10507 auto Body = FD->getBody(Definition);
10508
10509 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10510 return false;
10511
10512 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10513 cast<CXXConstructorDecl>(Definition), Info,
10514 Result);
10515}
10516
10517bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10518 const CXXStdInitializerListExpr *E) {
10520 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10521
10522 LValue Array;
10523 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10524 return false;
10525
10526 assert(ArrayType && "unexpected type for array initializer");
10527
10528 // Get a pointer to the first element of the array.
10529 Array.addArray(Info, E, ArrayType);
10530
10531 auto InvalidType = [&] {
10532 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10533 << E->getType();
10534 return false;
10535 };
10536
10537 // FIXME: Perform the checks on the field types in SemaInit.
10538 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10539 RecordDecl::field_iterator Field = Record->field_begin();
10540 if (Field == Record->field_end())
10541 return InvalidType();
10542
10543 // Start pointer.
10544 if (!Field->getType()->isPointerType() ||
10545 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10547 return InvalidType();
10548
10549 // FIXME: What if the initializer_list type has base classes, etc?
10550 Result = APValue(APValue::UninitStruct(), 0, 2);
10551 Array.moveInto(Result.getStructField(0));
10552
10553 if (++Field == Record->field_end())
10554 return InvalidType();
10555
10556 if (Field->getType()->isPointerType() &&
10557 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10559 // End pointer.
10560 if (!HandleLValueArrayAdjustment(Info, E, Array,
10562 ArrayType->getZExtSize()))
10563 return false;
10564 Array.moveInto(Result.getStructField(1));
10565 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10566 // Length.
10567 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10568 else
10569 return InvalidType();
10570
10571 if (++Field != Record->field_end())
10572 return InvalidType();
10573
10574 return true;
10575}
10576
10577bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10578 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10579 if (ClosureClass->isInvalidDecl())
10580 return false;
10581
10582 const size_t NumFields =
10583 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10584
10585 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10586 E->capture_init_end()) &&
10587 "The number of lambda capture initializers should equal the number of "
10588 "fields within the closure type");
10589
10590 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10591 // Iterate through all the lambda's closure object's fields and initialize
10592 // them.
10593 auto *CaptureInitIt = E->capture_init_begin();
10594 bool Success = true;
10595 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10596 for (const auto *Field : ClosureClass->fields()) {
10597 assert(CaptureInitIt != E->capture_init_end());
10598 // Get the initializer for this field
10599 Expr *const CurFieldInit = *CaptureInitIt++;
10600
10601 // If there is no initializer, either this is a VLA or an error has
10602 // occurred.
10603 if (!CurFieldInit)
10604 return Error(E);
10605
10606 LValue Subobject = This;
10607
10608 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10609 return false;
10610
10611 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10612 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10613 if (!Info.keepEvaluatingAfterFailure())
10614 return false;
10615 Success = false;
10616 }
10617 }
10618 return Success;
10619}
10620
10621static bool EvaluateRecord(const Expr *E, const LValue &This,
10622 APValue &Result, EvalInfo &Info) {
10623 assert(!E->isValueDependent());
10624 assert(E->isPRValue() && E->getType()->isRecordType() &&
10625 "can't evaluate expression as a record rvalue");
10626 return RecordExprEvaluator(Info, This, Result).Visit(E);
10627}
10628
10629//===----------------------------------------------------------------------===//
10630// Temporary Evaluation
10631//
10632// Temporaries are represented in the AST as rvalues, but generally behave like
10633// lvalues. The full-object of which the temporary is a subobject is implicitly
10634// materialized so that a reference can bind to it.
10635//===----------------------------------------------------------------------===//
10636namespace {
10637class TemporaryExprEvaluator
10638 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10639public:
10640 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10641 LValueExprEvaluatorBaseTy(Info, Result, false) {}
10642
10643 /// Visit an expression which constructs the value of this temporary.
10644 bool VisitConstructExpr(const Expr *E) {
10645 APValue &Value = Info.CurrentCall->createTemporary(
10646 E, E->getType(), ScopeKind::FullExpression, Result);
10647 return EvaluateInPlace(Value, Info, Result, E);
10648 }
10649
10650 bool VisitCastExpr(const CastExpr *E) {
10651 switch (E->getCastKind()) {
10652 default:
10653 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10654
10655 case CK_ConstructorConversion:
10656 return VisitConstructExpr(E->getSubExpr());
10657 }
10658 }
10659 bool VisitInitListExpr(const InitListExpr *E) {
10660 return VisitConstructExpr(E);
10661 }
10662 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10663 return VisitConstructExpr(E);
10664 }
10665 bool VisitCallExpr(const CallExpr *E) {
10666 return VisitConstructExpr(E);
10667 }
10668 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10669 return VisitConstructExpr(E);
10670 }
10671 bool VisitLambdaExpr(const LambdaExpr *E) {
10672 return VisitConstructExpr(E);
10673 }
10674};
10675} // end anonymous namespace
10676
10677/// Evaluate an expression of record type as a temporary.
10678static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10679 assert(!E->isValueDependent());
10680 assert(E->isPRValue() && E->getType()->isRecordType());
10681 return TemporaryExprEvaluator(Info, Result).Visit(E);
10682}
10683
10684//===----------------------------------------------------------------------===//
10685// Vector Evaluation
10686//===----------------------------------------------------------------------===//
10687
10688namespace {
10689 class VectorExprEvaluator
10690 : public ExprEvaluatorBase<VectorExprEvaluator> {
10691 APValue &Result;
10692 public:
10693
10694 VectorExprEvaluator(EvalInfo &info, APValue &Result)
10695 : ExprEvaluatorBaseTy(info), Result(Result) {}
10696
10697 bool Success(ArrayRef<APValue> V, const Expr *E) {
10698 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10699 // FIXME: remove this APValue copy.
10700 Result = APValue(V.data(), V.size());
10701 return true;
10702 }
10703 bool Success(const APValue &V, const Expr *E) {
10704 assert(V.isVector());
10705 Result = V;
10706 return true;
10707 }
10708 bool ZeroInitialization(const Expr *E);
10709
10710 bool VisitUnaryReal(const UnaryOperator *E)
10711 { return Visit(E->getSubExpr()); }
10712 bool VisitCastExpr(const CastExpr* E);
10713 bool VisitInitListExpr(const InitListExpr *E);
10714 bool VisitUnaryImag(const UnaryOperator *E);
10715 bool VisitBinaryOperator(const BinaryOperator *E);
10716 bool VisitUnaryOperator(const UnaryOperator *E);
10717 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
10718 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
10719
10720 // FIXME: Missing: conditional operator (for GNU
10721 // conditional select), ExtVectorElementExpr
10722 };
10723} // end anonymous namespace
10724
10725static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10726 assert(E->isPRValue() && E->getType()->isVectorType() &&
10727 "not a vector prvalue");
10728 return VectorExprEvaluator(Info, Result).Visit(E);
10729}
10730
10731bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10732 const VectorType *VTy = E->getType()->castAs<VectorType>();
10733 unsigned NElts = VTy->getNumElements();
10734
10735 const Expr *SE = E->getSubExpr();
10736 QualType SETy = SE->getType();
10737
10738 switch (E->getCastKind()) {
10739 case CK_VectorSplat: {
10740 APValue Val = APValue();
10741 if (SETy->isIntegerType()) {
10742 APSInt IntResult;
10743 if (!EvaluateInteger(SE, IntResult, Info))
10744 return false;
10745 Val = APValue(std::move(IntResult));
10746 } else if (SETy->isRealFloatingType()) {
10747 APFloat FloatResult(0.0);
10748 if (!EvaluateFloat(SE, FloatResult, Info))
10749 return false;
10750 Val = APValue(std::move(FloatResult));
10751 } else {
10752 return Error(E);
10753 }
10754
10755 // Splat and create vector APValue.
10756 SmallVector<APValue, 4> Elts(NElts, Val);
10757 return Success(Elts, E);
10758 }
10759 case CK_BitCast: {
10760 APValue SVal;
10761 if (!Evaluate(SVal, Info, SE))
10762 return false;
10763
10764 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
10765 // Give up if the input isn't an int, float, or vector. For example, we
10766 // reject "(v4i16)(intptr_t)&a".
10767 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
10768 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
10769 return false;
10770 }
10771
10772 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
10773 return false;
10774
10775 return true;
10776 }
10777 default:
10778 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10779 }
10780}
10781
10782bool
10783VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10784 const VectorType *VT = E->getType()->castAs<VectorType>();
10785 unsigned NumInits = E->getNumInits();
10786 unsigned NumElements = VT->getNumElements();
10787
10788 QualType EltTy = VT->getElementType();
10789 SmallVector<APValue, 4> Elements;
10790
10791 // The number of initializers can be less than the number of
10792 // vector elements. For OpenCL, this can be due to nested vector
10793 // initialization. For GCC compatibility, missing trailing elements
10794 // should be initialized with zeroes.
10795 unsigned CountInits = 0, CountElts = 0;
10796 while (CountElts < NumElements) {
10797 // Handle nested vector initialization.
10798 if (CountInits < NumInits
10799 && E->getInit(CountInits)->getType()->isVectorType()) {
10800 APValue v;
10801 if (!EvaluateVector(E->getInit(CountInits), v, Info))
10802 return Error(E);
10803 unsigned vlen = v.getVectorLength();
10804 for (unsigned j = 0; j < vlen; j++)
10805 Elements.push_back(v.getVectorElt(j));
10806 CountElts += vlen;
10807 } else if (EltTy->isIntegerType()) {
10808 llvm::APSInt sInt(32);
10809 if (CountInits < NumInits) {
10810 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10811 return false;
10812 } else // trailing integer zero.
10813 sInt = Info.Ctx.MakeIntValue(0, EltTy);
10814 Elements.push_back(APValue(sInt));
10815 CountElts++;
10816 } else {
10817 llvm::APFloat f(0.0);
10818 if (CountInits < NumInits) {
10819 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10820 return false;
10821 } else // trailing float zero.
10822 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10823 Elements.push_back(APValue(f));
10824 CountElts++;
10825 }
10826 CountInits++;
10827 }
10828 return Success(Elements, E);
10829}
10830
10831bool
10832VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10833 const auto *VT = E->getType()->castAs<VectorType>();
10834 QualType EltTy = VT->getElementType();
10835 APValue ZeroElement;
10836 if (EltTy->isIntegerType())
10837 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10838 else
10839 ZeroElement =
10840 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10841
10842 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10843 return Success(Elements, E);
10844}
10845
10846bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10847 VisitIgnoredValue(E->getSubExpr());
10848 return ZeroInitialization(E);
10849}
10850
10851bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10852 BinaryOperatorKind Op = E->getOpcode();
10853 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10854 "Operation not supported on vector types");
10855
10856 if (Op == BO_Comma)
10857 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10858
10859 Expr *LHS = E->getLHS();
10860 Expr *RHS = E->getRHS();
10861
10862 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10863 "Must both be vector types");
10864 // Checking JUST the types are the same would be fine, except shifts don't
10865 // need to have their types be the same (since you always shift by an int).
10866 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10868 RHS->getType()->castAs<VectorType>()->getNumElements() ==
10870 "All operands must be the same size.");
10871
10872 APValue LHSValue;
10873 APValue RHSValue;
10874 bool LHSOK = Evaluate(LHSValue, Info, LHS);
10875 if (!LHSOK && !Info.noteFailure())
10876 return false;
10877 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10878 return false;
10879
10880 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10881 return false;
10882
10883 return Success(LHSValue, E);
10884}
10885
10886static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10887 QualType ResultTy,
10889 APValue Elt) {
10890 switch (Op) {
10891 case UO_Plus:
10892 // Nothing to do here.
10893 return Elt;
10894 case UO_Minus:
10895 if (Elt.getKind() == APValue::Int) {
10896 Elt.getInt().negate();
10897 } else {
10898 assert(Elt.getKind() == APValue::Float &&
10899 "Vector can only be int or float type");
10900 Elt.getFloat().changeSign();
10901 }
10902 return Elt;
10903 case UO_Not:
10904 // This is only valid for integral types anyway, so we don't have to handle
10905 // float here.
10906 assert(Elt.getKind() == APValue::Int &&
10907 "Vector operator ~ can only be int");
10908 Elt.getInt().flipAllBits();
10909 return Elt;
10910 case UO_LNot: {
10911 if (Elt.getKind() == APValue::Int) {
10912 Elt.getInt() = !Elt.getInt();
10913 // operator ! on vectors returns -1 for 'truth', so negate it.
10914 Elt.getInt().negate();
10915 return Elt;
10916 }
10917 assert(Elt.getKind() == APValue::Float &&
10918 "Vector can only be int or float type");
10919 // Float types result in an int of the same size, but -1 for true, or 0 for
10920 // false.
10921 APSInt EltResult{Ctx.getIntWidth(ResultTy),
10922 ResultTy->isUnsignedIntegerType()};
10923 if (Elt.getFloat().isZero())
10924 EltResult.setAllBits();
10925 else
10926 EltResult.clearAllBits();
10927
10928 return APValue{EltResult};
10929 }
10930 default:
10931 // FIXME: Implement the rest of the unary operators.
10932 return std::nullopt;
10933 }
10934}
10935
10936bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10937 Expr *SubExpr = E->getSubExpr();
10938 const auto *VD = SubExpr->getType()->castAs<VectorType>();
10939 // This result element type differs in the case of negating a floating point
10940 // vector, since the result type is the a vector of the equivilant sized
10941 // integer.
10942 const QualType ResultEltTy = VD->getElementType();
10943 UnaryOperatorKind Op = E->getOpcode();
10944
10945 APValue SubExprValue;
10946 if (!Evaluate(SubExprValue, Info, SubExpr))
10947 return false;
10948
10949 // FIXME: This vector evaluator someday needs to be changed to be LValue
10950 // aware/keep LValue information around, rather than dealing with just vector
10951 // types directly. Until then, we cannot handle cases where the operand to
10952 // these unary operators is an LValue. The only case I've been able to see
10953 // cause this is operator++ assigning to a member expression (only valid in
10954 // altivec compilations) in C mode, so this shouldn't limit us too much.
10955 if (SubExprValue.isLValue())
10956 return false;
10957
10958 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10959 "Vector length doesn't match type?");
10960
10961 SmallVector<APValue, 4> ResultElements;
10962 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10963 std::optional<APValue> Elt = handleVectorUnaryOperator(
10964 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10965 if (!Elt)
10966 return false;
10967 ResultElements.push_back(*Elt);
10968 }
10969 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10970}
10971
10972static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
10973 const Expr *E, QualType SourceTy,
10974 QualType DestTy, APValue const &Original,
10975 APValue &Result) {
10976 if (SourceTy->isIntegerType()) {
10977 if (DestTy->isRealFloatingType()) {
10978 Result = APValue(APFloat(0.0));
10979 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
10980 DestTy, Result.getFloat());
10981 }
10982 if (DestTy->isIntegerType()) {
10983 Result = APValue(
10984 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
10985 return true;
10986 }
10987 } else if (SourceTy->isRealFloatingType()) {
10988 if (DestTy->isRealFloatingType()) {
10989 Result = Original;
10990 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
10991 Result.getFloat());
10992 }
10993 if (DestTy->isIntegerType()) {
10994 Result = APValue(APSInt());
10995 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
10996 DestTy, Result.getInt());
10997 }
10998 }
10999
11000 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11001 << SourceTy << DestTy;
11002 return false;
11003}
11004
11005bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
11006 APValue Source;
11007 QualType SourceVecType = E->getSrcExpr()->getType();
11008 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
11009 return false;
11010
11011 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
11012 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
11013
11014 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11015
11016 auto SourceLen = Source.getVectorLength();
11017 SmallVector<APValue, 4> ResultElements;
11018 ResultElements.reserve(SourceLen);
11019 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11020 APValue Elt;
11021 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
11022 Source.getVectorElt(EltNum), Elt))
11023 return false;
11024 ResultElements.push_back(std::move(Elt));
11025 }
11026
11027 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11028}
11029
11030static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
11031 QualType ElemType, APValue const &VecVal1,
11032 APValue const &VecVal2, unsigned EltNum,
11033 APValue &Result) {
11034 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
11035 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
11036
11037 APSInt IndexVal = E->getShuffleMaskIdx(Info.Ctx, EltNum);
11038 int64_t index = IndexVal.getExtValue();
11039 // The spec says that -1 should be treated as undef for optimizations,
11040 // but in constexpr we'd have to produce an APValue::Indeterminate,
11041 // which is prohibited from being a top-level constant value. Emit a
11042 // diagnostic instead.
11043 if (index == -1) {
11044 Info.FFDiag(
11045 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
11046 << EltNum;
11047 return false;
11048 }
11049
11050 if (index < 0 ||
11051 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
11052 llvm_unreachable("Out of bounds shuffle index");
11053
11054 if (index >= TotalElementsInInputVector1)
11055 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
11056 else
11057 Result = VecVal1.getVectorElt(index);
11058 return true;
11059}
11060
11061bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
11062 APValue VecVal1;
11063 const Expr *Vec1 = E->getExpr(0);
11064 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
11065 return false;
11066 APValue VecVal2;
11067 const Expr *Vec2 = E->getExpr(1);
11068 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
11069 return false;
11070
11071 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
11072 QualType DestElTy = DestVecTy->getElementType();
11073
11074 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
11075
11076 SmallVector<APValue, 4> ResultElements;
11077 ResultElements.reserve(TotalElementsInOutputVector);
11078 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
11079 APValue Elt;
11080 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
11081 return false;
11082 ResultElements.push_back(std::move(Elt));
11083 }
11084
11085 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11086}
11087
11088//===----------------------------------------------------------------------===//
11089// Array Evaluation
11090//===----------------------------------------------------------------------===//
11091
11092namespace {
11093 class ArrayExprEvaluator
11094 : public ExprEvaluatorBase<ArrayExprEvaluator> {
11095 const LValue &This;
11096 APValue &Result;
11097 public:
11098
11099 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
11100 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
11101
11102 bool Success(const APValue &V, const Expr *E) {
11103 assert(V.isArray() && "expected array");
11104 Result = V;
11105 return true;
11106 }
11107
11108 bool ZeroInitialization(const Expr *E) {
11109 const ConstantArrayType *CAT =
11110 Info.Ctx.getAsConstantArrayType(E->getType());
11111 if (!CAT) {
11112 if (E->getType()->isIncompleteArrayType()) {
11113 // We can be asked to zero-initialize a flexible array member; this
11114 // is represented as an ImplicitValueInitExpr of incomplete array
11115 // type. In this case, the array has zero elements.
11116 Result = APValue(APValue::UninitArray(), 0, 0);
11117 return true;
11118 }
11119 // FIXME: We could handle VLAs here.
11120 return Error(E);
11121 }
11122
11123 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
11124 if (!Result.hasArrayFiller())
11125 return true;
11126
11127 // Zero-initialize all elements.
11128 LValue Subobject = This;
11129 Subobject.addArray(Info, E, CAT);
11131 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
11132 }
11133
11134 bool VisitCallExpr(const CallExpr *E) {
11135 return handleCallExpr(E, Result, &This);
11136 }
11137 bool VisitInitListExpr(const InitListExpr *E,
11138 QualType AllocType = QualType());
11139 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
11140 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
11141 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
11142 const LValue &Subobject,
11144 bool VisitStringLiteral(const StringLiteral *E,
11145 QualType AllocType = QualType()) {
11146 expandStringLiteral(Info, E, Result, AllocType);
11147 return true;
11148 }
11149 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11150 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11151 ArrayRef<Expr *> Args,
11152 const Expr *ArrayFiller,
11153 QualType AllocType = QualType());
11154 };
11155} // end anonymous namespace
11156
11157static bool EvaluateArray(const Expr *E, const LValue &This,
11158 APValue &Result, EvalInfo &Info) {
11159 assert(!E->isValueDependent());
11160 assert(E->isPRValue() && E->getType()->isArrayType() &&
11161 "not an array prvalue");
11162 return ArrayExprEvaluator(Info, This, Result).Visit(E);
11163}
11164
11165static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
11166 APValue &Result, const InitListExpr *ILE,
11167 QualType AllocType) {
11168 assert(!ILE->isValueDependent());
11169 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
11170 "not an array prvalue");
11171 return ArrayExprEvaluator(Info, This, Result)
11172 .VisitInitListExpr(ILE, AllocType);
11173}
11174
11175static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
11176 APValue &Result,
11177 const CXXConstructExpr *CCE,
11178 QualType AllocType) {
11179 assert(!CCE->isValueDependent());
11180 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
11181 "not an array prvalue");
11182 return ArrayExprEvaluator(Info, This, Result)
11183 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
11184}
11185
11186// Return true iff the given array filler may depend on the element index.
11187static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
11188 // For now, just allow non-class value-initialization and initialization
11189 // lists comprised of them.
11190 if (isa<ImplicitValueInitExpr>(FillerExpr))
11191 return false;
11192 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
11193 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
11194 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
11195 return true;
11196 }
11197
11198 if (ILE->hasArrayFiller() &&
11199 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
11200 return true;
11201
11202 return false;
11203 }
11204 return true;
11205}
11206
11207bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
11208 QualType AllocType) {
11209 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11210 AllocType.isNull() ? E->getType() : AllocType);
11211 if (!CAT)
11212 return Error(E);
11213
11214 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
11215 // an appropriately-typed string literal enclosed in braces.
11216 if (E->isStringLiteralInit()) {
11217 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
11218 // FIXME: Support ObjCEncodeExpr here once we support it in
11219 // ArrayExprEvaluator generally.
11220 if (!SL)
11221 return Error(E);
11222 return VisitStringLiteral(SL, AllocType);
11223 }
11224 // Any other transparent list init will need proper handling of the
11225 // AllocType; we can't just recurse to the inner initializer.
11226 assert(!E->isTransparent() &&
11227 "transparent array list initialization is not string literal init?");
11228
11229 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
11230 AllocType);
11231}
11232
11233bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
11234 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
11235 QualType AllocType) {
11236 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11237 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
11238
11239 bool Success = true;
11240
11241 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
11242 "zero-initialized array shouldn't have any initialized elts");
11243 APValue Filler;
11244 if (Result.isArray() && Result.hasArrayFiller())
11245 Filler = Result.getArrayFiller();
11246
11247 unsigned NumEltsToInit = Args.size();
11248 unsigned NumElts = CAT->getZExtSize();
11249
11250 // If the initializer might depend on the array index, run it for each
11251 // array element.
11252 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(ArrayFiller))
11253 NumEltsToInit = NumElts;
11254
11255 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
11256 << NumEltsToInit << ".\n");
11257
11258 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
11259
11260 // If the array was previously zero-initialized, preserve the
11261 // zero-initialized values.
11262 if (Filler.hasValue()) {
11263 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
11264 Result.getArrayInitializedElt(I) = Filler;
11265 if (Result.hasArrayFiller())
11266 Result.getArrayFiller() = Filler;
11267 }
11268
11269 LValue Subobject = This;
11270 Subobject.addArray(Info, ExprToVisit, CAT);
11271 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
11272 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
11273 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11274 Info, Subobject, Init) ||
11275 !HandleLValueArrayAdjustment(Info, Init, Subobject,
11276 CAT->getElementType(), 1)) {
11277 if (!Info.noteFailure())
11278 return false;
11279 Success = false;
11280 }
11281 }
11282
11283 if (!Result.hasArrayFiller())
11284 return Success;
11285
11286 // If we get here, we have a trivial filler, which we can just evaluate
11287 // once and splat over the rest of the array elements.
11288 assert(ArrayFiller && "no array filler for incomplete init list");
11289 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
11290 ArrayFiller) &&
11291 Success;
11292}
11293
11294bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
11295 LValue CommonLV;
11296 if (E->getCommonExpr() &&
11297 !Evaluate(Info.CurrentCall->createTemporary(
11298 E->getCommonExpr(),
11299 getStorageType(Info.Ctx, E->getCommonExpr()),
11300 ScopeKind::FullExpression, CommonLV),
11301 Info, E->getCommonExpr()->getSourceExpr()))
11302 return false;
11303
11304 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
11305
11306 uint64_t Elements = CAT->getZExtSize();
11307 Result = APValue(APValue::UninitArray(), Elements, Elements);
11308
11309 LValue Subobject = This;
11310 Subobject.addArray(Info, E, CAT);
11311
11312 bool Success = true;
11313 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
11314 // C++ [class.temporary]/5
11315 // There are four contexts in which temporaries are destroyed at a different
11316 // point than the end of the full-expression. [...] The second context is
11317 // when a copy constructor is called to copy an element of an array while
11318 // the entire array is copied [...]. In either case, if the constructor has
11319 // one or more default arguments, the destruction of every temporary created
11320 // in a default argument is sequenced before the construction of the next
11321 // array element, if any.
11322 FullExpressionRAII Scope(Info);
11323
11324 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11325 Info, Subobject, E->getSubExpr()) ||
11326 !HandleLValueArrayAdjustment(Info, E, Subobject,
11327 CAT->getElementType(), 1)) {
11328 if (!Info.noteFailure())
11329 return false;
11330 Success = false;
11331 }
11332
11333 // Make sure we run the destructors too.
11334 Scope.destroy();
11335 }
11336
11337 return Success;
11338}
11339
11340bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
11341 return VisitCXXConstructExpr(E, This, &Result, E->getType());
11342}
11343
11344bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11345 const LValue &Subobject,
11346 APValue *Value,
11347 QualType Type) {
11348 bool HadZeroInit = Value->hasValue();
11349
11350 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
11351 unsigned FinalSize = CAT->getZExtSize();
11352
11353 // Preserve the array filler if we had prior zero-initialization.
11354 APValue Filler =
11355 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
11356 : APValue();
11357
11358 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
11359 if (FinalSize == 0)
11360 return true;
11361
11362 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
11363 Info, E->getExprLoc(), E->getConstructor(),
11365 LValue ArrayElt = Subobject;
11366 ArrayElt.addArray(Info, E, CAT);
11367 // We do the whole initialization in two passes, first for just one element,
11368 // then for the whole array. It's possible we may find out we can't do const
11369 // init in the first pass, in which case we avoid allocating a potentially
11370 // large array. We don't do more passes because expanding array requires
11371 // copying the data, which is wasteful.
11372 for (const unsigned N : {1u, FinalSize}) {
11373 unsigned OldElts = Value->getArrayInitializedElts();
11374 if (OldElts == N)
11375 break;
11376
11377 // Expand the array to appropriate size.
11378 APValue NewValue(APValue::UninitArray(), N, FinalSize);
11379 for (unsigned I = 0; I < OldElts; ++I)
11380 NewValue.getArrayInitializedElt(I).swap(
11381 Value->getArrayInitializedElt(I));
11382 Value->swap(NewValue);
11383
11384 if (HadZeroInit)
11385 for (unsigned I = OldElts; I < N; ++I)
11386 Value->getArrayInitializedElt(I) = Filler;
11387
11388 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
11389 // If we have a trivial constructor, only evaluate it once and copy
11390 // the result into all the array elements.
11391 APValue &FirstResult = Value->getArrayInitializedElt(0);
11392 for (unsigned I = OldElts; I < FinalSize; ++I)
11393 Value->getArrayInitializedElt(I) = FirstResult;
11394 } else {
11395 for (unsigned I = OldElts; I < N; ++I) {
11396 if (!VisitCXXConstructExpr(E, ArrayElt,
11397 &Value->getArrayInitializedElt(I),
11398 CAT->getElementType()) ||
11399 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
11400 CAT->getElementType(), 1))
11401 return false;
11402 // When checking for const initilization any diagnostic is considered
11403 // an error.
11404 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
11405 !Info.keepEvaluatingAfterFailure())
11406 return false;
11407 }
11408 }
11409 }
11410
11411 return true;
11412 }
11413
11414 if (!Type->isRecordType())
11415 return Error(E);
11416
11417 return RecordExprEvaluator(Info, Subobject, *Value)
11418 .VisitCXXConstructExpr(E, Type);
11419}
11420
11421bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
11422 const CXXParenListInitExpr *E) {
11423 assert(dyn_cast<ConstantArrayType>(E->getType()) &&
11424 "Expression result is not a constant array type");
11425
11426 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
11427 E->getArrayFiller());
11428}
11429
11430//===----------------------------------------------------------------------===//
11431// Integer Evaluation
11432//
11433// As a GNU extension, we support casting pointers to sufficiently-wide integer
11434// types and back in constant folding. Integer values are thus represented
11435// either as an integer-valued APValue, or as an lvalue-valued APValue.
11436//===----------------------------------------------------------------------===//
11437
11438namespace {
11439class IntExprEvaluator
11440 : public ExprEvaluatorBase<IntExprEvaluator> {
11441 APValue &Result;
11442public:
11443 IntExprEvaluator(EvalInfo &info, APValue &result)
11444 : ExprEvaluatorBaseTy(info), Result(result) {}
11445
11446 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
11447 assert(E->getType()->isIntegralOrEnumerationType() &&
11448 "Invalid evaluation result.");
11449 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
11450 "Invalid evaluation result.");
11451 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11452 "Invalid evaluation result.");
11453 Result = APValue(SI);
11454 return true;
11455 }
11456 bool Success(const llvm::APSInt &SI, const Expr *E) {
11457 return Success(SI, E, Result);
11458 }
11459
11460 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
11461 assert(E->getType()->isIntegralOrEnumerationType() &&
11462 "Invalid evaluation result.");
11463 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11464 "Invalid evaluation result.");
11465 Result = APValue(APSInt(I));
11466 Result.getInt().setIsUnsigned(
11468 return true;
11469 }
11470 bool Success(const llvm::APInt &I, const Expr *E) {
11471 return Success(I, E, Result);
11472 }
11473
11474 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11475 assert(E->getType()->isIntegralOrEnumerationType() &&
11476 "Invalid evaluation result.");
11477 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11478 return true;
11479 }
11480 bool Success(uint64_t Value, const Expr *E) {
11481 return Success(Value, E, Result);
11482 }
11483
11484 bool Success(CharUnits Size, const Expr *E) {
11485 return Success(Size.getQuantity(), E);
11486 }
11487
11488 bool Success(const APValue &V, const Expr *E) {
11489 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
11490 Result = V;
11491 return true;
11492 }
11493 return Success(V.getInt(), E);
11494 }
11495
11496 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11497
11498 //===--------------------------------------------------------------------===//
11499 // Visitor Methods
11500 //===--------------------------------------------------------------------===//
11501
11502 bool VisitIntegerLiteral(const IntegerLiteral *E) {
11503 return Success(E->getValue(), E);
11504 }
11505 bool VisitCharacterLiteral(const CharacterLiteral *E) {
11506 return Success(E->getValue(), E);
11507 }
11508
11509 bool CheckReferencedDecl(const Expr *E, const Decl *D);
11510 bool VisitDeclRefExpr(const DeclRefExpr *E) {
11511 if (CheckReferencedDecl(E, E->getDecl()))
11512 return true;
11513
11514 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11515 }
11516 bool VisitMemberExpr(const MemberExpr *E) {
11517 if (CheckReferencedDecl(E, E->getMemberDecl())) {
11518 VisitIgnoredBaseExpression(E->getBase());
11519 return true;
11520 }
11521
11522 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11523 }
11524
11525 bool VisitCallExpr(const CallExpr *E);
11526 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11527 bool VisitBinaryOperator(const BinaryOperator *E);
11528 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11529 bool VisitUnaryOperator(const UnaryOperator *E);
11530
11531 bool VisitCastExpr(const CastExpr* E);
11532 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11533
11534 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11535 return Success(E->getValue(), E);
11536 }
11537
11538 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11539 return Success(E->getValue(), E);
11540 }
11541
11542 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11543 if (Info.ArrayInitIndex == uint64_t(-1)) {
11544 // We were asked to evaluate this subexpression independent of the
11545 // enclosing ArrayInitLoopExpr. We can't do that.
11546 Info.FFDiag(E);
11547 return false;
11548 }
11549 return Success(Info.ArrayInitIndex, E);
11550 }
11551
11552 // Note, GNU defines __null as an integer, not a pointer.
11553 bool VisitGNUNullExpr(const GNUNullExpr *E) {
11554 return ZeroInitialization(E);
11555 }
11556
11557 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11558 return Success(E->getValue(), E);
11559 }
11560
11561 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11562 return Success(E->getValue(), E);
11563 }
11564
11565 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11566 return Success(E->getValue(), E);
11567 }
11568
11569 bool VisitUnaryReal(const UnaryOperator *E);
11570 bool VisitUnaryImag(const UnaryOperator *E);
11571
11572 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11573 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11574 bool VisitSourceLocExpr(const SourceLocExpr *E);
11575 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11576 bool VisitRequiresExpr(const RequiresExpr *E);
11577 // FIXME: Missing: array subscript of vector, member of vector
11578};
11579
11580class FixedPointExprEvaluator
11581 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11582 APValue &Result;
11583
11584 public:
11585 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11586 : ExprEvaluatorBaseTy(info), Result(result) {}
11587
11588 bool Success(const llvm::APInt &I, const Expr *E) {
11589 return Success(
11590 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11591 }
11592
11593 bool Success(uint64_t Value, const Expr *E) {
11594 return Success(
11595 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11596 }
11597
11598 bool Success(const APValue &V, const Expr *E) {
11599 return Success(V.getFixedPoint(), E);
11600 }
11601
11602 bool Success(const APFixedPoint &V, const Expr *E) {
11603 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11604 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11605 "Invalid evaluation result.");
11606 Result = APValue(V);
11607 return true;
11608 }
11609
11610 bool ZeroInitialization(const Expr *E) {
11611 return Success(0, E);
11612 }
11613
11614 //===--------------------------------------------------------------------===//
11615 // Visitor Methods
11616 //===--------------------------------------------------------------------===//
11617
11618 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11619 return Success(E->getValue(), E);
11620 }
11621
11622 bool VisitCastExpr(const CastExpr *E);
11623 bool VisitUnaryOperator(const UnaryOperator *E);
11624 bool VisitBinaryOperator(const BinaryOperator *E);
11625};
11626} // end anonymous namespace
11627
11628/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11629/// produce either the integer value or a pointer.
11630///
11631/// GCC has a heinous extension which folds casts between pointer types and
11632/// pointer-sized integral types. We support this by allowing the evaluation of
11633/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11634/// Some simple arithmetic on such values is supported (they are treated much
11635/// like char*).
11636static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11637 EvalInfo &Info) {
11638 assert(!E->isValueDependent());
11639 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11640 return IntExprEvaluator(Info, Result).Visit(E);
11641}
11642
11643static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11644 assert(!E->isValueDependent());
11645 APValue Val;
11646 if (!EvaluateIntegerOrLValue(E, Val, Info))
11647 return false;
11648 if (!Val.isInt()) {
11649 // FIXME: It would be better to produce the diagnostic for casting
11650 // a pointer to an integer.
11651 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11652 return false;
11653 }
11654 Result = Val.getInt();
11655 return true;
11656}
11657
11658bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11660 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11661 return Success(Evaluated, E);
11662}
11663
11664static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11665 EvalInfo &Info) {
11666 assert(!E->isValueDependent());
11667 if (E->getType()->isFixedPointType()) {
11668 APValue Val;
11669 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11670 return false;
11671 if (!Val.isFixedPoint())
11672 return false;
11673
11674 Result = Val.getFixedPoint();
11675 return true;
11676 }
11677 return false;
11678}
11679
11680static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11681 EvalInfo &Info) {
11682 assert(!E->isValueDependent());
11683 if (E->getType()->isIntegerType()) {
11684 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11685 APSInt Val;
11686 if (!EvaluateInteger(E, Val, Info))
11687 return false;
11688 Result = APFixedPoint(Val, FXSema);
11689 return true;
11690 } else if (E->getType()->isFixedPointType()) {
11691 return EvaluateFixedPoint(E, Result, Info);
11692 }
11693 return false;
11694}
11695
11696/// Check whether the given declaration can be directly converted to an integral
11697/// rvalue. If not, no diagnostic is produced; there are other things we can
11698/// try.
11699bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11700 // Enums are integer constant exprs.
11701 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11702 // Check for signedness/width mismatches between E type and ECD value.
11703 bool SameSign = (ECD->getInitVal().isSigned()
11705 bool SameWidth = (ECD->getInitVal().getBitWidth()
11706 == Info.Ctx.getIntWidth(E->getType()));
11707 if (SameSign && SameWidth)
11708 return Success(ECD->getInitVal(), E);
11709 else {
11710 // Get rid of mismatch (otherwise Success assertions will fail)
11711 // by computing a new value matching the type of E.
11712 llvm::APSInt Val = ECD->getInitVal();
11713 if (!SameSign)
11714 Val.setIsSigned(!ECD->getInitVal().isSigned());
11715 if (!SameWidth)
11716 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11717 return Success(Val, E);
11718 }
11719 }
11720 return false;
11721}
11722
11723/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11724/// as GCC.
11726 const LangOptions &LangOpts) {
11727 assert(!T->isDependentType() && "unexpected dependent type");
11728
11729 QualType CanTy = T.getCanonicalType();
11730
11731 switch (CanTy->getTypeClass()) {
11732#define TYPE(ID, BASE)
11733#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11734#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11735#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11736#include "clang/AST/TypeNodes.inc"
11737 case Type::Auto:
11738 case Type::DeducedTemplateSpecialization:
11739 llvm_unreachable("unexpected non-canonical or dependent type");
11740
11741 case Type::Builtin:
11742 switch (cast<BuiltinType>(CanTy)->getKind()) {
11743#define BUILTIN_TYPE(ID, SINGLETON_ID)
11744#define SIGNED_TYPE(ID, SINGLETON_ID) \
11745 case BuiltinType::ID: return GCCTypeClass::Integer;
11746#define FLOATING_TYPE(ID, SINGLETON_ID) \
11747 case BuiltinType::ID: return GCCTypeClass::RealFloat;
11748#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11749 case BuiltinType::ID: break;
11750#include "clang/AST/BuiltinTypes.def"
11751 case BuiltinType::Void:
11752 return GCCTypeClass::Void;
11753
11754 case BuiltinType::Bool:
11755 return GCCTypeClass::Bool;
11756
11757 case BuiltinType::Char_U:
11758 case BuiltinType::UChar:
11759 case BuiltinType::WChar_U:
11760 case BuiltinType::Char8:
11761 case BuiltinType::Char16:
11762 case BuiltinType::Char32:
11763 case BuiltinType::UShort:
11764 case BuiltinType::UInt:
11765 case BuiltinType::ULong:
11766 case BuiltinType::ULongLong:
11767 case BuiltinType::UInt128:
11768 return GCCTypeClass::Integer;
11769
11770 case BuiltinType::UShortAccum:
11771 case BuiltinType::UAccum:
11772 case BuiltinType::ULongAccum:
11773 case BuiltinType::UShortFract:
11774 case BuiltinType::UFract:
11775 case BuiltinType::ULongFract:
11776 case BuiltinType::SatUShortAccum:
11777 case BuiltinType::SatUAccum:
11778 case BuiltinType::SatULongAccum:
11779 case BuiltinType::SatUShortFract:
11780 case BuiltinType::SatUFract:
11781 case BuiltinType::SatULongFract:
11782 return GCCTypeClass::None;
11783
11784 case BuiltinType::NullPtr:
11785
11786 case BuiltinType::ObjCId:
11787 case BuiltinType::ObjCClass:
11788 case BuiltinType::ObjCSel:
11789#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11790 case BuiltinType::Id:
11791#include "clang/Basic/OpenCLImageTypes.def"
11792#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11793 case BuiltinType::Id:
11794#include "clang/Basic/OpenCLExtensionTypes.def"
11795 case BuiltinType::OCLSampler:
11796 case BuiltinType::OCLEvent:
11797 case BuiltinType::OCLClkEvent:
11798 case BuiltinType::OCLQueue:
11799 case BuiltinType::OCLReserveID:
11800#define SVE_TYPE(Name, Id, SingletonId) \
11801 case BuiltinType::Id:
11802#include "clang/Basic/AArch64SVEACLETypes.def"
11803#define PPC_VECTOR_TYPE(Name, Id, Size) \
11804 case BuiltinType::Id:
11805#include "clang/Basic/PPCTypes.def"
11806#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11807#include "clang/Basic/RISCVVTypes.def"
11808#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11809#include "clang/Basic/WebAssemblyReferenceTypes.def"
11810 return GCCTypeClass::None;
11811
11812 case BuiltinType::Dependent:
11813 llvm_unreachable("unexpected dependent type");
11814 };
11815 llvm_unreachable("unexpected placeholder type");
11816
11817 case Type::Enum:
11818 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11819
11820 case Type::Pointer:
11821 case Type::ConstantArray:
11822 case Type::VariableArray:
11823 case Type::IncompleteArray:
11824 case Type::FunctionNoProto:
11825 case Type::FunctionProto:
11826 case Type::ArrayParameter:
11827 return GCCTypeClass::Pointer;
11828
11829 case Type::MemberPointer:
11830 return CanTy->isMemberDataPointerType()
11831 ? GCCTypeClass::PointerToDataMember
11832 : GCCTypeClass::PointerToMemberFunction;
11833
11834 case Type::Complex:
11835 return GCCTypeClass::Complex;
11836
11837 case Type::Record:
11838 return CanTy->isUnionType() ? GCCTypeClass::Union
11839 : GCCTypeClass::ClassOrStruct;
11840
11841 case Type::Atomic:
11842 // GCC classifies _Atomic T the same as T.
11844 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11845
11846 case Type::Vector:
11847 case Type::ExtVector:
11848 return GCCTypeClass::Vector;
11849
11850 case Type::BlockPointer:
11851 case Type::ConstantMatrix:
11852 case Type::ObjCObject:
11853 case Type::ObjCInterface:
11854 case Type::ObjCObjectPointer:
11855 case Type::Pipe:
11856 // Classify all other types that don't fit into the regular
11857 // classification the same way.
11858 return GCCTypeClass::None;
11859
11860 case Type::BitInt:
11861 return GCCTypeClass::BitInt;
11862
11863 case Type::LValueReference:
11864 case Type::RValueReference:
11865 llvm_unreachable("invalid type for expression");
11866 }
11867
11868 llvm_unreachable("unexpected type class");
11869}
11870
11871/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11872/// as GCC.
11873static GCCTypeClass
11875 // If no argument was supplied, default to None. This isn't
11876 // ideal, however it is what gcc does.
11877 if (E->getNumArgs() == 0)
11878 return GCCTypeClass::None;
11879
11880 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11881 // being an ICE, but still folds it to a constant using the type of the first
11882 // argument.
11883 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11884}
11885
11886/// EvaluateBuiltinConstantPForLValue - Determine the result of
11887/// __builtin_constant_p when applied to the given pointer.
11888///
11889/// A pointer is only "constant" if it is null (or a pointer cast to integer)
11890/// or it points to the first character of a string literal.
11893 if (Base.isNull()) {
11894 // A null base is acceptable.
11895 return true;
11896 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11897 if (!isa<StringLiteral>(E))
11898 return false;
11899 return LV.getLValueOffset().isZero();
11900 } else if (Base.is<TypeInfoLValue>()) {
11901 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11902 // evaluate to true.
11903 return true;
11904 } else {
11905 // Any other base is not constant enough for GCC.
11906 return false;
11907 }
11908}
11909
11910/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11911/// GCC as we can manage.
11912static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11913 // This evaluation is not permitted to have side-effects, so evaluate it in
11914 // a speculative evaluation context.
11915 SpeculativeEvaluationRAII SpeculativeEval(Info);
11916
11917 // Constant-folding is always enabled for the operand of __builtin_constant_p
11918 // (even when the enclosing evaluation context otherwise requires a strict
11919 // language-specific constant expression).
11920 FoldConstant Fold(Info, true);
11921
11922 QualType ArgType = Arg->getType();
11923
11924 // __builtin_constant_p always has one operand. The rules which gcc follows
11925 // are not precisely documented, but are as follows:
11926 //
11927 // - If the operand is of integral, floating, complex or enumeration type,
11928 // and can be folded to a known value of that type, it returns 1.
11929 // - If the operand can be folded to a pointer to the first character
11930 // of a string literal (or such a pointer cast to an integral type)
11931 // or to a null pointer or an integer cast to a pointer, it returns 1.
11932 //
11933 // Otherwise, it returns 0.
11934 //
11935 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11936 // its support for this did not work prior to GCC 9 and is not yet well
11937 // understood.
11938 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11939 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11940 ArgType->isNullPtrType()) {
11941 APValue V;
11942 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11943 Fold.keepDiagnostics();
11944 return false;
11945 }
11946
11947 // For a pointer (possibly cast to integer), there are special rules.
11948 if (V.getKind() == APValue::LValue)
11950
11951 // Otherwise, any constant value is good enough.
11952 return V.hasValue();
11953 }
11954
11955 // Anything else isn't considered to be sufficiently constant.
11956 return false;
11957}
11958
11959/// Retrieves the "underlying object type" of the given expression,
11960/// as used by __builtin_object_size.
11962 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11963 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11964 return VD->getType();
11965 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11966 if (isa<CompoundLiteralExpr>(E))
11967 return E->getType();
11968 } else if (B.is<TypeInfoLValue>()) {
11969 return B.getTypeInfoType();
11970 } else if (B.is<DynamicAllocLValue>()) {
11971 return B.getDynamicAllocType();
11972 }
11973
11974 return QualType();
11975}
11976
11977/// A more selective version of E->IgnoreParenCasts for
11978/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11979/// to change the type of E.
11980/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11981///
11982/// Always returns an RValue with a pointer representation.
11983static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11984 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11985
11986 const Expr *NoParens = E->IgnoreParens();
11987 const auto *Cast = dyn_cast<CastExpr>(NoParens);
11988 if (Cast == nullptr)
11989 return NoParens;
11990
11991 // We only conservatively allow a few kinds of casts, because this code is
11992 // inherently a simple solution that seeks to support the common case.
11993 auto CastKind = Cast->getCastKind();
11994 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11995 CastKind != CK_AddressSpaceConversion)
11996 return NoParens;
11997
11998 const auto *SubExpr = Cast->getSubExpr();
11999 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
12000 return NoParens;
12001 return ignorePointerCastsAndParens(SubExpr);
12002}
12003
12004/// Checks to see if the given LValue's Designator is at the end of the LValue's
12005/// record layout. e.g.
12006/// struct { struct { int a, b; } fst, snd; } obj;
12007/// obj.fst // no
12008/// obj.snd // yes
12009/// obj.fst.a // no
12010/// obj.fst.b // no
12011/// obj.snd.a // no
12012/// obj.snd.b // yes
12013///
12014/// Please note: this function is specialized for how __builtin_object_size
12015/// views "objects".
12016///
12017/// If this encounters an invalid RecordDecl or otherwise cannot determine the
12018/// correct result, it will always return true.
12019static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
12020 assert(!LVal.Designator.Invalid);
12021
12022 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
12023 const RecordDecl *Parent = FD->getParent();
12024 Invalid = Parent->isInvalidDecl();
12025 if (Invalid || Parent->isUnion())
12026 return true;
12027 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
12028 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
12029 };
12030
12031 auto &Base = LVal.getLValueBase();
12032 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
12033 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
12034 bool Invalid;
12035 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12036 return Invalid;
12037 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
12038 for (auto *FD : IFD->chain()) {
12039 bool Invalid;
12040 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
12041 return Invalid;
12042 }
12043 }
12044 }
12045
12046 unsigned I = 0;
12047 QualType BaseType = getType(Base);
12048 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
12049 // If we don't know the array bound, conservatively assume we're looking at
12050 // the final array element.
12051 ++I;
12052 if (BaseType->isIncompleteArrayType())
12053 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
12054 else
12055 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
12056 }
12057
12058 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
12059 const auto &Entry = LVal.Designator.Entries[I];
12060 if (BaseType->isArrayType()) {
12061 // Because __builtin_object_size treats arrays as objects, we can ignore
12062 // the index iff this is the last array in the Designator.
12063 if (I + 1 == E)
12064 return true;
12065 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
12066 uint64_t Index = Entry.getAsArrayIndex();
12067 if (Index + 1 != CAT->getZExtSize())
12068 return false;
12069 BaseType = CAT->getElementType();
12070 } else if (BaseType->isAnyComplexType()) {
12071 const auto *CT = BaseType->castAs<ComplexType>();
12072 uint64_t Index = Entry.getAsArrayIndex();
12073 if (Index != 1)
12074 return false;
12075 BaseType = CT->getElementType();
12076 } else if (auto *FD = getAsField(Entry)) {
12077 bool Invalid;
12078 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12079 return Invalid;
12080 BaseType = FD->getType();
12081 } else {
12082 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
12083 return false;
12084 }
12085 }
12086 return true;
12087}
12088
12089/// Tests to see if the LValue has a user-specified designator (that isn't
12090/// necessarily valid). Note that this always returns 'true' if the LValue has
12091/// an unsized array as its first designator entry, because there's currently no
12092/// way to tell if the user typed *foo or foo[0].
12093static bool refersToCompleteObject(const LValue &LVal) {
12094 if (LVal.Designator.Invalid)
12095 return false;
12096
12097 if (!LVal.Designator.Entries.empty())
12098 return LVal.Designator.isMostDerivedAnUnsizedArray();
12099
12100 if (!LVal.InvalidBase)
12101 return true;
12102
12103 // If `E` is a MemberExpr, then the first part of the designator is hiding in
12104 // the LValueBase.
12105 const auto *E = LVal.Base.dyn_cast<const Expr *>();
12106 return !E || !isa<MemberExpr>(E);
12107}
12108
12109/// Attempts to detect a user writing into a piece of memory that's impossible
12110/// to figure out the size of by just using types.
12111static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
12112 const SubobjectDesignator &Designator = LVal.Designator;
12113 // Notes:
12114 // - Users can only write off of the end when we have an invalid base. Invalid
12115 // bases imply we don't know where the memory came from.
12116 // - We used to be a bit more aggressive here; we'd only be conservative if
12117 // the array at the end was flexible, or if it had 0 or 1 elements. This
12118 // broke some common standard library extensions (PR30346), but was
12119 // otherwise seemingly fine. It may be useful to reintroduce this behavior
12120 // with some sort of list. OTOH, it seems that GCC is always
12121 // conservative with the last element in structs (if it's an array), so our
12122 // current behavior is more compatible than an explicit list approach would
12123 // be.
12124 auto isFlexibleArrayMember = [&] {
12126 FAMKind StrictFlexArraysLevel =
12127 Ctx.getLangOpts().getStrictFlexArraysLevel();
12128
12129 if (Designator.isMostDerivedAnUnsizedArray())
12130 return true;
12131
12132 if (StrictFlexArraysLevel == FAMKind::Default)
12133 return true;
12134
12135 if (Designator.getMostDerivedArraySize() == 0 &&
12136 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
12137 return true;
12138
12139 if (Designator.getMostDerivedArraySize() == 1 &&
12140 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
12141 return true;
12142
12143 return false;
12144 };
12145
12146 return LVal.InvalidBase &&
12147 Designator.Entries.size() == Designator.MostDerivedPathLength &&
12148 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
12149 isDesignatorAtObjectEnd(Ctx, LVal);
12150}
12151
12152/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
12153/// Fails if the conversion would cause loss of precision.
12154static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
12155 CharUnits &Result) {
12156 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
12157 if (Int.ugt(CharUnitsMax))
12158 return false;
12159 Result = CharUnits::fromQuantity(Int.getZExtValue());
12160 return true;
12161}
12162
12163/// If we're evaluating the object size of an instance of a struct that
12164/// contains a flexible array member, add the size of the initializer.
12165static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
12166 const LValue &LV, CharUnits &Size) {
12167 if (!T.isNull() && T->isStructureType() &&
12169 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
12170 if (const auto *VD = dyn_cast<VarDecl>(V))
12171 if (VD->hasInit())
12172 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
12173}
12174
12175/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
12176/// determine how many bytes exist from the beginning of the object to either
12177/// the end of the current subobject, or the end of the object itself, depending
12178/// on what the LValue looks like + the value of Type.
12179///
12180/// If this returns false, the value of Result is undefined.
12181static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
12182 unsigned Type, const LValue &LVal,
12183 CharUnits &EndOffset) {
12184 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
12185
12186 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
12187 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
12188 return false;
12189 return HandleSizeof(Info, ExprLoc, Ty, Result);
12190 };
12191
12192 // We want to evaluate the size of the entire object. This is a valid fallback
12193 // for when Type=1 and the designator is invalid, because we're asked for an
12194 // upper-bound.
12195 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
12196 // Type=3 wants a lower bound, so we can't fall back to this.
12197 if (Type == 3 && !DetermineForCompleteObject)
12198 return false;
12199
12200 llvm::APInt APEndOffset;
12201 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12202 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12203 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12204
12205 if (LVal.InvalidBase)
12206 return false;
12207
12208 QualType BaseTy = getObjectType(LVal.getLValueBase());
12209 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
12210 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
12211 return Ret;
12212 }
12213
12214 // We want to evaluate the size of a subobject.
12215 const SubobjectDesignator &Designator = LVal.Designator;
12216
12217 // The following is a moderately common idiom in C:
12218 //
12219 // struct Foo { int a; char c[1]; };
12220 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
12221 // strcpy(&F->c[0], Bar);
12222 //
12223 // In order to not break too much legacy code, we need to support it.
12224 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
12225 // If we can resolve this to an alloc_size call, we can hand that back,
12226 // because we know for certain how many bytes there are to write to.
12227 llvm::APInt APEndOffset;
12228 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12229 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12230 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12231
12232 // If we cannot determine the size of the initial allocation, then we can't
12233 // given an accurate upper-bound. However, we are still able to give
12234 // conservative lower-bounds for Type=3.
12235 if (Type == 1)
12236 return false;
12237 }
12238
12239 CharUnits BytesPerElem;
12240 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
12241 return false;
12242
12243 // According to the GCC documentation, we want the size of the subobject
12244 // denoted by the pointer. But that's not quite right -- what we actually
12245 // want is the size of the immediately-enclosing array, if there is one.
12246 int64_t ElemsRemaining;
12247 if (Designator.MostDerivedIsArrayElement &&
12248 Designator.Entries.size() == Designator.MostDerivedPathLength) {
12249 uint64_t ArraySize = Designator.getMostDerivedArraySize();
12250 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
12251 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
12252 } else {
12253 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
12254 }
12255
12256 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
12257 return true;
12258}
12259
12260/// Tries to evaluate the __builtin_object_size for @p E. If successful,
12261/// returns true and stores the result in @p Size.
12262///
12263/// If @p WasError is non-null, this will report whether the failure to evaluate
12264/// is to be treated as an Error in IntExprEvaluator.
12265static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
12266 EvalInfo &Info, uint64_t &Size) {
12267 // Determine the denoted object.
12268 LValue LVal;
12269 {
12270 // The operand of __builtin_object_size is never evaluated for side-effects.
12271 // If there are any, but we can determine the pointed-to object anyway, then
12272 // ignore the side-effects.
12273 SpeculativeEvaluationRAII SpeculativeEval(Info);
12274 IgnoreSideEffectsRAII Fold(Info);
12275
12276 if (E->isGLValue()) {
12277 // It's possible for us to be given GLValues if we're called via
12278 // Expr::tryEvaluateObjectSize.
12279 APValue RVal;
12280 if (!EvaluateAsRValue(Info, E, RVal))
12281 return false;
12282 LVal.setFrom(Info.Ctx, RVal);
12283 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
12284 /*InvalidBaseOK=*/true))
12285 return false;
12286 }
12287
12288 // If we point to before the start of the object, there are no accessible
12289 // bytes.
12290 if (LVal.getLValueOffset().isNegative()) {
12291 Size = 0;
12292 return true;
12293 }
12294
12295 CharUnits EndOffset;
12296 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
12297 return false;
12298
12299 // If we've fallen outside of the end offset, just pretend there's nothing to
12300 // write to/read from.
12301 if (EndOffset <= LVal.getLValueOffset())
12302 Size = 0;
12303 else
12304 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
12305 return true;
12306}
12307
12308bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
12309 if (!IsConstantEvaluatedBuiltinCall(E))
12310 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12311 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
12312}
12313
12314static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
12315 APValue &Val, APSInt &Alignment) {
12316 QualType SrcTy = E->getArg(0)->getType();
12317 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
12318 return false;
12319 // Even though we are evaluating integer expressions we could get a pointer
12320 // argument for the __builtin_is_aligned() case.
12321 if (SrcTy->isPointerType()) {
12322 LValue Ptr;
12323 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
12324 return false;
12325 Ptr.moveInto(Val);
12326 } else if (!SrcTy->isIntegralOrEnumerationType()) {
12327 Info.FFDiag(E->getArg(0));
12328 return false;
12329 } else {
12330 APSInt SrcInt;
12331 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
12332 return false;
12333 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
12334 "Bit widths must be the same");
12335 Val = APValue(SrcInt);
12336 }
12337 assert(Val.hasValue());
12338 return true;
12339}
12340
12341bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
12342 unsigned BuiltinOp) {
12343 switch (BuiltinOp) {
12344 default:
12345 return false;
12346
12347 case Builtin::BI__builtin_dynamic_object_size:
12348 case Builtin::BI__builtin_object_size: {
12349 // The type was checked when we built the expression.
12350 unsigned Type =
12351 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12352 assert(Type <= 3 && "unexpected type");
12353
12354 uint64_t Size;
12355 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
12356 return Success(Size, E);
12357
12358 if (E->getArg(0)->HasSideEffects(Info.Ctx))
12359 return Success((Type & 2) ? 0 : -1, E);
12360
12361 // Expression had no side effects, but we couldn't statically determine the
12362 // size of the referenced object.
12363 switch (Info.EvalMode) {
12364 case EvalInfo::EM_ConstantExpression:
12365 case EvalInfo::EM_ConstantFold:
12366 case EvalInfo::EM_IgnoreSideEffects:
12367 // Leave it to IR generation.
12368 return Error(E);
12369 case EvalInfo::EM_ConstantExpressionUnevaluated:
12370 // Reduce it to a constant now.
12371 return Success((Type & 2) ? 0 : -1, E);
12372 }
12373
12374 llvm_unreachable("unexpected EvalMode");
12375 }
12376
12377 case Builtin::BI__builtin_os_log_format_buffer_size: {
12379 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
12380 return Success(Layout.size().getQuantity(), E);
12381 }
12382
12383 case Builtin::BI__builtin_is_aligned: {
12384 APValue Src;
12385 APSInt Alignment;
12386 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12387 return false;
12388 if (Src.isLValue()) {
12389 // If we evaluated a pointer, check the minimum known alignment.
12390 LValue Ptr;
12391 Ptr.setFrom(Info.Ctx, Src);
12392 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
12393 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
12394 // We can return true if the known alignment at the computed offset is
12395 // greater than the requested alignment.
12396 assert(PtrAlign.isPowerOfTwo());
12397 assert(Alignment.isPowerOf2());
12398 if (PtrAlign.getQuantity() >= Alignment)
12399 return Success(1, E);
12400 // If the alignment is not known to be sufficient, some cases could still
12401 // be aligned at run time. However, if the requested alignment is less or
12402 // equal to the base alignment and the offset is not aligned, we know that
12403 // the run-time value can never be aligned.
12404 if (BaseAlignment.getQuantity() >= Alignment &&
12405 PtrAlign.getQuantity() < Alignment)
12406 return Success(0, E);
12407 // Otherwise we can't infer whether the value is sufficiently aligned.
12408 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
12409 // in cases where we can't fully evaluate the pointer.
12410 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
12411 << Alignment;
12412 return false;
12413 }
12414 assert(Src.isInt());
12415 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
12416 }
12417 case Builtin::BI__builtin_align_up: {
12418 APValue Src;
12419 APSInt Alignment;
12420 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12421 return false;
12422 if (!Src.isInt())
12423 return Error(E);
12424 APSInt AlignedVal =
12425 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
12426 Src.getInt().isUnsigned());
12427 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12428 return Success(AlignedVal, E);
12429 }
12430 case Builtin::BI__builtin_align_down: {
12431 APValue Src;
12432 APSInt Alignment;
12433 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12434 return false;
12435 if (!Src.isInt())
12436 return Error(E);
12437 APSInt AlignedVal =
12438 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
12439 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12440 return Success(AlignedVal, E);
12441 }
12442
12443 case Builtin::BI__builtin_bitreverse8:
12444 case Builtin::BI__builtin_bitreverse16:
12445 case Builtin::BI__builtin_bitreverse32:
12446 case Builtin::BI__builtin_bitreverse64: {
12447 APSInt Val;
12448 if (!EvaluateInteger(E->getArg(0), Val, Info))
12449 return false;
12450
12451 return Success(Val.reverseBits(), E);
12452 }
12453
12454 case Builtin::BI__builtin_bswap16:
12455 case Builtin::BI__builtin_bswap32:
12456 case Builtin::BI__builtin_bswap64: {
12457 APSInt Val;
12458 if (!EvaluateInteger(E->getArg(0), Val, Info))
12459 return false;
12460
12461 return Success(Val.byteSwap(), E);
12462 }
12463
12464 case Builtin::BI__builtin_classify_type:
12465 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12466
12467 case Builtin::BI__builtin_clrsb:
12468 case Builtin::BI__builtin_clrsbl:
12469 case Builtin::BI__builtin_clrsbll: {
12470 APSInt Val;
12471 if (!EvaluateInteger(E->getArg(0), Val, Info))
12472 return false;
12473
12474 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
12475 }
12476
12477 case Builtin::BI__builtin_clz:
12478 case Builtin::BI__builtin_clzl:
12479 case Builtin::BI__builtin_clzll:
12480 case Builtin::BI__builtin_clzs:
12481 case Builtin::BI__builtin_clzg:
12482 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
12483 case Builtin::BI__lzcnt:
12484 case Builtin::BI__lzcnt64: {
12485 APSInt Val;
12486 if (!EvaluateInteger(E->getArg(0), Val, Info))
12487 return false;
12488
12489 std::optional<APSInt> Fallback;
12490 if (BuiltinOp == Builtin::BI__builtin_clzg && E->getNumArgs() > 1) {
12491 APSInt FallbackTemp;
12492 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
12493 return false;
12494 Fallback = FallbackTemp;
12495 }
12496
12497 if (!Val) {
12498 if (Fallback)
12499 return Success(*Fallback, E);
12500
12501 // When the argument is 0, the result of GCC builtins is undefined,
12502 // whereas for Microsoft intrinsics, the result is the bit-width of the
12503 // argument.
12504 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
12505 BuiltinOp != Builtin::BI__lzcnt &&
12506 BuiltinOp != Builtin::BI__lzcnt64;
12507
12508 if (ZeroIsUndefined)
12509 return Error(E);
12510 }
12511
12512 return Success(Val.countl_zero(), E);
12513 }
12514
12515 case Builtin::BI__builtin_constant_p: {
12516 const Expr *Arg = E->getArg(0);
12517 if (EvaluateBuiltinConstantP(Info, Arg))
12518 return Success(true, E);
12519 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
12520 // Outside a constant context, eagerly evaluate to false in the presence
12521 // of side-effects in order to avoid -Wunsequenced false-positives in
12522 // a branch on __builtin_constant_p(expr).
12523 return Success(false, E);
12524 }
12525 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12526 return false;
12527 }
12528
12529 case Builtin::BI__builtin_is_constant_evaluated: {
12530 const auto *Callee = Info.CurrentCall->getCallee();
12531 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12532 (Info.CallStackDepth == 1 ||
12533 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12534 Callee->getIdentifier() &&
12535 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12536 // FIXME: Find a better way to avoid duplicated diagnostics.
12537 if (Info.EvalStatus.Diag)
12538 Info.report((Info.CallStackDepth == 1)
12539 ? E->getExprLoc()
12540 : Info.CurrentCall->getCallRange().getBegin(),
12541 diag::warn_is_constant_evaluated_always_true_constexpr)
12542 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12543 : "std::is_constant_evaluated");
12544 }
12545
12546 return Success(Info.InConstantContext, E);
12547 }
12548
12549 case Builtin::BI__builtin_ctz:
12550 case Builtin::BI__builtin_ctzl:
12551 case Builtin::BI__builtin_ctzll:
12552 case Builtin::BI__builtin_ctzs:
12553 case Builtin::BI__builtin_ctzg: {
12554 APSInt Val;
12555 if (!EvaluateInteger(E->getArg(0), Val, Info))
12556 return false;
12557
12558 std::optional<APSInt> Fallback;
12559 if (BuiltinOp == Builtin::BI__builtin_ctzg && E->getNumArgs() > 1) {
12560 APSInt FallbackTemp;
12561 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
12562 return false;
12563 Fallback = FallbackTemp;
12564 }
12565
12566 if (!Val) {
12567 if (Fallback)
12568 return Success(*Fallback, E);
12569
12570 return Error(E);
12571 }
12572
12573 return Success(Val.countr_zero(), E);
12574 }
12575
12576 case Builtin::BI__builtin_eh_return_data_regno: {
12577 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12578 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
12579 return Success(Operand, E);
12580 }
12581
12582 case Builtin::BI__builtin_expect:
12583 case Builtin::BI__builtin_expect_with_probability:
12584 return Visit(E->getArg(0));
12585
12586 case Builtin::BI__builtin_ffs:
12587 case Builtin::BI__builtin_ffsl:
12588 case Builtin::BI__builtin_ffsll: {
12589 APSInt Val;
12590 if (!EvaluateInteger(E->getArg(0), Val, Info))
12591 return false;
12592
12593 unsigned N = Val.countr_zero();
12594 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12595 }
12596
12597 case Builtin::BI__builtin_fpclassify: {
12598 APFloat Val(0.0);
12599 if (!EvaluateFloat(E->getArg(5), Val, Info))
12600 return false;
12601 unsigned Arg;
12602 switch (Val.getCategory()) {
12603 case APFloat::fcNaN: Arg = 0; break;
12604 case APFloat::fcInfinity: Arg = 1; break;
12605 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12606 case APFloat::fcZero: Arg = 4; break;
12607 }
12608 return Visit(E->getArg(Arg));
12609 }
12610
12611 case Builtin::BI__builtin_isinf_sign: {
12612 APFloat Val(0.0);
12613 return EvaluateFloat(E->getArg(0), Val, Info) &&
12614 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12615 }
12616
12617 case Builtin::BI__builtin_isinf: {
12618 APFloat Val(0.0);
12619 return EvaluateFloat(E->getArg(0), Val, Info) &&
12620 Success(Val.isInfinity() ? 1 : 0, E);
12621 }
12622
12623 case Builtin::BI__builtin_isfinite: {
12624 APFloat Val(0.0);
12625 return EvaluateFloat(E->getArg(0), Val, Info) &&
12626 Success(Val.isFinite() ? 1 : 0, E);
12627 }
12628
12629 case Builtin::BI__builtin_isnan: {
12630 APFloat Val(0.0);
12631 return EvaluateFloat(E->getArg(0), Val, Info) &&
12632 Success(Val.isNaN() ? 1 : 0, E);
12633 }
12634
12635 case Builtin::BI__builtin_isnormal: {
12636 APFloat Val(0.0);
12637 return EvaluateFloat(E->getArg(0), Val, Info) &&
12638 Success(Val.isNormal() ? 1 : 0, E);
12639 }
12640
12641 case Builtin::BI__builtin_issubnormal: {
12642 APFloat Val(0.0);
12643 return EvaluateFloat(E->getArg(0), Val, Info) &&
12644 Success(Val.isDenormal() ? 1 : 0, E);
12645 }
12646
12647 case Builtin::BI__builtin_iszero: {
12648 APFloat Val(0.0);
12649 return EvaluateFloat(E->getArg(0), Val, Info) &&
12650 Success(Val.isZero() ? 1 : 0, E);
12651 }
12652
12653 case Builtin::BI__builtin_issignaling: {
12654 APFloat Val(0.0);
12655 return EvaluateFloat(E->getArg(0), Val, Info) &&
12656 Success(Val.isSignaling() ? 1 : 0, E);
12657 }
12658
12659 case Builtin::BI__builtin_isfpclass: {
12660 APSInt MaskVal;
12661 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
12662 return false;
12663 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
12664 APFloat Val(0.0);
12665 return EvaluateFloat(E->getArg(0), Val, Info) &&
12666 Success((Val.classify() & Test) ? 1 : 0, E);
12667 }
12668
12669 case Builtin::BI__builtin_parity:
12670 case Builtin::BI__builtin_parityl:
12671 case Builtin::BI__builtin_parityll: {
12672 APSInt Val;
12673 if (!EvaluateInteger(E->getArg(0), Val, Info))
12674 return false;
12675
12676 return Success(Val.popcount() % 2, E);
12677 }
12678
12679 case Builtin::BI__builtin_popcount:
12680 case Builtin::BI__builtin_popcountl:
12681 case Builtin::BI__builtin_popcountll:
12682 case Builtin::BI__builtin_popcountg:
12683 case Builtin::BI__popcnt16: // Microsoft variants of popcount
12684 case Builtin::BI__popcnt:
12685 case Builtin::BI__popcnt64: {
12686 APSInt Val;
12687 if (!EvaluateInteger(E->getArg(0), Val, Info))
12688 return false;
12689
12690 return Success(Val.popcount(), E);
12691 }
12692
12693 case Builtin::BI__builtin_rotateleft8:
12694 case Builtin::BI__builtin_rotateleft16:
12695 case Builtin::BI__builtin_rotateleft32:
12696 case Builtin::BI__builtin_rotateleft64:
12697 case Builtin::BI_rotl8: // Microsoft variants of rotate right
12698 case Builtin::BI_rotl16:
12699 case Builtin::BI_rotl:
12700 case Builtin::BI_lrotl:
12701 case Builtin::BI_rotl64: {
12702 APSInt Val, Amt;
12703 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12704 !EvaluateInteger(E->getArg(1), Amt, Info))
12705 return false;
12706
12707 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12708 }
12709
12710 case Builtin::BI__builtin_rotateright8:
12711 case Builtin::BI__builtin_rotateright16:
12712 case Builtin::BI__builtin_rotateright32:
12713 case Builtin::BI__builtin_rotateright64:
12714 case Builtin::BI_rotr8: // Microsoft variants of rotate right
12715 case Builtin::BI_rotr16:
12716 case Builtin::BI_rotr:
12717 case Builtin::BI_lrotr:
12718 case Builtin::BI_rotr64: {
12719 APSInt Val, Amt;
12720 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12721 !EvaluateInteger(E->getArg(1), Amt, Info))
12722 return false;
12723
12724 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12725 }
12726
12727 case Builtin::BIstrlen:
12728 case Builtin::BIwcslen:
12729 // A call to strlen is not a constant expression.
12730 if (Info.getLangOpts().CPlusPlus11)
12731 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12732 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12733 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12734 else
12735 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12736 [[fallthrough]];
12737 case Builtin::BI__builtin_strlen:
12738 case Builtin::BI__builtin_wcslen: {
12739 // As an extension, we support __builtin_strlen() as a constant expression,
12740 // and support folding strlen() to a constant.
12741 uint64_t StrLen;
12742 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12743 return Success(StrLen, E);
12744 return false;
12745 }
12746
12747 case Builtin::BIstrcmp:
12748 case Builtin::BIwcscmp:
12749 case Builtin::BIstrncmp:
12750 case Builtin::BIwcsncmp:
12751 case Builtin::BImemcmp:
12752 case Builtin::BIbcmp:
12753 case Builtin::BIwmemcmp:
12754 // A call to strlen is not a constant expression.
12755 if (Info.getLangOpts().CPlusPlus11)
12756 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12757 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12758 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12759 else
12760 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12761 [[fallthrough]];
12762 case Builtin::BI__builtin_strcmp:
12763 case Builtin::BI__builtin_wcscmp:
12764 case Builtin::BI__builtin_strncmp:
12765 case Builtin::BI__builtin_wcsncmp:
12766 case Builtin::BI__builtin_memcmp:
12767 case Builtin::BI__builtin_bcmp:
12768 case Builtin::BI__builtin_wmemcmp: {
12769 LValue String1, String2;
12770 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12771 !EvaluatePointer(E->getArg(1), String2, Info))
12772 return false;
12773
12774 uint64_t MaxLength = uint64_t(-1);
12775 if (BuiltinOp != Builtin::BIstrcmp &&
12776 BuiltinOp != Builtin::BIwcscmp &&
12777 BuiltinOp != Builtin::BI__builtin_strcmp &&
12778 BuiltinOp != Builtin::BI__builtin_wcscmp) {
12779 APSInt N;
12780 if (!EvaluateInteger(E->getArg(2), N, Info))
12781 return false;
12782 MaxLength = N.getZExtValue();
12783 }
12784
12785 // Empty substrings compare equal by definition.
12786 if (MaxLength == 0u)
12787 return Success(0, E);
12788
12789 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12790 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12791 String1.Designator.Invalid || String2.Designator.Invalid)
12792 return false;
12793
12794 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12795 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12796
12797 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12798 BuiltinOp == Builtin::BIbcmp ||
12799 BuiltinOp == Builtin::BI__builtin_memcmp ||
12800 BuiltinOp == Builtin::BI__builtin_bcmp;
12801
12802 assert(IsRawByte ||
12803 (Info.Ctx.hasSameUnqualifiedType(
12804 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12805 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12806
12807 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12808 // 'char8_t', but no other types.
12809 if (IsRawByte &&
12810 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12811 // FIXME: Consider using our bit_cast implementation to support this.
12812 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12813 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
12814 << CharTy1 << CharTy2;
12815 return false;
12816 }
12817
12818 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12819 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12820 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12821 Char1.isInt() && Char2.isInt();
12822 };
12823 const auto &AdvanceElems = [&] {
12824 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12825 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12826 };
12827
12828 bool StopAtNull =
12829 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12830 BuiltinOp != Builtin::BIwmemcmp &&
12831 BuiltinOp != Builtin::BI__builtin_memcmp &&
12832 BuiltinOp != Builtin::BI__builtin_bcmp &&
12833 BuiltinOp != Builtin::BI__builtin_wmemcmp);
12834 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12835 BuiltinOp == Builtin::BIwcsncmp ||
12836 BuiltinOp == Builtin::BIwmemcmp ||
12837 BuiltinOp == Builtin::BI__builtin_wcscmp ||
12838 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12839 BuiltinOp == Builtin::BI__builtin_wmemcmp;
12840
12841 for (; MaxLength; --MaxLength) {
12842 APValue Char1, Char2;
12843 if (!ReadCurElems(Char1, Char2))
12844 return false;
12845 if (Char1.getInt().ne(Char2.getInt())) {
12846 if (IsWide) // wmemcmp compares with wchar_t signedness.
12847 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12848 // memcmp always compares unsigned chars.
12849 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12850 }
12851 if (StopAtNull && !Char1.getInt())
12852 return Success(0, E);
12853 assert(!(StopAtNull && !Char2.getInt()));
12854 if (!AdvanceElems())
12855 return false;
12856 }
12857 // We hit the strncmp / memcmp limit.
12858 return Success(0, E);
12859 }
12860
12861 case Builtin::BI__atomic_always_lock_free:
12862 case Builtin::BI__atomic_is_lock_free:
12863 case Builtin::BI__c11_atomic_is_lock_free: {
12864 APSInt SizeVal;
12865 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12866 return false;
12867
12868 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12869 // of two less than or equal to the maximum inline atomic width, we know it
12870 // is lock-free. If the size isn't a power of two, or greater than the
12871 // maximum alignment where we promote atomics, we know it is not lock-free
12872 // (at least not in the sense of atomic_is_lock_free). Otherwise,
12873 // the answer can only be determined at runtime; for example, 16-byte
12874 // atomics have lock-free implementations on some, but not all,
12875 // x86-64 processors.
12876
12877 // Check power-of-two.
12878 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12879 if (Size.isPowerOfTwo()) {
12880 // Check against inlining width.
12881 unsigned InlineWidthBits =
12882 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12883 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12884 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12885 Size == CharUnits::One() ||
12886 E->getArg(1)->isNullPointerConstant(Info.Ctx,
12888 // OK, we will inline appropriately-aligned operations of this size,
12889 // and _Atomic(T) is appropriately-aligned.
12890 return Success(1, E);
12891
12892 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12893 castAs<PointerType>()->getPointeeType();
12894 if (!PointeeType->isIncompleteType() &&
12895 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12896 // OK, we will inline operations on this object.
12897 return Success(1, E);
12898 }
12899 }
12900 }
12901
12902 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12903 Success(0, E) : Error(E);
12904 }
12905 case Builtin::BI__builtin_addcb:
12906 case Builtin::BI__builtin_addcs:
12907 case Builtin::BI__builtin_addc:
12908 case Builtin::BI__builtin_addcl:
12909 case Builtin::BI__builtin_addcll:
12910 case Builtin::BI__builtin_subcb:
12911 case Builtin::BI__builtin_subcs:
12912 case Builtin::BI__builtin_subc:
12913 case Builtin::BI__builtin_subcl:
12914 case Builtin::BI__builtin_subcll: {
12915 LValue CarryOutLValue;
12916 APSInt LHS, RHS, CarryIn, CarryOut, Result;
12917 QualType ResultType = E->getArg(0)->getType();
12918 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12919 !EvaluateInteger(E->getArg(1), RHS, Info) ||
12920 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
12921 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
12922 return false;
12923 // Copy the number of bits and sign.
12924 Result = LHS;
12925 CarryOut = LHS;
12926
12927 bool FirstOverflowed = false;
12928 bool SecondOverflowed = false;
12929 switch (BuiltinOp) {
12930 default:
12931 llvm_unreachable("Invalid value for BuiltinOp");
12932 case Builtin::BI__builtin_addcb:
12933 case Builtin::BI__builtin_addcs:
12934 case Builtin::BI__builtin_addc:
12935 case Builtin::BI__builtin_addcl:
12936 case Builtin::BI__builtin_addcll:
12937 Result =
12938 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
12939 break;
12940 case Builtin::BI__builtin_subcb:
12941 case Builtin::BI__builtin_subcs:
12942 case Builtin::BI__builtin_subc:
12943 case Builtin::BI__builtin_subcl:
12944 case Builtin::BI__builtin_subcll:
12945 Result =
12946 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
12947 break;
12948 }
12949
12950 // It is possible for both overflows to happen but CGBuiltin uses an OR so
12951 // this is consistent.
12952 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
12953 APValue APV{CarryOut};
12954 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
12955 return false;
12956 return Success(Result, E);
12957 }
12958 case Builtin::BI__builtin_add_overflow:
12959 case Builtin::BI__builtin_sub_overflow:
12960 case Builtin::BI__builtin_mul_overflow:
12961 case Builtin::BI__builtin_sadd_overflow:
12962 case Builtin::BI__builtin_uadd_overflow:
12963 case Builtin::BI__builtin_uaddl_overflow:
12964 case Builtin::BI__builtin_uaddll_overflow:
12965 case Builtin::BI__builtin_usub_overflow:
12966 case Builtin::BI__builtin_usubl_overflow:
12967 case Builtin::BI__builtin_usubll_overflow:
12968 case Builtin::BI__builtin_umul_overflow:
12969 case Builtin::BI__builtin_umull_overflow:
12970 case Builtin::BI__builtin_umulll_overflow:
12971 case Builtin::BI__builtin_saddl_overflow:
12972 case Builtin::BI__builtin_saddll_overflow:
12973 case Builtin::BI__builtin_ssub_overflow:
12974 case Builtin::BI__builtin_ssubl_overflow:
12975 case Builtin::BI__builtin_ssubll_overflow:
12976 case Builtin::BI__builtin_smul_overflow:
12977 case Builtin::BI__builtin_smull_overflow:
12978 case Builtin::BI__builtin_smulll_overflow: {
12979 LValue ResultLValue;
12980 APSInt LHS, RHS;
12981
12982 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12983 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12984 !EvaluateInteger(E->getArg(1), RHS, Info) ||
12985 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12986 return false;
12987
12988 APSInt Result;
12989 bool DidOverflow = false;
12990
12991 // If the types don't have to match, enlarge all 3 to the largest of them.
12992 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12993 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12994 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12995 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12997 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12999 uint64_t LHSSize = LHS.getBitWidth();
13000 uint64_t RHSSize = RHS.getBitWidth();
13001 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
13002 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
13003
13004 // Add an additional bit if the signedness isn't uniformly agreed to. We
13005 // could do this ONLY if there is a signed and an unsigned that both have
13006 // MaxBits, but the code to check that is pretty nasty. The issue will be
13007 // caught in the shrink-to-result later anyway.
13008 if (IsSigned && !AllSigned)
13009 ++MaxBits;
13010
13011 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
13012 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
13013 Result = APSInt(MaxBits, !IsSigned);
13014 }
13015
13016 // Find largest int.
13017 switch (BuiltinOp) {
13018 default:
13019 llvm_unreachable("Invalid value for BuiltinOp");
13020 case Builtin::BI__builtin_add_overflow:
13021 case Builtin::BI__builtin_sadd_overflow:
13022 case Builtin::BI__builtin_saddl_overflow:
13023 case Builtin::BI__builtin_saddll_overflow:
13024 case Builtin::BI__builtin_uadd_overflow:
13025 case Builtin::BI__builtin_uaddl_overflow:
13026 case Builtin::BI__builtin_uaddll_overflow:
13027 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
13028 : LHS.uadd_ov(RHS, DidOverflow);
13029 break;
13030 case Builtin::BI__builtin_sub_overflow:
13031 case Builtin::BI__builtin_ssub_overflow:
13032 case Builtin::BI__builtin_ssubl_overflow:
13033 case Builtin::BI__builtin_ssubll_overflow:
13034 case Builtin::BI__builtin_usub_overflow:
13035 case Builtin::BI__builtin_usubl_overflow:
13036 case Builtin::BI__builtin_usubll_overflow:
13037 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
13038 : LHS.usub_ov(RHS, DidOverflow);
13039 break;
13040 case Builtin::BI__builtin_mul_overflow:
13041 case Builtin::BI__builtin_smul_overflow:
13042 case Builtin::BI__builtin_smull_overflow:
13043 case Builtin::BI__builtin_smulll_overflow:
13044 case Builtin::BI__builtin_umul_overflow:
13045 case Builtin::BI__builtin_umull_overflow:
13046 case Builtin::BI__builtin_umulll_overflow:
13047 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
13048 : LHS.umul_ov(RHS, DidOverflow);
13049 break;
13050 }
13051
13052 // In the case where multiple sizes are allowed, truncate and see if
13053 // the values are the same.
13054 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13055 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13056 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13057 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
13058 // since it will give us the behavior of a TruncOrSelf in the case where
13059 // its parameter <= its size. We previously set Result to be at least the
13060 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
13061 // will work exactly like TruncOrSelf.
13062 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
13063 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
13064
13065 if (!APSInt::isSameValue(Temp, Result))
13066 DidOverflow = true;
13067 Result = Temp;
13068 }
13069
13070 APValue APV{Result};
13071 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13072 return false;
13073 return Success(DidOverflow, E);
13074 }
13075 }
13076}
13077
13078/// Determine whether this is a pointer past the end of the complete
13079/// object referred to by the lvalue.
13081 const LValue &LV) {
13082 // A null pointer can be viewed as being "past the end" but we don't
13083 // choose to look at it that way here.
13084 if (!LV.getLValueBase())
13085 return false;
13086
13087 // If the designator is valid and refers to a subobject, we're not pointing
13088 // past the end.
13089 if (!LV.getLValueDesignator().Invalid &&
13090 !LV.getLValueDesignator().isOnePastTheEnd())
13091 return false;
13092
13093 // A pointer to an incomplete type might be past-the-end if the type's size is
13094 // zero. We cannot tell because the type is incomplete.
13095 QualType Ty = getType(LV.getLValueBase());
13096 if (Ty->isIncompleteType())
13097 return true;
13098
13099 // Can't be past the end of an invalid object.
13100 if (LV.getLValueDesignator().Invalid)
13101 return false;
13102
13103 // We're a past-the-end pointer if we point to the byte after the object,
13104 // no matter what our type or path is.
13105 auto Size = Ctx.getTypeSizeInChars(Ty);
13106 return LV.getLValueOffset() == Size;
13107}
13108
13109namespace {
13110
13111/// Data recursive integer evaluator of certain binary operators.
13112///
13113/// We use a data recursive algorithm for binary operators so that we are able
13114/// to handle extreme cases of chained binary operators without causing stack
13115/// overflow.
13116class DataRecursiveIntBinOpEvaluator {
13117 struct EvalResult {
13118 APValue Val;
13119 bool Failed = false;
13120
13121 EvalResult() = default;
13122
13123 void swap(EvalResult &RHS) {
13124 Val.swap(RHS.Val);
13125 Failed = RHS.Failed;
13126 RHS.Failed = false;
13127 }
13128 };
13129
13130 struct Job {
13131 const Expr *E;
13132 EvalResult LHSResult; // meaningful only for binary operator expression.
13133 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
13134
13135 Job() = default;
13136 Job(Job &&) = default;
13137
13138 void startSpeculativeEval(EvalInfo &Info) {
13139 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
13140 }
13141
13142 private:
13143 SpeculativeEvaluationRAII SpecEvalRAII;
13144 };
13145
13147
13148 IntExprEvaluator &IntEval;
13149 EvalInfo &Info;
13150 APValue &FinalResult;
13151
13152public:
13153 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
13154 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
13155
13156 /// True if \param E is a binary operator that we are going to handle
13157 /// data recursively.
13158 /// We handle binary operators that are comma, logical, or that have operands
13159 /// with integral or enumeration type.
13160 static bool shouldEnqueue(const BinaryOperator *E) {
13161 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
13165 }
13166
13167 bool Traverse(const BinaryOperator *E) {
13168 enqueue(E);
13169 EvalResult PrevResult;
13170 while (!Queue.empty())
13171 process(PrevResult);
13172
13173 if (PrevResult.Failed) return false;
13174
13175 FinalResult.swap(PrevResult.Val);
13176 return true;
13177 }
13178
13179private:
13180 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
13181 return IntEval.Success(Value, E, Result);
13182 }
13183 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
13184 return IntEval.Success(Value, E, Result);
13185 }
13186 bool Error(const Expr *E) {
13187 return IntEval.Error(E);
13188 }
13189 bool Error(const Expr *E, diag::kind D) {
13190 return IntEval.Error(E, D);
13191 }
13192
13193 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
13194 return Info.CCEDiag(E, D);
13195 }
13196
13197 // Returns true if visiting the RHS is necessary, false otherwise.
13198 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
13199 bool &SuppressRHSDiags);
13200
13201 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13202 const BinaryOperator *E, APValue &Result);
13203
13204 void EvaluateExpr(const Expr *E, EvalResult &Result) {
13205 Result.Failed = !Evaluate(Result.Val, Info, E);
13206 if (Result.Failed)
13207 Result.Val = APValue();
13208 }
13209
13210 void process(EvalResult &Result);
13211
13212 void enqueue(const Expr *E) {
13213 E = E->IgnoreParens();
13214 Queue.resize(Queue.size()+1);
13215 Queue.back().E = E;
13216 Queue.back().Kind = Job::AnyExprKind;
13217 }
13218};
13219
13220}
13221
13222bool DataRecursiveIntBinOpEvaluator::
13223 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
13224 bool &SuppressRHSDiags) {
13225 if (E->getOpcode() == BO_Comma) {
13226 // Ignore LHS but note if we could not evaluate it.
13227 if (LHSResult.Failed)
13228 return Info.noteSideEffect();
13229 return true;
13230 }
13231
13232 if (E->isLogicalOp()) {
13233 bool LHSAsBool;
13234 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
13235 // We were able to evaluate the LHS, see if we can get away with not
13236 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
13237 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
13238 Success(LHSAsBool, E, LHSResult.Val);
13239 return false; // Ignore RHS
13240 }
13241 } else {
13242 LHSResult.Failed = true;
13243
13244 // Since we weren't able to evaluate the left hand side, it
13245 // might have had side effects.
13246 if (!Info.noteSideEffect())
13247 return false;
13248
13249 // We can't evaluate the LHS; however, sometimes the result
13250 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13251 // Don't ignore RHS and suppress diagnostics from this arm.
13252 SuppressRHSDiags = true;
13253 }
13254
13255 return true;
13256 }
13257
13258 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13260
13261 if (LHSResult.Failed && !Info.noteFailure())
13262 return false; // Ignore RHS;
13263
13264 return true;
13265}
13266
13267static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
13268 bool IsSub) {
13269 // Compute the new offset in the appropriate width, wrapping at 64 bits.
13270 // FIXME: When compiling for a 32-bit target, we should use 32-bit
13271 // offsets.
13272 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
13273 CharUnits &Offset = LVal.getLValueOffset();
13274 uint64_t Offset64 = Offset.getQuantity();
13275 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
13276 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
13277 : Offset64 + Index64);
13278}
13279
13280bool DataRecursiveIntBinOpEvaluator::
13281 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13282 const BinaryOperator *E, APValue &Result) {
13283 if (E->getOpcode() == BO_Comma) {
13284 if (RHSResult.Failed)
13285 return false;
13286 Result = RHSResult.Val;
13287 return true;
13288 }
13289
13290 if (E->isLogicalOp()) {
13291 bool lhsResult, rhsResult;
13292 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
13293 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
13294
13295 if (LHSIsOK) {
13296 if (RHSIsOK) {
13297 if (E->getOpcode() == BO_LOr)
13298 return Success(lhsResult || rhsResult, E, Result);
13299 else
13300 return Success(lhsResult && rhsResult, E, Result);
13301 }
13302 } else {
13303 if (RHSIsOK) {
13304 // We can't evaluate the LHS; however, sometimes the result
13305 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13306 if (rhsResult == (E->getOpcode() == BO_LOr))
13307 return Success(rhsResult, E, Result);
13308 }
13309 }
13310
13311 return false;
13312 }
13313
13314 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13316
13317 if (LHSResult.Failed || RHSResult.Failed)
13318 return false;
13319
13320 const APValue &LHSVal = LHSResult.Val;
13321 const APValue &RHSVal = RHSResult.Val;
13322
13323 // Handle cases like (unsigned long)&a + 4.
13324 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
13325 Result = LHSVal;
13326 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
13327 return true;
13328 }
13329
13330 // Handle cases like 4 + (unsigned long)&a
13331 if (E->getOpcode() == BO_Add &&
13332 RHSVal.isLValue() && LHSVal.isInt()) {
13333 Result = RHSVal;
13334 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
13335 return true;
13336 }
13337
13338 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
13339 // Handle (intptr_t)&&A - (intptr_t)&&B.
13340 if (!LHSVal.getLValueOffset().isZero() ||
13341 !RHSVal.getLValueOffset().isZero())
13342 return false;
13343 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
13344 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
13345 if (!LHSExpr || !RHSExpr)
13346 return false;
13347 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13348 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13349 if (!LHSAddrExpr || !RHSAddrExpr)
13350 return false;
13351 // Make sure both labels come from the same function.
13352 if (LHSAddrExpr->getLabel()->getDeclContext() !=
13353 RHSAddrExpr->getLabel()->getDeclContext())
13354 return false;
13355 Result = APValue(LHSAddrExpr, RHSAddrExpr);
13356 return true;
13357 }
13358
13359 // All the remaining cases expect both operands to be an integer
13360 if (!LHSVal.isInt() || !RHSVal.isInt())
13361 return Error(E);
13362
13363 // Set up the width and signedness manually, in case it can't be deduced
13364 // from the operation we're performing.
13365 // FIXME: Don't do this in the cases where we can deduce it.
13366 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
13368 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
13369 RHSVal.getInt(), Value))
13370 return false;
13371 return Success(Value, E, Result);
13372}
13373
13374void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
13375 Job &job = Queue.back();
13376
13377 switch (job.Kind) {
13378 case Job::AnyExprKind: {
13379 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
13380 if (shouldEnqueue(Bop)) {
13381 job.Kind = Job::BinOpKind;
13382 enqueue(Bop->getLHS());
13383 return;
13384 }
13385 }
13386
13387 EvaluateExpr(job.E, Result);
13388 Queue.pop_back();
13389 return;
13390 }
13391
13392 case Job::BinOpKind: {
13393 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
13394 bool SuppressRHSDiags = false;
13395 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
13396 Queue.pop_back();
13397 return;
13398 }
13399 if (SuppressRHSDiags)
13400 job.startSpeculativeEval(Info);
13401 job.LHSResult.swap(Result);
13402 job.Kind = Job::BinOpVisitedLHSKind;
13403 enqueue(Bop->getRHS());
13404 return;
13405 }
13406
13407 case Job::BinOpVisitedLHSKind: {
13408 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
13409 EvalResult RHS;
13410 RHS.swap(Result);
13411 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
13412 Queue.pop_back();
13413 return;
13414 }
13415 }
13416
13417 llvm_unreachable("Invalid Job::Kind!");
13418}
13419
13420namespace {
13421enum class CmpResult {
13422 Unequal,
13423 Less,
13424 Equal,
13425 Greater,
13426 Unordered,
13427};
13428}
13429
13430template <class SuccessCB, class AfterCB>
13431static bool
13433 SuccessCB &&Success, AfterCB &&DoAfter) {
13434 assert(!E->isValueDependent());
13435 assert(E->isComparisonOp() && "expected comparison operator");
13436 assert((E->getOpcode() == BO_Cmp ||
13438 "unsupported binary expression evaluation");
13439 auto Error = [&](const Expr *E) {
13440 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13441 return false;
13442 };
13443
13444 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
13445 bool IsEquality = E->isEqualityOp();
13446
13447 QualType LHSTy = E->getLHS()->getType();
13448 QualType RHSTy = E->getRHS()->getType();
13449
13450 if (LHSTy->isIntegralOrEnumerationType() &&
13451 RHSTy->isIntegralOrEnumerationType()) {
13452 APSInt LHS, RHS;
13453 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
13454 if (!LHSOK && !Info.noteFailure())
13455 return false;
13456 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
13457 return false;
13458 if (LHS < RHS)
13459 return Success(CmpResult::Less, E);
13460 if (LHS > RHS)
13461 return Success(CmpResult::Greater, E);
13462 return Success(CmpResult::Equal, E);
13463 }
13464
13465 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
13466 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
13467 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
13468
13469 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
13470 if (!LHSOK && !Info.noteFailure())
13471 return false;
13472 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
13473 return false;
13474 if (LHSFX < RHSFX)
13475 return Success(CmpResult::Less, E);
13476 if (LHSFX > RHSFX)
13477 return Success(CmpResult::Greater, E);
13478 return Success(CmpResult::Equal, E);
13479 }
13480
13481 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
13482 ComplexValue LHS, RHS;
13483 bool LHSOK;
13484 if (E->isAssignmentOp()) {
13485 LValue LV;
13486 EvaluateLValue(E->getLHS(), LV, Info);
13487 LHSOK = false;
13488 } else if (LHSTy->isRealFloatingType()) {
13489 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
13490 if (LHSOK) {
13491 LHS.makeComplexFloat();
13492 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
13493 }
13494 } else {
13495 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
13496 }
13497 if (!LHSOK && !Info.noteFailure())
13498 return false;
13499
13500 if (E->getRHS()->getType()->isRealFloatingType()) {
13501 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
13502 return false;
13503 RHS.makeComplexFloat();
13504 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
13505 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13506 return false;
13507
13508 if (LHS.isComplexFloat()) {
13509 APFloat::cmpResult CR_r =
13510 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
13511 APFloat::cmpResult CR_i =
13512 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
13513 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
13514 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13515 } else {
13516 assert(IsEquality && "invalid complex comparison");
13517 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
13518 LHS.getComplexIntImag() == RHS.getComplexIntImag();
13519 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13520 }
13521 }
13522
13523 if (LHSTy->isRealFloatingType() &&
13524 RHSTy->isRealFloatingType()) {
13525 APFloat RHS(0.0), LHS(0.0);
13526
13527 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
13528 if (!LHSOK && !Info.noteFailure())
13529 return false;
13530
13531 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
13532 return false;
13533
13534 assert(E->isComparisonOp() && "Invalid binary operator!");
13535 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
13536 if (!Info.InConstantContext &&
13537 APFloatCmpResult == APFloat::cmpUnordered &&
13538 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
13539 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
13540 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
13541 return false;
13542 }
13543 auto GetCmpRes = [&]() {
13544 switch (APFloatCmpResult) {
13545 case APFloat::cmpEqual:
13546 return CmpResult::Equal;
13547 case APFloat::cmpLessThan:
13548 return CmpResult::Less;
13549 case APFloat::cmpGreaterThan:
13550 return CmpResult::Greater;
13551 case APFloat::cmpUnordered:
13552 return CmpResult::Unordered;
13553 }
13554 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
13555 };
13556 return Success(GetCmpRes(), E);
13557 }
13558
13559 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
13560 LValue LHSValue, RHSValue;
13561
13562 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13563 if (!LHSOK && !Info.noteFailure())
13564 return false;
13565
13566 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13567 return false;
13568
13569 // Reject differing bases from the normal codepath; we special-case
13570 // comparisons to null.
13571 if (!HasSameBase(LHSValue, RHSValue)) {
13572 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
13573 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
13574 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
13575 Info.FFDiag(E, DiagID)
13576 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
13577 return false;
13578 };
13579 // Inequalities and subtractions between unrelated pointers have
13580 // unspecified or undefined behavior.
13581 if (!IsEquality)
13582 return DiagComparison(
13583 diag::note_constexpr_pointer_comparison_unspecified);
13584 // A constant address may compare equal to the address of a symbol.
13585 // The one exception is that address of an object cannot compare equal
13586 // to a null pointer constant.
13587 // TODO: Should we restrict this to actual null pointers, and exclude the
13588 // case of zero cast to pointer type?
13589 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
13590 (!RHSValue.Base && !RHSValue.Offset.isZero()))
13591 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
13592 !RHSValue.Base);
13593 // It's implementation-defined whether distinct literals will have
13594 // distinct addresses. In clang, the result of such a comparison is
13595 // unspecified, so it is not a constant expression. However, we do know
13596 // that the address of a literal will be non-null.
13597 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
13598 LHSValue.Base && RHSValue.Base)
13599 return DiagComparison(diag::note_constexpr_literal_comparison);
13600 // We can't tell whether weak symbols will end up pointing to the same
13601 // object.
13602 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
13603 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
13604 !IsWeakLValue(LHSValue));
13605 // We can't compare the address of the start of one object with the
13606 // past-the-end address of another object, per C++ DR1652.
13607 if (LHSValue.Base && LHSValue.Offset.isZero() &&
13608 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
13609 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13610 true);
13611 if (RHSValue.Base && RHSValue.Offset.isZero() &&
13612 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
13613 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13614 false);
13615 // We can't tell whether an object is at the same address as another
13616 // zero sized object.
13617 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
13618 (LHSValue.Base && isZeroSized(RHSValue)))
13619 return DiagComparison(
13620 diag::note_constexpr_pointer_comparison_zero_sized);
13621 return Success(CmpResult::Unequal, E);
13622 }
13623
13624 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13625 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13626
13627 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13628 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13629
13630 // C++11 [expr.rel]p3:
13631 // Pointers to void (after pointer conversions) can be compared, with a
13632 // result defined as follows: If both pointers represent the same
13633 // address or are both the null pointer value, the result is true if the
13634 // operator is <= or >= and false otherwise; otherwise the result is
13635 // unspecified.
13636 // We interpret this as applying to pointers to *cv* void.
13637 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
13638 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
13639
13640 // C++11 [expr.rel]p2:
13641 // - If two pointers point to non-static data members of the same object,
13642 // or to subobjects or array elements fo such members, recursively, the
13643 // pointer to the later declared member compares greater provided the
13644 // two members have the same access control and provided their class is
13645 // not a union.
13646 // [...]
13647 // - Otherwise pointer comparisons are unspecified.
13648 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
13649 bool WasArrayIndex;
13650 unsigned Mismatch = FindDesignatorMismatch(
13651 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13652 // At the point where the designators diverge, the comparison has a
13653 // specified value if:
13654 // - we are comparing array indices
13655 // - we are comparing fields of a union, or fields with the same access
13656 // Otherwise, the result is unspecified and thus the comparison is not a
13657 // constant expression.
13658 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
13659 Mismatch < RHSDesignator.Entries.size()) {
13660 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13661 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13662 if (!LF && !RF)
13663 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13664 else if (!LF)
13665 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13666 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13667 << RF->getParent() << RF;
13668 else if (!RF)
13669 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13670 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13671 << LF->getParent() << LF;
13672 else if (!LF->getParent()->isUnion() &&
13673 LF->getAccess() != RF->getAccess())
13674 Info.CCEDiag(E,
13675 diag::note_constexpr_pointer_comparison_differing_access)
13676 << LF << LF->getAccess() << RF << RF->getAccess()
13677 << LF->getParent();
13678 }
13679 }
13680
13681 // The comparison here must be unsigned, and performed with the same
13682 // width as the pointer.
13683 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13684 uint64_t CompareLHS = LHSOffset.getQuantity();
13685 uint64_t CompareRHS = RHSOffset.getQuantity();
13686 assert(PtrSize <= 64 && "Unexpected pointer width");
13687 uint64_t Mask = ~0ULL >> (64 - PtrSize);
13688 CompareLHS &= Mask;
13689 CompareRHS &= Mask;
13690
13691 // If there is a base and this is a relational operator, we can only
13692 // compare pointers within the object in question; otherwise, the result
13693 // depends on where the object is located in memory.
13694 if (!LHSValue.Base.isNull() && IsRelational) {
13695 QualType BaseTy = getType(LHSValue.Base);
13696 if (BaseTy->isIncompleteType())
13697 return Error(E);
13698 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13699 uint64_t OffsetLimit = Size.getQuantity();
13700 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13701 return Error(E);
13702 }
13703
13704 if (CompareLHS < CompareRHS)
13705 return Success(CmpResult::Less, E);
13706 if (CompareLHS > CompareRHS)
13707 return Success(CmpResult::Greater, E);
13708 return Success(CmpResult::Equal, E);
13709 }
13710
13711 if (LHSTy->isMemberPointerType()) {
13712 assert(IsEquality && "unexpected member pointer operation");
13713 assert(RHSTy->isMemberPointerType() && "invalid comparison");
13714
13715 MemberPtr LHSValue, RHSValue;
13716
13717 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13718 if (!LHSOK && !Info.noteFailure())
13719 return false;
13720
13721 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13722 return false;
13723
13724 // If either operand is a pointer to a weak function, the comparison is not
13725 // constant.
13726 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
13727 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13728 << LHSValue.getDecl();
13729 return false;
13730 }
13731 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
13732 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13733 << RHSValue.getDecl();
13734 return false;
13735 }
13736
13737 // C++11 [expr.eq]p2:
13738 // If both operands are null, they compare equal. Otherwise if only one is
13739 // null, they compare unequal.
13740 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13741 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13742 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13743 }
13744
13745 // Otherwise if either is a pointer to a virtual member function, the
13746 // result is unspecified.
13747 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13748 if (MD->isVirtual())
13749 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13750 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13751 if (MD->isVirtual())
13752 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13753
13754 // Otherwise they compare equal if and only if they would refer to the
13755 // same member of the same most derived object or the same subobject if
13756 // they were dereferenced with a hypothetical object of the associated
13757 // class type.
13758 bool Equal = LHSValue == RHSValue;
13759 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13760 }
13761
13762 if (LHSTy->isNullPtrType()) {
13763 assert(E->isComparisonOp() && "unexpected nullptr operation");
13764 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13765 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13766 // are compared, the result is true of the operator is <=, >= or ==, and
13767 // false otherwise.
13768 LValue Res;
13769 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
13770 !EvaluatePointer(E->getRHS(), Res, Info))
13771 return false;
13772 return Success(CmpResult::Equal, E);
13773 }
13774
13775 return DoAfter();
13776}
13777
13778bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13779 if (!CheckLiteralType(Info, E))
13780 return false;
13781
13782 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13784 switch (CR) {
13785 case CmpResult::Unequal:
13786 llvm_unreachable("should never produce Unequal for three-way comparison");
13787 case CmpResult::Less:
13788 CCR = ComparisonCategoryResult::Less;
13789 break;
13790 case CmpResult::Equal:
13791 CCR = ComparisonCategoryResult::Equal;
13792 break;
13793 case CmpResult::Greater:
13794 CCR = ComparisonCategoryResult::Greater;
13795 break;
13796 case CmpResult::Unordered:
13797 CCR = ComparisonCategoryResult::Unordered;
13798 break;
13799 }
13800 // Evaluation succeeded. Lookup the information for the comparison category
13801 // type and fetch the VarDecl for the result.
13802 const ComparisonCategoryInfo &CmpInfo =
13803 Info.Ctx.CompCategories.getInfoForType(E->getType());
13804 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13805 // Check and evaluate the result as a constant expression.
13806 LValue LV;
13807 LV.set(VD);
13808 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13809 return false;
13810 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13811 ConstantExprKind::Normal);
13812 };
13813 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13814 return ExprEvaluatorBaseTy::VisitBinCmp(E);
13815 });
13816}
13817
13818bool RecordExprEvaluator::VisitCXXParenListInitExpr(
13819 const CXXParenListInitExpr *E) {
13820 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
13821}
13822
13823bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13824 // We don't support assignment in C. C++ assignments don't get here because
13825 // assignment is an lvalue in C++.
13826 if (E->isAssignmentOp()) {
13827 Error(E);
13828 if (!Info.noteFailure())
13829 return false;
13830 }
13831
13832 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13833 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13834
13835 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13837 "DataRecursiveIntBinOpEvaluator should have handled integral types");
13838
13839 if (E->isComparisonOp()) {
13840 // Evaluate builtin binary comparisons by evaluating them as three-way
13841 // comparisons and then translating the result.
13842 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13843 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13844 "should only produce Unequal for equality comparisons");
13845 bool IsEqual = CR == CmpResult::Equal,
13846 IsLess = CR == CmpResult::Less,
13847 IsGreater = CR == CmpResult::Greater;
13848 auto Op = E->getOpcode();
13849 switch (Op) {
13850 default:
13851 llvm_unreachable("unsupported binary operator");
13852 case BO_EQ:
13853 case BO_NE:
13854 return Success(IsEqual == (Op == BO_EQ), E);
13855 case BO_LT:
13856 return Success(IsLess, E);
13857 case BO_GT:
13858 return Success(IsGreater, E);
13859 case BO_LE:
13860 return Success(IsEqual || IsLess, E);
13861 case BO_GE:
13862 return Success(IsEqual || IsGreater, E);
13863 }
13864 };
13865 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13866 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13867 });
13868 }
13869
13870 QualType LHSTy = E->getLHS()->getType();
13871 QualType RHSTy = E->getRHS()->getType();
13872
13873 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13874 E->getOpcode() == BO_Sub) {
13875 LValue LHSValue, RHSValue;
13876
13877 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13878 if (!LHSOK && !Info.noteFailure())
13879 return false;
13880
13881 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13882 return false;
13883
13884 // Reject differing bases from the normal codepath; we special-case
13885 // comparisons to null.
13886 if (!HasSameBase(LHSValue, RHSValue)) {
13887 // Handle &&A - &&B.
13888 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13889 return Error(E);
13890 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13891 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13892 if (!LHSExpr || !RHSExpr)
13893 return Error(E);
13894 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13895 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13896 if (!LHSAddrExpr || !RHSAddrExpr)
13897 return Error(E);
13898 // Make sure both labels come from the same function.
13899 if (LHSAddrExpr->getLabel()->getDeclContext() !=
13900 RHSAddrExpr->getLabel()->getDeclContext())
13901 return Error(E);
13902 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13903 }
13904 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13905 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13906
13907 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13908 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13909
13910 // C++11 [expr.add]p6:
13911 // Unless both pointers point to elements of the same array object, or
13912 // one past the last element of the array object, the behavior is
13913 // undefined.
13914 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13915 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13916 RHSDesignator))
13917 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13918
13919 QualType Type = E->getLHS()->getType();
13920 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13921
13922 CharUnits ElementSize;
13923 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13924 return false;
13925
13926 // As an extension, a type may have zero size (empty struct or union in
13927 // C, array of zero length). Pointer subtraction in such cases has
13928 // undefined behavior, so is not constant.
13929 if (ElementSize.isZero()) {
13930 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13931 << ElementType;
13932 return false;
13933 }
13934
13935 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13936 // and produce incorrect results when it overflows. Such behavior
13937 // appears to be non-conforming, but is common, so perhaps we should
13938 // assume the standard intended for such cases to be undefined behavior
13939 // and check for them.
13940
13941 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13942 // overflow in the final conversion to ptrdiff_t.
13943 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13944 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13945 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13946 false);
13947 APSInt TrueResult = (LHS - RHS) / ElemSize;
13948 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13949
13950 if (Result.extend(65) != TrueResult &&
13951 !HandleOverflow(Info, E, TrueResult, E->getType()))
13952 return false;
13953 return Success(Result, E);
13954 }
13955
13956 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13957}
13958
13959/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13960/// a result as the expression's type.
13961bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13962 const UnaryExprOrTypeTraitExpr *E) {
13963 switch(E->getKind()) {
13964 case UETT_PreferredAlignOf:
13965 case UETT_AlignOf: {
13966 if (E->isArgumentType())
13967 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13968 E);
13969 else
13970 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13971 E);
13972 }
13973
13974 case UETT_VecStep: {
13975 QualType Ty = E->getTypeOfArgument();
13976
13977 if (Ty->isVectorType()) {
13978 unsigned n = Ty->castAs<VectorType>()->getNumElements();
13979
13980 // The vec_step built-in functions that take a 3-component
13981 // vector return 4. (OpenCL 1.1 spec 6.11.12)
13982 if (n == 3)
13983 n = 4;
13984
13985 return Success(n, E);
13986 } else
13987 return Success(1, E);
13988 }
13989
13990 case UETT_DataSizeOf:
13991 case UETT_SizeOf: {
13992 QualType SrcTy = E->getTypeOfArgument();
13993 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13994 // the result is the size of the referenced type."
13995 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13996 SrcTy = Ref->getPointeeType();
13997
13998 CharUnits Sizeof;
13999 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
14000 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
14001 : SizeOfType::SizeOf)) {
14002 return false;
14003 }
14004 return Success(Sizeof, E);
14005 }
14006 case UETT_OpenMPRequiredSimdAlign:
14007 assert(E->isArgumentType());
14008 return Success(
14009 Info.Ctx.toCharUnitsFromBits(
14010 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
14011 .getQuantity(),
14012 E);
14013 case UETT_VectorElements: {
14014 QualType Ty = E->getTypeOfArgument();
14015 // If the vector has a fixed size, we can determine the number of elements
14016 // at compile time.
14017 if (Ty->isVectorType())
14018 return Success(Ty->castAs<VectorType>()->getNumElements(), E);
14019
14020 assert(Ty->isSizelessVectorType());
14021 if (Info.InConstantContext)
14022 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
14023 << E->getSourceRange();
14024
14025 return false;
14026 }
14027 }
14028
14029 llvm_unreachable("unknown expr/type trait");
14030}
14031
14032bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
14033 CharUnits Result;
14034 unsigned n = OOE->getNumComponents();
14035 if (n == 0)
14036 return Error(OOE);
14037 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
14038 for (unsigned i = 0; i != n; ++i) {
14039 OffsetOfNode ON = OOE->getComponent(i);
14040 switch (ON.getKind()) {
14041 case OffsetOfNode::Array: {
14042 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
14043 APSInt IdxResult;
14044 if (!EvaluateInteger(Idx, IdxResult, Info))
14045 return false;
14046 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
14047 if (!AT)
14048 return Error(OOE);
14049 CurrentType = AT->getElementType();
14050 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
14051 Result += IdxResult.getSExtValue() * ElementSize;
14052 break;
14053 }
14054
14055 case OffsetOfNode::Field: {
14056 FieldDecl *MemberDecl = ON.getField();
14057 const RecordType *RT = CurrentType->getAs<RecordType>();
14058 if (!RT)
14059 return Error(OOE);
14060 RecordDecl *RD = RT->getDecl();
14061 if (RD->isInvalidDecl()) return false;
14062 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14063 unsigned i = MemberDecl->getFieldIndex();
14064 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
14065 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
14066 CurrentType = MemberDecl->getType().getNonReferenceType();
14067 break;
14068 }
14069
14071 llvm_unreachable("dependent __builtin_offsetof");
14072
14073 case OffsetOfNode::Base: {
14074 CXXBaseSpecifier *BaseSpec = ON.getBase();
14075 if (BaseSpec->isVirtual())
14076 return Error(OOE);
14077
14078 // Find the layout of the class whose base we are looking into.
14079 const RecordType *RT = CurrentType->getAs<RecordType>();
14080 if (!RT)
14081 return Error(OOE);
14082 RecordDecl *RD = RT->getDecl();
14083 if (RD->isInvalidDecl()) return false;
14084 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14085
14086 // Find the base class itself.
14087 CurrentType = BaseSpec->getType();
14088 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
14089 if (!BaseRT)
14090 return Error(OOE);
14091
14092 // Add the offset to the base.
14093 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
14094 break;
14095 }
14096 }
14097 }
14098 return Success(Result, OOE);
14099}
14100
14101bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14102 switch (E->getOpcode()) {
14103 default:
14104 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
14105 // See C99 6.6p3.
14106 return Error(E);
14107 case UO_Extension:
14108 // FIXME: Should extension allow i-c-e extension expressions in its scope?
14109 // If so, we could clear the diagnostic ID.
14110 return Visit(E->getSubExpr());
14111 case UO_Plus:
14112 // The result is just the value.
14113 return Visit(E->getSubExpr());
14114 case UO_Minus: {
14115 if (!Visit(E->getSubExpr()))
14116 return false;
14117 if (!Result.isInt()) return Error(E);
14118 const APSInt &Value = Result.getInt();
14119 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
14120 if (Info.checkingForUndefinedBehavior())
14121 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14122 diag::warn_integer_constant_overflow)
14123 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
14124 /*UpperCase=*/true, /*InsertSeparators=*/true)
14125 << E->getType() << E->getSourceRange();
14126
14127 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
14128 E->getType()))
14129 return false;
14130 }
14131 return Success(-Value, E);
14132 }
14133 case UO_Not: {
14134 if (!Visit(E->getSubExpr()))
14135 return false;
14136 if (!Result.isInt()) return Error(E);
14137 return Success(~Result.getInt(), E);
14138 }
14139 case UO_LNot: {
14140 bool bres;
14141 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14142 return false;
14143 return Success(!bres, E);
14144 }
14145 }
14146}
14147
14148/// HandleCast - This is used to evaluate implicit or explicit casts where the
14149/// result type is integer.
14150bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
14151 const Expr *SubExpr = E->getSubExpr();
14152 QualType DestType = E->getType();
14153 QualType SrcType = SubExpr->getType();
14154
14155 switch (E->getCastKind()) {
14156 case CK_BaseToDerived:
14157 case CK_DerivedToBase:
14158 case CK_UncheckedDerivedToBase:
14159 case CK_Dynamic:
14160 case CK_ToUnion:
14161 case CK_ArrayToPointerDecay:
14162 case CK_FunctionToPointerDecay:
14163 case CK_NullToPointer:
14164 case CK_NullToMemberPointer:
14165 case CK_BaseToDerivedMemberPointer:
14166 case CK_DerivedToBaseMemberPointer:
14167 case CK_ReinterpretMemberPointer:
14168 case CK_ConstructorConversion:
14169 case CK_IntegralToPointer:
14170 case CK_ToVoid:
14171 case CK_VectorSplat:
14172 case CK_IntegralToFloating:
14173 case CK_FloatingCast:
14174 case CK_CPointerToObjCPointerCast:
14175 case CK_BlockPointerToObjCPointerCast:
14176 case CK_AnyPointerToBlockPointerCast:
14177 case CK_ObjCObjectLValueCast:
14178 case CK_FloatingRealToComplex:
14179 case CK_FloatingComplexToReal:
14180 case CK_FloatingComplexCast:
14181 case CK_FloatingComplexToIntegralComplex:
14182 case CK_IntegralRealToComplex:
14183 case CK_IntegralComplexCast:
14184 case CK_IntegralComplexToFloatingComplex:
14185 case CK_BuiltinFnToFnPtr:
14186 case CK_ZeroToOCLOpaqueType:
14187 case CK_NonAtomicToAtomic:
14188 case CK_AddressSpaceConversion:
14189 case CK_IntToOCLSampler:
14190 case CK_FloatingToFixedPoint:
14191 case CK_FixedPointToFloating:
14192 case CK_FixedPointCast:
14193 case CK_IntegralToFixedPoint:
14194 case CK_MatrixCast:
14195 case CK_HLSLVectorTruncation:
14196 llvm_unreachable("invalid cast kind for integral value");
14197
14198 case CK_BitCast:
14199 case CK_Dependent:
14200 case CK_LValueBitCast:
14201 case CK_ARCProduceObject:
14202 case CK_ARCConsumeObject:
14203 case CK_ARCReclaimReturnedObject:
14204 case CK_ARCExtendBlockObject:
14205 case CK_CopyAndAutoreleaseBlockObject:
14206 return Error(E);
14207
14208 case CK_UserDefinedConversion:
14209 case CK_LValueToRValue:
14210 case CK_AtomicToNonAtomic:
14211 case CK_NoOp:
14212 case CK_LValueToRValueBitCast:
14213 case CK_HLSLArrayRValue:
14214 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14215
14216 case CK_MemberPointerToBoolean:
14217 case CK_PointerToBoolean:
14218 case CK_IntegralToBoolean:
14219 case CK_FloatingToBoolean:
14220 case CK_BooleanToSignedIntegral:
14221 case CK_FloatingComplexToBoolean:
14222 case CK_IntegralComplexToBoolean: {
14223 bool BoolResult;
14224 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
14225 return false;
14226 uint64_t IntResult = BoolResult;
14227 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
14228 IntResult = (uint64_t)-1;
14229 return Success(IntResult, E);
14230 }
14231
14232 case CK_FixedPointToIntegral: {
14233 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
14234 if (!EvaluateFixedPoint(SubExpr, Src, Info))
14235 return false;
14236 bool Overflowed;
14237 llvm::APSInt Result = Src.convertToInt(
14238 Info.Ctx.getIntWidth(DestType),
14239 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
14240 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
14241 return false;
14242 return Success(Result, E);
14243 }
14244
14245 case CK_FixedPointToBoolean: {
14246 // Unsigned padding does not affect this.
14247 APValue Val;
14248 if (!Evaluate(Val, Info, SubExpr))
14249 return false;
14250 return Success(Val.getFixedPoint().getBoolValue(), E);
14251 }
14252
14253 case CK_IntegralCast: {
14254 if (!Visit(SubExpr))
14255 return false;
14256
14257 if (!Result.isInt()) {
14258 // Allow casts of address-of-label differences if they are no-ops
14259 // or narrowing. (The narrowing case isn't actually guaranteed to
14260 // be constant-evaluatable except in some narrow cases which are hard
14261 // to detect here. We let it through on the assumption the user knows
14262 // what they are doing.)
14263 if (Result.isAddrLabelDiff())
14264 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
14265 // Only allow casts of lvalues if they are lossless.
14266 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
14267 }
14268
14269 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
14270 Info.EvalMode == EvalInfo::EM_ConstantExpression &&
14271 DestType->isEnumeralType()) {
14272
14273 bool ConstexprVar = true;
14274
14275 // We know if we are here that we are in a context that we might require
14276 // a constant expression or a context that requires a constant
14277 // value. But if we are initializing a value we don't know if it is a
14278 // constexpr variable or not. We can check the EvaluatingDecl to determine
14279 // if it constexpr or not. If not then we don't want to emit a diagnostic.
14280 if (const auto *VD = dyn_cast_or_null<VarDecl>(
14281 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
14282 ConstexprVar = VD->isConstexpr();
14283
14284 const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
14285 const EnumDecl *ED = ET->getDecl();
14286 // Check that the value is within the range of the enumeration values.
14287 //
14288 // This corressponds to [expr.static.cast]p10 which says:
14289 // A value of integral or enumeration type can be explicitly converted
14290 // to a complete enumeration type ... If the enumeration type does not
14291 // have a fixed underlying type, the value is unchanged if the original
14292 // value is within the range of the enumeration values ([dcl.enum]), and
14293 // otherwise, the behavior is undefined.
14294 //
14295 // This was resolved as part of DR2338 which has CD5 status.
14296 if (!ED->isFixed()) {
14297 llvm::APInt Min;
14298 llvm::APInt Max;
14299
14300 ED->getValueRange(Max, Min);
14301 --Max;
14302
14303 if (ED->getNumNegativeBits() && ConstexprVar &&
14304 (Max.slt(Result.getInt().getSExtValue()) ||
14305 Min.sgt(Result.getInt().getSExtValue())))
14306 Info.Ctx.getDiagnostics().Report(
14307 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
14308 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
14309 << Max.getSExtValue() << ED;
14310 else if (!ED->getNumNegativeBits() && ConstexprVar &&
14311 Max.ult(Result.getInt().getZExtValue()))
14312 Info.Ctx.getDiagnostics().Report(
14313 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
14314 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
14315 << Max.getZExtValue() << ED;
14316 }
14317 }
14318
14319 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
14320 Result.getInt()), E);
14321 }
14322
14323 case CK_PointerToIntegral: {
14324 CCEDiag(E, diag::note_constexpr_invalid_cast)
14325 << 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
14326
14327 LValue LV;
14328 if (!EvaluatePointer(SubExpr, LV, Info))
14329 return false;
14330
14331 if (LV.getLValueBase()) {
14332 // Only allow based lvalue casts if they are lossless.
14333 // FIXME: Allow a larger integer size than the pointer size, and allow
14334 // narrowing back down to pointer width in subsequent integral casts.
14335 // FIXME: Check integer type's active bits, not its type size.
14336 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
14337 return Error(E);
14338
14339 LV.Designator.setInvalid();
14340 LV.moveInto(Result);
14341 return true;
14342 }
14343
14344 APSInt AsInt;
14345 APValue V;
14346 LV.moveInto(V);
14347 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
14348 llvm_unreachable("Can't cast this!");
14349
14350 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
14351 }
14352
14353 case CK_IntegralComplexToReal: {
14354 ComplexValue C;
14355 if (!EvaluateComplex(SubExpr, C, Info))
14356 return false;
14357 return Success(C.getComplexIntReal(), E);
14358 }
14359
14360 case CK_FloatingToIntegral: {
14361 APFloat F(0.0);
14362 if (!EvaluateFloat(SubExpr, F, Info))
14363 return false;
14364
14365 APSInt Value;
14366 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
14367 return false;
14368 return Success(Value, E);
14369 }
14370 }
14371
14372 llvm_unreachable("unknown cast resulting in integral value");
14373}
14374
14375bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14376 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14377 ComplexValue LV;
14378 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
14379 return false;
14380 if (!LV.isComplexInt())
14381 return Error(E);
14382 return Success(LV.getComplexIntReal(), E);
14383 }
14384
14385 return Visit(E->getSubExpr());
14386}
14387
14388bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14389 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
14390 ComplexValue LV;
14391 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
14392 return false;
14393 if (!LV.isComplexInt())
14394 return Error(E);
14395 return Success(LV.getComplexIntImag(), E);
14396 }
14397
14398 VisitIgnoredValue(E->getSubExpr());
14399 return Success(0, E);
14400}
14401
14402bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
14403 return Success(E->getPackLength(), E);
14404}
14405
14406bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
14407 return Success(E->getValue(), E);
14408}
14409
14410bool IntExprEvaluator::VisitConceptSpecializationExpr(
14411 const ConceptSpecializationExpr *E) {
14412 return Success(E->isSatisfied(), E);
14413}
14414
14415bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
14416 return Success(E->isSatisfied(), E);
14417}
14418
14419bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14420 switch (E->getOpcode()) {
14421 default:
14422 // Invalid unary operators
14423 return Error(E);
14424 case UO_Plus:
14425 // The result is just the value.
14426 return Visit(E->getSubExpr());
14427 case UO_Minus: {
14428 if (!Visit(E->getSubExpr())) return false;
14429 if (!Result.isFixedPoint())
14430 return Error(E);
14431 bool Overflowed;
14432 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
14433 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
14434 return false;
14435 return Success(Negated, E);
14436 }
14437 case UO_LNot: {
14438 bool bres;
14439 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14440 return false;
14441 return Success(!bres, E);
14442 }
14443 }
14444}
14445
14446bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
14447 const Expr *SubExpr = E->getSubExpr();
14448 QualType DestType = E->getType();
14449 assert(DestType->isFixedPointType() &&
14450 "Expected destination type to be a fixed point type");
14451 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
14452
14453 switch (E->getCastKind()) {
14454 case CK_FixedPointCast: {
14455 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14456 if (!EvaluateFixedPoint(SubExpr, Src, Info))
14457 return false;
14458 bool Overflowed;
14459 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
14460 if (Overflowed) {
14461 if (Info.checkingForUndefinedBehavior())
14462 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14463 diag::warn_fixedpoint_constant_overflow)
14464 << Result.toString() << E->getType();
14465 if (!HandleOverflow(Info, E, Result, E->getType()))
14466 return false;
14467 }
14468 return Success(Result, E);
14469 }
14470 case CK_IntegralToFixedPoint: {
14471 APSInt Src;
14472 if (!EvaluateInteger(SubExpr, Src, Info))
14473 return false;
14474
14475 bool Overflowed;
14476 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
14477 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
14478
14479 if (Overflowed) {
14480 if (Info.checkingForUndefinedBehavior())
14481 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14482 diag::warn_fixedpoint_constant_overflow)
14483 << IntResult.toString() << E->getType();
14484 if (!HandleOverflow(Info, E, IntResult, E->getType()))
14485 return false;
14486 }
14487
14488 return Success(IntResult, E);
14489 }
14490 case CK_FloatingToFixedPoint: {
14491 APFloat Src(0.0);
14492 if (!EvaluateFloat(SubExpr, Src, Info))
14493 return false;
14494
14495 bool Overflowed;
14496 APFixedPoint Result = APFixedPoint::getFromFloatValue(
14497 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
14498
14499 if (Overflowed) {
14500 if (Info.checkingForUndefinedBehavior())
14501 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14502 diag::warn_fixedpoint_constant_overflow)
14503 << Result.toString() << E->getType();
14504 if (!HandleOverflow(Info, E, Result, E->getType()))
14505 return false;
14506 }
14507
14508 return Success(Result, E);
14509 }
14510 case CK_NoOp:
14511 case CK_LValueToRValue:
14512 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14513 default:
14514 return Error(E);
14515 }
14516}
14517
14518bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14519 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14520 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14521
14522 const Expr *LHS = E->getLHS();
14523 const Expr *RHS = E->getRHS();
14524 FixedPointSemantics ResultFXSema =
14525 Info.Ctx.getFixedPointSemantics(E->getType());
14526
14527 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
14528 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
14529 return false;
14530 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
14531 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
14532 return false;
14533
14534 bool OpOverflow = false, ConversionOverflow = false;
14535 APFixedPoint Result(LHSFX.getSemantics());
14536 switch (E->getOpcode()) {
14537 case BO_Add: {
14538 Result = LHSFX.add(RHSFX, &OpOverflow)
14539 .convert(ResultFXSema, &ConversionOverflow);
14540 break;
14541 }
14542 case BO_Sub: {
14543 Result = LHSFX.sub(RHSFX, &OpOverflow)
14544 .convert(ResultFXSema, &ConversionOverflow);
14545 break;
14546 }
14547 case BO_Mul: {
14548 Result = LHSFX.mul(RHSFX, &OpOverflow)
14549 .convert(ResultFXSema, &ConversionOverflow);
14550 break;
14551 }
14552 case BO_Div: {
14553 if (RHSFX.getValue() == 0) {
14554 Info.FFDiag(E, diag::note_expr_divide_by_zero);
14555 return false;
14556 }
14557 Result = LHSFX.div(RHSFX, &OpOverflow)
14558 .convert(ResultFXSema, &ConversionOverflow);
14559 break;
14560 }
14561 case BO_Shl:
14562 case BO_Shr: {
14563 FixedPointSemantics LHSSema = LHSFX.getSemantics();
14564 llvm::APSInt RHSVal = RHSFX.getValue();
14565
14566 unsigned ShiftBW =
14567 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
14568 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
14569 // Embedded-C 4.1.6.2.2:
14570 // The right operand must be nonnegative and less than the total number
14571 // of (nonpadding) bits of the fixed-point operand ...
14572 if (RHSVal.isNegative())
14573 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
14574 else if (Amt != RHSVal)
14575 Info.CCEDiag(E, diag::note_constexpr_large_shift)
14576 << RHSVal << E->getType() << ShiftBW;
14577
14578 if (E->getOpcode() == BO_Shl)
14579 Result = LHSFX.shl(Amt, &OpOverflow);
14580 else
14581 Result = LHSFX.shr(Amt, &OpOverflow);
14582 break;
14583 }
14584 default:
14585 return false;
14586 }
14587 if (OpOverflow || ConversionOverflow) {
14588 if (Info.checkingForUndefinedBehavior())
14589 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14590 diag::warn_fixedpoint_constant_overflow)
14591 << Result.toString() << E->getType();
14592 if (!HandleOverflow(Info, E, Result, E->getType()))
14593 return false;
14594 }
14595 return Success(Result, E);
14596}
14597
14598//===----------------------------------------------------------------------===//
14599// Float Evaluation
14600//===----------------------------------------------------------------------===//
14601
14602namespace {
14603class FloatExprEvaluator
14604 : public ExprEvaluatorBase<FloatExprEvaluator> {
14605 APFloat &Result;
14606public:
14607 FloatExprEvaluator(EvalInfo &info, APFloat &result)
14608 : ExprEvaluatorBaseTy(info), Result(result) {}
14609
14610 bool Success(const APValue &V, const Expr *e) {
14611 Result = V.getFloat();
14612 return true;
14613 }
14614
14615 bool ZeroInitialization(const Expr *E) {
14616 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
14617 return true;
14618 }
14619
14620 bool VisitCallExpr(const CallExpr *E);
14621
14622 bool VisitUnaryOperator(const UnaryOperator *E);
14623 bool VisitBinaryOperator(const BinaryOperator *E);
14624 bool VisitFloatingLiteral(const FloatingLiteral *E);
14625 bool VisitCastExpr(const CastExpr *E);
14626
14627 bool VisitUnaryReal(const UnaryOperator *E);
14628 bool VisitUnaryImag(const UnaryOperator *E);
14629
14630 // FIXME: Missing: array subscript of vector, member of vector
14631};
14632} // end anonymous namespace
14633
14634static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
14635 assert(!E->isValueDependent());
14636 assert(E->isPRValue() && E->getType()->isRealFloatingType());
14637 return FloatExprEvaluator(Info, Result).Visit(E);
14638}
14639
14640static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
14641 QualType ResultTy,
14642 const Expr *Arg,
14643 bool SNaN,
14644 llvm::APFloat &Result) {
14645 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
14646 if (!S) return false;
14647
14648 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
14649
14650 llvm::APInt fill;
14651
14652 // Treat empty strings as if they were zero.
14653 if (S->getString().empty())
14654 fill = llvm::APInt(32, 0);
14655 else if (S->getString().getAsInteger(0, fill))
14656 return false;
14657
14658 if (Context.getTargetInfo().isNan2008()) {
14659 if (SNaN)
14660 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14661 else
14662 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14663 } else {
14664 // Prior to IEEE 754-2008, architectures were allowed to choose whether
14665 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
14666 // a different encoding to what became a standard in 2008, and for pre-
14667 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
14668 // sNaN. This is now known as "legacy NaN" encoding.
14669 if (SNaN)
14670 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14671 else
14672 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14673 }
14674
14675 return true;
14676}
14677
14678bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
14679 if (!IsConstantEvaluatedBuiltinCall(E))
14680 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14681
14682 switch (E->getBuiltinCallee()) {
14683 default:
14684 return false;
14685
14686 case Builtin::BI__builtin_huge_val:
14687 case Builtin::BI__builtin_huge_valf:
14688 case Builtin::BI__builtin_huge_vall:
14689 case Builtin::BI__builtin_huge_valf16:
14690 case Builtin::BI__builtin_huge_valf128:
14691 case Builtin::BI__builtin_inf:
14692 case Builtin::BI__builtin_inff:
14693 case Builtin::BI__builtin_infl:
14694 case Builtin::BI__builtin_inff16:
14695 case Builtin::BI__builtin_inff128: {
14696 const llvm::fltSemantics &Sem =
14697 Info.Ctx.getFloatTypeSemantics(E->getType());
14698 Result = llvm::APFloat::getInf(Sem);
14699 return true;
14700 }
14701
14702 case Builtin::BI__builtin_nans:
14703 case Builtin::BI__builtin_nansf:
14704 case Builtin::BI__builtin_nansl:
14705 case Builtin::BI__builtin_nansf16:
14706 case Builtin::BI__builtin_nansf128:
14707 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14708 true, Result))
14709 return Error(E);
14710 return true;
14711
14712 case Builtin::BI__builtin_nan:
14713 case Builtin::BI__builtin_nanf:
14714 case Builtin::BI__builtin_nanl:
14715 case Builtin::BI__builtin_nanf16:
14716 case Builtin::BI__builtin_nanf128:
14717 // If this is __builtin_nan() turn this into a nan, otherwise we
14718 // can't constant fold it.
14719 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14720 false, Result))
14721 return Error(E);
14722 return true;
14723
14724 case Builtin::BI__builtin_fabs:
14725 case Builtin::BI__builtin_fabsf:
14726 case Builtin::BI__builtin_fabsl:
14727 case Builtin::BI__builtin_fabsf128:
14728 // The C standard says "fabs raises no floating-point exceptions,
14729 // even if x is a signaling NaN. The returned value is independent of
14730 // the current rounding direction mode." Therefore constant folding can
14731 // proceed without regard to the floating point settings.
14732 // Reference, WG14 N2478 F.10.4.3
14733 if (!EvaluateFloat(E->getArg(0), Result, Info))
14734 return false;
14735
14736 if (Result.isNegative())
14737 Result.changeSign();
14738 return true;
14739
14740 case Builtin::BI__arithmetic_fence:
14741 return EvaluateFloat(E->getArg(0), Result, Info);
14742
14743 // FIXME: Builtin::BI__builtin_powi
14744 // FIXME: Builtin::BI__builtin_powif
14745 // FIXME: Builtin::BI__builtin_powil
14746
14747 case Builtin::BI__builtin_copysign:
14748 case Builtin::BI__builtin_copysignf:
14749 case Builtin::BI__builtin_copysignl:
14750 case Builtin::BI__builtin_copysignf128: {
14751 APFloat RHS(0.);
14752 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14753 !EvaluateFloat(E->getArg(1), RHS, Info))
14754 return false;
14755 Result.copySign(RHS);
14756 return true;
14757 }
14758
14759 case Builtin::BI__builtin_fmax:
14760 case Builtin::BI__builtin_fmaxf:
14761 case Builtin::BI__builtin_fmaxl:
14762 case Builtin::BI__builtin_fmaxf16:
14763 case Builtin::BI__builtin_fmaxf128: {
14764 // TODO: Handle sNaN.
14765 APFloat RHS(0.);
14766 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14767 !EvaluateFloat(E->getArg(1), RHS, Info))
14768 return false;
14769 // When comparing zeroes, return +0.0 if one of the zeroes is positive.
14770 if (Result.isZero() && RHS.isZero() && Result.isNegative())
14771 Result = RHS;
14772 else if (Result.isNaN() || RHS > Result)
14773 Result = RHS;
14774 return true;
14775 }
14776
14777 case Builtin::BI__builtin_fmin:
14778 case Builtin::BI__builtin_fminf:
14779 case Builtin::BI__builtin_fminl:
14780 case Builtin::BI__builtin_fminf16:
14781 case Builtin::BI__builtin_fminf128: {
14782 // TODO: Handle sNaN.
14783 APFloat RHS(0.);
14784 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14785 !EvaluateFloat(E->getArg(1), RHS, Info))
14786 return false;
14787 // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14788 if (Result.isZero() && RHS.isZero() && RHS.isNegative())
14789 Result = RHS;
14790 else if (Result.isNaN() || RHS < Result)
14791 Result = RHS;
14792 return true;
14793 }
14794 }
14795}
14796
14797bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14798 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14799 ComplexValue CV;
14800 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14801 return false;
14802 Result = CV.FloatReal;
14803 return true;
14804 }
14805
14806 return Visit(E->getSubExpr());
14807}
14808
14809bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14810 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14811 ComplexValue CV;
14812 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14813 return false;
14814 Result = CV.FloatImag;
14815 return true;
14816 }
14817
14818 VisitIgnoredValue(E->getSubExpr());
14819 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
14820 Result = llvm::APFloat::getZero(Sem);
14821 return true;
14822}
14823
14824bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14825 switch (E->getOpcode()) {
14826 default: return Error(E);
14827 case UO_Plus:
14828 return EvaluateFloat(E->getSubExpr(), Result, Info);
14829 case UO_Minus:
14830 // In C standard, WG14 N2478 F.3 p4
14831 // "the unary - raises no floating point exceptions,
14832 // even if the operand is signalling."
14833 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
14834 return false;
14835 Result.changeSign();
14836 return true;
14837 }
14838}
14839
14840bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14841 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14842 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14843
14844 APFloat RHS(0.0);
14845 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14846 if (!LHSOK && !Info.noteFailure())
14847 return false;
14848 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14849 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14850}
14851
14852bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14853 Result = E->getValue();
14854 return true;
14855}
14856
14857bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14858 const Expr* SubExpr = E->getSubExpr();
14859
14860 switch (E->getCastKind()) {
14861 default:
14862 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14863
14864 case CK_IntegralToFloating: {
14865 APSInt IntResult;
14866 const FPOptions FPO = E->getFPFeaturesInEffect(
14867 Info.Ctx.getLangOpts());
14868 return EvaluateInteger(SubExpr, IntResult, Info) &&
14869 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14870 IntResult, E->getType(), Result);
14871 }
14872
14873 case CK_FixedPointToFloating: {
14874 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14875 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14876 return false;
14877 Result =
14878 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14879 return true;
14880 }
14881
14882 case CK_FloatingCast: {
14883 if (!Visit(SubExpr))
14884 return false;
14885 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14886 Result);
14887 }
14888
14889 case CK_FloatingComplexToReal: {
14890 ComplexValue V;
14891 if (!EvaluateComplex(SubExpr, V, Info))
14892 return false;
14893 Result = V.getComplexFloatReal();
14894 return true;
14895 }
14896 }
14897}
14898
14899//===----------------------------------------------------------------------===//
14900// Complex Evaluation (for float and integer)
14901//===----------------------------------------------------------------------===//
14902
14903namespace {
14904class ComplexExprEvaluator
14905 : public ExprEvaluatorBase<ComplexExprEvaluator> {
14906 ComplexValue &Result;
14907
14908public:
14909 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14910 : ExprEvaluatorBaseTy(info), Result(Result) {}
14911
14912 bool Success(const APValue &V, const Expr *e) {
14913 Result.setFrom(V);
14914 return true;
14915 }
14916
14917 bool ZeroInitialization(const Expr *E);
14918
14919 //===--------------------------------------------------------------------===//
14920 // Visitor Methods
14921 //===--------------------------------------------------------------------===//
14922
14923 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14924 bool VisitCastExpr(const CastExpr *E);
14925 bool VisitBinaryOperator(const BinaryOperator *E);
14926 bool VisitUnaryOperator(const UnaryOperator *E);
14927 bool VisitInitListExpr(const InitListExpr *E);
14928 bool VisitCallExpr(const CallExpr *E);
14929};
14930} // end anonymous namespace
14931
14932static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14933 EvalInfo &Info) {
14934 assert(!E->isValueDependent());
14935 assert(E->isPRValue() && E->getType()->isAnyComplexType());
14936 return ComplexExprEvaluator(Info, Result).Visit(E);
14937}
14938
14939bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14940 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14941 if (ElemTy->isRealFloatingType()) {
14942 Result.makeComplexFloat();
14943 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14944 Result.FloatReal = Zero;
14945 Result.FloatImag = Zero;
14946 } else {
14947 Result.makeComplexInt();
14948 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14949 Result.IntReal = Zero;
14950 Result.IntImag = Zero;
14951 }
14952 return true;
14953}
14954
14955bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14956 const Expr* SubExpr = E->getSubExpr();
14957
14958 if (SubExpr->getType()->isRealFloatingType()) {
14959 Result.makeComplexFloat();
14960 APFloat &Imag = Result.FloatImag;
14961 if (!EvaluateFloat(SubExpr, Imag, Info))
14962 return false;
14963
14964 Result.FloatReal = APFloat(Imag.getSemantics());
14965 return true;
14966 } else {
14967 assert(SubExpr->getType()->isIntegerType() &&
14968 "Unexpected imaginary literal.");
14969
14970 Result.makeComplexInt();
14971 APSInt &Imag = Result.IntImag;
14972 if (!EvaluateInteger(SubExpr, Imag, Info))
14973 return false;
14974
14975 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14976 return true;
14977 }
14978}
14979
14980bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14981
14982 switch (E->getCastKind()) {
14983 case CK_BitCast:
14984 case CK_BaseToDerived:
14985 case CK_DerivedToBase:
14986 case CK_UncheckedDerivedToBase:
14987 case CK_Dynamic:
14988 case CK_ToUnion:
14989 case CK_ArrayToPointerDecay:
14990 case CK_FunctionToPointerDecay:
14991 case CK_NullToPointer:
14992 case CK_NullToMemberPointer:
14993 case CK_BaseToDerivedMemberPointer:
14994 case CK_DerivedToBaseMemberPointer:
14995 case CK_MemberPointerToBoolean:
14996 case CK_ReinterpretMemberPointer:
14997 case CK_ConstructorConversion:
14998 case CK_IntegralToPointer:
14999 case CK_PointerToIntegral:
15000 case CK_PointerToBoolean:
15001 case CK_ToVoid:
15002 case CK_VectorSplat:
15003 case CK_IntegralCast:
15004 case CK_BooleanToSignedIntegral:
15005 case CK_IntegralToBoolean:
15006 case CK_IntegralToFloating:
15007 case CK_FloatingToIntegral:
15008 case CK_FloatingToBoolean:
15009 case CK_FloatingCast:
15010 case CK_CPointerToObjCPointerCast:
15011 case CK_BlockPointerToObjCPointerCast:
15012 case CK_AnyPointerToBlockPointerCast:
15013 case CK_ObjCObjectLValueCast:
15014 case CK_FloatingComplexToReal:
15015 case CK_FloatingComplexToBoolean:
15016 case CK_IntegralComplexToReal:
15017 case CK_IntegralComplexToBoolean:
15018 case CK_ARCProduceObject:
15019 case CK_ARCConsumeObject:
15020 case CK_ARCReclaimReturnedObject:
15021 case CK_ARCExtendBlockObject:
15022 case CK_CopyAndAutoreleaseBlockObject:
15023 case CK_BuiltinFnToFnPtr:
15024 case CK_ZeroToOCLOpaqueType:
15025 case CK_NonAtomicToAtomic:
15026 case CK_AddressSpaceConversion:
15027 case CK_IntToOCLSampler:
15028 case CK_FloatingToFixedPoint:
15029 case CK_FixedPointToFloating:
15030 case CK_FixedPointCast:
15031 case CK_FixedPointToBoolean:
15032 case CK_FixedPointToIntegral:
15033 case CK_IntegralToFixedPoint:
15034 case CK_MatrixCast:
15035 case CK_HLSLVectorTruncation:
15036 llvm_unreachable("invalid cast kind for complex value");
15037
15038 case CK_LValueToRValue:
15039 case CK_AtomicToNonAtomic:
15040 case CK_NoOp:
15041 case CK_LValueToRValueBitCast:
15042 case CK_HLSLArrayRValue:
15043 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15044
15045 case CK_Dependent:
15046 case CK_LValueBitCast:
15047 case CK_UserDefinedConversion:
15048 return Error(E);
15049
15050 case CK_FloatingRealToComplex: {
15051 APFloat &Real = Result.FloatReal;
15052 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
15053 return false;
15054
15055 Result.makeComplexFloat();
15056 Result.FloatImag = APFloat(Real.getSemantics());
15057 return true;
15058 }
15059
15060 case CK_FloatingComplexCast: {
15061 if (!Visit(E->getSubExpr()))
15062 return false;
15063
15064 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15065 QualType From
15066 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15067
15068 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
15069 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
15070 }
15071
15072 case CK_FloatingComplexToIntegralComplex: {
15073 if (!Visit(E->getSubExpr()))
15074 return false;
15075
15076 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15077 QualType From
15078 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15079 Result.makeComplexInt();
15080 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
15081 To, Result.IntReal) &&
15082 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
15083 To, Result.IntImag);
15084 }
15085
15086 case CK_IntegralRealToComplex: {
15087 APSInt &Real = Result.IntReal;
15088 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
15089 return false;
15090
15091 Result.makeComplexInt();
15092 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
15093 return true;
15094 }
15095
15096 case CK_IntegralComplexCast: {
15097 if (!Visit(E->getSubExpr()))
15098 return false;
15099
15100 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15101 QualType From
15102 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15103
15104 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
15105 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
15106 return true;
15107 }
15108
15109 case CK_IntegralComplexToFloatingComplex: {
15110 if (!Visit(E->getSubExpr()))
15111 return false;
15112
15113 const FPOptions FPO = E->getFPFeaturesInEffect(
15114 Info.Ctx.getLangOpts());
15115 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15116 QualType From
15117 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15118 Result.makeComplexFloat();
15119 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
15120 To, Result.FloatReal) &&
15121 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
15122 To, Result.FloatImag);
15123 }
15124 }
15125
15126 llvm_unreachable("unknown cast resulting in complex value");
15127}
15128
15129bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15130 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15131 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15132
15133 // Track whether the LHS or RHS is real at the type system level. When this is
15134 // the case we can simplify our evaluation strategy.
15135 bool LHSReal = false, RHSReal = false;
15136
15137 bool LHSOK;
15138 if (E->getLHS()->getType()->isRealFloatingType()) {
15139 LHSReal = true;
15140 APFloat &Real = Result.FloatReal;
15141 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
15142 if (LHSOK) {
15143 Result.makeComplexFloat();
15144 Result.FloatImag = APFloat(Real.getSemantics());
15145 }
15146 } else {
15147 LHSOK = Visit(E->getLHS());
15148 }
15149 if (!LHSOK && !Info.noteFailure())
15150 return false;
15151
15152 ComplexValue RHS;
15153 if (E->getRHS()->getType()->isRealFloatingType()) {
15154 RHSReal = true;
15155 APFloat &Real = RHS.FloatReal;
15156 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
15157 return false;
15158 RHS.makeComplexFloat();
15159 RHS.FloatImag = APFloat(Real.getSemantics());
15160 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
15161 return false;
15162
15163 assert(!(LHSReal && RHSReal) &&
15164 "Cannot have both operands of a complex operation be real.");
15165 switch (E->getOpcode()) {
15166 default: return Error(E);
15167 case BO_Add:
15168 if (Result.isComplexFloat()) {
15169 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
15170 APFloat::rmNearestTiesToEven);
15171 if (LHSReal)
15172 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
15173 else if (!RHSReal)
15174 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
15175 APFloat::rmNearestTiesToEven);
15176 } else {
15177 Result.getComplexIntReal() += RHS.getComplexIntReal();
15178 Result.getComplexIntImag() += RHS.getComplexIntImag();
15179 }
15180 break;
15181 case BO_Sub:
15182 if (Result.isComplexFloat()) {
15183 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
15184 APFloat::rmNearestTiesToEven);
15185 if (LHSReal) {
15186 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
15187 Result.getComplexFloatImag().changeSign();
15188 } else if (!RHSReal) {
15189 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
15190 APFloat::rmNearestTiesToEven);
15191 }
15192 } else {
15193 Result.getComplexIntReal() -= RHS.getComplexIntReal();
15194 Result.getComplexIntImag() -= RHS.getComplexIntImag();
15195 }
15196 break;
15197 case BO_Mul:
15198 if (Result.isComplexFloat()) {
15199 // This is an implementation of complex multiplication according to the
15200 // constraints laid out in C11 Annex G. The implementation uses the
15201 // following naming scheme:
15202 // (a + ib) * (c + id)
15203 ComplexValue LHS = Result;
15204 APFloat &A = LHS.getComplexFloatReal();
15205 APFloat &B = LHS.getComplexFloatImag();
15206 APFloat &C = RHS.getComplexFloatReal();
15207 APFloat &D = RHS.getComplexFloatImag();
15208 APFloat &ResR = Result.getComplexFloatReal();
15209 APFloat &ResI = Result.getComplexFloatImag();
15210 if (LHSReal) {
15211 assert(!RHSReal && "Cannot have two real operands for a complex op!");
15212 ResR = A * C;
15213 ResI = A * D;
15214 } else if (RHSReal) {
15215 ResR = C * A;
15216 ResI = C * B;
15217 } else {
15218 // In the fully general case, we need to handle NaNs and infinities
15219 // robustly.
15220 APFloat AC = A * C;
15221 APFloat BD = B * D;
15222 APFloat AD = A * D;
15223 APFloat BC = B * C;
15224 ResR = AC - BD;
15225 ResI = AD + BC;
15226 if (ResR.isNaN() && ResI.isNaN()) {
15227 bool Recalc = false;
15228 if (A.isInfinity() || B.isInfinity()) {
15229 A = APFloat::copySign(
15230 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
15231 B = APFloat::copySign(
15232 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
15233 if (C.isNaN())
15234 C = APFloat::copySign(APFloat(C.getSemantics()), C);
15235 if (D.isNaN())
15236 D = APFloat::copySign(APFloat(D.getSemantics()), D);
15237 Recalc = true;
15238 }
15239 if (C.isInfinity() || D.isInfinity()) {
15240 C = APFloat::copySign(
15241 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
15242 D = APFloat::copySign(
15243 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
15244 if (A.isNaN())
15245 A = APFloat::copySign(APFloat(A.getSemantics()), A);
15246 if (B.isNaN())
15247 B = APFloat::copySign(APFloat(B.getSemantics()), B);
15248 Recalc = true;
15249 }
15250 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
15251 AD.isInfinity() || BC.isInfinity())) {
15252 if (A.isNaN())
15253 A = APFloat::copySign(APFloat(A.getSemantics()), A);
15254 if (B.isNaN())
15255 B = APFloat::copySign(APFloat(B.getSemantics()), B);
15256 if (C.isNaN())
15257 C = APFloat::copySign(APFloat(C.getSemantics()), C);
15258 if (D.isNaN())
15259 D = APFloat::copySign(APFloat(D.getSemantics()), D);
15260 Recalc = true;
15261 }
15262 if (Recalc) {
15263 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
15264 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
15265 }
15266 }
15267 }
15268 } else {
15269 ComplexValue LHS = Result;
15270 Result.getComplexIntReal() =
15271 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
15272 LHS.getComplexIntImag() * RHS.getComplexIntImag());
15273 Result.getComplexIntImag() =
15274 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
15275 LHS.getComplexIntImag() * RHS.getComplexIntReal());
15276 }
15277 break;
15278 case BO_Div:
15279 if (Result.isComplexFloat()) {
15280 // This is an implementation of complex division according to the
15281 // constraints laid out in C11 Annex G. The implementation uses the
15282 // following naming scheme:
15283 // (a + ib) / (c + id)
15284 ComplexValue LHS = Result;
15285 APFloat &A = LHS.getComplexFloatReal();
15286 APFloat &B = LHS.getComplexFloatImag();
15287 APFloat &C = RHS.getComplexFloatReal();
15288 APFloat &D = RHS.getComplexFloatImag();
15289 APFloat &ResR = Result.getComplexFloatReal();
15290 APFloat &ResI = Result.getComplexFloatImag();
15291 if (RHSReal) {
15292 ResR = A / C;
15293 ResI = B / C;
15294 } else {
15295 if (LHSReal) {
15296 // No real optimizations we can do here, stub out with zero.
15297 B = APFloat::getZero(A.getSemantics());
15298 }
15299 int DenomLogB = 0;
15300 APFloat MaxCD = maxnum(abs(C), abs(D));
15301 if (MaxCD.isFinite()) {
15302 DenomLogB = ilogb(MaxCD);
15303 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
15304 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
15305 }
15306 APFloat Denom = C * C + D * D;
15307 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
15308 APFloat::rmNearestTiesToEven);
15309 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
15310 APFloat::rmNearestTiesToEven);
15311 if (ResR.isNaN() && ResI.isNaN()) {
15312 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
15313 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
15314 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
15315 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
15316 D.isFinite()) {
15317 A = APFloat::copySign(
15318 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
15319 B = APFloat::copySign(
15320 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
15321 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
15322 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
15323 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
15324 C = APFloat::copySign(
15325 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
15326 D = APFloat::copySign(
15327 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
15328 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
15329 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
15330 }
15331 }
15332 }
15333 } else {
15334 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
15335 return Error(E, diag::note_expr_divide_by_zero);
15336
15337 ComplexValue LHS = Result;
15338 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
15339 RHS.getComplexIntImag() * RHS.getComplexIntImag();
15340 Result.getComplexIntReal() =
15341 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
15342 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
15343 Result.getComplexIntImag() =
15344 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
15345 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
15346 }
15347 break;
15348 }
15349
15350 return true;
15351}
15352
15353bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15354 // Get the operand value into 'Result'.
15355 if (!Visit(E->getSubExpr()))
15356 return false;
15357
15358 switch (E->getOpcode()) {
15359 default:
15360 return Error(E);
15361 case UO_Extension:
15362 return true;
15363 case UO_Plus:
15364 // The result is always just the subexpr.
15365 return true;
15366 case UO_Minus:
15367 if (Result.isComplexFloat()) {
15368 Result.getComplexFloatReal().changeSign();
15369 Result.getComplexFloatImag().changeSign();
15370 }
15371 else {
15372 Result.getComplexIntReal() = -Result.getComplexIntReal();
15373 Result.getComplexIntImag() = -Result.getComplexIntImag();
15374 }
15375 return true;
15376 case UO_Not:
15377 if (Result.isComplexFloat())
15378 Result.getComplexFloatImag().changeSign();
15379 else
15380 Result.getComplexIntImag() = -Result.getComplexIntImag();
15381 return true;
15382 }
15383}
15384
15385bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
15386 if (E->getNumInits() == 2) {
15387 if (E->getType()->isComplexType()) {
15388 Result.makeComplexFloat();
15389 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
15390 return false;
15391 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
15392 return false;
15393 } else {
15394 Result.makeComplexInt();
15395 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
15396 return false;
15397 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
15398 return false;
15399 }
15400 return true;
15401 }
15402 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
15403}
15404
15405bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
15406 if (!IsConstantEvaluatedBuiltinCall(E))
15407 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15408
15409 switch (E->getBuiltinCallee()) {
15410 case Builtin::BI__builtin_complex:
15411 Result.makeComplexFloat();
15412 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
15413 return false;
15414 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
15415 return false;
15416 return true;
15417
15418 default:
15419 return false;
15420 }
15421}
15422
15423//===----------------------------------------------------------------------===//
15424// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
15425// implicit conversion.
15426//===----------------------------------------------------------------------===//
15427
15428namespace {
15429class AtomicExprEvaluator :
15430 public ExprEvaluatorBase<AtomicExprEvaluator> {
15431 const LValue *This;
15432 APValue &Result;
15433public:
15434 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
15435 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
15436
15437 bool Success(const APValue &V, const Expr *E) {
15438 Result = V;
15439 return true;
15440 }
15441
15442 bool ZeroInitialization(const Expr *E) {
15445 // For atomic-qualified class (and array) types in C++, initialize the
15446 // _Atomic-wrapped subobject directly, in-place.
15447 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
15448 : Evaluate(Result, Info, &VIE);
15449 }
15450
15451 bool VisitCastExpr(const CastExpr *E) {
15452 switch (E->getCastKind()) {
15453 default:
15454 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15455 case CK_NullToPointer:
15456 VisitIgnoredValue(E->getSubExpr());
15457 return ZeroInitialization(E);
15458 case CK_NonAtomicToAtomic:
15459 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
15460 : Evaluate(Result, Info, E->getSubExpr());
15461 }
15462 }
15463};
15464} // end anonymous namespace
15465
15466static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
15467 EvalInfo &Info) {
15468 assert(!E->isValueDependent());
15469 assert(E->isPRValue() && E->getType()->isAtomicType());
15470 return AtomicExprEvaluator(Info, This, Result).Visit(E);
15471}
15472
15473//===----------------------------------------------------------------------===//
15474// Void expression evaluation, primarily for a cast to void on the LHS of a
15475// comma operator
15476//===----------------------------------------------------------------------===//
15477
15478namespace {
15479class VoidExprEvaluator
15480 : public ExprEvaluatorBase<VoidExprEvaluator> {
15481public:
15482 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
15483
15484 bool Success(const APValue &V, const Expr *e) { return true; }
15485
15486 bool ZeroInitialization(const Expr *E) { return true; }
15487
15488 bool VisitCastExpr(const CastExpr *E) {
15489 switch (E->getCastKind()) {
15490 default:
15491 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15492 case CK_ToVoid:
15493 VisitIgnoredValue(E->getSubExpr());
15494 return true;
15495 }
15496 }
15497
15498 bool VisitCallExpr(const CallExpr *E) {
15499 if (!IsConstantEvaluatedBuiltinCall(E))
15500 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15501
15502 switch (E->getBuiltinCallee()) {
15503 case Builtin::BI__assume:
15504 case Builtin::BI__builtin_assume:
15505 // The argument is not evaluated!
15506 return true;
15507
15508 case Builtin::BI__builtin_operator_delete:
15509 return HandleOperatorDeleteCall(Info, E);
15510
15511 default:
15512 return false;
15513 }
15514 }
15515
15516 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
15517};
15518} // end anonymous namespace
15519
15520bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
15521 // We cannot speculatively evaluate a delete expression.
15522 if (Info.SpeculativeEvaluationDepth)
15523 return false;
15524
15525 FunctionDecl *OperatorDelete = E->getOperatorDelete();
15526 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
15527 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
15528 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
15529 return false;
15530 }
15531
15532 const Expr *Arg = E->getArgument();
15533
15534 LValue Pointer;
15535 if (!EvaluatePointer(Arg, Pointer, Info))
15536 return false;
15537 if (Pointer.Designator.Invalid)
15538 return false;
15539
15540 // Deleting a null pointer has no effect.
15541 if (Pointer.isNullPointer()) {
15542 // This is the only case where we need to produce an extension warning:
15543 // the only other way we can succeed is if we find a dynamic allocation,
15544 // and we will have warned when we allocated it in that case.
15545 if (!Info.getLangOpts().CPlusPlus20)
15546 Info.CCEDiag(E, diag::note_constexpr_new);
15547 return true;
15548 }
15549
15550 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
15551 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
15552 if (!Alloc)
15553 return false;
15554 QualType AllocType = Pointer.Base.getDynamicAllocType();
15555
15556 // For the non-array case, the designator must be empty if the static type
15557 // does not have a virtual destructor.
15558 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
15560 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
15561 << Arg->getType()->getPointeeType() << AllocType;
15562 return false;
15563 }
15564
15565 // For a class type with a virtual destructor, the selected operator delete
15566 // is the one looked up when building the destructor.
15567 if (!E->isArrayForm() && !E->isGlobalDelete()) {
15568 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
15569 if (VirtualDelete &&
15570 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
15571 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
15572 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
15573 return false;
15574 }
15575 }
15576
15577 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
15578 (*Alloc)->Value, AllocType))
15579 return false;
15580
15581 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
15582 // The element was already erased. This means the destructor call also
15583 // deleted the object.
15584 // FIXME: This probably results in undefined behavior before we get this
15585 // far, and should be diagnosed elsewhere first.
15586 Info.FFDiag(E, diag::note_constexpr_double_delete);
15587 return false;
15588 }
15589
15590 return true;
15591}
15592
15593static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
15594 assert(!E->isValueDependent());
15595 assert(E->isPRValue() && E->getType()->isVoidType());
15596 return VoidExprEvaluator(Info).Visit(E);
15597}
15598
15599//===----------------------------------------------------------------------===//
15600// Top level Expr::EvaluateAsRValue method.
15601//===----------------------------------------------------------------------===//
15602
15603static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
15604 assert(!E->isValueDependent());
15605 // In C, function designators are not lvalues, but we evaluate them as if they
15606 // are.
15607 QualType T = E->getType();
15608 if (E->isGLValue() || T->isFunctionType()) {
15609 LValue LV;
15610 if (!EvaluateLValue(E, LV, Info))
15611 return false;
15612 LV.moveInto(Result);
15613 } else if (T->isVectorType()) {
15614 if (!EvaluateVector(E, Result, Info))
15615 return false;
15616 } else if (T->isIntegralOrEnumerationType()) {
15617 if (!IntExprEvaluator(Info, Result).Visit(E))
15618 return false;
15619 } else if (T->hasPointerRepresentation()) {
15620 LValue LV;
15621 if (!EvaluatePointer(E, LV, Info))
15622 return false;
15623 LV.moveInto(Result);
15624 } else if (T->isRealFloatingType()) {
15625 llvm::APFloat F(0.0);
15626 if (!EvaluateFloat(E, F, Info))
15627 return false;
15628 Result = APValue(F);
15629 } else if (T->isAnyComplexType()) {
15630 ComplexValue C;
15631 if (!EvaluateComplex(E, C, Info))
15632 return false;
15633 C.moveInto(Result);
15634 } else if (T->isFixedPointType()) {
15635 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
15636 } else if (T->isMemberPointerType()) {
15637 MemberPtr P;
15638 if (!EvaluateMemberPointer(E, P, Info))
15639 return false;
15640 P.moveInto(Result);
15641 return true;
15642 } else if (T->isArrayType()) {
15643 LValue LV;
15644 APValue &Value =
15645 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15646 if (!EvaluateArray(E, LV, Value, Info))
15647 return false;
15648 Result = Value;
15649 } else if (T->isRecordType()) {
15650 LValue LV;
15651 APValue &Value =
15652 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15653 if (!EvaluateRecord(E, LV, Value, Info))
15654 return false;
15655 Result = Value;
15656 } else if (T->isVoidType()) {
15657 if (!Info.getLangOpts().CPlusPlus11)
15658 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
15659 << E->getType();
15660 if (!EvaluateVoid(E, Info))
15661 return false;
15662 } else if (T->isAtomicType()) {
15663 QualType Unqual = T.getAtomicUnqualifiedType();
15664 if (Unqual->isArrayType() || Unqual->isRecordType()) {
15665 LValue LV;
15666 APValue &Value = Info.CurrentCall->createTemporary(
15667 E, Unqual, ScopeKind::FullExpression, LV);
15668 if (!EvaluateAtomic(E, &LV, Value, Info))
15669 return false;
15670 Result = Value;
15671 } else {
15672 if (!EvaluateAtomic(E, nullptr, Result, Info))
15673 return false;
15674 }
15675 } else if (Info.getLangOpts().CPlusPlus11) {
15676 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
15677 return false;
15678 } else {
15679 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15680 return false;
15681 }
15682
15683 return true;
15684}
15685
15686/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15687/// cases, the in-place evaluation is essential, since later initializers for
15688/// an object can indirectly refer to subobjects which were initialized earlier.
15689static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
15690 const Expr *E, bool AllowNonLiteralTypes) {
15691 assert(!E->isValueDependent());
15692
15693 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
15694 return false;
15695
15696 if (E->isPRValue()) {
15697 // Evaluate arrays and record types in-place, so that later initializers can
15698 // refer to earlier-initialized members of the object.
15699 QualType T = E->getType();
15700 if (T->isArrayType())
15701 return EvaluateArray(E, This, Result, Info);
15702 else if (T->isRecordType())
15703 return EvaluateRecord(E, This, Result, Info);
15704 else if (T->isAtomicType()) {
15705 QualType Unqual = T.getAtomicUnqualifiedType();
15706 if (Unqual->isArrayType() || Unqual->isRecordType())
15707 return EvaluateAtomic(E, &This, Result, Info);
15708 }
15709 }
15710
15711 // For any other type, in-place evaluation is unimportant.
15712 return Evaluate(Result, Info, E);
15713}
15714
15715/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15716/// lvalue-to-rvalue cast if it is an lvalue.
15717static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
15718 assert(!E->isValueDependent());
15719
15720 if (E->getType().isNull())
15721 return false;
15722
15723 if (!CheckLiteralType(Info, E))
15724 return false;
15725
15726 if (Info.EnableNewConstInterp) {
15727 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
15728 return false;
15729 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15730 ConstantExprKind::Normal);
15731 }
15732
15733 if (!::Evaluate(Result, Info, E))
15734 return false;
15735
15736 // Implicit lvalue-to-rvalue cast.
15737 if (E->isGLValue()) {
15738 LValue LV;
15739 LV.setFrom(Info.Ctx, Result);
15740 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15741 return false;
15742 }
15743
15744 // Check this core constant expression is a constant expression.
15745 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15746 ConstantExprKind::Normal) &&
15747 CheckMemoryLeaks(Info);
15748}
15749
15750static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
15751 const ASTContext &Ctx, bool &IsConst) {
15752 // Fast-path evaluations of integer literals, since we sometimes see files
15753 // containing vast quantities of these.
15754 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
15755 Result.Val = APValue(APSInt(L->getValue(),
15756 L->getType()->isUnsignedIntegerType()));
15757 IsConst = true;
15758 return true;
15759 }
15760
15761 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
15762 Result.Val = APValue(APSInt(APInt(1, L->getValue())));
15763 IsConst = true;
15764 return true;
15765 }
15766
15767 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
15768 if (CE->hasAPValueResult()) {
15769 Result.Val = CE->getAPValueResult();
15770 IsConst = true;
15771 return true;
15772 }
15773
15774 // The SubExpr is usually just an IntegerLiteral.
15775 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
15776 }
15777
15778 // This case should be rare, but we need to check it before we check on
15779 // the type below.
15780 if (Exp->getType().isNull()) {
15781 IsConst = false;
15782 return true;
15783 }
15784
15785 return false;
15786}
15787
15790 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
15791 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
15792}
15793
15794static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
15795 const ASTContext &Ctx, EvalInfo &Info) {
15796 assert(!E->isValueDependent());
15797 bool IsConst;
15798 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
15799 return IsConst;
15800
15801 return EvaluateAsRValue(Info, E, Result.Val);
15802}
15803
15805 const ASTContext &Ctx,
15806 Expr::SideEffectsKind AllowSideEffects,
15807 EvalInfo &Info) {
15808 assert(!E->isValueDependent());
15810 return false;
15811
15812 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
15813 !ExprResult.Val.isInt() ||
15814 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15815 return false;
15816
15817 return true;
15818}
15819
15821 const ASTContext &Ctx,
15822 Expr::SideEffectsKind AllowSideEffects,
15823 EvalInfo &Info) {
15824 assert(!E->isValueDependent());
15825 if (!E->getType()->isFixedPointType())
15826 return false;
15827
15828 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
15829 return false;
15830
15831 if (!ExprResult.Val.isFixedPoint() ||
15832 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15833 return false;
15834
15835 return true;
15836}
15837
15838/// EvaluateAsRValue - Return true if this is a constant which we can fold using
15839/// any crazy technique (that has nothing to do with language standards) that
15840/// we want to. If this function returns true, it returns the folded constant
15841/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
15842/// will be applied to the result.
15844 bool InConstantContext) const {
15845 assert(!isValueDependent() &&
15846 "Expression evaluator can't be called on a dependent expression.");
15847 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
15848 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15849 Info.InConstantContext = InConstantContext;
15850 return ::EvaluateAsRValue(this, Result, Ctx, Info);
15851}
15852
15853bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
15854 bool InConstantContext) const {
15855 assert(!isValueDependent() &&
15856 "Expression evaluator can't be called on a dependent expression.");
15857 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
15858 EvalResult Scratch;
15859 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
15860 HandleConversionToBool(Scratch.Val, Result);
15861}
15862
15864 SideEffectsKind AllowSideEffects,
15865 bool InConstantContext) const {
15866 assert(!isValueDependent() &&
15867 "Expression evaluator can't be called on a dependent expression.");
15868 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
15869 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15870 Info.InConstantContext = InConstantContext;
15871 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15872}
15873
15875 SideEffectsKind AllowSideEffects,
15876 bool InConstantContext) const {
15877 assert(!isValueDependent() &&
15878 "Expression evaluator can't be called on a dependent expression.");
15879 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
15880 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15881 Info.InConstantContext = InConstantContext;
15882 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15883}
15884
15885bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15886 SideEffectsKind AllowSideEffects,
15887 bool InConstantContext) const {
15888 assert(!isValueDependent() &&
15889 "Expression evaluator can't be called on a dependent expression.");
15890
15891 if (!getType()->isRealFloatingType())
15892 return false;
15893
15894 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
15896 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15897 !ExprResult.Val.isFloat() ||
15898 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15899 return false;
15900
15901 Result = ExprResult.Val.getFloat();
15902 return true;
15903}
15904
15906 bool InConstantContext) const {
15907 assert(!isValueDependent() &&
15908 "Expression evaluator can't be called on a dependent expression.");
15909
15910 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
15911 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15912 Info.InConstantContext = InConstantContext;
15913 LValue LV;
15914 CheckedTemporaries CheckedTemps;
15915 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
15916 Result.HasSideEffects ||
15917 !CheckLValueConstantExpression(Info, getExprLoc(),
15918 Ctx.getLValueReferenceType(getType()), LV,
15919 ConstantExprKind::Normal, CheckedTemps))
15920 return false;
15921
15922 LV.moveInto(Result.Val);
15923 return true;
15924}
15925
15927 APValue DestroyedValue, QualType Type,
15929 bool IsConstantDestruction) {
15930 EvalInfo Info(Ctx, EStatus,
15931 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15932 : EvalInfo::EM_ConstantFold);
15933 Info.setEvaluatingDecl(Base, DestroyedValue,
15934 EvalInfo::EvaluatingDeclKind::Dtor);
15935 Info.InConstantContext = IsConstantDestruction;
15936
15937 LValue LVal;
15938 LVal.set(Base);
15939
15940 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15941 EStatus.HasSideEffects)
15942 return false;
15943
15944 if (!Info.discardCleanups())
15945 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15946
15947 return true;
15948}
15949
15951 ConstantExprKind Kind) const {
15952 assert(!isValueDependent() &&
15953 "Expression evaluator can't be called on a dependent expression.");
15954 bool IsConst;
15955 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
15956 return true;
15957
15958 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
15959 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15960 EvalInfo Info(Ctx, Result, EM);
15961 Info.InConstantContext = true;
15962
15963 if (Info.EnableNewConstInterp) {
15964 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val))
15965 return false;
15966 return CheckConstantExpression(Info, getExprLoc(),
15967 getStorageType(Ctx, this), Result.Val, Kind);
15968 }
15969
15970 // The type of the object we're initializing is 'const T' for a class NTTP.
15971 QualType T = getType();
15972 if (Kind == ConstantExprKind::ClassTemplateArgument)
15973 T.addConst();
15974
15975 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15976 // represent the result of the evaluation. CheckConstantExpression ensures
15977 // this doesn't escape.
15978 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15979 APValue::LValueBase Base(&BaseMTE);
15980 Info.setEvaluatingDecl(Base, Result.Val);
15981
15982 if (Info.EnableNewConstInterp) {
15983 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, this, Result.Val))
15984 return false;
15985 } else {
15986 LValue LVal;
15987 LVal.set(Base);
15988 // C++23 [intro.execution]/p5
15989 // A full-expression is [...] a constant-expression
15990 // So we need to make sure temporary objects are destroyed after having
15991 // evaluating the expression (per C++23 [class.temporary]/p4).
15992 FullExpressionRAII Scope(Info);
15993 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
15994 Result.HasSideEffects || !Scope.destroy())
15995 return false;
15996
15997 if (!Info.discardCleanups())
15998 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15999 }
16000
16001 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
16002 Result.Val, Kind))
16003 return false;
16004 if (!CheckMemoryLeaks(Info))
16005 return false;
16006
16007 // If this is a class template argument, it's required to have constant
16008 // destruction too.
16009 if (Kind == ConstantExprKind::ClassTemplateArgument &&
16010 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
16011 true) ||
16012 Result.HasSideEffects)) {
16013 // FIXME: Prefix a note to indicate that the problem is lack of constant
16014 // destruction.
16015 return false;
16016 }
16017
16018 return true;
16019}
16020
16022 const VarDecl *VD,
16024 bool IsConstantInitialization) const {
16025 assert(!isValueDependent() &&
16026 "Expression evaluator can't be called on a dependent expression.");
16027
16028 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
16029 std::string Name;
16030 llvm::raw_string_ostream OS(Name);
16031 VD->printQualifiedName(OS);
16032 return Name;
16033 });
16034
16035 Expr::EvalStatus EStatus;
16036 EStatus.Diag = &Notes;
16037
16038 EvalInfo Info(Ctx, EStatus,
16039 (IsConstantInitialization &&
16040 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
16041 ? EvalInfo::EM_ConstantExpression
16042 : EvalInfo::EM_ConstantFold);
16043 Info.setEvaluatingDecl(VD, Value);
16044 Info.InConstantContext = IsConstantInitialization;
16045
16046 SourceLocation DeclLoc = VD->getLocation();
16047 QualType DeclTy = VD->getType();
16048
16049 if (Info.EnableNewConstInterp) {
16050 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
16051 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
16052 return false;
16053
16054 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
16055 ConstantExprKind::Normal);
16056 } else {
16057 LValue LVal;
16058 LVal.set(VD);
16059
16060 {
16061 // C++23 [intro.execution]/p5
16062 // A full-expression is ... an init-declarator ([dcl.decl]) or a
16063 // mem-initializer.
16064 // So we need to make sure temporary objects are destroyed after having
16065 // evaluated the expression (per C++23 [class.temporary]/p4).
16066 //
16067 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
16068 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
16069 // outermost FullExpr, such as ExprWithCleanups.
16070 FullExpressionRAII Scope(Info);
16071 if (!EvaluateInPlace(Value, Info, LVal, this,
16072 /*AllowNonLiteralTypes=*/true) ||
16073 EStatus.HasSideEffects)
16074 return false;
16075 }
16076
16077 // At this point, any lifetime-extended temporaries are completely
16078 // initialized.
16079 Info.performLifetimeExtension();
16080
16081 if (!Info.discardCleanups())
16082 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16083 }
16084
16085 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
16086 ConstantExprKind::Normal) &&
16087 CheckMemoryLeaks(Info);
16088}
16089
16092 Expr::EvalStatus EStatus;
16093 EStatus.Diag = &Notes;
16094
16095 // Only treat the destruction as constant destruction if we formally have
16096 // constant initialization (or are usable in a constant expression).
16097 bool IsConstantDestruction = hasConstantInitialization();
16098
16099 // Make a copy of the value for the destructor to mutate, if we know it.
16100 // Otherwise, treat the value as default-initialized; if the destructor works
16101 // anyway, then the destruction is constant (and must be essentially empty).
16102 APValue DestroyedValue;
16103 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
16104 DestroyedValue = *getEvaluatedValue();
16105 else if (!handleDefaultInitValue(getType(), DestroyedValue))
16106 return false;
16107
16108 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
16109 getType(), getLocation(), EStatus,
16110 IsConstantDestruction) ||
16111 EStatus.HasSideEffects)
16112 return false;
16113
16114 ensureEvaluatedStmt()->HasConstantDestruction = true;
16115 return true;
16116}
16117
16118/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
16119/// constant folded, but discard the result.
16121 assert(!isValueDependent() &&
16122 "Expression evaluator can't be called on a dependent expression.");
16123
16124 EvalResult Result;
16125 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
16126 !hasUnacceptableSideEffect(Result, SEK);
16127}
16128
16131 assert(!isValueDependent() &&
16132 "Expression evaluator can't be called on a dependent expression.");
16133
16134 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
16135 EvalResult EVResult;
16136 EVResult.Diag = Diag;
16137 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16138 Info.InConstantContext = true;
16139
16140 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
16141 (void)Result;
16142 assert(Result && "Could not evaluate expression");
16143 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
16144
16145 return EVResult.Val.getInt();
16146}
16147
16150 assert(!isValueDependent() &&
16151 "Expression evaluator can't be called on a dependent expression.");
16152
16153 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
16154 EvalResult EVResult;
16155 EVResult.Diag = Diag;
16156 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16157 Info.InConstantContext = true;
16158 Info.CheckingForUndefinedBehavior = true;
16159
16160 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
16161 (void)Result;
16162 assert(Result && "Could not evaluate expression");
16163 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
16164
16165 return EVResult.Val.getInt();
16166}
16167
16169 assert(!isValueDependent() &&
16170 "Expression evaluator can't be called on a dependent expression.");
16171
16172 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
16173 bool IsConst;
16174 EvalResult EVResult;
16175 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
16176 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16177 Info.CheckingForUndefinedBehavior = true;
16178 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
16179 }
16180}
16181
16183 assert(Val.isLValue());
16184 return IsGlobalLValue(Val.getLValueBase());
16185}
16186
16187/// isIntegerConstantExpr - this recursive routine will test if an expression is
16188/// an integer constant expression.
16189
16190/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
16191/// comma, etc
16192
16193// CheckICE - This function does the fundamental ICE checking: the returned
16194// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
16195// and a (possibly null) SourceLocation indicating the location of the problem.
16196//
16197// Note that to reduce code duplication, this helper does no evaluation
16198// itself; the caller checks whether the expression is evaluatable, and
16199// in the rare cases where CheckICE actually cares about the evaluated
16200// value, it calls into Evaluate.
16201
16202namespace {
16203
16204enum ICEKind {
16205 /// This expression is an ICE.
16206 IK_ICE,
16207 /// This expression is not an ICE, but if it isn't evaluated, it's
16208 /// a legal subexpression for an ICE. This return value is used to handle
16209 /// the comma operator in C99 mode, and non-constant subexpressions.
16210 IK_ICEIfUnevaluated,
16211 /// This expression is not an ICE, and is not a legal subexpression for one.
16212 IK_NotICE
16213};
16214
16215struct ICEDiag {
16216 ICEKind Kind;
16218
16219 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
16220};
16221
16222}
16223
16224static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
16225
16226static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
16227
16228static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
16229 Expr::EvalResult EVResult;
16230 Expr::EvalStatus Status;
16231 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16232
16233 Info.InConstantContext = true;
16234 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
16235 !EVResult.Val.isInt())
16236 return ICEDiag(IK_NotICE, E->getBeginLoc());
16237
16238 return NoDiag();
16239}
16240
16241static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
16242 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
16244 return ICEDiag(IK_NotICE, E->getBeginLoc());
16245
16246 switch (E->getStmtClass()) {
16247#define ABSTRACT_STMT(Node)
16248#define STMT(Node, Base) case Expr::Node##Class:
16249#define EXPR(Node, Base)
16250#include "clang/AST/StmtNodes.inc"
16251 case Expr::PredefinedExprClass:
16252 case Expr::FloatingLiteralClass:
16253 case Expr::ImaginaryLiteralClass:
16254 case Expr::StringLiteralClass:
16255 case Expr::ArraySubscriptExprClass:
16256 case Expr::MatrixSubscriptExprClass:
16257 case Expr::ArraySectionExprClass:
16258 case Expr::OMPArrayShapingExprClass:
16259 case Expr::OMPIteratorExprClass:
16260 case Expr::MemberExprClass:
16261 case Expr::CompoundAssignOperatorClass:
16262 case Expr::CompoundLiteralExprClass:
16263 case Expr::ExtVectorElementExprClass:
16264 case Expr::DesignatedInitExprClass:
16265 case Expr::ArrayInitLoopExprClass:
16266 case Expr::ArrayInitIndexExprClass:
16267 case Expr::NoInitExprClass:
16268 case Expr::DesignatedInitUpdateExprClass:
16269 case Expr::ImplicitValueInitExprClass:
16270 case Expr::ParenListExprClass:
16271 case Expr::VAArgExprClass:
16272 case Expr::AddrLabelExprClass:
16273 case Expr::StmtExprClass:
16274 case Expr::CXXMemberCallExprClass:
16275 case Expr::CUDAKernelCallExprClass:
16276 case Expr::CXXAddrspaceCastExprClass:
16277 case Expr::CXXDynamicCastExprClass:
16278 case Expr::CXXTypeidExprClass:
16279 case Expr::CXXUuidofExprClass:
16280 case Expr::MSPropertyRefExprClass:
16281 case Expr::MSPropertySubscriptExprClass:
16282 case Expr::CXXNullPtrLiteralExprClass:
16283 case Expr::UserDefinedLiteralClass:
16284 case Expr::CXXThisExprClass:
16285 case Expr::CXXThrowExprClass:
16286 case Expr::CXXNewExprClass:
16287 case Expr::CXXDeleteExprClass:
16288 case Expr::CXXPseudoDestructorExprClass:
16289 case Expr::UnresolvedLookupExprClass:
16290 case Expr::TypoExprClass:
16291 case Expr::RecoveryExprClass:
16292 case Expr::DependentScopeDeclRefExprClass:
16293 case Expr::CXXConstructExprClass:
16294 case Expr::CXXInheritedCtorInitExprClass:
16295 case Expr::CXXStdInitializerListExprClass:
16296 case Expr::CXXBindTemporaryExprClass:
16297 case Expr::ExprWithCleanupsClass:
16298 case Expr::CXXTemporaryObjectExprClass:
16299 case Expr::CXXUnresolvedConstructExprClass:
16300 case Expr::CXXDependentScopeMemberExprClass:
16301 case Expr::UnresolvedMemberExprClass:
16302 case Expr::ObjCStringLiteralClass:
16303 case Expr::ObjCBoxedExprClass:
16304 case Expr::ObjCArrayLiteralClass:
16305 case Expr::ObjCDictionaryLiteralClass:
16306 case Expr::ObjCEncodeExprClass:
16307 case Expr::ObjCMessageExprClass:
16308 case Expr::ObjCSelectorExprClass:
16309 case Expr::ObjCProtocolExprClass:
16310 case Expr::ObjCIvarRefExprClass:
16311 case Expr::ObjCPropertyRefExprClass:
16312 case Expr::ObjCSubscriptRefExprClass:
16313 case Expr::ObjCIsaExprClass:
16314 case Expr::ObjCAvailabilityCheckExprClass:
16315 case Expr::ShuffleVectorExprClass:
16316 case Expr::ConvertVectorExprClass:
16317 case Expr::BlockExprClass:
16318 case Expr::NoStmtClass:
16319 case Expr::OpaqueValueExprClass:
16320 case Expr::PackExpansionExprClass:
16321 case Expr::SubstNonTypeTemplateParmPackExprClass:
16322 case Expr::FunctionParmPackExprClass:
16323 case Expr::AsTypeExprClass:
16324 case Expr::ObjCIndirectCopyRestoreExprClass:
16325 case Expr::MaterializeTemporaryExprClass:
16326 case Expr::PseudoObjectExprClass:
16327 case Expr::AtomicExprClass:
16328 case Expr::LambdaExprClass:
16329 case Expr::CXXFoldExprClass:
16330 case Expr::CoawaitExprClass:
16331 case Expr::DependentCoawaitExprClass:
16332 case Expr::CoyieldExprClass:
16333 case Expr::SYCLUniqueStableNameExprClass:
16334 case Expr::CXXParenListInitExprClass:
16335 return ICEDiag(IK_NotICE, E->getBeginLoc());
16336
16337 case Expr::InitListExprClass: {
16338 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
16339 // form "T x = { a };" is equivalent to "T x = a;".
16340 // Unless we're initializing a reference, T is a scalar as it is known to be
16341 // of integral or enumeration type.
16342 if (E->isPRValue())
16343 if (cast<InitListExpr>(E)->getNumInits() == 1)
16344 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
16345 return ICEDiag(IK_NotICE, E->getBeginLoc());
16346 }
16347
16348 case Expr::SizeOfPackExprClass:
16349 case Expr::GNUNullExprClass:
16350 case Expr::SourceLocExprClass:
16351 return NoDiag();
16352
16353 case Expr::PackIndexingExprClass:
16354 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
16355
16356 case Expr::SubstNonTypeTemplateParmExprClass:
16357 return
16358 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
16359
16360 case Expr::ConstantExprClass:
16361 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
16362
16363 case Expr::ParenExprClass:
16364 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
16365 case Expr::GenericSelectionExprClass:
16366 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
16367 case Expr::IntegerLiteralClass:
16368 case Expr::FixedPointLiteralClass:
16369 case Expr::CharacterLiteralClass:
16370 case Expr::ObjCBoolLiteralExprClass:
16371 case Expr::CXXBoolLiteralExprClass:
16372 case Expr::CXXScalarValueInitExprClass:
16373 case Expr::TypeTraitExprClass:
16374 case Expr::ConceptSpecializationExprClass:
16375 case Expr::RequiresExprClass:
16376 case Expr::ArrayTypeTraitExprClass:
16377 case Expr::ExpressionTraitExprClass:
16378 case Expr::CXXNoexceptExprClass:
16379 return NoDiag();
16380 case Expr::CallExprClass:
16381 case Expr::CXXOperatorCallExprClass: {
16382 // C99 6.6/3 allows function calls within unevaluated subexpressions of
16383 // constant expressions, but they can never be ICEs because an ICE cannot
16384 // contain an operand of (pointer to) function type.
16385 const CallExpr *CE = cast<CallExpr>(E);
16386 if (CE->getBuiltinCallee())
16387 return CheckEvalInICE(E, Ctx);
16388 return ICEDiag(IK_NotICE, E->getBeginLoc());
16389 }
16390 case Expr::CXXRewrittenBinaryOperatorClass:
16391 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
16392 Ctx);
16393 case Expr::DeclRefExprClass: {
16394 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
16395 if (isa<EnumConstantDecl>(D))
16396 return NoDiag();
16397
16398 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
16399 // integer variables in constant expressions:
16400 //
16401 // C++ 7.1.5.1p2
16402 // A variable of non-volatile const-qualified integral or enumeration
16403 // type initialized by an ICE can be used in ICEs.
16404 //
16405 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
16406 // that mode, use of reference variables should not be allowed.
16407 const VarDecl *VD = dyn_cast<VarDecl>(D);
16408 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
16409 !VD->getType()->isReferenceType())
16410 return NoDiag();
16411
16412 return ICEDiag(IK_NotICE, E->getBeginLoc());
16413 }
16414 case Expr::UnaryOperatorClass: {
16415 const UnaryOperator *Exp = cast<UnaryOperator>(E);
16416 switch (Exp->getOpcode()) {
16417 case UO_PostInc:
16418 case UO_PostDec:
16419 case UO_PreInc:
16420 case UO_PreDec:
16421 case UO_AddrOf:
16422 case UO_Deref:
16423 case UO_Coawait:
16424 // C99 6.6/3 allows increment and decrement within unevaluated
16425 // subexpressions of constant expressions, but they can never be ICEs
16426 // because an ICE cannot contain an lvalue operand.
16427 return ICEDiag(IK_NotICE, E->getBeginLoc());
16428 case UO_Extension:
16429 case UO_LNot:
16430 case UO_Plus:
16431 case UO_Minus:
16432 case UO_Not:
16433 case UO_Real:
16434 case UO_Imag:
16435 return CheckICE(Exp->getSubExpr(), Ctx);
16436 }
16437 llvm_unreachable("invalid unary operator class");
16438 }
16439 case Expr::OffsetOfExprClass: {
16440 // Note that per C99, offsetof must be an ICE. And AFAIK, using
16441 // EvaluateAsRValue matches the proposed gcc behavior for cases like
16442 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
16443 // compliance: we should warn earlier for offsetof expressions with
16444 // array subscripts that aren't ICEs, and if the array subscripts
16445 // are ICEs, the value of the offsetof must be an integer constant.
16446 return CheckEvalInICE(E, Ctx);
16447 }
16448 case Expr::UnaryExprOrTypeTraitExprClass: {
16449 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
16450 if ((Exp->getKind() == UETT_SizeOf) &&
16452 return ICEDiag(IK_NotICE, E->getBeginLoc());
16453 return NoDiag();
16454 }
16455 case Expr::BinaryOperatorClass: {
16456 const BinaryOperator *Exp = cast<BinaryOperator>(E);
16457 switch (Exp->getOpcode()) {
16458 case BO_PtrMemD:
16459 case BO_PtrMemI:
16460 case BO_Assign:
16461 case BO_MulAssign:
16462 case BO_DivAssign:
16463 case BO_RemAssign:
16464 case BO_AddAssign:
16465 case BO_SubAssign:
16466 case BO_ShlAssign:
16467 case BO_ShrAssign:
16468 case BO_AndAssign:
16469 case BO_XorAssign:
16470 case BO_OrAssign:
16471 // C99 6.6/3 allows assignments within unevaluated subexpressions of
16472 // constant expressions, but they can never be ICEs because an ICE cannot
16473 // contain an lvalue operand.
16474 return ICEDiag(IK_NotICE, E->getBeginLoc());
16475
16476 case BO_Mul:
16477 case BO_Div:
16478 case BO_Rem:
16479 case BO_Add:
16480 case BO_Sub:
16481 case BO_Shl:
16482 case BO_Shr:
16483 case BO_LT:
16484 case BO_GT:
16485 case BO_LE:
16486 case BO_GE:
16487 case BO_EQ:
16488 case BO_NE:
16489 case BO_And:
16490 case BO_Xor:
16491 case BO_Or:
16492 case BO_Comma:
16493 case BO_Cmp: {
16494 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
16495 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
16496 if (Exp->getOpcode() == BO_Div ||
16497 Exp->getOpcode() == BO_Rem) {
16498 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
16499 // we don't evaluate one.
16500 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
16501 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
16502 if (REval == 0)
16503 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16504 if (REval.isSigned() && REval.isAllOnes()) {
16505 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
16506 if (LEval.isMinSignedValue())
16507 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16508 }
16509 }
16510 }
16511 if (Exp->getOpcode() == BO_Comma) {
16512 if (Ctx.getLangOpts().C99) {
16513 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
16514 // if it isn't evaluated.
16515 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
16516 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16517 } else {
16518 // In both C89 and C++, commas in ICEs are illegal.
16519 return ICEDiag(IK_NotICE, E->getBeginLoc());
16520 }
16521 }
16522 return Worst(LHSResult, RHSResult);
16523 }
16524 case BO_LAnd:
16525 case BO_LOr: {
16526 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
16527 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
16528 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
16529 // Rare case where the RHS has a comma "side-effect"; we need
16530 // to actually check the condition to see whether the side
16531 // with the comma is evaluated.
16532 if ((Exp->getOpcode() == BO_LAnd) !=
16533 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
16534 return RHSResult;
16535 return NoDiag();
16536 }
16537
16538 return Worst(LHSResult, RHSResult);
16539 }
16540 }
16541 llvm_unreachable("invalid binary operator kind");
16542 }
16543 case Expr::ImplicitCastExprClass:
16544 case Expr::CStyleCastExprClass:
16545 case Expr::CXXFunctionalCastExprClass:
16546 case Expr::CXXStaticCastExprClass:
16547 case Expr::CXXReinterpretCastExprClass:
16548 case Expr::CXXConstCastExprClass:
16549 case Expr::ObjCBridgedCastExprClass: {
16550 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
16551 if (isa<ExplicitCastExpr>(E)) {
16552 if (const FloatingLiteral *FL
16553 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
16554 unsigned DestWidth = Ctx.getIntWidth(E->getType());
16555 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
16556 APSInt IgnoredVal(DestWidth, !DestSigned);
16557 bool Ignored;
16558 // If the value does not fit in the destination type, the behavior is
16559 // undefined, so we are not required to treat it as a constant
16560 // expression.
16561 if (FL->getValue().convertToInteger(IgnoredVal,
16562 llvm::APFloat::rmTowardZero,
16563 &Ignored) & APFloat::opInvalidOp)
16564 return ICEDiag(IK_NotICE, E->getBeginLoc());
16565 return NoDiag();
16566 }
16567 }
16568 switch (cast<CastExpr>(E)->getCastKind()) {
16569 case CK_LValueToRValue:
16570 case CK_AtomicToNonAtomic:
16571 case CK_NonAtomicToAtomic:
16572 case CK_NoOp:
16573 case CK_IntegralToBoolean:
16574 case CK_IntegralCast:
16575 return CheckICE(SubExpr, Ctx);
16576 default:
16577 return ICEDiag(IK_NotICE, E->getBeginLoc());
16578 }
16579 }
16580 case Expr::BinaryConditionalOperatorClass: {
16581 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
16582 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
16583 if (CommonResult.Kind == IK_NotICE) return CommonResult;
16584 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16585 if (FalseResult.Kind == IK_NotICE) return FalseResult;
16586 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
16587 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
16588 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
16589 return FalseResult;
16590 }
16591 case Expr::ConditionalOperatorClass: {
16592 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
16593 // If the condition (ignoring parens) is a __builtin_constant_p call,
16594 // then only the true side is actually considered in an integer constant
16595 // expression, and it is fully evaluated. This is an important GNU
16596 // extension. See GCC PR38377 for discussion.
16597 if (const CallExpr *CallCE
16598 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
16599 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
16600 return CheckEvalInICE(E, Ctx);
16601 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
16602 if (CondResult.Kind == IK_NotICE)
16603 return CondResult;
16604
16605 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
16606 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16607
16608 if (TrueResult.Kind == IK_NotICE)
16609 return TrueResult;
16610 if (FalseResult.Kind == IK_NotICE)
16611 return FalseResult;
16612 if (CondResult.Kind == IK_ICEIfUnevaluated)
16613 return CondResult;
16614 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
16615 return NoDiag();
16616 // Rare case where the diagnostics depend on which side is evaluated
16617 // Note that if we get here, CondResult is 0, and at least one of
16618 // TrueResult and FalseResult is non-zero.
16619 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
16620 return FalseResult;
16621 return TrueResult;
16622 }
16623 case Expr::CXXDefaultArgExprClass:
16624 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
16625 case Expr::CXXDefaultInitExprClass:
16626 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
16627 case Expr::ChooseExprClass: {
16628 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
16629 }
16630 case Expr::BuiltinBitCastExprClass: {
16631 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
16632 return ICEDiag(IK_NotICE, E->getBeginLoc());
16633 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
16634 }
16635 }
16636
16637 llvm_unreachable("Invalid StmtClass!");
16638}
16639
16640/// Evaluate an expression as a C++11 integral constant expression.
16642 const Expr *E,
16643 llvm::APSInt *Value,
16646 if (Loc) *Loc = E->getExprLoc();
16647 return false;
16648 }
16649
16650 APValue Result;
16651 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
16652 return false;
16653
16654 if (!Result.isInt()) {
16655 if (Loc) *Loc = E->getExprLoc();
16656 return false;
16657 }
16658
16659 if (Value) *Value = Result.getInt();
16660 return true;
16661}
16662
16664 SourceLocation *Loc) const {
16665 assert(!isValueDependent() &&
16666 "Expression evaluator can't be called on a dependent expression.");
16667
16668 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
16669
16670 if (Ctx.getLangOpts().CPlusPlus11)
16671 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
16672
16673 ICEDiag D = CheckICE(this, Ctx);
16674 if (D.Kind != IK_ICE) {
16675 if (Loc) *Loc = D.Loc;
16676 return false;
16677 }
16678 return true;
16679}
16680
16681std::optional<llvm::APSInt>
16683 if (isValueDependent()) {
16684 // Expression evaluator can't succeed on a dependent expression.
16685 return std::nullopt;
16686 }
16687
16688 APSInt Value;
16689
16690 if (Ctx.getLangOpts().CPlusPlus11) {
16692 return Value;
16693 return std::nullopt;
16694 }
16695
16696 if (!isIntegerConstantExpr(Ctx, Loc))
16697 return std::nullopt;
16698
16699 // The only possible side-effects here are due to UB discovered in the
16700 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
16701 // required to treat the expression as an ICE, so we produce the folded
16702 // value.
16704 Expr::EvalStatus Status;
16705 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
16706 Info.InConstantContext = true;
16707
16708 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
16709 llvm_unreachable("ICE cannot be evaluated!");
16710
16711 return ExprResult.Val.getInt();
16712}
16713
16715 assert(!isValueDependent() &&
16716 "Expression evaluator can't be called on a dependent expression.");
16717
16718 return CheckICE(this, Ctx).Kind == IK_ICE;
16719}
16720
16722 SourceLocation *Loc) const {
16723 assert(!isValueDependent() &&
16724 "Expression evaluator can't be called on a dependent expression.");
16725
16726 // We support this checking in C++98 mode in order to diagnose compatibility
16727 // issues.
16728 assert(Ctx.getLangOpts().CPlusPlus);
16729
16730 // Build evaluation settings.
16731 Expr::EvalStatus Status;
16733 Status.Diag = &Diags;
16734 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16735
16736 APValue Scratch;
16737 bool IsConstExpr =
16738 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
16739 // FIXME: We don't produce a diagnostic for this, but the callers that
16740 // call us on arbitrary full-expressions should generally not care.
16741 Info.discardCleanups() && !Status.HasSideEffects;
16742
16743 if (!Diags.empty()) {
16744 IsConstExpr = false;
16745 if (Loc) *Loc = Diags[0].first;
16746 } else if (!IsConstExpr) {
16747 // FIXME: This shouldn't happen.
16748 if (Loc) *Loc = getExprLoc();
16749 }
16750
16751 return IsConstExpr;
16752}
16753
16755 const FunctionDecl *Callee,
16757 const Expr *This) const {
16758 assert(!isValueDependent() &&
16759 "Expression evaluator can't be called on a dependent expression.");
16760
16761 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
16762 std::string Name;
16763 llvm::raw_string_ostream OS(Name);
16764 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
16765 /*Qualified=*/true);
16766 return Name;
16767 });
16768
16769 Expr::EvalStatus Status;
16770 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
16771 Info.InConstantContext = true;
16772
16773 LValue ThisVal;
16774 const LValue *ThisPtr = nullptr;
16775 if (This) {
16776#ifndef NDEBUG
16777 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
16778 assert(MD && "Don't provide `this` for non-methods.");
16779 assert(MD->isImplicitObjectMemberFunction() &&
16780 "Don't provide `this` for methods without an implicit object.");
16781#endif
16782 if (!This->isValueDependent() &&
16783 EvaluateObjectArgument(Info, This, ThisVal) &&
16784 !Info.EvalStatus.HasSideEffects)
16785 ThisPtr = &ThisVal;
16786
16787 // Ignore any side-effects from a failed evaluation. This is safe because
16788 // they can't interfere with any other argument evaluation.
16789 Info.EvalStatus.HasSideEffects = false;
16790 }
16791
16792 CallRef Call = Info.CurrentCall->createCall(Callee);
16793 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
16794 I != E; ++I) {
16795 unsigned Idx = I - Args.begin();
16796 if (Idx >= Callee->getNumParams())
16797 break;
16798 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
16799 if ((*I)->isValueDependent() ||
16800 !EvaluateCallArg(PVD, *I, Call, Info) ||
16801 Info.EvalStatus.HasSideEffects) {
16802 // If evaluation fails, throw away the argument entirely.
16803 if (APValue *Slot = Info.getParamSlot(Call, PVD))
16804 *Slot = APValue();
16805 }
16806
16807 // Ignore any side-effects from a failed evaluation. This is safe because
16808 // they can't interfere with any other argument evaluation.
16809 Info.EvalStatus.HasSideEffects = false;
16810 }
16811
16812 // Parameter cleanups happen in the caller and are not part of this
16813 // evaluation.
16814 Info.discardCleanups();
16815 Info.EvalStatus.HasSideEffects = false;
16816
16817 // Build fake call to Callee.
16818 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
16819 Call);
16820 // FIXME: Missing ExprWithCleanups in enable_if conditions?
16821 FullExpressionRAII Scope(Info);
16822 return Evaluate(Value, Info, this) && Scope.destroy() &&
16823 !Info.EvalStatus.HasSideEffects;
16824}
16825
16828 PartialDiagnosticAt> &Diags) {
16829 // FIXME: It would be useful to check constexpr function templates, but at the
16830 // moment the constant expression evaluator cannot cope with the non-rigorous
16831 // ASTs which we build for dependent expressions.
16832 if (FD->isDependentContext())
16833 return true;
16834
16835 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
16836 std::string Name;
16837 llvm::raw_string_ostream OS(Name);
16839 /*Qualified=*/true);
16840 return Name;
16841 });
16842
16843 Expr::EvalStatus Status;
16844 Status.Diag = &Diags;
16845
16846 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
16847 Info.InConstantContext = true;
16848 Info.CheckingPotentialConstantExpression = true;
16849
16850 // The constexpr VM attempts to compile all methods to bytecode here.
16851 if (Info.EnableNewConstInterp) {
16852 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
16853 return Diags.empty();
16854 }
16855
16856 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
16857 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
16858
16859 // Fabricate an arbitrary expression on the stack and pretend that it
16860 // is a temporary being used as the 'this' pointer.
16861 LValue This;
16862 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
16863 This.set({&VIE, Info.CurrentCall->Index});
16864
16866
16867 APValue Scratch;
16868 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
16869 // Evaluate the call as a constant initializer, to allow the construction
16870 // of objects of non-literal types.
16871 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
16872 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
16873 } else {
16876 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
16877 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
16878 /*ResultSlot=*/nullptr);
16879 }
16880
16881 return Diags.empty();
16882}
16883
16885 const FunctionDecl *FD,
16887 PartialDiagnosticAt> &Diags) {
16888 assert(!E->isValueDependent() &&
16889 "Expression evaluator can't be called on a dependent expression.");
16890
16891 Expr::EvalStatus Status;
16892 Status.Diag = &Diags;
16893
16894 EvalInfo Info(FD->getASTContext(), Status,
16895 EvalInfo::EM_ConstantExpressionUnevaluated);
16896 Info.InConstantContext = true;
16897 Info.CheckingPotentialConstantExpression = true;
16898
16899 // Fabricate a call stack frame to give the arguments a plausible cover story.
16900 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
16901 /*CallExpr=*/nullptr, CallRef());
16902
16903 APValue ResultScratch;
16904 Evaluate(ResultScratch, Info, E);
16905 return Diags.empty();
16906}
16907
16908bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
16909 unsigned Type) const {
16910 if (!getType()->isPointerType())
16911 return false;
16912
16913 Expr::EvalStatus Status;
16914 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16915 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
16916}
16917
16918static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
16919 EvalInfo &Info) {
16920 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
16921 return false;
16922
16923 LValue String;
16924
16925 if (!EvaluatePointer(E, String, Info))
16926 return false;
16927
16928 QualType CharTy = E->getType()->getPointeeType();
16929
16930 // Fast path: if it's a string literal, search the string value.
16931 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
16932 String.getLValueBase().dyn_cast<const Expr *>())) {
16933 StringRef Str = S->getBytes();
16934 int64_t Off = String.Offset.getQuantity();
16935 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
16936 S->getCharByteWidth() == 1 &&
16937 // FIXME: Add fast-path for wchar_t too.
16938 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
16939 Str = Str.substr(Off);
16940
16941 StringRef::size_type Pos = Str.find(0);
16942 if (Pos != StringRef::npos)
16943 Str = Str.substr(0, Pos);
16944
16945 Result = Str.size();
16946 return true;
16947 }
16948
16949 // Fall through to slow path.
16950 }
16951
16952 // Slow path: scan the bytes of the string looking for the terminating 0.
16953 for (uint64_t Strlen = 0; /**/; ++Strlen) {
16954 APValue Char;
16955 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16956 !Char.isInt())
16957 return false;
16958 if (!Char.getInt()) {
16959 Result = Strlen;
16960 return true;
16961 }
16962 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16963 return false;
16964 }
16965}
16966
16967bool Expr::EvaluateCharRangeAsString(std::string &Result,
16968 const Expr *SizeExpression,
16969 const Expr *PtrExpression, ASTContext &Ctx,
16970 EvalResult &Status) const {
16971 LValue String;
16972 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16973 Info.InConstantContext = true;
16974
16975 FullExpressionRAII Scope(Info);
16976 APSInt SizeValue;
16977 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
16978 return false;
16979
16980 uint64_t Size = SizeValue.getZExtValue();
16981
16982 if (!::EvaluatePointer(PtrExpression, String, Info))
16983 return false;
16984
16985 QualType CharTy = PtrExpression->getType()->getPointeeType();
16986 for (uint64_t I = 0; I < Size; ++I) {
16987 APValue Char;
16988 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
16989 Char))
16990 return false;
16991
16992 APSInt C = Char.getInt();
16993 Result.push_back(static_cast<char>(C.getExtValue()));
16994 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
16995 return false;
16996 }
16997 if (!Scope.destroy())
16998 return false;
16999
17000 if (!CheckMemoryLeaks(Info))
17001 return false;
17002
17003 return true;
17004}
17005
17006bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
17007 Expr::EvalStatus Status;
17008 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17009 return EvaluateBuiltinStrLen(this, Result, Info);
17010}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3285
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines enum values for all the target-independent builtin functions.
llvm::APSInt APSInt
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1125
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC's builtin.
static bool isRead(AccessKinds AK)
static bool isValidIndeterminateAccess(AccessKinds AK)
Is this kind of axcess valid on an indeterminate object value?
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 CharUnits GetAlignOfType(EvalInfo &Info, QualType T, UnaryExprOrTypeTrait ExprKind)
static const CXXMethodDecl * HandleVirtualDispatch(EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, llvm::SmallVectorImpl< QualType > &CovariantAdjustmentPath)
Perform virtual dispatch.
static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD)
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind, const FieldDecl *SubobjectDecl, CheckedTemporaries &CheckedTemps)
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, bool Imag)
Update an lvalue to refer to a component of a complex number.
static bool 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 FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, const ASTContext &Ctx, bool &IsConst)
static bool HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result)
Evaluate a constructor call.
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.
static bool isAnyAccess(AccessKinds AK)
static bool EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, SuccessCB &&Success, AfterCB &&DoAfter)
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result)
Perform zero-initialization on an object of non-union class type.
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info)
static bool CheckMemoryLeaks(EvalInfo &Info)
Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless "the allocated storage is dea...
static ICEDiag CheckEvalInICE(const Expr *E, const ASTContext &Ctx)
static bool IsLiteralLValue(const LValue &Value)
static bool HandleFunctionCall(SourceLocation CallLoc, const FunctionDecl *Callee, const LValue *This, 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 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.
bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E)
static ICEDiag Worst(ICEDiag A, ICEDiag B)
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, const VarDecl *VD, CallStackFrame *Frame, unsigned Version, APValue *&Result)
Try to evaluate the initializer for a variable declaration.
static bool handleDefaultInitValue(QualType T, APValue &Result)
Get the value to use for a default-initialized object of type T.
static 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 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 CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, UnaryExprOrTypeTrait ExprKind)
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.
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 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 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 EvaluateArgs(ArrayRef< const Expr * > Args, CallRef Call, EvalInfo &Info, const FunctionDecl *Callee, bool RightToLeft=false)
Evaluate the arguments to a function call.
static QualType getSubobjectType(QualType ObjType, QualType SubobjType, bool IsMutable=false)
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate an integer or fixed point expression into an APResult.
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
static const CXXRecordDecl * getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength)
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, const CXXRecordDecl *DerivedRD, const CXXRecordDecl *BaseRD)
Cast an lvalue referring to a derived class to a known base subobject.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
static bool HandleConversionToBool(const APValue &Val, bool &Result)
static bool IsNoOpCall(const CallExpr *E)
Should this call expression be treated as a no-op?
static bool isModification(AccessKinds AK)
static bool handleCompareOpForVector(const APValue &LHSValue, BinaryOperatorKind Opcode, const APValue &RHSValue, APInt &Result)
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, const CallExpr *Call, llvm::APInt &Result)
Attempts to compute the number of bytes available at the pointer returned by a function with the allo...
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 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 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 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 bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value, SourceLocation *Loc)
Evaluate an expression as a C++11 integral constant expression.
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.
static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, uint64_t &Size)
Tries to evaluate the __builtin_object_size for E.
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static const FunctionDecl * getVirtualOperatorDelete(QualType T)
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal)
Checks to see if the given LValue's Designator is at the end of the LValue's record layout.
static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT, SourceLocation CallLoc={})
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, const Expr *E, bool AllowNonLiteralTypes=false)
EvaluateInPlace - Evaluate an expression in-place in an APValue.
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, APFloat &LHS, BinaryOperatorKind Opcode, const APFloat &RHS)
Perform the given binary floating-point operation, in-place, on LHS.
static std::optional< DynAlloc * > CheckDeleteKind(EvalInfo &Info, const Expr *E, const LValue &Pointer, DynAlloc::Kind DeallocKind)
Check that the given object is a suitable pointer to a heap allocation that still exists and is of th...
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
Evaluate an expression as an lvalue.
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, EvalInfo &Info)
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, CallRef Call, EvalInfo &Info, bool NonNull=false)
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 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 EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, EvalInfo &Info)
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 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 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.
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 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 EvaluateDecl(EvalInfo &Info, const Decl *D)
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, const Stmt *S, const SwitchCase *SC=nullptr)
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, APValue &Result, const InitListExpr *ILE, QualType AllocType)
static bool HasSameBase(const LValue &A, const LValue &B)
static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD)
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool IsGlobalLValue(APValue::LValueBase B)
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E)
Get rounding mode to use in evaluation of the specified expression.
static QualType getObjectType(APValue::LValueBase B)
Retrieves the "underlying object type" of the given expression, as used by __builtin_object_size.
static bool handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, const APTy &RHSValue, APInt &Result)
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
static void negateAsSigned(APSInt &Int)
Negate an APSInt in place, converting it to a signed form if necessary, and preserving its value (by ...
static bool 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 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...
static bool isFormalAccess(AccessKinds AK)
Is this an access per the C++ definition?
static bool handleCompoundAssignment(EvalInfo &Info, const CompoundAssignOperator *E, const LValue &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, const APValue &RVal)
Perform a compound assignment of LVal <op>= RVal.
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, bool IsIncrement, APValue *Old)
Perform an increment or decrement on LVal.
static ICEDiag NoDiag()
static bool EvaluateVoid(const Expr *E, EvalInfo &Info)
static bool HandleDestruction(EvalInfo &Info, const Expr *E, const LValue &This, QualType ThisType)
Perform a destructor or pseudo-destructor call on the given object, which might in general not be a c...
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T)
const CFGBlock * Block
Definition: HTMLLogger.cpp:153
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:22
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
SourceLocation Loc
Definition: SemaObjC.cpp:755
bool Indirect
Definition: SemaObjC.cpp:756
Defines the clang::TypeLoc interface and its subclasses.
__DEVICE__ long long abs(long long __n)
__device__ int
do v
Definition: arm_acle.h:83
llvm::APInt getValue() const
QualType getType() const
Definition: APValue.cpp:63
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:518
const LValueBase getLValueBase() const
Definition: APValue.cpp:974
APValue & getArrayInitializedElt(unsigned I)
Definition: APValue.h:510
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition: APValue.cpp:468
APSInt & getInt()
Definition: APValue.h:423
APValue & getStructField(unsigned i)
Definition: APValue.h:551
const FieldDecl * getUnionField() const
Definition: APValue.h:563
bool isVector() const
Definition: APValue.h:407
APSInt & getComplexIntImag()
Definition: APValue.h:461
bool isAbsent() const
Definition: APValue.h:397
bool isComplexInt() const
Definition: APValue.h:404
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:395
unsigned getArrayInitializedElts() const
Definition: APValue.h:529
static APValue IndeterminateValue()
Definition: APValue.h:366
bool isFloat() const
Definition: APValue.h:402
APFixedPoint & getFixedPoint()
Definition: APValue.h:445
bool hasValue() const
Definition: APValue.h:399
bool hasLValuePath() const
Definition: APValue.cpp:989
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1057
APValue & getUnionValue()
Definition: APValue.h:567
CharUnits & getLValueOffset()
Definition: APValue.cpp:984
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:693
bool isComplexFloat() const
Definition: APValue.h:405
APValue & getVectorElt(unsigned I)
Definition: APValue.h:497
APValue & getArrayFiller()
Definition: APValue.h:521
unsigned getVectorLength() const
Definition: APValue.h:505
bool isLValue() const
Definition: APValue.h:406
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition: APValue.cpp:1050
bool isIndeterminate() const
Definition: APValue.h:398
bool isInt() const
Definition: APValue.h:401
unsigned getArraySize() const
Definition: APValue.h:533
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
bool isFixedPoint() const
Definition: APValue.h:403
@ 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:409
APSInt & getComplexIntReal()
Definition: APValue.h:453
APFloat & getComplexFloatImag()
Definition: APValue.h:477
APFloat & getComplexFloatReal()
Definition: APValue.h:469
APFloat & getFloat()
Definition: APValue.h:437
APValue & getStructBase(unsigned i)
Definition: APValue.h:546
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
SourceManager & getSourceManager()
Definition: ASTContext.h:705
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
QualType getRecordType(const RecordDecl *Decl) const
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,...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2272
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:697
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.
Definition: ASTContext.h:2341
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
Definition: RecordLayout.h:196
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:259
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:4338
LabelDecl * getLabel() const
Definition: Expr.h:4361
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition: Expr.h:5564
Represents a loop initializing the elements of an array.
Definition: Expr.h:5511
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition: Expr.h:5526
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition: Expr.h:5531
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2664
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition: Expr.h:2693
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition: ExprCXX.h:2848
uint64_t getValue() const
Definition: ExprCXX.h:2894
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3518
QualType getElementType() const
Definition: Type.h:3530
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7189
Attr - This represents one attribute.
Definition: Attr.h:42
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4241
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition: Expr.h:4295
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition: Expr.h:4279
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition: Expr.h:4276
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:3972
Expr * getLHS() const
Definition: Expr.h:3889
static bool isRelationalOp(Opcode Opc)
Definition: Expr.h:3933
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3939
bool isComparisonOp() const
Definition: Expr.h:3940
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition: Expr.h:3986
bool isLogicalOp() const
Definition: Expr.h:3973
SourceLocation getExprLoc() const
Definition: Expr.h:3880
Expr * getRHS() const
Definition: Expr.h:3891
static bool isAdditiveOp(Opcode Opc)
Definition: Expr.h:3925
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition: Expr.h:3916
static bool isAssignmentOp(Opcode Opc)
Definition: Expr.h:3975
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition: Expr.h:4039
Opcode getOpcode() const
Definition: Expr.h:3884
static bool isEqualityOp(Opcode Opc)
Definition: Expr.h:3936
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition: Decl.h:4613
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6173
const BlockDecl * getBlockDecl() const
Definition: Expr.h:6185
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition: ExprCXX.h:5282
This class is used for builtin types like 'int'.
Definition: Type.h:2981
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
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
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1487
const Expr * getSubExpr() const
Definition: ExprCXX.h:1509
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
bool getValue() const
Definition: ExprCXX.h:737
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1542
bool isElidable() const
Whether this construction is elidable.
Definition: ExprCXX.h:1611
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1685
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition: ExprCXX.h:1644
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1605
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1682
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2753
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition: DeclCXX.h:2620
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1264
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1371
Expr * getExpr()
Get the initialization expression that will be used.
Definition: ExprCXX.cpp:1035
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2493
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2532
bool isArrayForm() const
Definition: ExprCXX.h:2519
bool isGlobalDelete() const
Definition: ExprCXX.h:2518
Expr * getArgument()
Definition: ExprCXX.h:2534
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition: ExprCXX.h:478
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition: StmtCXX.h:135
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1733
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition: ExprCXX.h:1770
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
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:2455
CXXMethodDecl * getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD, bool MayBeBase=false)
Find if RD declares a function that overrides this function, and if so, return it.
Definition: DeclCXX.cpp:2208
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:2462
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2565
bool isInstance() const
Definition: DeclCXX.h:2087
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2488
bool isStatic() const
Definition: DeclCXX.cpp:2186
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2466
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition: DeclCXX.cpp:2601
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2236
bool isArray() const
Definition: ExprCXX.h:2344
QualType getAllocatedType() const
Definition: ExprCXX.h:2314
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:2349
Expr * getPlacementArg(unsigned I)
Definition: ExprCXX.h:2383
unsigned getNumPlacementArgs() const
Definition: ExprCXX.h:2374
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:2339
Expr * getInitializer()
The initializer of this new-expression.
Definition: ExprCXX.h:2409
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:4119
bool getValue() const
Definition: ExprCXX.h:4142
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:4944
ArrayRef< Expr * > getInitExprs()
Definition: ExprCXX.h:4984
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:1234
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1564
base_class_iterator bases_end()
Definition: DeclCXX.h:628
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1367
base_class_range bases()
Definition: DeclCXX.h:619
capture_const_iterator captures_end() const
Definition: DeclCXX.h:1111
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:1641
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
base_class_iterator bases_begin()
Definition: DeclCXX.h:626
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1190
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1975
capture_const_iterator captures_begin() const
Definition: DeclCXX.h:1105
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1594
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:634
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
A C++ reinterpret_cast expression (C++ [expr.reinterpret.cast]).
Definition: ExprCXX.h:523
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:283
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition: ExprCXX.h:301
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type.
Definition: ExprCXX.h:2177
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition: ExprCXX.h:797
Represents the this expression in C++.
Definition: ExprCXX.h:1148
bool isImplicit() const
Definition: ExprCXX.h:1171
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:845
QualType getTypeOperand(ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition: ExprCXX.cpp:162
bool isTypeOperand() const
Definition: ExprCXX.h:881
Expr * getExprOperand() const
Definition: ExprCXX.h:892
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition: ExprCXX.cpp:135
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1062
MSGuidDecl * getGuidDecl() const
Definition: ExprCXX.h:1108
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1579
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2990
Expr * getCallee()
Definition: Expr.h:2970
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2998
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:3001
Decl * getCalleeDecl()
Definition: Expr.h:2984
CaseStmt - Represent a case statement.
Definition: Stmt.h:1801
Expr * getLHS()
Definition: Stmt.h:1888
Expr * getRHS()
Definition: Stmt.h:1900
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3483
path_iterator path_begin()
Definition: Expr.h:3553
unsigned path_size() const
Definition: Expr.h:3552
CastKind getCastKind() const
Definition: Expr.h:3527
path_iterator path_end()
Definition: Expr.h:3554
const CXXBaseSpecifier *const * path_const_iterator
Definition: Expr.h:3550
bool path_empty() const
Definition: Expr.h:3551
Expr * getSubExpr()
Definition: Expr.h:3533
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
Definition: Expr.h:3592
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:1610
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4558
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition: Expr.h:4594
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryResult makeWeakResult(ComparisonCategoryResult Res) const
Converts the specified result kind into the correct result kind for this category.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3086
QualType getElementType() const
Definition: Type.h:3096
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4088
QualType getComputationLHSType() const
Definition: Expr.h:4122
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3413
bool isFileScope() const
Definition: Expr.h:3440
const Expr * getInitializer() const
Definition: Expr.h:3436
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
bool body_empty() const
Definition: Stmt.h:1650
Stmt *const * const_body_iterator
Definition: Stmt.h:1673
body_iterator body_end()
Definition: Stmt.h:1666
body_range body()
Definition: Stmt.h:1664
body_iterator body_begin()
Definition: Stmt.h:1665
Represents the specialization of a concept - evaluates to a prvalue of type bool.
Definition: ExprConcepts.h:42
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
Definition: ExprConcepts.h:124
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4179
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4211
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4202
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4206
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:195
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3556
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition: Type.h:3619
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:178
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:218
uint64_t getLimitedSize() const
Return the size zero-extended to uint64_t or UINT64_MAX if the value is larger than UINT64_MAX.
Definition: Type.h:3645
bool isZeroSize() const
Return true if the size is zero.
Definition: Type.h:3626
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: Type.h:3652
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3612
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3632
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1072
APValue getAPValueResult() const
Definition: Expr.cpp:413
bool hasAPValueResult() const
Definition: Expr.h:1147
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4499
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition: Expr.h:4519
Represents the current source location and context used to determine the value of the source location...
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2342
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1282
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
ValueDecl * getDecl()
Definition: Expr.h:1328
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1497
decl_range decls()
Definition: Stmt.h:1545
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:403
static void add(Kind k)
Definition: DeclBase.cpp:202
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
bool isInvalidDecl() const
Definition: DeclBase.h:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
DeclContext * getDeclContext()
Definition: DeclBase.h:454
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
A decomposition declaration.
Definition: DeclCXX.h:4166
Designator - A designator in a C99 designated initializer.
Definition: Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition: Stmt.h:2725
Stmt * getBody()
Definition: Stmt.h:2750
Expr * getCond()
Definition: Stmt.h:2743
Symbolic representation of a dynamic allocation.
Definition: APValue.h:65
static unsigned getMaxIndex()
Definition: APValue.h:85
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3297
Represents an enum.
Definition: Decl.h:3867
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4064
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4081
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4027
void getValueRange(llvm::APInt &Max, llvm::APInt &Min) const
Calculates the [Min,Max) values the enum can store based on the NumPositiveBits and NumNegativeBits.
Definition: Decl.cpp:4973
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5575
EnumDecl * getDecl() const
Definition: Type.h:5582
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3730
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3757
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3467
This represents one expression.
Definition: Expr.h:110
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:82
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...
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:280
SideEffectsKind
Definition: Expr.h:667
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition: Expr.h:671
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition: Expr.h:669
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:3064
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) 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:3846
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3059
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
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:3055
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:817
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3556
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3039
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:3193
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3923
ConstantExprKind
Definition: Expr.h:748
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This=nullptr) const
EvaluateWithSubstitution - Evaluate an expression as if from the context of a call to the given funct...
bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, const VarDecl *VD, SmallVectorImpl< PartialDiagnosticAt > &Notes, bool IsConstantInitializer) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
void EvaluateForOverflow(const ASTContext &Ctx) const
bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result=nullptr, SourceLocation *Loc=nullptr) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
An expression trait intrinsic.
Definition: ExprCXX.h:2919
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:6113
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition: Expr.cpp:4315
const Expr * getBase() const
Definition: Expr.h:6130
bool isFPConstrained() const
Definition: LangOptions.h:843
LangOptions::FPExceptionModeKind getExceptionMode() const
Definition: LangOptions.h:861
RoundingMode getRoundingMode() const
Definition: LangOptions.h:849
Represents a member of a struct/union/class.
Definition: Decl.h:3057
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3148
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4644
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4592
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3270
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3281
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:97
llvm::APFloat getValue() const
Definition: Expr.h:1647
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2781
const Expr * getSubExpr() const
Definition: Expr.h:1052
Represents a function declaration or definition.
Definition: Decl.h:1971
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2706
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3236
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4054
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4042
QualType getReturnType() const
Definition: Decl.h:2754
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2339
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4178
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition: Decl.h:2692
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2432
bool isReservedGlobalPlacementOperator() const
Determines whether this operator new or delete is one of the reserved global placement operators: voi...
Definition: Decl.cpp:3341
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3366
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2347
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:3081
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4633
Represents a C11 generic selection.
Definition: Expr.h:5725
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition: Expr.h:6009
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:2138
Stmt * getThen()
Definition: Stmt.h:2227
Stmt * getInit()
Definition: Stmt.h:2288
bool isNonNegatedConsteval() const
Definition: Stmt.h:2323
Expr * getCond()
Definition: Stmt.h:2215
Stmt * getElse()
Definition: Stmt.h:2236
bool isConsteval() const
Definition: Stmt.h:2318
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition: Stmt.cpp:982
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1712
const Expr * getSubExpr() const
Definition: Expr.h:1724
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5600
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3341
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3363
Describes an C or C++ initializer list.
Definition: Expr.h:4847
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition: Expr.cpp:2432
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
Definition: Expr.cpp:2418
unsigned getNumInits() const
Definition: Expr.h:4877
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition: Expr.h:4941
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4893
ArrayRef< Expr * > inits()
Definition: Expr.h:4887
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1950
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition: ExprCXX.h:2088
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition: ExprCXX.h:2076
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition: ExprCXX.cpp:1332
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
A global _GUID constant.
Definition: DeclCXX.h:4289
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4710
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4735
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition: ExprCXX.h:4727
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition: ExprCXX.h:4743
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3172
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
Expr * getBase() const
Definition: Expr.h:3249
bool isArrow() const
Definition: Expr.h:3356
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3460
This represents a decl that may have a name.
Definition: Decl.h:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
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
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:87
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:127
Expr * getSubExpr()
Definition: ExprObjC.h:143
bool isExpressibleAsConstantInitializer() const
Definition: ExprObjC.h:152
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:410
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:51
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition: Expr.h:2465
Expr * getIndexExpr(unsigned Idx)
Definition: Expr.h:2526
const OffsetOfNode & getComponent(unsigned Idx) const
Definition: Expr.h:2512
TypeSourceInfo * getTypeSourceInfo() const
Definition: Expr.h:2505
unsigned getNumComponents() const
Definition: Expr.h:2522
Helper class for OffsetOfExpr.
Definition: Expr.h:2359
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition: Expr.h:2417
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition: Expr.h:2423
@ Array
An index into an array.
Definition: Expr.h:2364
@ Identifier
A field in a dependent type, known only by its name.
Definition: Expr.h:2368
@ Field
A field.
Definition: Expr.h:2366
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition: Expr.h:2371
Kind getKind() const
Determine what kind of offsetof node this is.
Definition: Expr.h:2413
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition: Expr.h:2433
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition: Expr.h:1218
A partial diagnostic which we might know in advance that we are not going to emit.
Expr * getSelectedExpr() const
Definition: ExprCXX.h:4442
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2130
const Expr * getSubExpr() const
Definition: Expr.h:2145
Represents a parameter to a function.
Definition: Decl.h:1761
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1821
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3139
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1986
StringLiteral * getFunctionName()
Definition: Expr.h:2030
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6305
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition: Expr.h:6358
ArrayRef< Expr * > semantics()
Definition: Expr.h:6384
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7443
QualType withConst() const
Definition: Type.h:1154
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7359
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:1100
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7560
QualType getCanonicalType() const
Definition: Type.h:7411
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7453
void removeLocalVolatile()
Definition: Type.h:7475
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:1174
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition: Type.h:1159
void removeLocalConst()
Definition: Type.h:7467
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7432
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1530
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7405
Represents a struct/union/class.
Definition: Decl.h:4168
bool hasFlexibleArrayMember() const
Definition: Decl.h:4201
field_iterator field_end() const
Definition: Decl.h:4377
field_range fields() const
Definition: Decl.h:4374
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4220
bool field_empty() const
Definition: Decl.h:4382
field_iterator field_begin() const
Definition: Decl.cpp:5069
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5549
RecordDecl * getDecl() const
Definition: Type.h:5559
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3380
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:510
bool isSatisfied() const
Whether or not the requires clause is satisfied.
Definition: ExprConcepts.h:562
SourceLocation getLocation() const
Definition: Expr.h:2103
std::string ComputeName(ASTContext &Context) const
Definition: Expr.cpp:592
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:4431
llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const
Definition: Expr.h:4482
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition: Expr.h:4471
Represents an expression that computes the length of a parameter pack.
Definition: ExprCXX.h:4251
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition: ExprCXX.h:4326
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4727
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:2273
bool isIntType() const
Definition: Expr.h:4751
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4383
CompoundStmt * getSubStmt()
Definition: Expr.h:4400
Stmt - This represents one statement.
Definition: Stmt.h:84
StmtClass getStmtClass() const
Definition: Stmt.h:1358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1191
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4466
SourceLocation getBeginLoc() const
Definition: Stmt.h:1788
const SwitchCase * getNextSwitchCase() const
Definition: Stmt.h:1774
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:2388
Expr * getCond()
Definition: Stmt.h:2451
Stmt * getBody()
Definition: Stmt.h:2463
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition: Stmt.cpp:1100
Stmt * getInit()
Definition: Stmt.h:2472
SwitchCase * getSwitchCaseList()
Definition: Stmt.h:2525
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4726
bool isUnion() const
Definition: Decl.h:3790
virtual bool isNan2008() const
Returns true if NaN encoding is IEEE 754-2008.
Definition: TargetInfo.h:1251
A template argument list.
Definition: DeclTemplate.h:244
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:280
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
A template parameter object.
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: Type.h:7341
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition: ExprCXX.h:2763
bool getValue() const
Definition: ExprCXX.h:2804
The base class of the type hierarchy.
Definition: Type.h:1813
bool isStructureType() const
Definition: Type.cpp:629
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1871
bool isVoidType() const
Definition: Type.h:7905
bool isBooleanType() const
Definition: Type.h:8033
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2156
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2893
bool isIncompleteArrayType() const
Definition: Type.h:7686
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2135
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:667
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8202
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2206
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2060
bool isNothrowT() const
Definition: Type.cpp:3062
bool isVoidPointerType() const
Definition: Type.cpp:655
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2341
bool isArrayType() const
Definition: Type.h:7678
bool isCharType() const
Definition: Type.cpp:2078
bool isFunctionPointerType() const
Definition: Type.h:7646
bool isPointerType() const
Definition: Type.h:7612
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7945
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8193
bool isReferenceType() const
Definition: Type.h:7624
bool isEnumeralType() const
Definition: Type.h:7710
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:1856
bool isVariableArrayType() const
Definition: Type.h:7690
bool isChar8Type() const
Definition: Type.cpp:2094
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2488
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8020
bool isExtVectorBoolType() const
Definition: Type.h:7726
bool isMemberDataPointerType() const
Definition: Type.h:7671
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7874
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2653
bool isAnyComplexType() const
Definition: Type.h:7714
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7958
const RecordType * getAsStructureType() const
Definition: Type.cpp:711
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8076
bool isMemberPointerType() const
Definition: Type.h:7660
bool isAtomicType() const
Definition: Type.h:7757
bool isComplexIntegerType() const
Definition: Type.cpp:673
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8179
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2351
bool isFunctionType() const
Definition: Type.h:7608
bool isVectorType() const
Definition: Type.h:7718
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2255
bool isFloatingType() const
Definition: Type.cpp:2238
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:2185
bool isAnyPointerType() const
Definition: Type.h:7616
TypeClass getTypeClass() const
Definition: Type.h:2300
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
bool isNullPtrType() const
Definition: Type.h:7938
bool isRecordType() const
Definition: Type.h:7706
bool isUnionType() const
Definition: Type.cpp:661
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2457
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:8067
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1875
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2568
QualType getArgumentType() const
Definition: Expr.h:2611
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition: Expr.h:2637
bool isArgumentType() const
Definition: Expr.h:2610
UnaryExprOrTypeTrait getKind() const
Definition: Expr.h:2600
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2183
SourceLocation getExprLoc() const
Definition: Expr.h:2311
Expr * getSubExpr() const
Definition: Expr.h:2228
Opcode getOpcode() const
Definition: Expr.h:2223
static bool isIncrementOp(Opcode Op)
Definition: Expr.h:2269
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition: Expr.h:2241
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4346
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5365
QualType getType() const
Definition: Value.cpp:234
bool hasValue() const
Definition: Value.h:134
Represents a variable declaration or definition.
Definition: Decl.h:918
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1549
bool hasInit() const
Definition: Decl.cpp:2395
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition: Decl.cpp:2612
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1558
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2551
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition: Decl.cpp:2846
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition: Decl.cpp:2624
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2363
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:2463
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:1195
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1164
const Expr * getInit() const
Definition: Decl.h:1355
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or NULL if the value is not yet kn...
Definition: Decl.cpp:2604
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1171
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2372
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1240
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:2505
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1345
Represents a GCC generic vector type.
Definition: Type.h:3969
unsigned getNumElements() const
Definition: Type.h:3984
QualType getElementType() const
Definition: Type.h:3983
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2584
Expr * getCond()
Definition: Stmt.h:2636
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition: Stmt.cpp:1161
Stmt * getBody()
Definition: Stmt.h:2648
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:55
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:181
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.
Definition: Format.cpp:3799
llvm::APFloat APFloat
Definition: Floating.h:23
llvm::APInt APInt
Definition: Integral.h:29
bool ReturnValue(const T &V, APValue &R)
Convert a value to an APValue.
Definition: Interp.h:43
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:868
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1899
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1873
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.
@ NonNull
Values of this type can never be null.
BinaryOperatorKind
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition: CallGraph.h:207
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:38
@ TSCS_unspecified
Definition: Specifiers.h:233
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:51
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
CheckSubobjectKind
The order of this enum is important for diagnostics.
Definition: State.h:40
@ CSK_ArrayToPointer
Definition: State.h:44
@ CSK_Derived
Definition: State.h:42
@ CSK_Base
Definition: State.h:41
@ CSK_Real
Definition: State.h:46
@ CSK_ArrayIndex
Definition: State.h:45
@ CSK_Imag
Definition: State.h:47
@ CSK_Field
Definition: State.h:43
@ SD_Static
Static storage duration.
Definition: Specifiers.h:328
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition: Specifiers.h:325
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition: State.h:26
@ AK_TypeId
Definition: State.h:34
@ AK_Construct
Definition: State.h:35
@ AK_Increment
Definition: State.h:30
@ AK_DynamicCast
Definition: State.h:33
@ AK_Read
Definition: State.h:27
@ AK_Assign
Definition: State.h:29
@ AK_MemberCall
Definition: State.h:32
@ AK_ReadObjectRepresentation
Definition: State.h:28
@ AK_Destroy
Definition: State.h:36
@ AK_Decrement
Definition: State.h:31
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Success
Template argument deduction was successful.
@ None
The alignment was not explicit in code.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Other
Other implicit parameter.
@ AS_public
Definition: Specifiers.h:121
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::tooling::dependencies::ModuleID &ID)
#define false
Definition: stdbool.h:26
#define bool
Definition: stdbool.h:24
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
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:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition: Expr.h:606
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:630
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition: Expr.h:614
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:609
static ObjectUnderConstruction getTombstoneKey()
DenseMapInfo< APValue::LValueBase > Base
static ObjectUnderConstruction getEmptyKey()
static unsigned getHashValue(const ObjectUnderConstruction &Object)
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
#define ilogb(__x)
Definition: tgmath.h:851
#define scalbn(__x, __y)
Definition: tgmath.h:1165