clang 20.0.0git
ExprConstant.cpp
Go to the documentation of this file.
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
11// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
25// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
27//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
33//===----------------------------------------------------------------------===//
34
35#include "ByteCode/Context.h"
36#include "ByteCode/Frame.h"
37#include "ByteCode/State.h"
38#include "ExprConstShared.h"
39#include "clang/AST/APValue.h"
41#include "clang/AST/ASTLambda.h"
42#include "clang/AST/Attr.h"
44#include "clang/AST/CharUnits.h"
46#include "clang/AST/Expr.h"
47#include "clang/AST/OSLog.h"
51#include "clang/AST/TypeLoc.h"
56#include "llvm/ADT/APFixedPoint.h"
57#include "llvm/ADT/Sequence.h"
58#include "llvm/ADT/SmallBitVector.h"
59#include "llvm/ADT/StringExtras.h"
60#include "llvm/Support/Casting.h"
61#include "llvm/Support/Debug.h"
62#include "llvm/Support/SaveAndRestore.h"
63#include "llvm/Support/SipHash.h"
64#include "llvm/Support/TimeProfiler.h"
65#include "llvm/Support/raw_ostream.h"
66#include <cstring>
67#include <functional>
68#include <optional>
69
70#define DEBUG_TYPE "exprconstant"
71
72using namespace clang;
73using llvm::APFixedPoint;
74using llvm::APInt;
75using llvm::APSInt;
76using llvm::APFloat;
77using llvm::FixedPointSemantics;
78
79namespace {
80 struct LValue;
81 class CallStackFrame;
82 class EvalInfo;
83
84 using SourceLocExprScopeGuard =
86
87 static QualType getType(APValue::LValueBase B) {
88 return B.getType();
89 }
90
91 /// Get an LValue path entry, which is known to not be an array index, as a
92 /// field declaration.
93 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
94 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
95 }
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// base class declaration.
98 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
99 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
100 }
101 /// Determine whether this LValue path entry for a base class names a virtual
102 /// base class.
103 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
104 return E.getAsBaseOrMember().getInt();
105 }
106
107 /// Given an expression, determine the type used to store the result of
108 /// evaluating that expression.
109 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
110 if (E->isPRValue())
111 return E->getType();
112 return Ctx.getLValueReferenceType(E->getType());
113 }
114
115 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
116 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
117 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
118 return DirectCallee->getAttr<AllocSizeAttr>();
119 if (const Decl *IndirectCallee = CE->getCalleeDecl())
120 return IndirectCallee->getAttr<AllocSizeAttr>();
121 return nullptr;
122 }
123
124 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
125 /// This will look through a single cast.
126 ///
127 /// Returns null if we couldn't unwrap a function with alloc_size.
128 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
129 if (!E->getType()->isPointerType())
130 return nullptr;
131
132 E = E->IgnoreParens();
133 // If we're doing a variable assignment from e.g. malloc(N), there will
134 // probably be a cast of some kind. In exotic cases, we might also see a
135 // top-level ExprWithCleanups. Ignore them either way.
136 if (const auto *FE = dyn_cast<FullExpr>(E))
137 E = FE->getSubExpr()->IgnoreParens();
138
139 if (const auto *Cast = dyn_cast<CastExpr>(E))
140 E = Cast->getSubExpr()->IgnoreParens();
141
142 if (const auto *CE = dyn_cast<CallExpr>(E))
143 return getAllocSizeAttr(CE) ? CE : nullptr;
144 return nullptr;
145 }
146
147 /// Determines whether or not the given Base contains a call to a function
148 /// with the alloc_size attribute.
149 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
150 const auto *E = Base.dyn_cast<const Expr *>();
151 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
152 }
153
154 /// Determines whether the given kind of constant expression is only ever
155 /// used for name mangling. If so, it's permitted to reference things that we
156 /// can't generate code for (in particular, dllimported functions).
157 static bool isForManglingOnly(ConstantExprKind Kind) {
158 switch (Kind) {
159 case ConstantExprKind::Normal:
160 case ConstantExprKind::ClassTemplateArgument:
161 case ConstantExprKind::ImmediateInvocation:
162 // Note that non-type template arguments of class type are emitted as
163 // template parameter objects.
164 return false;
165
166 case ConstantExprKind::NonClassTemplateArgument:
167 return true;
168 }
169 llvm_unreachable("unknown ConstantExprKind");
170 }
171
172 static bool isTemplateArgument(ConstantExprKind Kind) {
173 switch (Kind) {
174 case ConstantExprKind::Normal:
175 case ConstantExprKind::ImmediateInvocation:
176 return false;
177
178 case ConstantExprKind::ClassTemplateArgument:
179 case ConstantExprKind::NonClassTemplateArgument:
180 return true;
181 }
182 llvm_unreachable("unknown ConstantExprKind");
183 }
184
185 /// The bound to claim that an array of unknown bound has.
186 /// The value in MostDerivedArraySize is undefined in this case. So, set it
187 /// to an arbitrary value that's likely to loudly break things if it's used.
188 static const uint64_t AssumedSizeForUnsizedArray =
189 std::numeric_limits<uint64_t>::max() / 2;
190
191 /// Determines if an LValue with the given LValueBase will have an unsized
192 /// array in its designator.
193 /// Find the path length and type of the most-derived subobject in the given
194 /// path, and find the size of the containing array, if any.
195 static unsigned
196 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
198 uint64_t &ArraySize, QualType &Type, bool &IsArray,
199 bool &FirstEntryIsUnsizedArray) {
200 // This only accepts LValueBases from APValues, and APValues don't support
201 // arrays that lack size info.
202 assert(!isBaseAnAllocSizeCall(Base) &&
203 "Unsized arrays shouldn't appear here");
204 unsigned MostDerivedLength = 0;
205 Type = getType(Base);
206
207 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
208 if (Type->isArrayType()) {
209 const ArrayType *AT = Ctx.getAsArrayType(Type);
210 Type = AT->getElementType();
211 MostDerivedLength = I + 1;
212 IsArray = true;
213
214 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
215 ArraySize = CAT->getZExtSize();
216 } else {
217 assert(I == 0 && "unexpected unsized array designator");
218 FirstEntryIsUnsizedArray = true;
219 ArraySize = AssumedSizeForUnsizedArray;
220 }
221 } else if (Type->isAnyComplexType()) {
222 const ComplexType *CT = Type->castAs<ComplexType>();
223 Type = CT->getElementType();
224 ArraySize = 2;
225 MostDerivedLength = I + 1;
226 IsArray = true;
227 } else if (const auto *VT = Type->getAs<VectorType>()) {
228 Type = VT->getElementType();
229 ArraySize = VT->getNumElements();
230 MostDerivedLength = I + 1;
231 IsArray = true;
232 } else if (const FieldDecl *FD = getAsField(Path[I])) {
233 Type = FD->getType();
234 ArraySize = 0;
235 MostDerivedLength = I + 1;
236 IsArray = false;
237 } else {
238 // Path[I] describes a base class.
239 ArraySize = 0;
240 IsArray = false;
241 }
242 }
243 return MostDerivedLength;
244 }
245
246 /// A path from a glvalue to a subobject of that glvalue.
247 struct SubobjectDesignator {
248 /// True if the subobject was named in a manner not supported by C++11. Such
249 /// lvalues can still be folded, but they are not core constant expressions
250 /// and we cannot perform lvalue-to-rvalue conversions on them.
251 LLVM_PREFERRED_TYPE(bool)
252 unsigned Invalid : 1;
253
254 /// Is this a pointer one past the end of an object?
255 LLVM_PREFERRED_TYPE(bool)
256 unsigned IsOnePastTheEnd : 1;
257
258 /// Indicator of whether the first entry is an unsized array.
259 LLVM_PREFERRED_TYPE(bool)
260 unsigned FirstEntryIsAnUnsizedArray : 1;
261
262 /// Indicator of whether the most-derived object is an array element.
263 LLVM_PREFERRED_TYPE(bool)
264 unsigned MostDerivedIsArrayElement : 1;
265
266 /// The length of the path to the most-derived object of which this is a
267 /// subobject.
268 unsigned MostDerivedPathLength : 28;
269
270 /// The size of the array of which the most-derived object is an element.
271 /// This will always be 0 if the most-derived object is not an array
272 /// element. 0 is not an indicator of whether or not the most-derived object
273 /// is an array, however, because 0-length arrays are allowed.
274 ///
275 /// If the current array is an unsized array, the value of this is
276 /// undefined.
277 uint64_t MostDerivedArraySize;
278 /// The type of the most derived object referred to by this address.
279 QualType MostDerivedType;
280
281 typedef APValue::LValuePathEntry PathEntry;
282
283 /// The entries on the path from the glvalue to the designated subobject.
285
286 SubobjectDesignator() : Invalid(true) {}
287
288 explicit SubobjectDesignator(QualType T)
289 : Invalid(false), IsOnePastTheEnd(false),
290 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
291 MostDerivedPathLength(0), MostDerivedArraySize(0),
292 MostDerivedType(T) {}
293
294 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
295 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
296 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
297 MostDerivedPathLength(0), MostDerivedArraySize(0) {
298 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
299 if (!Invalid) {
300 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
301 ArrayRef<PathEntry> VEntries = V.getLValuePath();
302 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
303 if (V.getLValueBase()) {
304 bool IsArray = false;
305 bool FirstIsUnsizedArray = false;
306 MostDerivedPathLength = findMostDerivedSubobject(
307 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
308 MostDerivedType, IsArray, FirstIsUnsizedArray);
309 MostDerivedIsArrayElement = IsArray;
310 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
311 }
312 }
313 }
314
315 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
316 unsigned NewLength) {
317 if (Invalid)
318 return;
319
320 assert(Base && "cannot truncate path for null pointer");
321 assert(NewLength <= Entries.size() && "not a truncation");
322
323 if (NewLength == Entries.size())
324 return;
325 Entries.resize(NewLength);
326
327 bool IsArray = false;
328 bool FirstIsUnsizedArray = false;
329 MostDerivedPathLength = findMostDerivedSubobject(
330 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
331 FirstIsUnsizedArray);
332 MostDerivedIsArrayElement = IsArray;
333 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
334 }
335
336 void setInvalid() {
337 Invalid = true;
338 Entries.clear();
339 }
340
341 /// Determine whether the most derived subobject is an array without a
342 /// known bound.
343 bool isMostDerivedAnUnsizedArray() const {
344 assert(!Invalid && "Calling this makes no sense on invalid designators");
345 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
346 }
347
348 /// Determine what the most derived array's size is. Results in an assertion
349 /// failure if the most derived array lacks a size.
350 uint64_t getMostDerivedArraySize() const {
351 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
352 return MostDerivedArraySize;
353 }
354
355 /// Determine whether this is a one-past-the-end pointer.
356 bool isOnePastTheEnd() const {
357 assert(!Invalid);
358 if (IsOnePastTheEnd)
359 return true;
360 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
361 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
362 MostDerivedArraySize)
363 return true;
364 return false;
365 }
366
367 /// Get the range of valid index adjustments in the form
368 /// {maximum value that can be subtracted from this pointer,
369 /// maximum value that can be added to this pointer}
370 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
371 if (Invalid || isMostDerivedAnUnsizedArray())
372 return {0, 0};
373
374 // [expr.add]p4: For the purposes of these operators, a pointer to a
375 // nonarray object behaves the same as a pointer to the first element of
376 // an array of length one with the type of the object as its element type.
377 bool IsArray = MostDerivedPathLength == Entries.size() &&
378 MostDerivedIsArrayElement;
379 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
380 : (uint64_t)IsOnePastTheEnd;
381 uint64_t ArraySize =
382 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
383 return {ArrayIndex, ArraySize - ArrayIndex};
384 }
385
386 /// Check that this refers to a valid subobject.
387 bool isValidSubobject() const {
388 if (Invalid)
389 return false;
390 return !isOnePastTheEnd();
391 }
392 /// Check that this refers to a valid subobject, and if not, produce a
393 /// relevant diagnostic and set the designator as invalid.
394 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
395
396 /// Get the type of the designated object.
397 QualType getType(ASTContext &Ctx) const {
398 assert(!Invalid && "invalid designator has no subobject type");
399 return MostDerivedPathLength == Entries.size()
400 ? MostDerivedType
401 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
402 }
403
404 /// Update this designator to refer to the first element within this array.
405 void addArrayUnchecked(const ConstantArrayType *CAT) {
406 Entries.push_back(PathEntry::ArrayIndex(0));
407
408 // This is a most-derived object.
409 MostDerivedType = CAT->getElementType();
410 MostDerivedIsArrayElement = true;
411 MostDerivedArraySize = CAT->getZExtSize();
412 MostDerivedPathLength = Entries.size();
413 }
414 /// Update this designator to refer to the first element within the array of
415 /// elements of type T. This is an array of unknown size.
416 void addUnsizedArrayUnchecked(QualType ElemTy) {
417 Entries.push_back(PathEntry::ArrayIndex(0));
418
419 MostDerivedType = ElemTy;
420 MostDerivedIsArrayElement = true;
421 // The value in MostDerivedArraySize is undefined in this case. So, set it
422 // to an arbitrary value that's likely to loudly break things if it's
423 // used.
424 MostDerivedArraySize = AssumedSizeForUnsizedArray;
425 MostDerivedPathLength = Entries.size();
426 }
427 /// Update this designator to refer to the given base or member of this
428 /// object.
429 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
430 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
431
432 // If this isn't a base class, it's a new most-derived object.
433 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
434 MostDerivedType = FD->getType();
435 MostDerivedIsArrayElement = false;
436 MostDerivedArraySize = 0;
437 MostDerivedPathLength = Entries.size();
438 }
439 }
440 /// Update this designator to refer to the given complex component.
441 void addComplexUnchecked(QualType EltTy, bool Imag) {
442 Entries.push_back(PathEntry::ArrayIndex(Imag));
443
444 // This is technically a most-derived object, though in practice this
445 // is unlikely to matter.
446 MostDerivedType = EltTy;
447 MostDerivedIsArrayElement = true;
448 MostDerivedArraySize = 2;
449 MostDerivedPathLength = Entries.size();
450 }
451
452 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
453 uint64_t Idx) {
454 Entries.push_back(PathEntry::ArrayIndex(Idx));
455 MostDerivedType = EltTy;
456 MostDerivedPathLength = Entries.size();
457 MostDerivedArraySize = 0;
458 MostDerivedIsArrayElement = false;
459 }
460
461 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
462 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
463 const APSInt &N);
464 /// Add N to the address of this subobject.
465 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
466 if (Invalid || !N) return;
467 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
468 if (isMostDerivedAnUnsizedArray()) {
469 diagnoseUnsizedArrayPointerArithmetic(Info, E);
470 // Can't verify -- trust that the user is doing the right thing (or if
471 // not, trust that the caller will catch the bad behavior).
472 // FIXME: Should we reject if this overflows, at least?
473 Entries.back() = PathEntry::ArrayIndex(
474 Entries.back().getAsArrayIndex() + TruncatedN);
475 return;
476 }
477
478 // [expr.add]p4: For the purposes of these operators, a pointer to a
479 // nonarray object behaves the same as a pointer to the first element of
480 // an array of length one with the type of the object as its element type.
481 bool IsArray = MostDerivedPathLength == Entries.size() &&
482 MostDerivedIsArrayElement;
483 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
484 : (uint64_t)IsOnePastTheEnd;
485 uint64_t ArraySize =
486 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
487
488 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
489 // Calculate the actual index in a wide enough type, so we can include
490 // it in the note.
491 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
492 (llvm::APInt&)N += ArrayIndex;
493 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
494 diagnosePointerArithmetic(Info, E, N);
495 setInvalid();
496 return;
497 }
498
499 ArrayIndex += TruncatedN;
500 assert(ArrayIndex <= ArraySize &&
501 "bounds check succeeded for out-of-bounds index");
502
503 if (IsArray)
504 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
505 else
506 IsOnePastTheEnd = (ArrayIndex != 0);
507 }
508 };
509
510 /// A scope at the end of which an object can need to be destroyed.
511 enum class ScopeKind {
512 Block,
513 FullExpression,
514 Call
515 };
516
517 /// A reference to a particular call and its arguments.
518 struct CallRef {
519 CallRef() : OrigCallee(), CallIndex(0), Version() {}
520 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
521 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
522
523 explicit operator bool() const { return OrigCallee; }
524
525 /// Get the parameter that the caller initialized, corresponding to the
526 /// given parameter in the callee.
527 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
528 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
529 : PVD;
530 }
531
532 /// The callee at the point where the arguments were evaluated. This might
533 /// be different from the actual callee (a different redeclaration, or a
534 /// virtual override), but this function's parameters are the ones that
535 /// appear in the parameter map.
536 const FunctionDecl *OrigCallee;
537 /// The call index of the frame that holds the argument values.
538 unsigned CallIndex;
539 /// The version of the parameters corresponding to this call.
540 unsigned Version;
541 };
542
543 /// A stack frame in the constexpr call stack.
544 class CallStackFrame : public interp::Frame {
545 public:
546 EvalInfo &Info;
547
548 /// Parent - The caller of this stack frame.
549 CallStackFrame *Caller;
550
551 /// Callee - The function which was called.
552 const FunctionDecl *Callee;
553
554 /// This - The binding for the this pointer in this call, if any.
555 const LValue *This;
556
557 /// CallExpr - The syntactical structure of member function calls
558 const Expr *CallExpr;
559
560 /// Information on how to find the arguments to this call. Our arguments
561 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
562 /// key and this value as the version.
563 CallRef Arguments;
564
565 /// Source location information about the default argument or default
566 /// initializer expression we're evaluating, if any.
567 CurrentSourceLocExprScope CurSourceLocExprScope;
568
569 // Note that we intentionally use std::map here so that references to
570 // values are stable.
571 typedef std::pair<const void *, unsigned> MapKeyTy;
572 typedef std::map<MapKeyTy, APValue> MapTy;
573 /// Temporaries - Temporary lvalues materialized within this stack frame.
574 MapTy Temporaries;
575
576 /// CallRange - The source range of the call expression for this call.
577 SourceRange CallRange;
578
579 /// Index - The call index of this call.
580 unsigned Index;
581
582 /// The stack of integers for tracking version numbers for temporaries.
583 SmallVector<unsigned, 2> TempVersionStack = {1};
584 unsigned CurTempVersion = TempVersionStack.back();
585
586 unsigned getTempVersion() const { return TempVersionStack.back(); }
587
588 void pushTempVersion() {
589 TempVersionStack.push_back(++CurTempVersion);
590 }
591
592 void popTempVersion() {
593 TempVersionStack.pop_back();
594 }
595
596 CallRef createCall(const FunctionDecl *Callee) {
597 return {Callee, Index, ++CurTempVersion};
598 }
599
600 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
601 // on the overall stack usage of deeply-recursing constexpr evaluations.
602 // (We should cache this map rather than recomputing it repeatedly.)
603 // But let's try this and see how it goes; we can look into caching the map
604 // as a later change.
605
606 /// LambdaCaptureFields - Mapping from captured variables/this to
607 /// corresponding data members in the closure class.
608 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
609 FieldDecl *LambdaThisCaptureField = nullptr;
610
611 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
612 const FunctionDecl *Callee, const LValue *This,
613 const Expr *CallExpr, CallRef Arguments);
614 ~CallStackFrame();
615
616 // Return the temporary for Key whose version number is Version.
617 APValue *getTemporary(const void *Key, unsigned Version) {
618 MapKeyTy KV(Key, Version);
619 auto LB = Temporaries.lower_bound(KV);
620 if (LB != Temporaries.end() && LB->first == KV)
621 return &LB->second;
622 return nullptr;
623 }
624
625 // Return the current temporary for Key in the map.
626 APValue *getCurrentTemporary(const void *Key) {
627 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
628 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
629 return &std::prev(UB)->second;
630 return nullptr;
631 }
632
633 // Return the version number of the current temporary for Key.
634 unsigned getCurrentTemporaryVersion(const void *Key) const {
635 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
636 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
637 return std::prev(UB)->first.second;
638 return 0;
639 }
640
641 /// Allocate storage for an object of type T in this stack frame.
642 /// Populates LV with a handle to the created object. Key identifies
643 /// the temporary within the stack frame, and must not be reused without
644 /// bumping the temporary version number.
645 template<typename KeyT>
646 APValue &createTemporary(const KeyT *Key, QualType T,
647 ScopeKind Scope, LValue &LV);
648
649 /// Allocate storage for a parameter of a function call made in this frame.
650 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
651
652 void describe(llvm::raw_ostream &OS) const override;
653
654 Frame *getCaller() const override { return Caller; }
655 SourceRange getCallRange() const override { return CallRange; }
656 const FunctionDecl *getCallee() const override { return Callee; }
657
658 bool isStdFunction() const {
659 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
660 if (DC->isStdNamespace())
661 return true;
662 return false;
663 }
664
665 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
666 /// permitted. See MSConstexprDocs for description of permitted contexts.
667 bool CanEvalMSConstexpr = false;
668
669 private:
670 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
671 ScopeKind Scope);
672 };
673
674 /// Temporarily override 'this'.
675 class ThisOverrideRAII {
676 public:
677 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
678 : Frame(Frame), OldThis(Frame.This) {
679 if (Enable)
680 Frame.This = NewThis;
681 }
682 ~ThisOverrideRAII() {
683 Frame.This = OldThis;
684 }
685 private:
686 CallStackFrame &Frame;
687 const LValue *OldThis;
688 };
689
690 // A shorthand time trace scope struct, prints source range, for example
691 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
692 class ExprTimeTraceScope {
693 public:
694 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
695 : TimeScope(Name, [E, &Ctx] {
696 return E->getSourceRange().printToString(Ctx.getSourceManager());
697 }) {}
698
699 private:
700 llvm::TimeTraceScope TimeScope;
701 };
702
703 /// RAII object used to change the current ability of
704 /// [[msvc::constexpr]] evaulation.
705 struct MSConstexprContextRAII {
706 CallStackFrame &Frame;
707 bool OldValue;
708 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
709 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
710 Frame.CanEvalMSConstexpr = Value;
711 }
712
713 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
714 };
715}
716
717static bool HandleDestruction(EvalInfo &Info, const Expr *E,
718 const LValue &This, QualType ThisType);
719static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
721 QualType T);
722
723namespace {
724 /// A cleanup, and a flag indicating whether it is lifetime-extended.
725 class Cleanup {
726 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
728 QualType T;
729
730 public:
731 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
732 ScopeKind Scope)
733 : Value(Val, Scope), Base(Base), T(T) {}
734
735 /// Determine whether this cleanup should be performed at the end of the
736 /// given kind of scope.
737 bool isDestroyedAtEndOf(ScopeKind K) const {
738 return (int)Value.getInt() >= (int)K;
739 }
740 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
741 if (RunDestructors) {
743 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
744 Loc = VD->getLocation();
745 else if (const Expr *E = Base.dyn_cast<const Expr*>())
746 Loc = E->getExprLoc();
747 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
748 }
749 *Value.getPointer() = APValue();
750 return true;
751 }
752
753 bool hasSideEffect() {
754 return T.isDestructedType();
755 }
756 };
757
758 /// A reference to an object whose construction we are currently evaluating.
759 struct ObjectUnderConstruction {
762 friend bool operator==(const ObjectUnderConstruction &LHS,
763 const ObjectUnderConstruction &RHS) {
764 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
765 }
766 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
767 return llvm::hash_combine(Obj.Base, Obj.Path);
768 }
769 };
770 enum class ConstructionPhase {
771 None,
772 Bases,
773 AfterBases,
774 AfterFields,
775 Destroying,
776 DestroyingBases
777 };
778}
779
780namespace llvm {
781template<> struct DenseMapInfo<ObjectUnderConstruction> {
782 using Base = DenseMapInfo<APValue::LValueBase>;
783 static ObjectUnderConstruction getEmptyKey() {
784 return {Base::getEmptyKey(), {}}; }
785 static ObjectUnderConstruction getTombstoneKey() {
786 return {Base::getTombstoneKey(), {}};
787 }
788 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
789 return hash_value(Object);
790 }
791 static bool isEqual(const ObjectUnderConstruction &LHS,
792 const ObjectUnderConstruction &RHS) {
793 return LHS == RHS;
794 }
795};
796}
797
798namespace {
799 /// A dynamically-allocated heap object.
800 struct DynAlloc {
801 /// The value of this heap-allocated object.
803 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
804 /// or a CallExpr (the latter is for direct calls to operator new inside
805 /// std::allocator<T>::allocate).
806 const Expr *AllocExpr = nullptr;
807
808 enum Kind {
809 New,
810 ArrayNew,
811 StdAllocator
812 };
813
814 /// Get the kind of the allocation. This must match between allocation
815 /// and deallocation.
816 Kind getKind() const {
817 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
818 return NE->isArray() ? ArrayNew : New;
819 assert(isa<CallExpr>(AllocExpr));
820 return StdAllocator;
821 }
822 };
823
824 struct DynAllocOrder {
825 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
826 return L.getIndex() < R.getIndex();
827 }
828 };
829
830 /// EvalInfo - This is a private struct used by the evaluator to capture
831 /// information about a subexpression as it is folded. It retains information
832 /// about the AST context, but also maintains information about the folded
833 /// expression.
834 ///
835 /// If an expression could be evaluated, it is still possible it is not a C
836 /// "integer constant expression" or constant expression. If not, this struct
837 /// captures information about how and why not.
838 ///
839 /// One bit of information passed *into* the request for constant folding
840 /// indicates whether the subexpression is "evaluated" or not according to C
841 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
842 /// evaluate the expression regardless of what the RHS is, but C only allows
843 /// certain things in certain situations.
844 class EvalInfo : public interp::State {
845 public:
846 ASTContext &Ctx;
847
848 /// EvalStatus - Contains information about the evaluation.
849 Expr::EvalStatus &EvalStatus;
850
851 /// CurrentCall - The top of the constexpr call stack.
852 CallStackFrame *CurrentCall;
853
854 /// CallStackDepth - The number of calls in the call stack right now.
855 unsigned CallStackDepth;
856
857 /// NextCallIndex - The next call index to assign.
858 unsigned NextCallIndex;
859
860 /// StepsLeft - The remaining number of evaluation steps we're permitted
861 /// to perform. This is essentially a limit for the number of statements
862 /// we will evaluate.
863 unsigned StepsLeft;
864
865 /// Enable the experimental new constant interpreter. If an expression is
866 /// not supported by the interpreter, an error is triggered.
867 bool EnableNewConstInterp;
868
869 /// BottomFrame - The frame in which evaluation started. This must be
870 /// initialized after CurrentCall and CallStackDepth.
871 CallStackFrame BottomFrame;
872
873 /// A stack of values whose lifetimes end at the end of some surrounding
874 /// evaluation frame.
876
877 /// EvaluatingDecl - This is the declaration whose initializer is being
878 /// evaluated, if any.
879 APValue::LValueBase EvaluatingDecl;
880
881 enum class EvaluatingDeclKind {
882 None,
883 /// We're evaluating the construction of EvaluatingDecl.
884 Ctor,
885 /// We're evaluating the destruction of EvaluatingDecl.
886 Dtor,
887 };
888 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
889
890 /// EvaluatingDeclValue - This is the value being constructed for the
891 /// declaration whose initializer is being evaluated, if any.
892 APValue *EvaluatingDeclValue;
893
894 /// Set of objects that are currently being constructed.
895 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
896 ObjectsUnderConstruction;
897
898 /// Current heap allocations, along with the location where each was
899 /// allocated. We use std::map here because we need stable addresses
900 /// for the stored APValues.
901 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
902
903 /// The number of heap allocations performed so far in this evaluation.
904 unsigned NumHeapAllocs = 0;
905
906 struct EvaluatingConstructorRAII {
907 EvalInfo &EI;
908 ObjectUnderConstruction Object;
909 bool DidInsert;
910 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
911 bool HasBases)
912 : EI(EI), Object(Object) {
913 DidInsert =
914 EI.ObjectsUnderConstruction
915 .insert({Object, HasBases ? ConstructionPhase::Bases
916 : ConstructionPhase::AfterBases})
917 .second;
918 }
919 void finishedConstructingBases() {
920 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
921 }
922 void finishedConstructingFields() {
923 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
924 }
925 ~EvaluatingConstructorRAII() {
926 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
927 }
928 };
929
930 struct EvaluatingDestructorRAII {
931 EvalInfo &EI;
932 ObjectUnderConstruction Object;
933 bool DidInsert;
934 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
935 : EI(EI), Object(Object) {
936 DidInsert = EI.ObjectsUnderConstruction
937 .insert({Object, ConstructionPhase::Destroying})
938 .second;
939 }
940 void startedDestroyingBases() {
941 EI.ObjectsUnderConstruction[Object] =
942 ConstructionPhase::DestroyingBases;
943 }
944 ~EvaluatingDestructorRAII() {
945 if (DidInsert)
946 EI.ObjectsUnderConstruction.erase(Object);
947 }
948 };
949
950 ConstructionPhase
951 isEvaluatingCtorDtor(APValue::LValueBase Base,
953 return ObjectsUnderConstruction.lookup({Base, Path});
954 }
955
956 /// If we're currently speculatively evaluating, the outermost call stack
957 /// depth at which we can mutate state, otherwise 0.
958 unsigned SpeculativeEvaluationDepth = 0;
959
960 /// The current array initialization index, if we're performing array
961 /// initialization.
962 uint64_t ArrayInitIndex = -1;
963
964 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
965 /// notes attached to it will also be stored, otherwise they will not be.
966 bool HasActiveDiagnostic;
967
968 /// Have we emitted a diagnostic explaining why we couldn't constant
969 /// fold (not just why it's not strictly a constant expression)?
970 bool HasFoldFailureDiagnostic;
971
972 /// Whether we're checking that an expression is a potential constant
973 /// expression. If so, do not fail on constructs that could become constant
974 /// later on (such as a use of an undefined global).
975 bool CheckingPotentialConstantExpression = false;
976
977 /// Whether we're checking for an expression that has undefined behavior.
978 /// If so, we will produce warnings if we encounter an operation that is
979 /// always undefined.
980 ///
981 /// Note that we still need to evaluate the expression normally when this
982 /// is set; this is used when evaluating ICEs in C.
983 bool CheckingForUndefinedBehavior = false;
984
985 enum EvaluationMode {
986 /// Evaluate as a constant expression. Stop if we find that the expression
987 /// is not a constant expression.
988 EM_ConstantExpression,
989
990 /// Evaluate as a constant expression. Stop if we find that the expression
991 /// is not a constant expression. Some expressions can be retried in the
992 /// optimizer if we don't constant fold them here, but in an unevaluated
993 /// context we try to fold them immediately since the optimizer never
994 /// gets a chance to look at it.
995 EM_ConstantExpressionUnevaluated,
996
997 /// Fold the expression to a constant. Stop if we hit a side-effect that
998 /// we can't model.
999 EM_ConstantFold,
1000
1001 /// Evaluate in any way we know how. Don't worry about side-effects that
1002 /// can't be modeled.
1003 EM_IgnoreSideEffects,
1004 } EvalMode;
1005
1006 /// Are we checking whether the expression is a potential constant
1007 /// expression?
1008 bool checkingPotentialConstantExpression() const override {
1009 return CheckingPotentialConstantExpression;
1010 }
1011
1012 /// Are we checking an expression for overflow?
1013 // FIXME: We should check for any kind of undefined or suspicious behavior
1014 // in such constructs, not just overflow.
1015 bool checkingForUndefinedBehavior() const override {
1016 return CheckingForUndefinedBehavior;
1017 }
1018
1019 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
1020 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
1021 CallStackDepth(0), NextCallIndex(1),
1022 StepsLeft(C.getLangOpts().ConstexprStepLimit),
1023 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
1024 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
1025 /*This=*/nullptr,
1026 /*CallExpr=*/nullptr, CallRef()),
1027 EvaluatingDecl((const ValueDecl *)nullptr),
1028 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
1029 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
1030
1031 ~EvalInfo() {
1032 discardCleanups();
1033 }
1034
1035 ASTContext &getASTContext() const override { return Ctx; }
1036
1037 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1038 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1039 EvaluatingDecl = Base;
1040 IsEvaluatingDecl = EDK;
1041 EvaluatingDeclValue = &Value;
1042 }
1043
1044 bool CheckCallLimit(SourceLocation Loc) {
1045 // Don't perform any constexpr calls (other than the call we're checking)
1046 // when checking a potential constant expression.
1047 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1048 return false;
1049 if (NextCallIndex == 0) {
1050 // NextCallIndex has wrapped around.
1051 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1052 return false;
1053 }
1054 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1055 return true;
1056 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1057 << getLangOpts().ConstexprCallDepth;
1058 return false;
1059 }
1060
1061 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1062 uint64_t ElemCount, bool Diag) {
1063 // FIXME: GH63562
1064 // APValue stores array extents as unsigned,
1065 // so anything that is greater that unsigned would overflow when
1066 // constructing the array, we catch this here.
1067 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1068 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1069 if (Diag)
1070 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1071 return false;
1072 }
1073
1074 // FIXME: GH63562
1075 // Arrays allocate an APValue per element.
1076 // We use the number of constexpr steps as a proxy for the maximum size
1077 // of arrays to avoid exhausting the system resources, as initialization
1078 // of each element is likely to take some number of steps anyway.
1079 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1080 if (ElemCount > Limit) {
1081 if (Diag)
1082 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1083 << ElemCount << Limit;
1084 return false;
1085 }
1086 return true;
1087 }
1088
1089 std::pair<CallStackFrame *, unsigned>
1090 getCallFrameAndDepth(unsigned CallIndex) {
1091 assert(CallIndex && "no call index in getCallFrameAndDepth");
1092 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1093 // be null in this loop.
1094 unsigned Depth = CallStackDepth;
1095 CallStackFrame *Frame = CurrentCall;
1096 while (Frame->Index > CallIndex) {
1097 Frame = Frame->Caller;
1098 --Depth;
1099 }
1100 if (Frame->Index == CallIndex)
1101 return {Frame, Depth};
1102 return {nullptr, 0};
1103 }
1104
1105 bool nextStep(const Stmt *S) {
1106 if (!StepsLeft) {
1107 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1108 return false;
1109 }
1110 --StepsLeft;
1111 return true;
1112 }
1113
1114 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1115
1116 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1117 std::optional<DynAlloc *> Result;
1118 auto It = HeapAllocs.find(DA);
1119 if (It != HeapAllocs.end())
1120 Result = &It->second;
1121 return Result;
1122 }
1123
1124 /// Get the allocated storage for the given parameter of the given call.
1125 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1126 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1127 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1128 : nullptr;
1129 }
1130
1131 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1132 struct StdAllocatorCaller {
1133 unsigned FrameIndex;
1134 QualType ElemType;
1135 explicit operator bool() const { return FrameIndex != 0; };
1136 };
1137
1138 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1139 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1140 Call = Call->Caller) {
1141 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1142 if (!MD)
1143 continue;
1144 const IdentifierInfo *FnII = MD->getIdentifier();
1145 if (!FnII || !FnII->isStr(FnName))
1146 continue;
1147
1148 const auto *CTSD =
1149 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1150 if (!CTSD)
1151 continue;
1152
1153 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1154 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1155 if (CTSD->isInStdNamespace() && ClassII &&
1156 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1157 TAL[0].getKind() == TemplateArgument::Type)
1158 return {Call->Index, TAL[0].getAsType()};
1159 }
1160
1161 return {};
1162 }
1163
1164 void performLifetimeExtension() {
1165 // Disable the cleanups for lifetime-extended temporaries.
1166 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1167 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1168 });
1169 }
1170
1171 /// Throw away any remaining cleanups at the end of evaluation. If any
1172 /// cleanups would have had a side-effect, note that as an unmodeled
1173 /// side-effect and return false. Otherwise, return true.
1174 bool discardCleanups() {
1175 for (Cleanup &C : CleanupStack) {
1176 if (C.hasSideEffect() && !noteSideEffect()) {
1177 CleanupStack.clear();
1178 return false;
1179 }
1180 }
1181 CleanupStack.clear();
1182 return true;
1183 }
1184
1185 private:
1186 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1187 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1188
1189 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1190 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1191
1192 void setFoldFailureDiagnostic(bool Flag) override {
1193 HasFoldFailureDiagnostic = Flag;
1194 }
1195
1196 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1197
1198 // If we have a prior diagnostic, it will be noting that the expression
1199 // isn't a constant expression. This diagnostic is more important,
1200 // unless we require this evaluation to produce a constant expression.
1201 //
1202 // FIXME: We might want to show both diagnostics to the user in
1203 // EM_ConstantFold mode.
1204 bool hasPriorDiagnostic() override {
1205 if (!EvalStatus.Diag->empty()) {
1206 switch (EvalMode) {
1207 case EM_ConstantFold:
1208 case EM_IgnoreSideEffects:
1209 if (!HasFoldFailureDiagnostic)
1210 break;
1211 // We've already failed to fold something. Keep that diagnostic.
1212 [[fallthrough]];
1213 case EM_ConstantExpression:
1214 case EM_ConstantExpressionUnevaluated:
1215 setActiveDiagnostic(false);
1216 return true;
1217 }
1218 }
1219 return false;
1220 }
1221
1222 unsigned getCallStackDepth() override { return CallStackDepth; }
1223
1224 public:
1225 /// Should we continue evaluation after encountering a side-effect that we
1226 /// couldn't model?
1227 bool keepEvaluatingAfterSideEffect() const override {
1228 switch (EvalMode) {
1229 case EM_IgnoreSideEffects:
1230 return true;
1231
1232 case EM_ConstantExpression:
1233 case EM_ConstantExpressionUnevaluated:
1234 case EM_ConstantFold:
1235 // By default, assume any side effect might be valid in some other
1236 // evaluation of this expression from a different context.
1237 return checkingPotentialConstantExpression() ||
1238 checkingForUndefinedBehavior();
1239 }
1240 llvm_unreachable("Missed EvalMode case");
1241 }
1242
1243 /// Note that we have had a side-effect, and determine whether we should
1244 /// keep evaluating.
1245 bool noteSideEffect() override {
1246 EvalStatus.HasSideEffects = true;
1247 return keepEvaluatingAfterSideEffect();
1248 }
1249
1250 /// Should we continue evaluation after encountering undefined behavior?
1251 bool keepEvaluatingAfterUndefinedBehavior() {
1252 switch (EvalMode) {
1253 case EM_IgnoreSideEffects:
1254 case EM_ConstantFold:
1255 return true;
1256
1257 case EM_ConstantExpression:
1258 case EM_ConstantExpressionUnevaluated:
1259 return checkingForUndefinedBehavior();
1260 }
1261 llvm_unreachable("Missed EvalMode case");
1262 }
1263
1264 /// Note that we hit something that was technically undefined behavior, but
1265 /// that we can evaluate past it (such as signed overflow or floating-point
1266 /// division by zero.)
1267 bool noteUndefinedBehavior() override {
1268 EvalStatus.HasUndefinedBehavior = true;
1269 return keepEvaluatingAfterUndefinedBehavior();
1270 }
1271
1272 /// Should we continue evaluation as much as possible after encountering a
1273 /// construct which can't be reduced to a value?
1274 bool keepEvaluatingAfterFailure() const override {
1275 if (!StepsLeft)
1276 return false;
1277
1278 switch (EvalMode) {
1279 case EM_ConstantExpression:
1280 case EM_ConstantExpressionUnevaluated:
1281 case EM_ConstantFold:
1282 case EM_IgnoreSideEffects:
1283 return checkingPotentialConstantExpression() ||
1284 checkingForUndefinedBehavior();
1285 }
1286 llvm_unreachable("Missed EvalMode case");
1287 }
1288
1289 /// Notes that we failed to evaluate an expression that other expressions
1290 /// directly depend on, and determine if we should keep evaluating. This
1291 /// should only be called if we actually intend to keep evaluating.
1292 ///
1293 /// Call noteSideEffect() instead if we may be able to ignore the value that
1294 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1295 ///
1296 /// (Foo(), 1) // use noteSideEffect
1297 /// (Foo() || true) // use noteSideEffect
1298 /// Foo() + 1 // use noteFailure
1299 [[nodiscard]] bool noteFailure() {
1300 // Failure when evaluating some expression often means there is some
1301 // subexpression whose evaluation was skipped. Therefore, (because we
1302 // don't track whether we skipped an expression when unwinding after an
1303 // evaluation failure) every evaluation failure that bubbles up from a
1304 // subexpression implies that a side-effect has potentially happened. We
1305 // skip setting the HasSideEffects flag to true until we decide to
1306 // continue evaluating after that point, which happens here.
1307 bool KeepGoing = keepEvaluatingAfterFailure();
1308 EvalStatus.HasSideEffects |= KeepGoing;
1309 return KeepGoing;
1310 }
1311
1312 class ArrayInitLoopIndex {
1313 EvalInfo &Info;
1314 uint64_t OuterIndex;
1315
1316 public:
1317 ArrayInitLoopIndex(EvalInfo &Info)
1318 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1319 Info.ArrayInitIndex = 0;
1320 }
1321 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1322
1323 operator uint64_t&() { return Info.ArrayInitIndex; }
1324 };
1325 };
1326
1327 /// Object used to treat all foldable expressions as constant expressions.
1328 struct FoldConstant {
1329 EvalInfo &Info;
1330 bool Enabled;
1331 bool HadNoPriorDiags;
1332 EvalInfo::EvaluationMode OldMode;
1333
1334 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1335 : Info(Info),
1336 Enabled(Enabled),
1337 HadNoPriorDiags(Info.EvalStatus.Diag &&
1338 Info.EvalStatus.Diag->empty() &&
1339 !Info.EvalStatus.HasSideEffects),
1340 OldMode(Info.EvalMode) {
1341 if (Enabled)
1342 Info.EvalMode = EvalInfo::EM_ConstantFold;
1343 }
1344 void keepDiagnostics() { Enabled = false; }
1345 ~FoldConstant() {
1346 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1347 !Info.EvalStatus.HasSideEffects)
1348 Info.EvalStatus.Diag->clear();
1349 Info.EvalMode = OldMode;
1350 }
1351 };
1352
1353 /// RAII object used to set the current evaluation mode to ignore
1354 /// side-effects.
1355 struct IgnoreSideEffectsRAII {
1356 EvalInfo &Info;
1357 EvalInfo::EvaluationMode OldMode;
1358 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1359 : Info(Info), OldMode(Info.EvalMode) {
1360 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1361 }
1362
1363 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1364 };
1365
1366 /// RAII object used to optionally suppress diagnostics and side-effects from
1367 /// a speculative evaluation.
1368 class SpeculativeEvaluationRAII {
1369 EvalInfo *Info = nullptr;
1370 Expr::EvalStatus OldStatus;
1371 unsigned OldSpeculativeEvaluationDepth = 0;
1372
1373 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1374 Info = Other.Info;
1375 OldStatus = Other.OldStatus;
1376 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1377 Other.Info = nullptr;
1378 }
1379
1380 void maybeRestoreState() {
1381 if (!Info)
1382 return;
1383
1384 Info->EvalStatus = OldStatus;
1385 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1386 }
1387
1388 public:
1389 SpeculativeEvaluationRAII() = default;
1390
1391 SpeculativeEvaluationRAII(
1392 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1393 : Info(&Info), OldStatus(Info.EvalStatus),
1394 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1395 Info.EvalStatus.Diag = NewDiag;
1396 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1397 }
1398
1399 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1400 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1401 moveFromAndCancel(std::move(Other));
1402 }
1403
1404 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1405 maybeRestoreState();
1406 moveFromAndCancel(std::move(Other));
1407 return *this;
1408 }
1409
1410 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1411 };
1412
1413 /// RAII object wrapping a full-expression or block scope, and handling
1414 /// the ending of the lifetime of temporaries created within it.
1415 template<ScopeKind Kind>
1416 class ScopeRAII {
1417 EvalInfo &Info;
1418 unsigned OldStackSize;
1419 public:
1420 ScopeRAII(EvalInfo &Info)
1421 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1422 // Push a new temporary version. This is needed to distinguish between
1423 // temporaries created in different iterations of a loop.
1424 Info.CurrentCall->pushTempVersion();
1425 }
1426 bool destroy(bool RunDestructors = true) {
1427 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1428 OldStackSize = -1U;
1429 return OK;
1430 }
1431 ~ScopeRAII() {
1432 if (OldStackSize != -1U)
1433 destroy(false);
1434 // Body moved to a static method to encourage the compiler to inline away
1435 // instances of this class.
1436 Info.CurrentCall->popTempVersion();
1437 }
1438 private:
1439 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1440 unsigned OldStackSize) {
1441 assert(OldStackSize <= Info.CleanupStack.size() &&
1442 "running cleanups out of order?");
1443
1444 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1445 // for a full-expression scope.
1446 bool Success = true;
1447 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1448 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1449 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1450 Success = false;
1451 break;
1452 }
1453 }
1454 }
1455
1456 // Compact any retained cleanups.
1457 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1458 if (Kind != ScopeKind::Block)
1459 NewEnd =
1460 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1461 return C.isDestroyedAtEndOf(Kind);
1462 });
1463 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1464 return Success;
1465 }
1466 };
1467 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1468 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1469 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1470}
1471
1472bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1473 CheckSubobjectKind CSK) {
1474 if (Invalid)
1475 return false;
1476 if (isOnePastTheEnd()) {
1477 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1478 << CSK;
1479 setInvalid();
1480 return false;
1481 }
1482 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1483 // must actually be at least one array element; even a VLA cannot have a
1484 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1485 return true;
1486}
1487
1488void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1489 const Expr *E) {
1490 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1491 // Do not set the designator as invalid: we can represent this situation,
1492 // and correct handling of __builtin_object_size requires us to do so.
1493}
1494
1495void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1496 const Expr *E,
1497 const APSInt &N) {
1498 // If we're complaining, we must be able to statically determine the size of
1499 // the most derived array.
1500 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1501 Info.CCEDiag(E, diag::note_constexpr_array_index)
1502 << N << /*array*/ 0
1503 << static_cast<unsigned>(getMostDerivedArraySize());
1504 else
1505 Info.CCEDiag(E, diag::note_constexpr_array_index)
1506 << N << /*non-array*/ 1;
1507 setInvalid();
1508}
1509
1510CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1511 const FunctionDecl *Callee, const LValue *This,
1512 const Expr *CallExpr, CallRef Call)
1513 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1514 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1515 Index(Info.NextCallIndex++) {
1516 Info.CurrentCall = this;
1517 ++Info.CallStackDepth;
1518}
1519
1520CallStackFrame::~CallStackFrame() {
1521 assert(Info.CurrentCall == this && "calls retired out of order");
1522 --Info.CallStackDepth;
1523 Info.CurrentCall = Caller;
1524}
1525
1526static bool isRead(AccessKinds AK) {
1527 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1528 AK == AK_IsWithinLifetime;
1529}
1530
1532 switch (AK) {
1533 case AK_Read:
1535 case AK_MemberCall:
1536 case AK_DynamicCast:
1537 case AK_TypeId:
1539 return false;
1540 case AK_Assign:
1541 case AK_Increment:
1542 case AK_Decrement:
1543 case AK_Construct:
1544 case AK_Destroy:
1545 return true;
1546 }
1547 llvm_unreachable("unknown access kind");
1548}
1549
1550static bool isAnyAccess(AccessKinds AK) {
1551 return isRead(AK) || isModification(AK);
1552}
1553
1554/// Is this an access per the C++ definition?
1556 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1557 AK != AK_IsWithinLifetime;
1558}
1559
1560/// Is this kind of axcess valid on an indeterminate object value?
1562 switch (AK) {
1563 case AK_Read:
1564 case AK_Increment:
1565 case AK_Decrement:
1566 // These need the object's value.
1567 return false;
1568
1571 case AK_Assign:
1572 case AK_Construct:
1573 case AK_Destroy:
1574 // Construction and destruction don't need the value.
1575 return true;
1576
1577 case AK_MemberCall:
1578 case AK_DynamicCast:
1579 case AK_TypeId:
1580 // These aren't really meaningful on scalars.
1581 return true;
1582 }
1583 llvm_unreachable("unknown access kind");
1584}
1585
1586namespace {
1587 struct ComplexValue {
1588 private:
1589 bool IsInt;
1590
1591 public:
1592 APSInt IntReal, IntImag;
1593 APFloat FloatReal, FloatImag;
1594
1595 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1596
1597 void makeComplexFloat() { IsInt = false; }
1598 bool isComplexFloat() const { return !IsInt; }
1599 APFloat &getComplexFloatReal() { return FloatReal; }
1600 APFloat &getComplexFloatImag() { return FloatImag; }
1601
1602 void makeComplexInt() { IsInt = true; }
1603 bool isComplexInt() const { return IsInt; }
1604 APSInt &getComplexIntReal() { return IntReal; }
1605 APSInt &getComplexIntImag() { return IntImag; }
1606
1607 void moveInto(APValue &v) const {
1608 if (isComplexFloat())
1609 v = APValue(FloatReal, FloatImag);
1610 else
1611 v = APValue(IntReal, IntImag);
1612 }
1613 void setFrom(const APValue &v) {
1614 assert(v.isComplexFloat() || v.isComplexInt());
1615 if (v.isComplexFloat()) {
1616 makeComplexFloat();
1617 FloatReal = v.getComplexFloatReal();
1618 FloatImag = v.getComplexFloatImag();
1619 } else {
1620 makeComplexInt();
1621 IntReal = v.getComplexIntReal();
1622 IntImag = v.getComplexIntImag();
1623 }
1624 }
1625 };
1626
1627 struct LValue {
1629 CharUnits Offset;
1630 SubobjectDesignator Designator;
1631 bool IsNullPtr : 1;
1632 bool InvalidBase : 1;
1633
1634 const APValue::LValueBase getLValueBase() const { return Base; }
1635 CharUnits &getLValueOffset() { return Offset; }
1636 const CharUnits &getLValueOffset() const { return Offset; }
1637 SubobjectDesignator &getLValueDesignator() { return Designator; }
1638 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1639 bool isNullPointer() const { return IsNullPtr;}
1640
1641 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1642 unsigned getLValueVersion() const { return Base.getVersion(); }
1643
1644 void moveInto(APValue &V) const {
1645 if (Designator.Invalid)
1646 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1647 else {
1648 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1649 V = APValue(Base, Offset, Designator.Entries,
1650 Designator.IsOnePastTheEnd, IsNullPtr);
1651 }
1652 }
1653 void setFrom(ASTContext &Ctx, const APValue &V) {
1654 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1655 Base = V.getLValueBase();
1656 Offset = V.getLValueOffset();
1657 InvalidBase = false;
1658 Designator = SubobjectDesignator(Ctx, V);
1659 IsNullPtr = V.isNullPointer();
1660 }
1661
1662 void set(APValue::LValueBase B, bool BInvalid = false) {
1663#ifndef NDEBUG
1664 // We only allow a few types of invalid bases. Enforce that here.
1665 if (BInvalid) {
1666 const auto *E = B.get<const Expr *>();
1667 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1668 "Unexpected type of invalid base");
1669 }
1670#endif
1671
1672 Base = B;
1673 Offset = CharUnits::fromQuantity(0);
1674 InvalidBase = BInvalid;
1675 Designator = SubobjectDesignator(getType(B));
1676 IsNullPtr = false;
1677 }
1678
1679 void setNull(ASTContext &Ctx, QualType PointerTy) {
1680 Base = (const ValueDecl *)nullptr;
1681 Offset =
1683 InvalidBase = false;
1684 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1685 IsNullPtr = true;
1686 }
1687
1688 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1689 set(B, true);
1690 }
1691
1692 std::string toString(ASTContext &Ctx, QualType T) const {
1693 APValue Printable;
1694 moveInto(Printable);
1695 return Printable.getAsString(Ctx, T);
1696 }
1697
1698 private:
1699 // Check that this LValue is not based on a null pointer. If it is, produce
1700 // a diagnostic and mark the designator as invalid.
1701 template <typename GenDiagType>
1702 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1703 if (Designator.Invalid)
1704 return false;
1705 if (IsNullPtr) {
1706 GenDiag();
1707 Designator.setInvalid();
1708 return false;
1709 }
1710 return true;
1711 }
1712
1713 public:
1714 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1715 CheckSubobjectKind CSK) {
1716 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1717 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1718 });
1719 }
1720
1721 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1722 AccessKinds AK) {
1723 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1724 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1725 });
1726 }
1727
1728 // Check this LValue refers to an object. If not, set the designator to be
1729 // invalid and emit a diagnostic.
1730 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1731 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1732 Designator.checkSubobject(Info, E, CSK);
1733 }
1734
1735 void addDecl(EvalInfo &Info, const Expr *E,
1736 const Decl *D, bool Virtual = false) {
1737 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1738 Designator.addDeclUnchecked(D, Virtual);
1739 }
1740 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1741 if (!Designator.Entries.empty()) {
1742 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1743 Designator.setInvalid();
1744 return;
1745 }
1746 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1747 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1748 Designator.FirstEntryIsAnUnsizedArray = true;
1749 Designator.addUnsizedArrayUnchecked(ElemTy);
1750 }
1751 }
1752 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1753 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1754 Designator.addArrayUnchecked(CAT);
1755 }
1756 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1757 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1758 Designator.addComplexUnchecked(EltTy, Imag);
1759 }
1760 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1761 uint64_t Size, uint64_t Idx) {
1762 if (checkSubobject(Info, E, CSK_VectorElement))
1763 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1764 }
1765 void clearIsNullPointer() {
1766 IsNullPtr = false;
1767 }
1768 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1769 const APSInt &Index, CharUnits ElementSize) {
1770 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1771 // but we're not required to diagnose it and it's valid in C++.)
1772 if (!Index)
1773 return;
1774
1775 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1776 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1777 // offsets.
1778 uint64_t Offset64 = Offset.getQuantity();
1779 uint64_t ElemSize64 = ElementSize.getQuantity();
1780 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1781 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1782
1783 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1784 Designator.adjustIndex(Info, E, Index);
1785 clearIsNullPointer();
1786 }
1787 void adjustOffset(CharUnits N) {
1788 Offset += N;
1789 if (N.getQuantity())
1790 clearIsNullPointer();
1791 }
1792 };
1793
1794 struct MemberPtr {
1795 MemberPtr() {}
1796 explicit MemberPtr(const ValueDecl *Decl)
1797 : DeclAndIsDerivedMember(Decl, false) {}
1798
1799 /// The member or (direct or indirect) field referred to by this member
1800 /// pointer, or 0 if this is a null member pointer.
1801 const ValueDecl *getDecl() const {
1802 return DeclAndIsDerivedMember.getPointer();
1803 }
1804 /// Is this actually a member of some type derived from the relevant class?
1805 bool isDerivedMember() const {
1806 return DeclAndIsDerivedMember.getInt();
1807 }
1808 /// Get the class which the declaration actually lives in.
1809 const CXXRecordDecl *getContainingRecord() const {
1810 return cast<CXXRecordDecl>(
1811 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1812 }
1813
1814 void moveInto(APValue &V) const {
1815 V = APValue(getDecl(), isDerivedMember(), Path);
1816 }
1817 void setFrom(const APValue &V) {
1818 assert(V.isMemberPointer());
1819 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1820 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1821 Path.clear();
1822 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1823 Path.insert(Path.end(), P.begin(), P.end());
1824 }
1825
1826 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1827 /// whether the member is a member of some class derived from the class type
1828 /// of the member pointer.
1829 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1830 /// Path - The path of base/derived classes from the member declaration's
1831 /// class (exclusive) to the class type of the member pointer (inclusive).
1833
1834 /// Perform a cast towards the class of the Decl (either up or down the
1835 /// hierarchy).
1836 bool castBack(const CXXRecordDecl *Class) {
1837 assert(!Path.empty());
1838 const CXXRecordDecl *Expected;
1839 if (Path.size() >= 2)
1840 Expected = Path[Path.size() - 2];
1841 else
1842 Expected = getContainingRecord();
1843 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1844 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1845 // if B does not contain the original member and is not a base or
1846 // derived class of the class containing the original member, the result
1847 // of the cast is undefined.
1848 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1849 // (D::*). We consider that to be a language defect.
1850 return false;
1851 }
1852 Path.pop_back();
1853 return true;
1854 }
1855 /// Perform a base-to-derived member pointer cast.
1856 bool castToDerived(const CXXRecordDecl *Derived) {
1857 if (!getDecl())
1858 return true;
1859 if (!isDerivedMember()) {
1860 Path.push_back(Derived);
1861 return true;
1862 }
1863 if (!castBack(Derived))
1864 return false;
1865 if (Path.empty())
1866 DeclAndIsDerivedMember.setInt(false);
1867 return true;
1868 }
1869 /// Perform a derived-to-base member pointer cast.
1870 bool castToBase(const CXXRecordDecl *Base) {
1871 if (!getDecl())
1872 return true;
1873 if (Path.empty())
1874 DeclAndIsDerivedMember.setInt(true);
1875 if (isDerivedMember()) {
1876 Path.push_back(Base);
1877 return true;
1878 }
1879 return castBack(Base);
1880 }
1881 };
1882
1883 /// Compare two member pointers, which are assumed to be of the same type.
1884 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1885 if (!LHS.getDecl() || !RHS.getDecl())
1886 return !LHS.getDecl() && !RHS.getDecl();
1887 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1888 return false;
1889 return LHS.Path == RHS.Path;
1890 }
1891}
1892
1893static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1894static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1895 const LValue &This, const Expr *E,
1896 bool AllowNonLiteralTypes = false);
1897static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1898 bool InvalidBaseOK = false);
1899static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1900 bool InvalidBaseOK = false);
1901static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1902 EvalInfo &Info);
1903static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1904static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1905static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1906 EvalInfo &Info);
1907static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1908static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1909static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1910 EvalInfo &Info);
1911static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1912static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1913 EvalInfo &Info,
1914 std::string *StringResult = nullptr);
1915
1916/// Evaluate an integer or fixed point expression into an APResult.
1917static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1918 EvalInfo &Info);
1919
1920/// Evaluate only a fixed point expression into an APResult.
1921static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1922 EvalInfo &Info);
1923
1924//===----------------------------------------------------------------------===//
1925// Misc utilities
1926//===----------------------------------------------------------------------===//
1927
1928/// Negate an APSInt in place, converting it to a signed form if necessary, and
1929/// preserving its value (by extending by up to one bit as needed).
1930static void negateAsSigned(APSInt &Int) {
1931 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1932 Int = Int.extend(Int.getBitWidth() + 1);
1933 Int.setIsSigned(true);
1934 }
1935 Int = -Int;
1936}
1937
1938template<typename KeyT>
1939APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1940 ScopeKind Scope, LValue &LV) {
1941 unsigned Version = getTempVersion();
1942 APValue::LValueBase Base(Key, Index, Version);
1943 LV.set(Base);
1944 return createLocal(Base, Key, T, Scope);
1945}
1946
1947/// Allocate storage for a parameter of a function call made in this frame.
1948APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1949 LValue &LV) {
1950 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1951 APValue::LValueBase Base(PVD, Index, Args.Version);
1952 LV.set(Base);
1953 // We always destroy parameters at the end of the call, even if we'd allow
1954 // them to live to the end of the full-expression at runtime, in order to
1955 // give portable results and match other compilers.
1956 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1957}
1958
1959APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1960 QualType T, ScopeKind Scope) {
1961 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1962 unsigned Version = Base.getVersion();
1963 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1964 assert(Result.isAbsent() && "local created multiple times");
1965
1966 // If we're creating a local immediately in the operand of a speculative
1967 // evaluation, don't register a cleanup to be run outside the speculative
1968 // evaluation context, since we won't actually be able to initialize this
1969 // object.
1970 if (Index <= Info.SpeculativeEvaluationDepth) {
1971 if (T.isDestructedType())
1972 Info.noteSideEffect();
1973 } else {
1974 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1975 }
1976 return Result;
1977}
1978
1979APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1980 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1981 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1982 return nullptr;
1983 }
1984
1985 DynamicAllocLValue DA(NumHeapAllocs++);
1987 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1988 std::forward_as_tuple(DA), std::tuple<>());
1989 assert(Result.second && "reused a heap alloc index?");
1990 Result.first->second.AllocExpr = E;
1991 return &Result.first->second.Value;
1992}
1993
1994/// Produce a string describing the given constexpr call.
1995void CallStackFrame::describe(raw_ostream &Out) const {
1996 unsigned ArgIndex = 0;
1997 bool IsMemberCall =
1998 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1999 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
2000
2001 if (!IsMemberCall)
2002 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2003 /*Qualified=*/false);
2004
2005 if (This && IsMemberCall) {
2006 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
2007 const Expr *Object = MCE->getImplicitObjectArgument();
2008 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
2009 /*Indentation=*/0);
2010 if (Object->getType()->isPointerType())
2011 Out << "->";
2012 else
2013 Out << ".";
2014 } else if (const auto *OCE =
2015 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
2016 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
2017 Info.Ctx.getPrintingPolicy(),
2018 /*Indentation=*/0);
2019 Out << ".";
2020 } else {
2021 APValue Val;
2022 This->moveInto(Val);
2023 Val.printPretty(
2024 Out, Info.Ctx,
2025 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2026 Out << ".";
2027 }
2028 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2029 /*Qualified=*/false);
2030 IsMemberCall = false;
2031 }
2032
2033 Out << '(';
2034
2035 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2036 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2037 if (ArgIndex > (unsigned)IsMemberCall)
2038 Out << ", ";
2039
2040 const ParmVarDecl *Param = *I;
2041 APValue *V = Info.getParamSlot(Arguments, Param);
2042 if (V)
2043 V->printPretty(Out, Info.Ctx, Param->getType());
2044 else
2045 Out << "<...>";
2046
2047 if (ArgIndex == 0 && IsMemberCall)
2048 Out << "->" << *Callee << '(';
2049 }
2050
2051 Out << ')';
2052}
2053
2054/// Evaluate an expression to see if it had side-effects, and discard its
2055/// result.
2056/// \return \c true if the caller should keep evaluating.
2057static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2058 assert(!E->isValueDependent());
2059 APValue Scratch;
2060 if (!Evaluate(Scratch, Info, E))
2061 // We don't need the value, but we might have skipped a side effect here.
2062 return Info.noteSideEffect();
2063 return true;
2064}
2065
2066/// Should this call expression be treated as forming an opaque constant?
2067static bool IsOpaqueConstantCall(const CallExpr *E) {
2068 unsigned Builtin = E->getBuiltinCallee();
2069 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2070 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2071 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2072 Builtin == Builtin::BI__builtin_function_start);
2073}
2074
2075static bool IsOpaqueConstantCall(const LValue &LVal) {
2076 const auto *BaseExpr =
2077 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2078 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2079}
2080
2082 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2083 // constant expression of pointer type that evaluates to...
2084
2085 // ... a null pointer value, or a prvalue core constant expression of type
2086 // std::nullptr_t.
2087 if (!B)
2088 return true;
2089
2090 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2091 // ... the address of an object with static storage duration,
2092 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2093 return VD->hasGlobalStorage();
2094 if (isa<TemplateParamObjectDecl>(D))
2095 return true;
2096 // ... the address of a function,
2097 // ... the address of a GUID [MS extension],
2098 // ... the address of an unnamed global constant
2099 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2100 }
2101
2102 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2103 return true;
2104
2105 const Expr *E = B.get<const Expr*>();
2106 switch (E->getStmtClass()) {
2107 default:
2108 return false;
2109 case Expr::CompoundLiteralExprClass: {
2110 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2111 return CLE->isFileScope() && CLE->isLValue();
2112 }
2113 case Expr::MaterializeTemporaryExprClass:
2114 // A materialized temporary might have been lifetime-extended to static
2115 // storage duration.
2116 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2117 // A string literal has static storage duration.
2118 case Expr::StringLiteralClass:
2119 case Expr::PredefinedExprClass:
2120 case Expr::ObjCStringLiteralClass:
2121 case Expr::ObjCEncodeExprClass:
2122 return true;
2123 case Expr::ObjCBoxedExprClass:
2124 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2125 case Expr::CallExprClass:
2126 return IsOpaqueConstantCall(cast<CallExpr>(E));
2127 // For GCC compatibility, &&label has static storage duration.
2128 case Expr::AddrLabelExprClass:
2129 return true;
2130 // A Block literal expression may be used as the initialization value for
2131 // Block variables at global or local static scope.
2132 case Expr::BlockExprClass:
2133 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2134 // The APValue generated from a __builtin_source_location will be emitted as a
2135 // literal.
2136 case Expr::SourceLocExprClass:
2137 return true;
2138 case Expr::ImplicitValueInitExprClass:
2139 // FIXME:
2140 // We can never form an lvalue with an implicit value initialization as its
2141 // base through expression evaluation, so these only appear in one case: the
2142 // implicit variable declaration we invent when checking whether a constexpr
2143 // constructor can produce a constant expression. We must assume that such
2144 // an expression might be a global lvalue.
2145 return true;
2146 }
2147}
2148
2149static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2150 return LVal.Base.dyn_cast<const ValueDecl*>();
2151}
2152
2153// Information about an LValueBase that is some kind of string.
2156 StringRef Bytes;
2158};
2159
2160// Gets the lvalue base of LVal as a string.
2161static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2162 LValueBaseString &AsString) {
2163 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2164 if (!BaseExpr)
2165 return false;
2166
2167 // For ObjCEncodeExpr, we need to compute and store the string.
2168 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2169 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2170 AsString.ObjCEncodeStorage);
2171 AsString.Bytes = AsString.ObjCEncodeStorage;
2172 AsString.CharWidth = 1;
2173 return true;
2174 }
2175
2176 // Otherwise, we have a StringLiteral.
2177 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2178 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2179 Lit = PE->getFunctionName();
2180
2181 if (!Lit)
2182 return false;
2183
2184 AsString.Bytes = Lit->getBytes();
2185 AsString.CharWidth = Lit->getCharByteWidth();
2186 return true;
2187}
2188
2189// Determine whether two string literals potentially overlap. This will be the
2190// case if they agree on the values of all the bytes on the overlapping region
2191// between them.
2192//
2193// The overlapping region is the portion of the two string literals that must
2194// overlap in memory if the pointers actually point to the same address at
2195// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2196// the overlapping region is "cdef\0", which in this case does agree, so the
2197// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2198// "bazbar" + 3, the overlapping region contains all of both strings, so they
2199// are not potentially overlapping, even though they agree from the given
2200// addresses onwards.
2201//
2202// See open core issue CWG2765 which is discussing the desired rule here.
2203static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2204 const LValue &LHS,
2205 const LValue &RHS) {
2206 LValueBaseString LHSString, RHSString;
2207 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2208 !GetLValueBaseAsString(Info, RHS, RHSString))
2209 return false;
2210
2211 // This is the byte offset to the location of the first character of LHS
2212 // within RHS. We don't need to look at the characters of one string that
2213 // would appear before the start of the other string if they were merged.
2214 CharUnits Offset = RHS.Offset - LHS.Offset;
2215 if (Offset.isNegative())
2216 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2217 else
2218 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2219
2220 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2221 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2222 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2223 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2224
2225 // The null terminator isn't included in the string data, so check for it
2226 // manually. If the longer string doesn't have a null terminator where the
2227 // shorter string ends, they aren't potentially overlapping.
2228 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2229 if (Shorter.size() + NullByte >= Longer.size())
2230 break;
2231 if (Longer[Shorter.size() + NullByte])
2232 return false;
2233 }
2234
2235 // Otherwise, they're potentially overlapping if and only if the overlapping
2236 // region is the same.
2237 return Shorter == Longer.take_front(Shorter.size());
2238}
2239
2240static bool IsWeakLValue(const LValue &Value) {
2242 return Decl && Decl->isWeak();
2243}
2244
2245static bool isZeroSized(const LValue &Value) {
2247 if (isa_and_nonnull<VarDecl>(Decl)) {
2248 QualType Ty = Decl->getType();
2249 if (Ty->isArrayType())
2250 return Ty->isIncompleteType() ||
2251 Decl->getASTContext().getTypeSize(Ty) == 0;
2252 }
2253 return false;
2254}
2255
2256static bool HasSameBase(const LValue &A, const LValue &B) {
2257 if (!A.getLValueBase())
2258 return !B.getLValueBase();
2259 if (!B.getLValueBase())
2260 return false;
2261
2262 if (A.getLValueBase().getOpaqueValue() !=
2263 B.getLValueBase().getOpaqueValue())
2264 return false;
2265
2266 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2267 A.getLValueVersion() == B.getLValueVersion();
2268}
2269
2270static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2271 assert(Base && "no location for a null lvalue");
2272 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2273
2274 // For a parameter, find the corresponding call stack frame (if it still
2275 // exists), and point at the parameter of the function definition we actually
2276 // invoked.
2277 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2278 unsigned Idx = PVD->getFunctionScopeIndex();
2279 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2280 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2281 F->Arguments.Version == Base.getVersion() && F->Callee &&
2282 Idx < F->Callee->getNumParams()) {
2283 VD = F->Callee->getParamDecl(Idx);
2284 break;
2285 }
2286 }
2287 }
2288
2289 if (VD)
2290 Info.Note(VD->getLocation(), diag::note_declared_at);
2291 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2292 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2293 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2294 // FIXME: Produce a note for dangling pointers too.
2295 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2296 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2297 diag::note_constexpr_dynamic_alloc_here);
2298 }
2299
2300 // We have no information to show for a typeid(T) object.
2301}
2302
2306};
2307
2308/// Materialized temporaries that we've already checked to determine if they're
2309/// initializsed by a constant expression.
2312
2314 EvalInfo &Info, SourceLocation DiagLoc,
2315 QualType Type, const APValue &Value,
2316 ConstantExprKind Kind,
2317 const FieldDecl *SubobjectDecl,
2318 CheckedTemporaries &CheckedTemps);
2319
2320/// Check that this reference or pointer core constant expression is a valid
2321/// value for an address or reference constant expression. Return true if we
2322/// can fold this expression, whether or not it's a constant expression.
2324 QualType Type, const LValue &LVal,
2325 ConstantExprKind Kind,
2326 CheckedTemporaries &CheckedTemps) {
2327 bool IsReferenceType = Type->isReferenceType();
2328
2329 APValue::LValueBase Base = LVal.getLValueBase();
2330 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2331
2332 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2333 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2334
2335 // Additional restrictions apply in a template argument. We only enforce the
2336 // C++20 restrictions here; additional syntactic and semantic restrictions
2337 // are applied elsewhere.
2338 if (isTemplateArgument(Kind)) {
2339 int InvalidBaseKind = -1;
2340 StringRef Ident;
2341 if (Base.is<TypeInfoLValue>())
2342 InvalidBaseKind = 0;
2343 else if (isa_and_nonnull<StringLiteral>(BaseE))
2344 InvalidBaseKind = 1;
2345 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2346 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2347 InvalidBaseKind = 2;
2348 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2349 InvalidBaseKind = 3;
2350 Ident = PE->getIdentKindName();
2351 }
2352
2353 if (InvalidBaseKind != -1) {
2354 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2355 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2356 << Ident;
2357 return false;
2358 }
2359 }
2360
2361 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2362 FD && FD->isImmediateFunction()) {
2363 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2364 << !Type->isAnyPointerType();
2365 Info.Note(FD->getLocation(), diag::note_declared_at);
2366 return false;
2367 }
2368
2369 // Check that the object is a global. Note that the fake 'this' object we
2370 // manufacture when checking potential constant expressions is conservatively
2371 // assumed to be global here.
2372 if (!IsGlobalLValue(Base)) {
2373 if (Info.getLangOpts().CPlusPlus11) {
2374 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2375 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2376 << BaseVD;
2377 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2378 if (VarD && VarD->isConstexpr()) {
2379 // Non-static local constexpr variables have unintuitive semantics:
2380 // constexpr int a = 1;
2381 // constexpr const int *p = &a;
2382 // ... is invalid because the address of 'a' is not constant. Suggest
2383 // adding a 'static' in this case.
2384 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2385 << VarD
2386 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2387 } else {
2388 NoteLValueLocation(Info, Base);
2389 }
2390 } else {
2391 Info.FFDiag(Loc);
2392 }
2393 // Don't allow references to temporaries to escape.
2394 return false;
2395 }
2396 assert((Info.checkingPotentialConstantExpression() ||
2397 LVal.getLValueCallIndex() == 0) &&
2398 "have call index for global lvalue");
2399
2400 if (Base.is<DynamicAllocLValue>()) {
2401 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2402 << IsReferenceType << !Designator.Entries.empty();
2403 NoteLValueLocation(Info, Base);
2404 return false;
2405 }
2406
2407 if (BaseVD) {
2408 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2409 // Check if this is a thread-local variable.
2410 if (Var->getTLSKind())
2411 // FIXME: Diagnostic!
2412 return false;
2413
2414 // A dllimport variable never acts like a constant, unless we're
2415 // evaluating a value for use only in name mangling.
2416 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2417 // FIXME: Diagnostic!
2418 return false;
2419
2420 // In CUDA/HIP device compilation, only device side variables have
2421 // constant addresses.
2422 if (Info.getASTContext().getLangOpts().CUDA &&
2423 Info.getASTContext().getLangOpts().CUDAIsDevice &&
2424 Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2425 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2426 !Var->hasAttr<CUDAConstantAttr>() &&
2427 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2428 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2429 Var->hasAttr<HIPManagedAttr>())
2430 return false;
2431 }
2432 }
2433 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2434 // __declspec(dllimport) must be handled very carefully:
2435 // We must never initialize an expression with the thunk in C++.
2436 // Doing otherwise would allow the same id-expression to yield
2437 // different addresses for the same function in different translation
2438 // units. However, this means that we must dynamically initialize the
2439 // expression with the contents of the import address table at runtime.
2440 //
2441 // The C language has no notion of ODR; furthermore, it has no notion of
2442 // dynamic initialization. This means that we are permitted to
2443 // perform initialization with the address of the thunk.
2444 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2445 FD->hasAttr<DLLImportAttr>())
2446 // FIXME: Diagnostic!
2447 return false;
2448 }
2449 } else if (const auto *MTE =
2450 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2451 if (CheckedTemps.insert(MTE).second) {
2452 QualType TempType = getType(Base);
2453 if (TempType.isDestructedType()) {
2454 Info.FFDiag(MTE->getExprLoc(),
2455 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2456 << TempType;
2457 return false;
2458 }
2459
2460 APValue *V = MTE->getOrCreateValue(false);
2461 assert(V && "evasluation result refers to uninitialised temporary");
2462 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2463 Info, MTE->getExprLoc(), TempType, *V, Kind,
2464 /*SubobjectDecl=*/nullptr, CheckedTemps))
2465 return false;
2466 }
2467 }
2468
2469 // Allow address constant expressions to be past-the-end pointers. This is
2470 // an extension: the standard requires them to point to an object.
2471 if (!IsReferenceType)
2472 return true;
2473
2474 // A reference constant expression must refer to an object.
2475 if (!Base) {
2476 // FIXME: diagnostic
2477 Info.CCEDiag(Loc);
2478 return true;
2479 }
2480
2481 // Does this refer one past the end of some object?
2482 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2483 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2484 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2485 NoteLValueLocation(Info, Base);
2486 }
2487
2488 return true;
2489}
2490
2491/// Member pointers are constant expressions unless they point to a
2492/// non-virtual dllimport member function.
2493static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2495 QualType Type,
2496 const APValue &Value,
2497 ConstantExprKind Kind) {
2498 const ValueDecl *Member = Value.getMemberPointerDecl();
2499 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2500 if (!FD)
2501 return true;
2502 if (FD->isImmediateFunction()) {
2503 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2504 Info.Note(FD->getLocation(), diag::note_declared_at);
2505 return false;
2506 }
2507 return isForManglingOnly(Kind) || FD->isVirtual() ||
2508 !FD->hasAttr<DLLImportAttr>();
2509}
2510
2511/// Check that this core constant expression is of literal type, and if not,
2512/// produce an appropriate diagnostic.
2513static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2514 const LValue *This = nullptr) {
2515 // The restriction to literal types does not exist in C++23 anymore.
2516 if (Info.getLangOpts().CPlusPlus23)
2517 return true;
2518
2519 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2520 return true;
2521
2522 // C++1y: A constant initializer for an object o [...] may also invoke
2523 // constexpr constructors for o and its subobjects even if those objects
2524 // are of non-literal class types.
2525 //
2526 // C++11 missed this detail for aggregates, so classes like this:
2527 // struct foo_t { union { int i; volatile int j; } u; };
2528 // are not (obviously) initializable like so:
2529 // __attribute__((__require_constant_initialization__))
2530 // static const foo_t x = {{0}};
2531 // because "i" is a subobject with non-literal initialization (due to the
2532 // volatile member of the union). See:
2533 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2534 // Therefore, we use the C++1y behavior.
2535 if (This && Info.EvaluatingDecl == This->getLValueBase())
2536 return true;
2537
2538 // Prvalue constant expressions must be of literal types.
2539 if (Info.getLangOpts().CPlusPlus11)
2540 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2541 << E->getType();
2542 else
2543 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2544 return false;
2545}
2546
2548 EvalInfo &Info, SourceLocation DiagLoc,
2549 QualType Type, const APValue &Value,
2550 ConstantExprKind Kind,
2551 const FieldDecl *SubobjectDecl,
2552 CheckedTemporaries &CheckedTemps) {
2553 if (!Value.hasValue()) {
2554 if (SubobjectDecl) {
2555 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2556 << /*(name)*/ 1 << SubobjectDecl;
2557 Info.Note(SubobjectDecl->getLocation(),
2558 diag::note_constexpr_subobject_declared_here);
2559 } else {
2560 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2561 << /*of type*/ 0 << Type;
2562 }
2563 return false;
2564 }
2565
2566 // We allow _Atomic(T) to be initialized from anything that T can be
2567 // initialized from.
2568 if (const AtomicType *AT = Type->getAs<AtomicType>())
2569 Type = AT->getValueType();
2570
2571 // Core issue 1454: For a literal constant expression of array or class type,
2572 // each subobject of its value shall have been initialized by a constant
2573 // expression.
2574 if (Value.isArray()) {
2576 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2577 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2578 Value.getArrayInitializedElt(I), Kind,
2579 SubobjectDecl, CheckedTemps))
2580 return false;
2581 }
2582 if (!Value.hasArrayFiller())
2583 return true;
2584 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2585 Value.getArrayFiller(), Kind, SubobjectDecl,
2586 CheckedTemps);
2587 }
2588 if (Value.isUnion() && Value.getUnionField()) {
2589 return CheckEvaluationResult(
2590 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2591 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2592 }
2593 if (Value.isStruct()) {
2594 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2595 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2596 unsigned BaseIndex = 0;
2597 for (const CXXBaseSpecifier &BS : CD->bases()) {
2598 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2599 if (!BaseValue.hasValue()) {
2600 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2601 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2602 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2603 return false;
2604 }
2605 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2606 Kind, /*SubobjectDecl=*/nullptr,
2607 CheckedTemps))
2608 return false;
2609 ++BaseIndex;
2610 }
2611 }
2612 for (const auto *I : RD->fields()) {
2613 if (I->isUnnamedBitField())
2614 continue;
2615
2616 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2617 Value.getStructField(I->getFieldIndex()), Kind,
2618 I, CheckedTemps))
2619 return false;
2620 }
2621 }
2622
2623 if (Value.isLValue() &&
2624 CERK == CheckEvaluationResultKind::ConstantExpression) {
2625 LValue LVal;
2626 LVal.setFrom(Info.Ctx, Value);
2627 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2628 CheckedTemps);
2629 }
2630
2631 if (Value.isMemberPointer() &&
2632 CERK == CheckEvaluationResultKind::ConstantExpression)
2633 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2634
2635 // Everything else is fine.
2636 return true;
2637}
2638
2639/// Check that this core constant expression value is a valid value for a
2640/// constant expression. If not, report an appropriate diagnostic. Does not
2641/// check that the expression is of literal type.
2642static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2643 QualType Type, const APValue &Value,
2644 ConstantExprKind Kind) {
2645 // Nothing to check for a constant expression of type 'cv void'.
2646 if (Type->isVoidType())
2647 return true;
2648
2649 CheckedTemporaries CheckedTemps;
2650 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2651 Info, DiagLoc, Type, Value, Kind,
2652 /*SubobjectDecl=*/nullptr, CheckedTemps);
2653}
2654
2655/// Check that this evaluated value is fully-initialized and can be loaded by
2656/// an lvalue-to-rvalue conversion.
2657static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2658 QualType Type, const APValue &Value) {
2659 CheckedTemporaries CheckedTemps;
2660 return CheckEvaluationResult(
2661 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2662 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2663}
2664
2665/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2666/// "the allocated storage is deallocated within the evaluation".
2667static bool CheckMemoryLeaks(EvalInfo &Info) {
2668 if (!Info.HeapAllocs.empty()) {
2669 // We can still fold to a constant despite a compile-time memory leak,
2670 // so long as the heap allocation isn't referenced in the result (we check
2671 // that in CheckConstantExpression).
2672 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2673 diag::note_constexpr_memory_leak)
2674 << unsigned(Info.HeapAllocs.size() - 1);
2675 }
2676 return true;
2677}
2678
2679static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2680 // A null base expression indicates a null pointer. These are always
2681 // evaluatable, and they are false unless the offset is zero.
2682 if (!Value.getLValueBase()) {
2683 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2684 Result = !Value.getLValueOffset().isZero();
2685 return true;
2686 }
2687
2688 // We have a non-null base. These are generally known to be true, but if it's
2689 // a weak declaration it can be null at runtime.
2690 Result = true;
2691 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2692 return !Decl || !Decl->isWeak();
2693}
2694
2695static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2696 // TODO: This function should produce notes if it fails.
2697 switch (Val.getKind()) {
2698 case APValue::None:
2700 return false;
2701 case APValue::Int:
2702 Result = Val.getInt().getBoolValue();
2703 return true;
2705 Result = Val.getFixedPoint().getBoolValue();
2706 return true;
2707 case APValue::Float:
2708 Result = !Val.getFloat().isZero();
2709 return true;
2711 Result = Val.getComplexIntReal().getBoolValue() ||
2712 Val.getComplexIntImag().getBoolValue();
2713 return true;
2715 Result = !Val.getComplexFloatReal().isZero() ||
2716 !Val.getComplexFloatImag().isZero();
2717 return true;
2718 case APValue::LValue:
2719 return EvalPointerValueAsBool(Val, Result);
2721 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2722 return false;
2723 }
2724 Result = Val.getMemberPointerDecl();
2725 return true;
2726 case APValue::Vector:
2727 case APValue::Array:
2728 case APValue::Struct:
2729 case APValue::Union:
2731 return false;
2732 }
2733
2734 llvm_unreachable("unknown APValue kind");
2735}
2736
2737static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2738 EvalInfo &Info) {
2739 assert(!E->isValueDependent());
2740 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2741 APValue Val;
2742 if (!Evaluate(Val, Info, E))
2743 return false;
2744 return HandleConversionToBool(Val, Result);
2745}
2746
2747template<typename T>
2748static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2749 const T &SrcValue, QualType DestType) {
2750 Info.CCEDiag(E, diag::note_constexpr_overflow)
2751 << SrcValue << DestType;
2752 return Info.noteUndefinedBehavior();
2753}
2754
2755static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2756 QualType SrcType, const APFloat &Value,
2757 QualType DestType, APSInt &Result) {
2758 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2759 // Determine whether we are converting to unsigned or signed.
2760 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2761
2762 Result = APSInt(DestWidth, !DestSigned);
2763 bool ignored;
2764 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2765 & APFloat::opInvalidOp)
2766 return HandleOverflow(Info, E, Value, DestType);
2767 return true;
2768}
2769
2770/// Get rounding mode to use in evaluation of the specified expression.
2771///
2772/// If rounding mode is unknown at compile time, still try to evaluate the
2773/// expression. If the result is exact, it does not depend on rounding mode.
2774/// So return "tonearest" mode instead of "dynamic".
2775static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2776 llvm::RoundingMode RM =
2777 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2778 if (RM == llvm::RoundingMode::Dynamic)
2779 RM = llvm::RoundingMode::NearestTiesToEven;
2780 return RM;
2781}
2782
2783/// Check if the given evaluation result is allowed for constant evaluation.
2784static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2785 APFloat::opStatus St) {
2786 // In a constant context, assume that any dynamic rounding mode or FP
2787 // exception state matches the default floating-point environment.
2788 if (Info.InConstantContext)
2789 return true;
2790
2791 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2792 if ((St & APFloat::opInexact) &&
2793 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2794 // Inexact result means that it depends on rounding mode. If the requested
2795 // mode is dynamic, the evaluation cannot be made in compile time.
2796 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2797 return false;
2798 }
2799
2800 if ((St != APFloat::opOK) &&
2801 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2802 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2803 FPO.getAllowFEnvAccess())) {
2804 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2805 return false;
2806 }
2807
2808 if ((St & APFloat::opStatus::opInvalidOp) &&
2809 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2810 // There is no usefully definable result.
2811 Info.FFDiag(E);
2812 return false;
2813 }
2814
2815 // FIXME: if:
2816 // - evaluation triggered other FP exception, and
2817 // - exception mode is not "ignore", and
2818 // - the expression being evaluated is not a part of global variable
2819 // initializer,
2820 // the evaluation probably need to be rejected.
2821 return true;
2822}
2823
2824static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2825 QualType SrcType, QualType DestType,
2826 APFloat &Result) {
2827 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2828 isa<ConvertVectorExpr>(E)) &&
2829 "HandleFloatToFloatCast has been checked with only CastExpr, "
2830 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2831 "the new expression or address the root cause of this usage.");
2832 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2833 APFloat::opStatus St;
2834 APFloat Value = Result;
2835 bool ignored;
2836 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2837 return checkFloatingPointResult(Info, E, St);
2838}
2839
2840static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2841 QualType DestType, QualType SrcType,
2842 const APSInt &Value) {
2843 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2844 // Figure out if this is a truncate, extend or noop cast.
2845 // If the input is signed, do a sign extend, noop, or truncate.
2846 APSInt Result = Value.extOrTrunc(DestWidth);
2847 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2848 if (DestType->isBooleanType())
2849 Result = Value.getBoolValue();
2850 return Result;
2851}
2852
2853static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2854 const FPOptions FPO,
2855 QualType SrcType, const APSInt &Value,
2856 QualType DestType, APFloat &Result) {
2857 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2858 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2859 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2860 return checkFloatingPointResult(Info, E, St);
2861}
2862
2863static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2864 APValue &Value, const FieldDecl *FD) {
2865 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2866
2867 if (!Value.isInt()) {
2868 // Trying to store a pointer-cast-to-integer into a bitfield.
2869 // FIXME: In this case, we should provide the diagnostic for casting
2870 // a pointer to an integer.
2871 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2872 Info.FFDiag(E);
2873 return false;
2874 }
2875
2876 APSInt &Int = Value.getInt();
2877 unsigned OldBitWidth = Int.getBitWidth();
2878 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2879 if (NewBitWidth < OldBitWidth)
2880 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2881 return true;
2882}
2883
2884/// Perform the given integer operation, which is known to need at most BitWidth
2885/// bits, and check for overflow in the original type (if that type was not an
2886/// unsigned type).
2887template<typename Operation>
2888static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2889 const APSInt &LHS, const APSInt &RHS,
2890 unsigned BitWidth, Operation Op,
2891 APSInt &Result) {
2892 if (LHS.isUnsigned()) {
2893 Result = Op(LHS, RHS);
2894 return true;
2895 }
2896
2897 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2898 Result = Value.trunc(LHS.getBitWidth());
2899 if (Result.extend(BitWidth) != Value) {
2900 if (Info.checkingForUndefinedBehavior())
2901 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2902 diag::warn_integer_constant_overflow)
2903 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2904 /*UpperCase=*/true, /*InsertSeparators=*/true)
2905 << E->getType() << E->getSourceRange();
2906 return HandleOverflow(Info, E, Value, E->getType());
2907 }
2908 return true;
2909}
2910
2911/// Perform the given binary integer operation.
2912static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2913 const APSInt &LHS, BinaryOperatorKind Opcode,
2914 APSInt RHS, APSInt &Result) {
2915 bool HandleOverflowResult = true;
2916 switch (Opcode) {
2917 default:
2918 Info.FFDiag(E);
2919 return false;
2920 case BO_Mul:
2921 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2922 std::multiplies<APSInt>(), Result);
2923 case BO_Add:
2924 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2925 std::plus<APSInt>(), Result);
2926 case BO_Sub:
2927 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2928 std::minus<APSInt>(), Result);
2929 case BO_And: Result = LHS & RHS; return true;
2930 case BO_Xor: Result = LHS ^ RHS; return true;
2931 case BO_Or: Result = LHS | RHS; return true;
2932 case BO_Div:
2933 case BO_Rem:
2934 if (RHS == 0) {
2935 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2936 << E->getRHS()->getSourceRange();
2937 return false;
2938 }
2939 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2940 // this operation and gives the two's complement result.
2941 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2942 LHS.isMinSignedValue())
2943 HandleOverflowResult = HandleOverflow(
2944 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2945 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2946 return HandleOverflowResult;
2947 case BO_Shl: {
2948 if (Info.getLangOpts().OpenCL)
2949 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2950 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2951 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2952 RHS.isUnsigned());
2953 else if (RHS.isSigned() && RHS.isNegative()) {
2954 // During constant-folding, a negative shift is an opposite shift. Such
2955 // a shift is not a constant expression.
2956 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2957 if (!Info.noteUndefinedBehavior())
2958 return false;
2959 RHS = -RHS;
2960 goto shift_right;
2961 }
2962 shift_left:
2963 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2964 // the shifted type.
2965 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2966 if (SA != RHS) {
2967 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2968 << RHS << E->getType() << LHS.getBitWidth();
2969 if (!Info.noteUndefinedBehavior())
2970 return false;
2971 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2972 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2973 // operand, and must not overflow the corresponding unsigned type.
2974 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2975 // E1 x 2^E2 module 2^N.
2976 if (LHS.isNegative()) {
2977 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2978 if (!Info.noteUndefinedBehavior())
2979 return false;
2980 } else if (LHS.countl_zero() < SA) {
2981 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2982 if (!Info.noteUndefinedBehavior())
2983 return false;
2984 }
2985 }
2986 Result = LHS << SA;
2987 return true;
2988 }
2989 case BO_Shr: {
2990 if (Info.getLangOpts().OpenCL)
2991 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2992 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2993 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2994 RHS.isUnsigned());
2995 else if (RHS.isSigned() && RHS.isNegative()) {
2996 // During constant-folding, a negative shift is an opposite shift. Such a
2997 // shift is not a constant expression.
2998 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2999 if (!Info.noteUndefinedBehavior())
3000 return false;
3001 RHS = -RHS;
3002 goto shift_left;
3003 }
3004 shift_right:
3005 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
3006 // shifted type.
3007 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3008 if (SA != RHS) {
3009 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3010 << RHS << E->getType() << LHS.getBitWidth();
3011 if (!Info.noteUndefinedBehavior())
3012 return false;
3013 }
3014
3015 Result = LHS >> SA;
3016 return true;
3017 }
3018
3019 case BO_LT: Result = LHS < RHS; return true;
3020 case BO_GT: Result = LHS > RHS; return true;
3021 case BO_LE: Result = LHS <= RHS; return true;
3022 case BO_GE: Result = LHS >= RHS; return true;
3023 case BO_EQ: Result = LHS == RHS; return true;
3024 case BO_NE: Result = LHS != RHS; return true;
3025 case BO_Cmp:
3026 llvm_unreachable("BO_Cmp should be handled elsewhere");
3027 }
3028}
3029
3030/// Perform the given binary floating-point operation, in-place, on LHS.
3031static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3032 APFloat &LHS, BinaryOperatorKind Opcode,
3033 const APFloat &RHS) {
3034 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3035 APFloat::opStatus St;
3036 switch (Opcode) {
3037 default:
3038 Info.FFDiag(E);
3039 return false;
3040 case BO_Mul:
3041 St = LHS.multiply(RHS, RM);
3042 break;
3043 case BO_Add:
3044 St = LHS.add(RHS, RM);
3045 break;
3046 case BO_Sub:
3047 St = LHS.subtract(RHS, RM);
3048 break;
3049 case BO_Div:
3050 // [expr.mul]p4:
3051 // If the second operand of / or % is zero the behavior is undefined.
3052 if (RHS.isZero())
3053 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3054 St = LHS.divide(RHS, RM);
3055 break;
3056 }
3057
3058 // [expr.pre]p4:
3059 // If during the evaluation of an expression, the result is not
3060 // mathematically defined [...], the behavior is undefined.
3061 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3062 if (LHS.isNaN()) {
3063 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3064 return Info.noteUndefinedBehavior();
3065 }
3066
3067 return checkFloatingPointResult(Info, E, St);
3068}
3069
3070static bool handleLogicalOpForVector(const APInt &LHSValue,
3071 BinaryOperatorKind Opcode,
3072 const APInt &RHSValue, APInt &Result) {
3073 bool LHS = (LHSValue != 0);
3074 bool RHS = (RHSValue != 0);
3075
3076 if (Opcode == BO_LAnd)
3077 Result = LHS && RHS;
3078 else
3079 Result = LHS || RHS;
3080 return true;
3081}
3082static bool handleLogicalOpForVector(const APFloat &LHSValue,
3083 BinaryOperatorKind Opcode,
3084 const APFloat &RHSValue, APInt &Result) {
3085 bool LHS = !LHSValue.isZero();
3086 bool RHS = !RHSValue.isZero();
3087
3088 if (Opcode == BO_LAnd)
3089 Result = LHS && RHS;
3090 else
3091 Result = LHS || RHS;
3092 return true;
3093}
3094
3095static bool handleLogicalOpForVector(const APValue &LHSValue,
3096 BinaryOperatorKind Opcode,
3097 const APValue &RHSValue, APInt &Result) {
3098 // The result is always an int type, however operands match the first.
3099 if (LHSValue.getKind() == APValue::Int)
3100 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3101 RHSValue.getInt(), Result);
3102 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3103 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3104 RHSValue.getFloat(), Result);
3105}
3106
3107template <typename APTy>
3108static bool
3110 const APTy &RHSValue, APInt &Result) {
3111 switch (Opcode) {
3112 default:
3113 llvm_unreachable("unsupported binary operator");
3114 case BO_EQ:
3115 Result = (LHSValue == RHSValue);
3116 break;
3117 case BO_NE:
3118 Result = (LHSValue != RHSValue);
3119 break;
3120 case BO_LT:
3121 Result = (LHSValue < RHSValue);
3122 break;
3123 case BO_GT:
3124 Result = (LHSValue > RHSValue);
3125 break;
3126 case BO_LE:
3127 Result = (LHSValue <= RHSValue);
3128 break;
3129 case BO_GE:
3130 Result = (LHSValue >= RHSValue);
3131 break;
3132 }
3133
3134 // The boolean operations on these vector types use an instruction that
3135 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3136 // to -1 to make sure that we produce the correct value.
3137 Result.negate();
3138
3139 return true;
3140}
3141
3142static bool handleCompareOpForVector(const APValue &LHSValue,
3143 BinaryOperatorKind Opcode,
3144 const APValue &RHSValue, APInt &Result) {
3145 // The result is always an int type, however operands match the first.
3146 if (LHSValue.getKind() == APValue::Int)
3147 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3148 RHSValue.getInt(), Result);
3149 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3150 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3151 RHSValue.getFloat(), Result);
3152}
3153
3154// Perform binary operations for vector types, in place on the LHS.
3155static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3156 BinaryOperatorKind Opcode,
3157 APValue &LHSValue,
3158 const APValue &RHSValue) {
3159 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3160 "Operation not supported on vector types");
3161
3162 const auto *VT = E->getType()->castAs<VectorType>();
3163 unsigned NumElements = VT->getNumElements();
3164 QualType EltTy = VT->getElementType();
3165
3166 // In the cases (typically C as I've observed) where we aren't evaluating
3167 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3168 // just give up.
3169 if (!LHSValue.isVector()) {
3170 assert(LHSValue.isLValue() &&
3171 "A vector result that isn't a vector OR uncalculated LValue");
3172 Info.FFDiag(E);
3173 return false;
3174 }
3175
3176 assert(LHSValue.getVectorLength() == NumElements &&
3177 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3178
3179 SmallVector<APValue, 4> ResultElements;
3180
3181 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3182 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3183 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3184
3185 if (EltTy->isIntegerType()) {
3186 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3187 EltTy->isUnsignedIntegerType()};
3188 bool Success = true;
3189
3190 if (BinaryOperator::isLogicalOp(Opcode))
3191 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3192 else if (BinaryOperator::isComparisonOp(Opcode))
3193 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3194 else
3195 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3196 RHSElt.getInt(), EltResult);
3197
3198 if (!Success) {
3199 Info.FFDiag(E);
3200 return false;
3201 }
3202 ResultElements.emplace_back(EltResult);
3203
3204 } else if (EltTy->isFloatingType()) {
3205 assert(LHSElt.getKind() == APValue::Float &&
3206 RHSElt.getKind() == APValue::Float &&
3207 "Mismatched LHS/RHS/Result Type");
3208 APFloat LHSFloat = LHSElt.getFloat();
3209
3210 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3211 RHSElt.getFloat())) {
3212 Info.FFDiag(E);
3213 return false;
3214 }
3215
3216 ResultElements.emplace_back(LHSFloat);
3217 }
3218 }
3219
3220 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3221 return true;
3222}
3223
3224/// Cast an lvalue referring to a base subobject to a derived class, by
3225/// truncating the lvalue's path to the given length.
3226static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3227 const RecordDecl *TruncatedType,
3228 unsigned TruncatedElements) {
3229 SubobjectDesignator &D = Result.Designator;
3230
3231 // Check we actually point to a derived class object.
3232 if (TruncatedElements == D.Entries.size())
3233 return true;
3234 assert(TruncatedElements >= D.MostDerivedPathLength &&
3235 "not casting to a derived class");
3236 if (!Result.checkSubobject(Info, E, CSK_Derived))
3237 return false;
3238
3239 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3240 const RecordDecl *RD = TruncatedType;
3241 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3242 if (RD->isInvalidDecl()) return false;
3243 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3244 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3245 if (isVirtualBaseClass(D.Entries[I]))
3246 Result.Offset -= Layout.getVBaseClassOffset(Base);
3247 else
3248 Result.Offset -= Layout.getBaseClassOffset(Base);
3249 RD = Base;
3250 }
3251 D.Entries.resize(TruncatedElements);
3252 return true;
3253}
3254
3255static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3256 const CXXRecordDecl *Derived,
3257 const CXXRecordDecl *Base,
3258 const ASTRecordLayout *RL = nullptr) {
3259 if (!RL) {
3260 if (Derived->isInvalidDecl()) return false;
3261 RL = &Info.Ctx.getASTRecordLayout(Derived);
3262 }
3263
3264 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3265 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3266 return true;
3267}
3268
3269static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3270 const CXXRecordDecl *DerivedDecl,
3271 const CXXBaseSpecifier *Base) {
3272 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3273
3274 if (!Base->isVirtual())
3275 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3276
3277 SubobjectDesignator &D = Obj.Designator;
3278 if (D.Invalid)
3279 return false;
3280
3281 // Extract most-derived object and corresponding type.
3282 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3283 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3284 return false;
3285
3286 // Find the virtual base class.
3287 if (DerivedDecl->isInvalidDecl()) return false;
3288 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3289 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3290 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3291 return true;
3292}
3293
3294static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3295 QualType Type, LValue &Result) {
3296 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3297 PathE = E->path_end();
3298 PathI != PathE; ++PathI) {
3299 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3300 *PathI))
3301 return false;
3302 Type = (*PathI)->getType();
3303 }
3304 return true;
3305}
3306
3307/// Cast an lvalue referring to a derived class to a known base subobject.
3308static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3309 const CXXRecordDecl *DerivedRD,
3310 const CXXRecordDecl *BaseRD) {
3311 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3312 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3313 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3314 llvm_unreachable("Class must be derived from the passed in base class!");
3315
3316 for (CXXBasePathElement &Elem : Paths.front())
3317 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3318 return false;
3319 return true;
3320}
3321
3322/// Update LVal to refer to the given field, which must be a member of the type
3323/// currently described by LVal.
3324static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3325 const FieldDecl *FD,
3326 const ASTRecordLayout *RL = nullptr) {
3327 if (!RL) {
3328 if (FD->getParent()->isInvalidDecl()) return false;
3329 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3330 }
3331
3332 unsigned I = FD->getFieldIndex();
3333 LVal.addDecl(Info, E, FD);
3334 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3335 return true;
3336}
3337
3338/// Update LVal to refer to the given indirect field.
3339static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3340 LValue &LVal,
3341 const IndirectFieldDecl *IFD) {
3342 for (const auto *C : IFD->chain())
3343 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3344 return false;
3345 return true;
3346}
3347
3348enum class SizeOfType {
3349 SizeOf,
3350 DataSizeOf,
3351};
3352
3353/// Get the size of the given type in char units.
3354static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3355 CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3356 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3357 // extension.
3358 if (Type->isVoidType() || Type->isFunctionType()) {
3359 Size = CharUnits::One();
3360 return true;
3361 }
3362
3363 if (Type->isDependentType()) {
3364 Info.FFDiag(Loc);
3365 return false;
3366 }
3367
3368 if (!Type->isConstantSizeType()) {
3369 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3370 // FIXME: Better diagnostic.
3371 Info.FFDiag(Loc);
3372 return false;
3373 }
3374
3375 if (SOT == SizeOfType::SizeOf)
3376 Size = Info.Ctx.getTypeSizeInChars(Type);
3377 else
3378 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3379 return true;
3380}
3381
3382/// Update a pointer value to model pointer arithmetic.
3383/// \param Info - Information about the ongoing evaluation.
3384/// \param E - The expression being evaluated, for diagnostic purposes.
3385/// \param LVal - The pointer value to be updated.
3386/// \param EltTy - The pointee type represented by LVal.
3387/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3388static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3389 LValue &LVal, QualType EltTy,
3390 APSInt Adjustment) {
3391 CharUnits SizeOfPointee;
3392 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3393 return false;
3394
3395 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3396 return true;
3397}
3398
3399static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3400 LValue &LVal, QualType EltTy,
3401 int64_t Adjustment) {
3402 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3403 APSInt::get(Adjustment));
3404}
3405
3406/// Update an lvalue to refer to a component of a complex number.
3407/// \param Info - Information about the ongoing evaluation.
3408/// \param LVal - The lvalue to be updated.
3409/// \param EltTy - The complex number's component type.
3410/// \param Imag - False for the real component, true for the imaginary.
3411static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3412 LValue &LVal, QualType EltTy,
3413 bool Imag) {
3414 if (Imag) {
3415 CharUnits SizeOfComponent;
3416 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3417 return false;
3418 LVal.Offset += SizeOfComponent;
3419 }
3420 LVal.addComplex(Info, E, EltTy, Imag);
3421 return true;
3422}
3423
3424static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3425 LValue &LVal, QualType EltTy,
3426 uint64_t Size, uint64_t Idx) {
3427 if (Idx) {
3428 CharUnits SizeOfElement;
3429 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3430 return false;
3431 LVal.Offset += SizeOfElement * Idx;
3432 }
3433 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3434 return true;
3435}
3436
3437/// Try to evaluate the initializer for a variable declaration.
3438///
3439/// \param Info Information about the ongoing evaluation.
3440/// \param E An expression to be used when printing diagnostics.
3441/// \param VD The variable whose initializer should be obtained.
3442/// \param Version The version of the variable within the frame.
3443/// \param Frame The frame in which the variable was created. Must be null
3444/// if this variable is not local to the evaluation.
3445/// \param Result Filled in with a pointer to the value of the variable.
3446static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3447 const VarDecl *VD, CallStackFrame *Frame,
3448 unsigned Version, APValue *&Result) {
3449 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3450
3451 // If this is a local variable, dig out its value.
3452 if (Frame) {
3453 Result = Frame->getTemporary(VD, Version);
3454 if (Result)
3455 return true;
3456
3457 if (!isa<ParmVarDecl>(VD)) {
3458 // Assume variables referenced within a lambda's call operator that were
3459 // not declared within the call operator are captures and during checking
3460 // of a potential constant expression, assume they are unknown constant
3461 // expressions.
3462 assert(isLambdaCallOperator(Frame->Callee) &&
3463 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3464 "missing value for local variable");
3465 if (Info.checkingPotentialConstantExpression())
3466 return false;
3467 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3468 // still reachable at all?
3469 Info.FFDiag(E->getBeginLoc(),
3470 diag::note_unimplemented_constexpr_lambda_feature_ast)
3471 << "captures not currently allowed";
3472 return false;
3473 }
3474 }
3475
3476 // If we're currently evaluating the initializer of this declaration, use that
3477 // in-flight value.
3478 if (Info.EvaluatingDecl == Base) {
3479 Result = Info.EvaluatingDeclValue;
3480 return true;
3481 }
3482
3483 if (isa<ParmVarDecl>(VD)) {
3484 // Assume parameters of a potential constant expression are usable in
3485 // constant expressions.
3486 if (!Info.checkingPotentialConstantExpression() ||
3487 !Info.CurrentCall->Callee ||
3488 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3489 if (Info.getLangOpts().CPlusPlus11) {
3490 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3491 << VD;
3492 NoteLValueLocation(Info, Base);
3493 } else {
3494 Info.FFDiag(E);
3495 }
3496 }
3497 return false;
3498 }
3499
3500 if (E->isValueDependent())
3501 return false;
3502
3503 // Dig out the initializer, and use the declaration which it's attached to.
3504 // FIXME: We should eventually check whether the variable has a reachable
3505 // initializing declaration.
3506 const Expr *Init = VD->getAnyInitializer(VD);
3507 if (!Init) {
3508 // Don't diagnose during potential constant expression checking; an
3509 // initializer might be added later.
3510 if (!Info.checkingPotentialConstantExpression()) {
3511 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3512 << VD;
3513 NoteLValueLocation(Info, Base);
3514 }
3515 return false;
3516 }
3517
3518 if (Init->isValueDependent()) {
3519 // The DeclRefExpr is not value-dependent, but the variable it refers to
3520 // has a value-dependent initializer. This should only happen in
3521 // constant-folding cases, where the variable is not actually of a suitable
3522 // type for use in a constant expression (otherwise the DeclRefExpr would
3523 // have been value-dependent too), so diagnose that.
3524 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3525 if (!Info.checkingPotentialConstantExpression()) {
3526 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3527 ? diag::note_constexpr_ltor_non_constexpr
3528 : diag::note_constexpr_ltor_non_integral, 1)
3529 << VD << VD->getType();
3530 NoteLValueLocation(Info, Base);
3531 }
3532 return false;
3533 }
3534
3535 // Check that we can fold the initializer. In C++, we will have already done
3536 // this in the cases where it matters for conformance.
3537 if (!VD->evaluateValue()) {
3538 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3539 NoteLValueLocation(Info, Base);
3540 return false;
3541 }
3542
3543 // Check that the variable is actually usable in constant expressions. For a
3544 // const integral variable or a reference, we might have a non-constant
3545 // initializer that we can nonetheless evaluate the initializer for. Such
3546 // variables are not usable in constant expressions. In C++98, the
3547 // initializer also syntactically needs to be an ICE.
3548 //
3549 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3550 // expressions here; doing so would regress diagnostics for things like
3551 // reading from a volatile constexpr variable.
3552 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3553 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3554 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3555 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3556 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3557 NoteLValueLocation(Info, Base);
3558 }
3559
3560 // Never use the initializer of a weak variable, not even for constant
3561 // folding. We can't be sure that this is the definition that will be used.
3562 if (VD->isWeak()) {
3563 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3564 NoteLValueLocation(Info, Base);
3565 return false;
3566 }
3567
3568 Result = VD->getEvaluatedValue();
3569 return true;
3570}
3571
3572/// Get the base index of the given base class within an APValue representing
3573/// the given derived class.
3574static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3575 const CXXRecordDecl *Base) {
3576 Base = Base->getCanonicalDecl();
3577 unsigned Index = 0;
3579 E = Derived->bases_end(); I != E; ++I, ++Index) {
3580 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3581 return Index;
3582 }
3583
3584 llvm_unreachable("base class missing from derived class's bases list");
3585}
3586
3587/// Extract the value of a character from a string literal.
3588static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3589 uint64_t Index) {
3590 assert(!isa<SourceLocExpr>(Lit) &&
3591 "SourceLocExpr should have already been converted to a StringLiteral");
3592
3593 // FIXME: Support MakeStringConstant
3594 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3595 std::string Str;
3596 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3597 assert(Index <= Str.size() && "Index too large");
3598 return APSInt::getUnsigned(Str.c_str()[Index]);
3599 }
3600
3601 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3602 Lit = PE->getFunctionName();
3603 const StringLiteral *S = cast<StringLiteral>(Lit);
3604 const ConstantArrayType *CAT =
3605 Info.Ctx.getAsConstantArrayType(S->getType());
3606 assert(CAT && "string literal isn't an array");
3607 QualType CharType = CAT->getElementType();
3608 assert(CharType->isIntegerType() && "unexpected character type");
3609 APSInt Value(Info.Ctx.getTypeSize(CharType),
3610 CharType->isUnsignedIntegerType());
3611 if (Index < S->getLength())
3612 Value = S->getCodeUnit(Index);
3613 return Value;
3614}
3615
3616// Expand a string literal into an array of characters.
3617//
3618// FIXME: This is inefficient; we should probably introduce something similar
3619// to the LLVM ConstantDataArray to make this cheaper.
3620static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3621 APValue &Result,
3622 QualType AllocType = QualType()) {
3623 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3624 AllocType.isNull() ? S->getType() : AllocType);
3625 assert(CAT && "string literal isn't an array");
3626 QualType CharType = CAT->getElementType();
3627 assert(CharType->isIntegerType() && "unexpected character type");
3628
3629 unsigned Elts = CAT->getZExtSize();
3630 Result = APValue(APValue::UninitArray(),
3631 std::min(S->getLength(), Elts), Elts);
3632 APSInt Value(Info.Ctx.getTypeSize(CharType),
3633 CharType->isUnsignedIntegerType());
3634 if (Result.hasArrayFiller())
3635 Result.getArrayFiller() = APValue(Value);
3636 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3637 Value = S->getCodeUnit(I);
3638 Result.getArrayInitializedElt(I) = APValue(Value);
3639 }
3640}
3641
3642// Expand an array so that it has more than Index filled elements.
3643static void expandArray(APValue &Array, unsigned Index) {
3644 unsigned Size = Array.getArraySize();
3645 assert(Index < Size);
3646
3647 // Always at least double the number of elements for which we store a value.
3648 unsigned OldElts = Array.getArrayInitializedElts();
3649 unsigned NewElts = std::max(Index+1, OldElts * 2);
3650 NewElts = std::min(Size, std::max(NewElts, 8u));
3651
3652 // Copy the data across.
3653 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3654 for (unsigned I = 0; I != OldElts; ++I)
3655 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3656 for (unsigned I = OldElts; I != NewElts; ++I)
3657 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3658 if (NewValue.hasArrayFiller())
3659 NewValue.getArrayFiller() = Array.getArrayFiller();
3660 Array.swap(NewValue);
3661}
3662
3663/// Determine whether a type would actually be read by an lvalue-to-rvalue
3664/// conversion. If it's of class type, we may assume that the copy operation
3665/// is trivial. Note that this is never true for a union type with fields
3666/// (because the copy always "reads" the active member) and always true for
3667/// a non-class type.
3668static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3671 return !RD || isReadByLvalueToRvalueConversion(RD);
3672}
3674 // FIXME: A trivial copy of a union copies the object representation, even if
3675 // the union is empty.
3676 if (RD->isUnion())
3677 return !RD->field_empty();
3678 if (RD->isEmpty())
3679 return false;
3680
3681 for (auto *Field : RD->fields())
3682 if (!Field->isUnnamedBitField() &&
3683 isReadByLvalueToRvalueConversion(Field->getType()))
3684 return true;
3685
3686 for (auto &BaseSpec : RD->bases())
3687 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3688 return true;
3689
3690 return false;
3691}
3692
3693/// Diagnose an attempt to read from any unreadable field within the specified
3694/// type, which might be a class type.
3695static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3696 QualType T) {
3698 if (!RD)
3699 return false;
3700
3701 if (!RD->hasMutableFields())
3702 return false;
3703
3704 for (auto *Field : RD->fields()) {
3705 // If we're actually going to read this field in some way, then it can't
3706 // be mutable. If we're in a union, then assigning to a mutable field
3707 // (even an empty one) can change the active member, so that's not OK.
3708 // FIXME: Add core issue number for the union case.
3709 if (Field->isMutable() &&
3710 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3711 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3712 Info.Note(Field->getLocation(), diag::note_declared_at);
3713 return true;
3714 }
3715
3716 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3717 return true;
3718 }
3719
3720 for (auto &BaseSpec : RD->bases())
3721 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3722 return true;
3723
3724 // All mutable fields were empty, and thus not actually read.
3725 return false;
3726}
3727
3728static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3730 bool MutableSubobject = false) {
3731 // A temporary or transient heap allocation we created.
3732 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3733 return true;
3734
3735 switch (Info.IsEvaluatingDecl) {
3736 case EvalInfo::EvaluatingDeclKind::None:
3737 return false;
3738
3739 case EvalInfo::EvaluatingDeclKind::Ctor:
3740 // The variable whose initializer we're evaluating.
3741 if (Info.EvaluatingDecl == Base)
3742 return true;
3743
3744 // A temporary lifetime-extended by the variable whose initializer we're
3745 // evaluating.
3746 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3747 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3748 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3749 return false;
3750
3751 case EvalInfo::EvaluatingDeclKind::Dtor:
3752 // C++2a [expr.const]p6:
3753 // [during constant destruction] the lifetime of a and its non-mutable
3754 // subobjects (but not its mutable subobjects) [are] considered to start
3755 // within e.
3756 if (MutableSubobject || Base != Info.EvaluatingDecl)
3757 return false;
3758 // FIXME: We can meaningfully extend this to cover non-const objects, but
3759 // we will need special handling: we should be able to access only
3760 // subobjects of such objects that are themselves declared const.
3761 QualType T = getType(Base);
3762 return T.isConstQualified() || T->isReferenceType();
3763 }
3764
3765 llvm_unreachable("unknown evaluating decl kind");
3766}
3767
3768static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3769 SourceLocation CallLoc = {}) {
3770 return Info.CheckArraySize(
3771 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3772 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3773 /*Diag=*/true);
3774}
3775
3776namespace {
3777/// A handle to a complete object (an object that is not a subobject of
3778/// another object).
3779struct CompleteObject {
3780 /// The identity of the object.
3782 /// The value of the complete object.
3783 APValue *Value;
3784 /// The type of the complete object.
3785 QualType Type;
3786
3787 CompleteObject() : Value(nullptr) {}
3789 : Base(Base), Value(Value), Type(Type) {}
3790
3791 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3792 // If this isn't a "real" access (eg, if it's just accessing the type
3793 // info), allow it. We assume the type doesn't change dynamically for
3794 // subobjects of constexpr objects (even though we'd hit UB here if it
3795 // did). FIXME: Is this right?
3796 if (!isAnyAccess(AK))
3797 return true;
3798
3799 // In C++14 onwards, it is permitted to read a mutable member whose
3800 // lifetime began within the evaluation.
3801 // FIXME: Should we also allow this in C++11?
3802 if (!Info.getLangOpts().CPlusPlus14 &&
3803 AK != AccessKinds::AK_IsWithinLifetime)
3804 return false;
3805 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3806 }
3807
3808 explicit operator bool() const { return !Type.isNull(); }
3809};
3810} // end anonymous namespace
3811
3812static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3813 bool IsMutable = false) {
3814 // C++ [basic.type.qualifier]p1:
3815 // - A const object is an object of type const T or a non-mutable subobject
3816 // of a const object.
3817 if (ObjType.isConstQualified() && !IsMutable)
3818 SubobjType.addConst();
3819 // - A volatile object is an object of type const T or a subobject of a
3820 // volatile object.
3821 if (ObjType.isVolatileQualified())
3822 SubobjType.addVolatile();
3823 return SubobjType;
3824}
3825
3826/// Find the designated sub-object of an rvalue.
3827template <typename SubobjectHandler>
3828static typename SubobjectHandler::result_type
3829findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3830 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3831 if (Sub.Invalid)
3832 // A diagnostic will have already been produced.
3833 return handler.failed();
3834 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3835 if (Info.getLangOpts().CPlusPlus11)
3836 Info.FFDiag(E, Sub.isOnePastTheEnd()
3837 ? diag::note_constexpr_access_past_end
3838 : diag::note_constexpr_access_unsized_array)
3839 << handler.AccessKind;
3840 else
3841 Info.FFDiag(E);
3842 return handler.failed();
3843 }
3844
3845 APValue *O = Obj.Value;
3846 QualType ObjType = Obj.Type;
3847 const FieldDecl *LastField = nullptr;
3848 const FieldDecl *VolatileField = nullptr;
3849
3850 // Walk the designator's path to find the subobject.
3851 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3852 // Reading an indeterminate value is undefined, but assigning over one is OK.
3853 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3854 (O->isIndeterminate() &&
3855 !isValidIndeterminateAccess(handler.AccessKind))) {
3856 // Object has ended lifetime.
3857 // If I is non-zero, some subobject (member or array element) of a
3858 // complete object has ended its lifetime, so this is valid for
3859 // IsWithinLifetime, resulting in false.
3860 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
3861 return false;
3862 if (!Info.checkingPotentialConstantExpression())
3863 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3864 << handler.AccessKind << O->isIndeterminate()
3865 << E->getSourceRange();
3866 return handler.failed();
3867 }
3868
3869 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3870 // const and volatile semantics are not applied on an object under
3871 // {con,de}struction.
3872 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3873 ObjType->isRecordType() &&
3874 Info.isEvaluatingCtorDtor(
3875 Obj.Base,
3876 llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3877 ConstructionPhase::None) {
3878 ObjType = Info.Ctx.getCanonicalType(ObjType);
3879 ObjType.removeLocalConst();
3880 ObjType.removeLocalVolatile();
3881 }
3882
3883 // If this is our last pass, check that the final object type is OK.
3884 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3885 // Accesses to volatile objects are prohibited.
3886 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3887 if (Info.getLangOpts().CPlusPlus) {
3888 int DiagKind;
3890 const NamedDecl *Decl = nullptr;
3891 if (VolatileField) {
3892 DiagKind = 2;
3893 Loc = VolatileField->getLocation();
3894 Decl = VolatileField;
3895 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3896 DiagKind = 1;
3897 Loc = VD->getLocation();
3898 Decl = VD;
3899 } else {
3900 DiagKind = 0;
3901 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3902 Loc = E->getExprLoc();
3903 }
3904 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3905 << handler.AccessKind << DiagKind << Decl;
3906 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3907 } else {
3908 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3909 }
3910 return handler.failed();
3911 }
3912
3913 // If we are reading an object of class type, there may still be more
3914 // things we need to check: if there are any mutable subobjects, we
3915 // cannot perform this read. (This only happens when performing a trivial
3916 // copy or assignment.)
3917 if (ObjType->isRecordType() &&
3918 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3919 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3920 return handler.failed();
3921 }
3922
3923 if (I == N) {
3924 if (!handler.found(*O, ObjType))
3925 return false;
3926
3927 // If we modified a bit-field, truncate it to the right width.
3928 if (isModification(handler.AccessKind) &&
3929 LastField && LastField->isBitField() &&
3930 !truncateBitfieldValue(Info, E, *O, LastField))
3931 return false;
3932
3933 return true;
3934 }
3935
3936 LastField = nullptr;
3937 if (ObjType->isArrayType()) {
3938 // Next subobject is an array element.
3939 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3940 assert(CAT && "vla in literal type?");
3941 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3942 if (CAT->getSize().ule(Index)) {
3943 // Note, it should not be possible to form a pointer with a valid
3944 // designator which points more than one past the end of the array.
3945 if (Info.getLangOpts().CPlusPlus11)
3946 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3947 << handler.AccessKind;
3948 else
3949 Info.FFDiag(E);
3950 return handler.failed();
3951 }
3952
3953 ObjType = CAT->getElementType();
3954
3955 if (O->getArrayInitializedElts() > Index)
3956 O = &O->getArrayInitializedElt(Index);
3957 else if (!isRead(handler.AccessKind)) {
3958 if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3959 return handler.failed();
3960
3961 expandArray(*O, Index);
3962 O = &O->getArrayInitializedElt(Index);
3963 } else
3964 O = &O->getArrayFiller();
3965 } else if (ObjType->isAnyComplexType()) {
3966 // Next subobject is a complex number.
3967 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3968 if (Index > 1) {
3969 if (Info.getLangOpts().CPlusPlus11)
3970 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3971 << handler.AccessKind;
3972 else
3973 Info.FFDiag(E);
3974 return handler.failed();
3975 }
3976
3977 ObjType = getSubobjectType(
3978 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3979
3980 assert(I == N - 1 && "extracting subobject of scalar?");
3981 if (O->isComplexInt()) {
3982 return handler.found(Index ? O->getComplexIntImag()
3983 : O->getComplexIntReal(), ObjType);
3984 } else {
3985 assert(O->isComplexFloat());
3986 return handler.found(Index ? O->getComplexFloatImag()
3987 : O->getComplexFloatReal(), ObjType);
3988 }
3989 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
3990 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3991 unsigned NumElements = VT->getNumElements();
3992 if (Index == NumElements) {
3993 if (Info.getLangOpts().CPlusPlus11)
3994 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3995 << handler.AccessKind;
3996 else
3997 Info.FFDiag(E);
3998 return handler.failed();
3999 }
4000
4001 if (Index > NumElements) {
4002 Info.CCEDiag(E, diag::note_constexpr_array_index)
4003 << Index << /*array*/ 0 << NumElements;
4004 return handler.failed();
4005 }
4006
4007 ObjType = VT->getElementType();
4008 assert(I == N - 1 && "extracting subobject of scalar?");
4009 return handler.found(O->getVectorElt(Index), ObjType);
4010 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4011 if (Field->isMutable() &&
4012 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4013 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4014 << handler.AccessKind << Field;
4015 Info.Note(Field->getLocation(), diag::note_declared_at);
4016 return handler.failed();
4017 }
4018
4019 // Next subobject is a class, struct or union field.
4020 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
4021 if (RD->isUnion()) {
4022 const FieldDecl *UnionField = O->getUnionField();
4023 if (!UnionField ||
4024 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4025 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4026 // Placement new onto an inactive union member makes it active.
4027 O->setUnion(Field, APValue());
4028 } else {
4029 // Pointer to/into inactive union member: Not within lifetime
4030 if (handler.AccessKind == AK_IsWithinLifetime)
4031 return false;
4032 // FIXME: If O->getUnionValue() is absent, report that there's no
4033 // active union member rather than reporting the prior active union
4034 // member. We'll need to fix nullptr_t to not use APValue() as its
4035 // representation first.
4036 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4037 << handler.AccessKind << Field << !UnionField << UnionField;
4038 return handler.failed();
4039 }
4040 }
4041 O = &O->getUnionValue();
4042 } else
4043 O = &O->getStructField(Field->getFieldIndex());
4044
4045 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4046 LastField = Field;
4047 if (Field->getType().isVolatileQualified())
4048 VolatileField = Field;
4049 } else {
4050 // Next subobject is a base class.
4051 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4052 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4053 O = &O->getStructBase(getBaseIndex(Derived, Base));
4054
4055 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
4056 }
4057 }
4058}
4059
4060namespace {
4061struct ExtractSubobjectHandler {
4062 EvalInfo &Info;
4063 const Expr *E;
4064 APValue &Result;
4065 const AccessKinds AccessKind;
4066
4067 typedef bool result_type;
4068 bool failed() { return false; }
4069 bool found(APValue &Subobj, QualType SubobjType) {
4070 Result = Subobj;
4071 if (AccessKind == AK_ReadObjectRepresentation)
4072 return true;
4073 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4074 }
4075 bool found(APSInt &Value, QualType SubobjType) {
4076 Result = APValue(Value);
4077 return true;
4078 }
4079 bool found(APFloat &Value, QualType SubobjType) {
4080 Result = APValue(Value);
4081 return true;
4082 }
4083};
4084} // end anonymous namespace
4085
4086/// Extract the designated sub-object of an rvalue.
4087static bool extractSubobject(EvalInfo &Info, const Expr *E,
4088 const CompleteObject &Obj,
4089 const SubobjectDesignator &Sub, APValue &Result,
4090 AccessKinds AK = AK_Read) {
4091 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4092 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4093 return findSubobject(Info, E, Obj, Sub, Handler);
4094}
4095
4096namespace {
4097struct ModifySubobjectHandler {
4098 EvalInfo &Info;
4099 APValue &NewVal;
4100 const Expr *E;
4101
4102 typedef bool result_type;
4103 static const AccessKinds AccessKind = AK_Assign;
4104
4105 bool checkConst(QualType QT) {
4106 // Assigning to a const object has undefined behavior.
4107 if (QT.isConstQualified()) {
4108 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4109 return false;
4110 }
4111 return true;
4112 }
4113
4114 bool failed() { return false; }
4115 bool found(APValue &Subobj, QualType SubobjType) {
4116 if (!checkConst(SubobjType))
4117 return false;
4118 // We've been given ownership of NewVal, so just swap it in.
4119 Subobj.swap(NewVal);
4120 return true;
4121 }
4122 bool found(APSInt &Value, QualType SubobjType) {
4123 if (!checkConst(SubobjType))
4124 return false;
4125 if (!NewVal.isInt()) {
4126 // Maybe trying to write a cast pointer value into a complex?
4127 Info.FFDiag(E);
4128 return false;
4129 }
4130 Value = NewVal.getInt();
4131 return true;
4132 }
4133 bool found(APFloat &Value, QualType SubobjType) {
4134 if (!checkConst(SubobjType))
4135 return false;
4136 Value = NewVal.getFloat();
4137 return true;
4138 }
4139};
4140} // end anonymous namespace
4141
4142const AccessKinds ModifySubobjectHandler::AccessKind;
4143
4144/// Update the designated sub-object of an rvalue to the given value.
4145static bool modifySubobject(EvalInfo &Info, const Expr *E,
4146 const CompleteObject &Obj,
4147 const SubobjectDesignator &Sub,
4148 APValue &NewVal) {
4149 ModifySubobjectHandler Handler = { Info, NewVal, E };
4150 return findSubobject(Info, E, Obj, Sub, Handler);
4151}
4152
4153/// Find the position where two subobject designators diverge, or equivalently
4154/// the length of the common initial subsequence.
4155static unsigned FindDesignatorMismatch(QualType ObjType,
4156 const SubobjectDesignator &A,
4157 const SubobjectDesignator &B,
4158 bool &WasArrayIndex) {
4159 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4160 for (/**/; I != N; ++I) {
4161 if (!ObjType.isNull() &&
4162 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4163 // Next subobject is an array element.
4164 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4165 WasArrayIndex = true;
4166 return I;
4167 }
4168 if (ObjType->isAnyComplexType())
4169 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4170 else
4171 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4172 } else {
4173 if (A.Entries[I].getAsBaseOrMember() !=
4174 B.Entries[I].getAsBaseOrMember()) {
4175 WasArrayIndex = false;
4176 return I;
4177 }
4178 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4179 // Next subobject is a field.
4180 ObjType = FD->getType();
4181 else
4182 // Next subobject is a base class.
4183 ObjType = QualType();
4184 }
4185 }
4186 WasArrayIndex = false;
4187 return I;
4188}
4189
4190/// Determine whether the given subobject designators refer to elements of the
4191/// same array object.
4193 const SubobjectDesignator &A,
4194 const SubobjectDesignator &B) {
4195 if (A.Entries.size() != B.Entries.size())
4196 return false;
4197
4198 bool IsArray = A.MostDerivedIsArrayElement;
4199 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4200 // A is a subobject of the array element.
4201 return false;
4202
4203 // If A (and B) designates an array element, the last entry will be the array
4204 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4205 // of length 1' case, and the entire path must match.
4206 bool WasArrayIndex;
4207 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4208 return CommonLength >= A.Entries.size() - IsArray;
4209}
4210
4211/// Find the complete object to which an LValue refers.
4212static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4213 AccessKinds AK, const LValue &LVal,
4214 QualType LValType) {
4215 if (LVal.InvalidBase) {
4216 Info.FFDiag(E);
4217 return CompleteObject();
4218 }
4219
4220 if (!LVal.Base) {
4221 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4222 return CompleteObject();
4223 }
4224
4225 CallStackFrame *Frame = nullptr;
4226 unsigned Depth = 0;
4227 if (LVal.getLValueCallIndex()) {
4228 std::tie(Frame, Depth) =
4229 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4230 if (!Frame) {
4231 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4232 << AK << LVal.Base.is<const ValueDecl*>();
4233 NoteLValueLocation(Info, LVal.Base);
4234 return CompleteObject();
4235 }
4236 }
4237
4238 bool IsAccess = isAnyAccess(AK);
4239
4240 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4241 // is not a constant expression (even if the object is non-volatile). We also
4242 // apply this rule to C++98, in order to conform to the expected 'volatile'
4243 // semantics.
4244 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4245 if (Info.getLangOpts().CPlusPlus)
4246 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4247 << AK << LValType;
4248 else
4249 Info.FFDiag(E);
4250 return CompleteObject();
4251 }
4252
4253 // Compute value storage location and type of base object.
4254 APValue *BaseVal = nullptr;
4255 QualType BaseType = getType(LVal.Base);
4256
4257 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4258 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4259 // This is the object whose initializer we're evaluating, so its lifetime
4260 // started in the current evaluation.
4261 BaseVal = Info.EvaluatingDeclValue;
4262 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4263 // Allow reading from a GUID declaration.
4264 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4265 if (isModification(AK)) {
4266 // All the remaining cases do not permit modification of the object.
4267 Info.FFDiag(E, diag::note_constexpr_modify_global);
4268 return CompleteObject();
4269 }
4270 APValue &V = GD->getAsAPValue();
4271 if (V.isAbsent()) {
4272 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4273 << GD->getType();
4274 return CompleteObject();
4275 }
4276 return CompleteObject(LVal.Base, &V, GD->getType());
4277 }
4278
4279 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4280 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4281 if (isModification(AK)) {
4282 Info.FFDiag(E, diag::note_constexpr_modify_global);
4283 return CompleteObject();
4284 }
4285 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4286 GCD->getType());
4287 }
4288
4289 // Allow reading from template parameter objects.
4290 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4291 if (isModification(AK)) {
4292 Info.FFDiag(E, diag::note_constexpr_modify_global);
4293 return CompleteObject();
4294 }
4295 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4296 TPO->getType());
4297 }
4298
4299 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4300 // In C++11, constexpr, non-volatile variables initialized with constant
4301 // expressions are constant expressions too. Inside constexpr functions,
4302 // parameters are constant expressions even if they're non-const.
4303 // In C++1y, objects local to a constant expression (those with a Frame) are
4304 // both readable and writable inside constant expressions.
4305 // In C, such things can also be folded, although they are not ICEs.
4306 const VarDecl *VD = dyn_cast<VarDecl>(D);
4307 if (VD) {
4308 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4309 VD = VDef;
4310 }
4311 if (!VD || VD->isInvalidDecl()) {
4312 Info.FFDiag(E);
4313 return CompleteObject();
4314 }
4315
4316 bool IsConstant = BaseType.isConstant(Info.Ctx);
4317 bool ConstexprVar = false;
4318 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4319 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4320 ConstexprVar = VD->isConstexpr();
4321
4322 // Unless we're looking at a local variable or argument in a constexpr call,
4323 // the variable we're reading must be const.
4324 if (!Frame) {
4325 if (IsAccess && isa<ParmVarDecl>(VD)) {
4326 // Access of a parameter that's not associated with a frame isn't going
4327 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4328 // suitable diagnostic.
4329 } else if (Info.getLangOpts().CPlusPlus14 &&
4330 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4331 // OK, we can read and modify an object if we're in the process of
4332 // evaluating its initializer, because its lifetime began in this
4333 // evaluation.
4334 } else if (isModification(AK)) {
4335 // All the remaining cases do not permit modification of the object.
4336 Info.FFDiag(E, diag::note_constexpr_modify_global);
4337 return CompleteObject();
4338 } else if (VD->isConstexpr()) {
4339 // OK, we can read this variable.
4340 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4341 Info.FFDiag(E);
4342 return CompleteObject();
4343 } else if (BaseType->isIntegralOrEnumerationType()) {
4344 if (!IsConstant) {
4345 if (!IsAccess)
4346 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4347 if (Info.getLangOpts().CPlusPlus) {
4348 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4349 Info.Note(VD->getLocation(), diag::note_declared_at);
4350 } else {
4351 Info.FFDiag(E);
4352 }
4353 return CompleteObject();
4354 }
4355 } else if (!IsAccess) {
4356 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4357 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4358 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4359 // This variable might end up being constexpr. Don't diagnose it yet.
4360 } else if (IsConstant) {
4361 // Keep evaluating to see what we can do. In particular, we support
4362 // folding of const floating-point types, in order to make static const
4363 // data members of such types (supported as an extension) more useful.
4364 if (Info.getLangOpts().CPlusPlus) {
4365 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4366 ? diag::note_constexpr_ltor_non_constexpr
4367 : diag::note_constexpr_ltor_non_integral, 1)
4368 << VD << BaseType;
4369 Info.Note(VD->getLocation(), diag::note_declared_at);
4370 } else {
4371 Info.CCEDiag(E);
4372 }
4373 } else {
4374 // Never allow reading a non-const value.
4375 if (Info.getLangOpts().CPlusPlus) {
4376 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4377 ? diag::note_constexpr_ltor_non_constexpr
4378 : diag::note_constexpr_ltor_non_integral, 1)
4379 << VD << BaseType;
4380 Info.Note(VD->getLocation(), diag::note_declared_at);
4381 } else {
4382 Info.FFDiag(E);
4383 }
4384 return CompleteObject();
4385 }
4386 }
4387
4388 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4389 return CompleteObject();
4390 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4391 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4392 if (!Alloc) {
4393 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4394 return CompleteObject();
4395 }
4396 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4397 LVal.Base.getDynamicAllocType());
4398 } else {
4399 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4400
4401 if (!Frame) {
4402 if (const MaterializeTemporaryExpr *MTE =
4403 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4404 assert(MTE->getStorageDuration() == SD_Static &&
4405 "should have a frame for a non-global materialized temporary");
4406
4407 // C++20 [expr.const]p4: [DR2126]
4408 // An object or reference is usable in constant expressions if it is
4409 // - a temporary object of non-volatile const-qualified literal type
4410 // whose lifetime is extended to that of a variable that is usable
4411 // in constant expressions
4412 //
4413 // C++20 [expr.const]p5:
4414 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4415 // - a non-volatile glvalue that refers to an object that is usable
4416 // in constant expressions, or
4417 // - a non-volatile glvalue of literal type that refers to a
4418 // non-volatile object whose lifetime began within the evaluation
4419 // of E;
4420 //
4421 // C++11 misses the 'began within the evaluation of e' check and
4422 // instead allows all temporaries, including things like:
4423 // int &&r = 1;
4424 // int x = ++r;
4425 // constexpr int k = r;
4426 // Therefore we use the C++14-onwards rules in C++11 too.
4427 //
4428 // Note that temporaries whose lifetimes began while evaluating a
4429 // variable's constructor are not usable while evaluating the
4430 // corresponding destructor, not even if they're of const-qualified
4431 // types.
4432 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4433 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4434 if (!IsAccess)
4435 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4436 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4437 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4438 return CompleteObject();
4439 }
4440
4441 BaseVal = MTE->getOrCreateValue(false);
4442 assert(BaseVal && "got reference to unevaluated temporary");
4443 } else {
4444 if (!IsAccess)
4445 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4446 APValue Val;
4447 LVal.moveInto(Val);
4448 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4449 << AK
4450 << Val.getAsString(Info.Ctx,
4451 Info.Ctx.getLValueReferenceType(LValType));
4452 NoteLValueLocation(Info, LVal.Base);
4453 return CompleteObject();
4454 }
4455 } else {
4456 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4457 assert(BaseVal && "missing value for temporary");
4458 }
4459 }
4460
4461 // In C++14, we can't safely access any mutable state when we might be
4462 // evaluating after an unmodeled side effect. Parameters are modeled as state
4463 // in the caller, but aren't visible once the call returns, so they can be
4464 // modified in a speculatively-evaluated call.
4465 //
4466 // FIXME: Not all local state is mutable. Allow local constant subobjects
4467 // to be read here (but take care with 'mutable' fields).
4468 unsigned VisibleDepth = Depth;
4469 if (llvm::isa_and_nonnull<ParmVarDecl>(
4470 LVal.Base.dyn_cast<const ValueDecl *>()))
4471 ++VisibleDepth;
4472 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4473 Info.EvalStatus.HasSideEffects) ||
4474 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4475 return CompleteObject();
4476
4477 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4478}
4479
4480/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4481/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4482/// glvalue referred to by an entity of reference type.
4483///
4484/// \param Info - Information about the ongoing evaluation.
4485/// \param Conv - The expression for which we are performing the conversion.
4486/// Used for diagnostics.
4487/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4488/// case of a non-class type).
4489/// \param LVal - The glvalue on which we are attempting to perform this action.
4490/// \param RVal - The produced value will be placed here.
4491/// \param WantObjectRepresentation - If true, we're looking for the object
4492/// representation rather than the value, and in particular,
4493/// there is no requirement that the result be fully initialized.
4494static bool
4496 const LValue &LVal, APValue &RVal,
4497 bool WantObjectRepresentation = false) {
4498 if (LVal.Designator.Invalid)
4499 return false;
4500
4501 // Check for special cases where there is no existing APValue to look at.
4502 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4503
4504 AccessKinds AK =
4505 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4506
4507 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4508 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4509 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4510 // initializer until now for such expressions. Such an expression can't be
4511 // an ICE in C, so this only matters for fold.
4512 if (Type.isVolatileQualified()) {
4513 Info.FFDiag(Conv);
4514 return false;
4515 }
4516
4517 APValue Lit;
4518 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4519 return false;
4520
4521 // According to GCC info page:
4522 //
4523 // 6.28 Compound Literals
4524 //
4525 // As an optimization, G++ sometimes gives array compound literals longer
4526 // lifetimes: when the array either appears outside a function or has a
4527 // const-qualified type. If foo and its initializer had elements of type
4528 // char *const rather than char *, or if foo were a global variable, the
4529 // array would have static storage duration. But it is probably safest
4530 // just to avoid the use of array compound literals in C++ code.
4531 //
4532 // Obey that rule by checking constness for converted array types.
4533
4534 QualType CLETy = CLE->getType();
4535 if (CLETy->isArrayType() && !Type->isArrayType()) {
4536 if (!CLETy.isConstant(Info.Ctx)) {
4537 Info.FFDiag(Conv);
4538 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4539 return false;
4540 }
4541 }
4542
4543 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4544 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4545 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4546 // Special-case character extraction so we don't have to construct an
4547 // APValue for the whole string.
4548 assert(LVal.Designator.Entries.size() <= 1 &&
4549 "Can only read characters from string literals");
4550 if (LVal.Designator.Entries.empty()) {
4551 // Fail for now for LValue to RValue conversion of an array.
4552 // (This shouldn't show up in C/C++, but it could be triggered by a
4553 // weird EvaluateAsRValue call from a tool.)
4554 Info.FFDiag(Conv);
4555 return false;
4556 }
4557 if (LVal.Designator.isOnePastTheEnd()) {
4558 if (Info.getLangOpts().CPlusPlus11)
4559 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4560 else
4561 Info.FFDiag(Conv);
4562 return false;
4563 }
4564 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4565 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4566 return true;
4567 }
4568 }
4569
4570 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4571 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4572}
4573
4574/// Perform an assignment of Val to LVal. Takes ownership of Val.
4575static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4576 QualType LValType, APValue &Val) {
4577 if (LVal.Designator.Invalid)
4578 return false;
4579
4580 if (!Info.getLangOpts().CPlusPlus14) {
4581 Info.FFDiag(E);
4582 return false;
4583 }
4584
4585 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4586 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4587}
4588
4589namespace {
4590struct CompoundAssignSubobjectHandler {
4591 EvalInfo &Info;
4593 QualType PromotedLHSType;
4595 const APValue &RHS;
4596
4597 static const AccessKinds AccessKind = AK_Assign;
4598
4599 typedef bool result_type;
4600
4601 bool checkConst(QualType QT) {
4602 // Assigning to a const object has undefined behavior.
4603 if (QT.isConstQualified()) {
4604 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4605 return false;
4606 }
4607 return true;
4608 }
4609
4610 bool failed() { return false; }
4611 bool found(APValue &Subobj, QualType SubobjType) {
4612 switch (Subobj.getKind()) {
4613 case APValue::Int:
4614 return found(Subobj.getInt(), SubobjType);
4615 case APValue::Float:
4616 return found(Subobj.getFloat(), SubobjType);
4619 // FIXME: Implement complex compound assignment.
4620 Info.FFDiag(E);
4621 return false;
4622 case APValue::LValue:
4623 return foundPointer(Subobj, SubobjType);
4624 case APValue::Vector:
4625 return foundVector(Subobj, SubobjType);
4627 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4628 << /*read of=*/0 << /*uninitialized object=*/1
4629 << E->getLHS()->getSourceRange();
4630 return false;
4631 default:
4632 // FIXME: can this happen?
4633 Info.FFDiag(E);
4634 return false;
4635 }
4636 }
4637
4638 bool foundVector(APValue &Value, QualType SubobjType) {
4639 if (!checkConst(SubobjType))
4640 return false;
4641
4642 if (!SubobjType->isVectorType()) {
4643 Info.FFDiag(E);
4644 return false;
4645 }
4646 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4647 }
4648
4649 bool found(APSInt &Value, QualType SubobjType) {
4650 if (!checkConst(SubobjType))
4651 return false;
4652
4653 if (!SubobjType->isIntegerType()) {
4654 // We don't support compound assignment on integer-cast-to-pointer
4655 // values.
4656 Info.FFDiag(E);
4657 return false;
4658 }
4659
4660 if (RHS.isInt()) {
4661 APSInt LHS =
4662 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4663 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4664 return false;
4665 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4666 return true;
4667 } else if (RHS.isFloat()) {
4668 const FPOptions FPO = E->getFPFeaturesInEffect(
4669 Info.Ctx.getLangOpts());
4670 APFloat FValue(0.0);
4671 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4672 PromotedLHSType, FValue) &&
4673 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4674 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4675 Value);
4676 }
4677
4678 Info.FFDiag(E);
4679 return false;
4680 }
4681 bool found(APFloat &Value, QualType SubobjType) {
4682 return checkConst(SubobjType) &&
4683 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4684 Value) &&
4685 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4686 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4687 }
4688 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4689 if (!checkConst(SubobjType))
4690 return false;
4691
4692 QualType PointeeType;
4693 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4694 PointeeType = PT->getPointeeType();
4695
4696 if (PointeeType.isNull() || !RHS.isInt() ||
4697 (Opcode != BO_Add && Opcode != BO_Sub)) {
4698 Info.FFDiag(E);
4699 return false;
4700 }
4701
4702 APSInt Offset = RHS.getInt();
4703 if (Opcode == BO_Sub)
4704 negateAsSigned(Offset);
4705
4706 LValue LVal;
4707 LVal.setFrom(Info.Ctx, Subobj);
4708 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4709 return false;
4710 LVal.moveInto(Subobj);
4711 return true;
4712 }
4713};
4714} // end anonymous namespace
4715
4716const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4717
4718/// Perform a compound assignment of LVal <op>= RVal.
4719static bool handleCompoundAssignment(EvalInfo &Info,
4721 const LValue &LVal, QualType LValType,
4722 QualType PromotedLValType,
4723 BinaryOperatorKind Opcode,
4724 const APValue &RVal) {
4725 if (LVal.Designator.Invalid)
4726 return false;
4727
4728 if (!Info.getLangOpts().CPlusPlus14) {
4729 Info.FFDiag(E);
4730 return false;
4731 }
4732
4733 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4734 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4735 RVal };
4736 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4737}
4738
4739namespace {
4740struct IncDecSubobjectHandler {
4741 EvalInfo &Info;
4742 const UnaryOperator *E;
4743 AccessKinds AccessKind;
4744 APValue *Old;
4745
4746 typedef bool result_type;
4747
4748 bool checkConst(QualType QT) {
4749 // Assigning to a const object has undefined behavior.
4750 if (QT.isConstQualified()) {
4751 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4752 return false;
4753 }
4754 return true;
4755 }
4756
4757 bool failed() { return false; }
4758 bool found(APValue &Subobj, QualType SubobjType) {
4759 // Stash the old value. Also clear Old, so we don't clobber it later
4760 // if we're post-incrementing a complex.
4761 if (Old) {
4762 *Old = Subobj;
4763 Old = nullptr;
4764 }
4765
4766 switch (Subobj.getKind()) {
4767 case APValue::Int:
4768 return found(Subobj.getInt(), SubobjType);
4769 case APValue::Float:
4770 return found(Subobj.getFloat(), SubobjType);
4772 return found(Subobj.getComplexIntReal(),
4773 SubobjType->castAs<ComplexType>()->getElementType()
4774 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4776 return found(Subobj.getComplexFloatReal(),
4777 SubobjType->castAs<ComplexType>()->getElementType()
4778 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4779 case APValue::LValue:
4780 return foundPointer(Subobj, SubobjType);
4781 default:
4782 // FIXME: can this happen?
4783 Info.FFDiag(E);
4784 return false;
4785 }
4786 }
4787 bool found(APSInt &Value, QualType SubobjType) {
4788 if (!checkConst(SubobjType))
4789 return false;
4790
4791 if (!SubobjType->isIntegerType()) {
4792 // We don't support increment / decrement on integer-cast-to-pointer
4793 // values.
4794 Info.FFDiag(E);
4795 return false;
4796 }
4797
4798 if (Old) *Old = APValue(Value);
4799
4800 // bool arithmetic promotes to int, and the conversion back to bool
4801 // doesn't reduce mod 2^n, so special-case it.
4802 if (SubobjType->isBooleanType()) {
4803 if (AccessKind == AK_Increment)
4804 Value = 1;
4805 else
4806 Value = !Value;
4807 return true;
4808 }
4809
4810 bool WasNegative = Value.isNegative();
4811 if (AccessKind == AK_Increment) {
4812 ++Value;
4813
4814 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4815 APSInt ActualValue(Value, /*IsUnsigned*/true);
4816 return HandleOverflow(Info, E, ActualValue, SubobjType);
4817 }
4818 } else {
4819 --Value;
4820
4821 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4822 unsigned BitWidth = Value.getBitWidth();
4823 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4824 ActualValue.setBit(BitWidth);
4825 return HandleOverflow(Info, E, ActualValue, SubobjType);
4826 }
4827 }
4828 return true;
4829 }
4830 bool found(APFloat &Value, QualType SubobjType) {
4831 if (!checkConst(SubobjType))
4832 return false;
4833
4834 if (Old) *Old = APValue(Value);
4835
4836 APFloat One(Value.getSemantics(), 1);
4837 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4838 APFloat::opStatus St;
4839 if (AccessKind == AK_Increment)
4840 St = Value.add(One, RM);
4841 else
4842 St = Value.subtract(One, RM);
4843 return checkFloatingPointResult(Info, E, St);
4844 }
4845 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4846 if (!checkConst(SubobjType))
4847 return false;
4848
4849 QualType PointeeType;
4850 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4851 PointeeType = PT->getPointeeType();
4852 else {
4853 Info.FFDiag(E);
4854 return false;
4855 }
4856
4857 LValue LVal;
4858 LVal.setFrom(Info.Ctx, Subobj);
4859 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4860 AccessKind == AK_Increment ? 1 : -1))
4861 return false;
4862 LVal.moveInto(Subobj);
4863 return true;
4864 }
4865};
4866} // end anonymous namespace
4867
4868/// Perform an increment or decrement on LVal.
4869static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4870 QualType LValType, bool IsIncrement, APValue *Old) {
4871 if (LVal.Designator.Invalid)
4872 return false;
4873
4874 if (!Info.getLangOpts().CPlusPlus14) {
4875 Info.FFDiag(E);
4876 return false;
4877 }
4878
4879 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4880 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4881 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4882 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4883}
4884
4885/// Build an lvalue for the object argument of a member function call.
4886static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4887 LValue &This) {
4888 if (Object->getType()->isPointerType() && Object->isPRValue())
4889 return EvaluatePointer(Object, This, Info);
4890
4891 if (Object->isGLValue())
4892 return EvaluateLValue(Object, This, Info);
4893
4894 if (Object->getType()->isLiteralType(Info.Ctx))
4895 return EvaluateTemporary(Object, This, Info);
4896
4897 if (Object->getType()->isRecordType() && Object->isPRValue())
4898 return EvaluateTemporary(Object, This, Info);
4899
4900 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4901 return false;
4902}
4903
4904/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4905/// lvalue referring to the result.
4906///
4907/// \param Info - Information about the ongoing evaluation.
4908/// \param LV - An lvalue referring to the base of the member pointer.
4909/// \param RHS - The member pointer expression.
4910/// \param IncludeMember - Specifies whether the member itself is included in
4911/// the resulting LValue subobject designator. This is not possible when
4912/// creating a bound member function.
4913/// \return The field or method declaration to which the member pointer refers,
4914/// or 0 if evaluation fails.
4915static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4916 QualType LVType,
4917 LValue &LV,
4918 const Expr *RHS,
4919 bool IncludeMember = true) {
4920 MemberPtr MemPtr;
4921 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4922 return nullptr;
4923
4924 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4925 // member value, the behavior is undefined.
4926 if (!MemPtr.getDecl()) {
4927 // FIXME: Specific diagnostic.
4928 Info.FFDiag(RHS);
4929 return nullptr;
4930 }
4931
4932 if (MemPtr.isDerivedMember()) {
4933 // This is a member of some derived class. Truncate LV appropriately.
4934 // The end of the derived-to-base path for the base object must match the
4935 // derived-to-base path for the member pointer.
4936 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4937 LV.Designator.Entries.size()) {
4938 Info.FFDiag(RHS);
4939 return nullptr;
4940 }
4941 unsigned PathLengthToMember =
4942 LV.Designator.Entries.size() - MemPtr.Path.size();
4943 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4944 const CXXRecordDecl *LVDecl = getAsBaseClass(
4945 LV.Designator.Entries[PathLengthToMember + I]);
4946 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4947 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4948 Info.FFDiag(RHS);
4949 return nullptr;
4950 }
4951 }
4952
4953 // Truncate the lvalue to the appropriate derived class.
4954 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4955 PathLengthToMember))
4956 return nullptr;
4957 } else if (!MemPtr.Path.empty()) {
4958 // Extend the LValue path with the member pointer's path.
4959 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4960 MemPtr.Path.size() + IncludeMember);
4961
4962 // Walk down to the appropriate base class.
4963 if (const PointerType *PT = LVType->getAs<PointerType>())
4964 LVType = PT->getPointeeType();
4965 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4966 assert(RD && "member pointer access on non-class-type expression");
4967 // The first class in the path is that of the lvalue.
4968 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4969 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4970 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4971 return nullptr;
4972 RD = Base;
4973 }
4974 // Finally cast to the class containing the member.
4975 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4976 MemPtr.getContainingRecord()))
4977 return nullptr;
4978 }
4979
4980 // Add the member. Note that we cannot build bound member functions here.
4981 if (IncludeMember) {
4982 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4983 if (!HandleLValueMember(Info, RHS, LV, FD))
4984 return nullptr;
4985 } else if (const IndirectFieldDecl *IFD =
4986 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4987 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4988 return nullptr;
4989 } else {
4990 llvm_unreachable("can't construct reference to bound member function");
4991 }
4992 }
4993
4994 return MemPtr.getDecl();
4995}
4996
4997static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4998 const BinaryOperator *BO,
4999 LValue &LV,
5000 bool IncludeMember = true) {
5001 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5002
5003 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5004 if (Info.noteFailure()) {
5005 MemberPtr MemPtr;
5006 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5007 }
5008 return nullptr;
5009 }
5010
5011 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5012 BO->getRHS(), IncludeMember);
5013}
5014
5015/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5016/// the provided lvalue, which currently refers to the base object.
5017static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5018 LValue &Result) {
5019 SubobjectDesignator &D = Result.Designator;
5020 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5021 return false;
5022
5023 QualType TargetQT = E->getType();
5024 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5025 TargetQT = PT->getPointeeType();
5026
5027 // Check this cast lands within the final derived-to-base subobject path.
5028 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
5029 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5030 << D.MostDerivedType << TargetQT;
5031 return false;
5032 }
5033
5034 // Check the type of the final cast. We don't need to check the path,
5035 // since a cast can only be formed if the path is unique.
5036 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5037 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5038 const CXXRecordDecl *FinalType;
5039 if (NewEntriesSize == D.MostDerivedPathLength)
5040 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5041 else
5042 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5043 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
5044 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5045 << D.MostDerivedType << TargetQT;
5046 return false;
5047 }
5048
5049 // Truncate the lvalue to the appropriate derived class.
5050 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5051}
5052
5053/// Get the value to use for a default-initialized object of type T.
5054/// Return false if it encounters something invalid.
5056 bool Success = true;
5057
5058 // If there is already a value present don't overwrite it.
5059 if (!Result.isAbsent())
5060 return true;
5061
5062 if (auto *RD = T->getAsCXXRecordDecl()) {
5063 if (RD->isInvalidDecl()) {
5064 Result = APValue();
5065 return false;
5066 }
5067 if (RD->isUnion()) {
5068 Result = APValue((const FieldDecl *)nullptr);
5069 return true;
5070 }
5071 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5072 std::distance(RD->field_begin(), RD->field_end()));
5073
5074 unsigned Index = 0;
5075 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5076 End = RD->bases_end();
5077 I != End; ++I, ++Index)
5078 Success &=
5079 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5080
5081 for (const auto *I : RD->fields()) {
5082 if (I->isUnnamedBitField())
5083 continue;
5085 I->getType(), Result.getStructField(I->getFieldIndex()));
5086 }
5087 return Success;
5088 }
5089
5090 if (auto *AT =
5091 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5092 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5093 if (Result.hasArrayFiller())
5094 Success &=
5095 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5096
5097 return Success;
5098 }
5099
5100 Result = APValue::IndeterminateValue();
5101 return true;
5102}
5103
5104namespace {
5105enum EvalStmtResult {
5106 /// Evaluation failed.
5107 ESR_Failed,
5108 /// Hit a 'return' statement.
5109 ESR_Returned,
5110 /// Evaluation succeeded.
5111 ESR_Succeeded,
5112 /// Hit a 'continue' statement.
5113 ESR_Continue,
5114 /// Hit a 'break' statement.
5115 ESR_Break,
5116 /// Still scanning for 'case' or 'default' statement.
5117 ESR_CaseNotFound
5118};
5119}
5120
5121static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5122 if (VD->isInvalidDecl())
5123 return false;
5124 // We don't need to evaluate the initializer for a static local.
5125 if (!VD->hasLocalStorage())
5126 return true;
5127
5128 LValue Result;
5129 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5130 ScopeKind::Block, Result);
5131
5132 const Expr *InitE = VD->getInit();
5133 if (!InitE) {
5134 if (VD->getType()->isDependentType())
5135 return Info.noteSideEffect();
5136 return handleDefaultInitValue(VD->getType(), Val);
5137 }
5138 if (InitE->isValueDependent())
5139 return false;
5140
5141 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5142 // Wipe out any partially-computed value, to allow tracking that this
5143 // evaluation failed.
5144 Val = APValue();
5145 return false;
5146 }
5147
5148 return true;
5149}
5150
5151static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
5152 bool OK = true;
5153
5154 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5155 OK &= EvaluateVarDecl(Info, VD);
5156
5157 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
5158 for (auto *BD : DD->bindings())
5159 if (auto *VD = BD->getHoldingVar())
5160 OK &= EvaluateDecl(Info, VD);
5161
5162 return OK;
5163}
5164
5165static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5166 assert(E->isValueDependent());
5167 if (Info.noteSideEffect())
5168 return true;
5169 assert(E->containsErrors() && "valid value-dependent expression should never "
5170 "reach invalid code path.");
5171 return false;
5172}
5173
5174/// Evaluate a condition (either a variable declaration or an expression).
5175static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5176 const Expr *Cond, bool &Result) {
5177 if (Cond->isValueDependent())
5178 return false;
5179 FullExpressionRAII Scope(Info);
5180 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5181 return false;
5182 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5183 return false;
5184 return Scope.destroy();
5185}
5186
5187namespace {
5188/// A location where the result (returned value) of evaluating a
5189/// statement should be stored.
5190struct StmtResult {
5191 /// The APValue that should be filled in with the returned value.
5192 APValue &Value;
5193 /// The location containing the result, if any (used to support RVO).
5194 const LValue *Slot;
5195};
5196
5197struct TempVersionRAII {
5198 CallStackFrame &Frame;
5199
5200 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5201 Frame.pushTempVersion();
5202 }
5203
5204 ~TempVersionRAII() {
5205 Frame.popTempVersion();
5206 }
5207};
5208
5209}
5210
5211static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5212 const Stmt *S,
5213 const SwitchCase *SC = nullptr);
5214
5215/// Evaluate the body of a loop, and translate the result as appropriate.
5216static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5217 const Stmt *Body,
5218 const SwitchCase *Case = nullptr) {
5219 BlockScopeRAII Scope(Info);
5220
5221 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5222 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5223 ESR = ESR_Failed;
5224
5225 switch (ESR) {
5226 case ESR_Break:
5227 return ESR_Succeeded;
5228 case ESR_Succeeded:
5229 case ESR_Continue:
5230 return ESR_Continue;
5231 case ESR_Failed:
5232 case ESR_Returned:
5233 case ESR_CaseNotFound:
5234 return ESR;
5235 }
5236 llvm_unreachable("Invalid EvalStmtResult!");
5237}
5238
5239/// Evaluate a switch statement.
5240static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5241 const SwitchStmt *SS) {
5242 BlockScopeRAII Scope(Info);
5243
5244 // Evaluate the switch condition.
5245 APSInt Value;
5246 {
5247 if (const Stmt *Init = SS->getInit()) {
5248 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5249 if (ESR != ESR_Succeeded) {
5250 if (ESR != ESR_Failed && !Scope.destroy())
5251 ESR = ESR_Failed;
5252 return ESR;
5253 }
5254 }
5255
5256 FullExpressionRAII CondScope(Info);
5257 if (SS->getConditionVariable() &&
5258 !EvaluateDecl(Info, SS->getConditionVariable()))
5259 return ESR_Failed;
5260 if (SS->getCond()->isValueDependent()) {
5261 // We don't know what the value is, and which branch should jump to.
5262 EvaluateDependentExpr(SS->getCond(), Info);
5263 return ESR_Failed;
5264 }
5265 if (!EvaluateInteger(SS->getCond(), Value, Info))
5266 return ESR_Failed;
5267
5268 if (!CondScope.destroy())
5269 return ESR_Failed;
5270 }
5271
5272 // Find the switch case corresponding to the value of the condition.
5273 // FIXME: Cache this lookup.
5274 const SwitchCase *Found = nullptr;
5275 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5276 SC = SC->getNextSwitchCase()) {
5277 if (isa<DefaultStmt>(SC)) {
5278 Found = SC;
5279 continue;
5280 }
5281
5282 const CaseStmt *CS = cast<CaseStmt>(SC);
5283 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5284 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5285 : LHS;
5286 if (LHS <= Value && Value <= RHS) {
5287 Found = SC;
5288 break;
5289 }
5290 }
5291
5292 if (!Found)
5293 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5294
5295 // Search the switch body for the switch case and evaluate it from there.
5296 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5297 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5298 return ESR_Failed;
5299
5300 switch (ESR) {
5301 case ESR_Break:
5302 return ESR_Succeeded;
5303 case ESR_Succeeded:
5304 case ESR_Continue:
5305 case ESR_Failed:
5306 case ESR_Returned:
5307 return ESR;
5308 case ESR_CaseNotFound:
5309 // This can only happen if the switch case is nested within a statement
5310 // expression. We have no intention of supporting that.
5311 Info.FFDiag(Found->getBeginLoc(),
5312 diag::note_constexpr_stmt_expr_unsupported);
5313 return ESR_Failed;
5314 }
5315 llvm_unreachable("Invalid EvalStmtResult!");
5316}
5317
5318static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5319 // An expression E is a core constant expression unless the evaluation of E
5320 // would evaluate one of the following: [C++23] - a control flow that passes
5321 // through a declaration of a variable with static or thread storage duration
5322 // unless that variable is usable in constant expressions.
5323 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5324 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5325 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5326 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5327 return false;
5328 }
5329 return true;
5330}
5331
5332// Evaluate a statement.
5333static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5334 const Stmt *S, const SwitchCase *Case) {
5335 if (!Info.nextStep(S))
5336 return ESR_Failed;
5337
5338 // If we're hunting down a 'case' or 'default' label, recurse through
5339 // substatements until we hit the label.
5340 if (Case) {
5341 switch (S->getStmtClass()) {
5342 case Stmt::CompoundStmtClass:
5343 // FIXME: Precompute which substatement of a compound statement we
5344 // would jump to, and go straight there rather than performing a
5345 // linear scan each time.
5346 case Stmt::LabelStmtClass:
5347 case Stmt::AttributedStmtClass:
5348 case Stmt::DoStmtClass:
5349 break;
5350
5351 case Stmt::CaseStmtClass:
5352 case Stmt::DefaultStmtClass:
5353 if (Case == S)
5354 Case = nullptr;
5355 break;
5356
5357 case Stmt::IfStmtClass: {
5358 // FIXME: Precompute which side of an 'if' we would jump to, and go
5359 // straight there rather than scanning both sides.
5360 const IfStmt *IS = cast<IfStmt>(S);
5361
5362 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5363 // preceded by our switch label.
5364 BlockScopeRAII Scope(Info);
5365
5366 // Step into the init statement in case it brings an (uninitialized)
5367 // variable into scope.
5368 if (const Stmt *Init = IS->getInit()) {
5369 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5370 if (ESR != ESR_CaseNotFound) {
5371 assert(ESR != ESR_Succeeded);
5372 return ESR;
5373 }
5374 }
5375
5376 // Condition variable must be initialized if it exists.
5377 // FIXME: We can skip evaluating the body if there's a condition
5378 // variable, as there can't be any case labels within it.
5379 // (The same is true for 'for' statements.)
5380
5381 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5382 if (ESR == ESR_Failed)
5383 return ESR;
5384 if (ESR != ESR_CaseNotFound)
5385 return Scope.destroy() ? ESR : ESR_Failed;
5386 if (!IS->getElse())
5387 return ESR_CaseNotFound;
5388
5389 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5390 if (ESR == ESR_Failed)
5391 return ESR;
5392 if (ESR != ESR_CaseNotFound)
5393 return Scope.destroy() ? ESR : ESR_Failed;
5394 return ESR_CaseNotFound;
5395 }
5396
5397 case Stmt::WhileStmtClass: {
5398 EvalStmtResult ESR =
5399 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5400 if (ESR != ESR_Continue)
5401 return ESR;
5402 break;
5403 }
5404
5405 case Stmt::ForStmtClass: {
5406 const ForStmt *FS = cast<ForStmt>(S);
5407 BlockScopeRAII Scope(Info);
5408
5409 // Step into the init statement in case it brings an (uninitialized)
5410 // variable into scope.
5411 if (const Stmt *Init = FS->getInit()) {
5412 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5413 if (ESR != ESR_CaseNotFound) {
5414 assert(ESR != ESR_Succeeded);
5415 return ESR;
5416 }
5417 }
5418
5419 EvalStmtResult ESR =
5420 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5421 if (ESR != ESR_Continue)
5422 return ESR;
5423 if (const auto *Inc = FS->getInc()) {
5424 if (Inc->isValueDependent()) {
5425 if (!EvaluateDependentExpr(Inc, Info))
5426 return ESR_Failed;
5427 } else {
5428 FullExpressionRAII IncScope(Info);
5429 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5430 return ESR_Failed;
5431 }
5432 }
5433 break;
5434 }
5435
5436 case Stmt::DeclStmtClass: {
5437 // Start the lifetime of any uninitialized variables we encounter. They
5438 // might be used by the selected branch of the switch.
5439 const DeclStmt *DS = cast<DeclStmt>(S);
5440 for (const auto *D : DS->decls()) {
5441 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5442 if (!CheckLocalVariableDeclaration(Info, VD))
5443 return ESR_Failed;
5444 if (VD->hasLocalStorage() && !VD->getInit())
5445 if (!EvaluateVarDecl(Info, VD))
5446 return ESR_Failed;
5447 // FIXME: If the variable has initialization that can't be jumped
5448 // over, bail out of any immediately-surrounding compound-statement
5449 // too. There can't be any case labels here.
5450 }
5451 }
5452 return ESR_CaseNotFound;
5453 }
5454
5455 default:
5456 return ESR_CaseNotFound;
5457 }
5458 }
5459
5460 switch (S->getStmtClass()) {
5461 default:
5462 if (const Expr *E = dyn_cast<Expr>(S)) {
5463 if (E->isValueDependent()) {
5464 if (!EvaluateDependentExpr(E, Info))
5465 return ESR_Failed;
5466 } else {
5467 // Don't bother evaluating beyond an expression-statement which couldn't
5468 // be evaluated.
5469 // FIXME: Do we need the FullExpressionRAII object here?
5470 // VisitExprWithCleanups should create one when necessary.
5471 FullExpressionRAII Scope(Info);
5472 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5473 return ESR_Failed;
5474 }
5475 return ESR_Succeeded;
5476 }
5477
5478 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5479 return ESR_Failed;
5480
5481 case Stmt::NullStmtClass:
5482 return ESR_Succeeded;
5483
5484 case Stmt::DeclStmtClass: {
5485 const DeclStmt *DS = cast<DeclStmt>(S);
5486 for (const auto *D : DS->decls()) {
5487 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5488 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5489 return ESR_Failed;
5490 // Each declaration initialization is its own full-expression.
5491 FullExpressionRAII Scope(Info);
5492 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5493 return ESR_Failed;
5494 if (!Scope.destroy())
5495 return ESR_Failed;
5496 }
5497 return ESR_Succeeded;
5498 }
5499
5500 case Stmt::ReturnStmtClass: {
5501 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5502 FullExpressionRAII Scope(Info);
5503 if (RetExpr && RetExpr->isValueDependent()) {
5504 EvaluateDependentExpr(RetExpr, Info);
5505 // We know we returned, but we don't know what the value is.
5506 return ESR_Failed;
5507 }
5508 if (RetExpr &&
5509 !(Result.Slot
5510 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5511 : Evaluate(Result.Value, Info, RetExpr)))
5512 return ESR_Failed;
5513 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5514 }
5515
5516 case Stmt::CompoundStmtClass: {
5517 BlockScopeRAII Scope(Info);
5518
5519 const CompoundStmt *CS = cast<CompoundStmt>(S);
5520 for (const auto *BI : CS->body()) {
5521 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5522 if (ESR == ESR_Succeeded)
5523 Case = nullptr;
5524 else if (ESR != ESR_CaseNotFound) {
5525 if (ESR != ESR_Failed && !Scope.destroy())
5526 return ESR_Failed;
5527 return ESR;
5528 }
5529 }
5530 if (Case)
5531 return ESR_CaseNotFound;
5532 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5533 }
5534
5535 case Stmt::IfStmtClass: {
5536 const IfStmt *IS = cast<IfStmt>(S);
5537
5538 // Evaluate the condition, as either a var decl or as an expression.
5539 BlockScopeRAII Scope(Info);
5540 if (const Stmt *Init = IS->getInit()) {
5541 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5542 if (ESR != ESR_Succeeded) {
5543 if (ESR != ESR_Failed && !Scope.destroy())
5544 return ESR_Failed;
5545 return ESR;
5546 }
5547 }
5548 bool Cond;
5549 if (IS->isConsteval()) {
5550 Cond = IS->isNonNegatedConsteval();
5551 // If we are not in a constant context, if consteval should not evaluate
5552 // to true.
5553 if (!Info.InConstantContext)
5554 Cond = !Cond;
5555 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5556 Cond))
5557 return ESR_Failed;
5558
5559 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5560 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5561 if (ESR != ESR_Succeeded) {
5562 if (ESR != ESR_Failed && !Scope.destroy())
5563 return ESR_Failed;
5564 return ESR;
5565 }
5566 }
5567 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5568 }
5569
5570 case Stmt::WhileStmtClass: {
5571 const WhileStmt *WS = cast<WhileStmt>(S);
5572 while (true) {
5573 BlockScopeRAII Scope(Info);
5574 bool Continue;
5575 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5576 Continue))
5577 return ESR_Failed;
5578 if (!Continue)
5579 break;
5580
5581 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5582 if (ESR != ESR_Continue) {
5583 if (ESR != ESR_Failed && !Scope.destroy())
5584 return ESR_Failed;
5585 return ESR;
5586 }
5587 if (!Scope.destroy())
5588 return ESR_Failed;
5589 }
5590 return ESR_Succeeded;
5591 }
5592
5593 case Stmt::DoStmtClass: {
5594 const DoStmt *DS = cast<DoStmt>(S);
5595 bool Continue;
5596 do {
5597 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5598 if (ESR != ESR_Continue)
5599 return ESR;
5600 Case = nullptr;
5601
5602 if (DS->getCond()->isValueDependent()) {
5603 EvaluateDependentExpr(DS->getCond(), Info);
5604 // Bailout as we don't know whether to keep going or terminate the loop.
5605 return ESR_Failed;
5606 }
5607 FullExpressionRAII CondScope(Info);
5608 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5609 !CondScope.destroy())
5610 return ESR_Failed;
5611 } while (Continue);
5612 return ESR_Succeeded;
5613 }
5614
5615 case Stmt::ForStmtClass: {
5616 const ForStmt *FS = cast<ForStmt>(S);
5617 BlockScopeRAII ForScope(Info);
5618 if (FS->getInit()) {
5619 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5620 if (ESR != ESR_Succeeded) {
5621 if (ESR != ESR_Failed && !ForScope.destroy())
5622 return ESR_Failed;
5623 return ESR;
5624 }
5625 }
5626 while (true) {
5627 BlockScopeRAII IterScope(Info);
5628 bool Continue = true;
5629 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5630 FS->getCond(), Continue))
5631 return ESR_Failed;
5632 if (!Continue)
5633 break;
5634
5635 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5636 if (ESR != ESR_Continue) {
5637 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5638 return ESR_Failed;
5639 return ESR;
5640 }
5641
5642 if (const auto *Inc = FS->getInc()) {
5643 if (Inc->isValueDependent()) {
5644 if (!EvaluateDependentExpr(Inc, Info))
5645 return ESR_Failed;
5646 } else {
5647 FullExpressionRAII IncScope(Info);
5648 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5649 return ESR_Failed;
5650 }
5651 }
5652
5653 if (!IterScope.destroy())
5654 return ESR_Failed;
5655 }
5656 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5657 }
5658
5659 case Stmt::CXXForRangeStmtClass: {
5660 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5661 BlockScopeRAII Scope(Info);
5662
5663 // Evaluate the init-statement if present.
5664 if (FS->getInit()) {
5665 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5666 if (ESR != ESR_Succeeded) {
5667 if (ESR != ESR_Failed && !Scope.destroy())
5668 return ESR_Failed;
5669 return ESR;
5670 }
5671 }
5672
5673 // Initialize the __range variable.
5674 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5675 if (ESR != ESR_Succeeded) {
5676 if (ESR != ESR_Failed && !Scope.destroy())
5677 return ESR_Failed;
5678 return ESR;
5679 }
5680
5681 // In error-recovery cases it's possible to get here even if we failed to
5682 // synthesize the __begin and __end variables.
5683 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5684 return ESR_Failed;
5685
5686 // Create the __begin and __end iterators.
5687 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5688 if (ESR != ESR_Succeeded) {
5689 if (ESR != ESR_Failed && !Scope.destroy())
5690 return ESR_Failed;
5691 return ESR;
5692 }
5693 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5694 if (ESR != ESR_Succeeded) {
5695 if (ESR != ESR_Failed && !Scope.destroy())
5696 return ESR_Failed;
5697 return ESR;
5698 }
5699
5700 while (true) {
5701 // Condition: __begin != __end.
5702 {
5703 if (FS->getCond()->isValueDependent()) {
5704 EvaluateDependentExpr(FS->getCond(), Info);
5705 // We don't know whether to keep going or terminate the loop.
5706 return ESR_Failed;
5707 }
5708 bool Continue = true;
5709 FullExpressionRAII CondExpr(Info);
5710 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5711 return ESR_Failed;
5712 if (!Continue)
5713 break;
5714 }
5715
5716 // User's variable declaration, initialized by *__begin.
5717 BlockScopeRAII InnerScope(Info);
5718 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5719 if (ESR != ESR_Succeeded) {
5720 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5721 return ESR_Failed;
5722 return ESR;
5723 }
5724
5725 // Loop body.
5726 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5727 if (ESR != ESR_Continue) {
5728 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5729 return ESR_Failed;
5730 return ESR;
5731 }
5732 if (FS->getInc()->isValueDependent()) {
5733 if (!EvaluateDependentExpr(FS->getInc(), Info))
5734 return ESR_Failed;
5735 } else {
5736 // Increment: ++__begin
5737 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5738 return ESR_Failed;
5739 }
5740
5741 if (!InnerScope.destroy())
5742 return ESR_Failed;
5743 }
5744
5745 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5746 }
5747
5748 case Stmt::SwitchStmtClass:
5749 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5750
5751 case Stmt::ContinueStmtClass:
5752 return ESR_Continue;
5753
5754 case Stmt::BreakStmtClass:
5755 return ESR_Break;
5756
5757 case Stmt::LabelStmtClass:
5758 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5759
5760 case Stmt::AttributedStmtClass: {
5761 const auto *AS = cast<AttributedStmt>(S);
5762 const auto *SS = AS->getSubStmt();
5763 MSConstexprContextRAII ConstexprContext(
5764 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5765 isa<ReturnStmt>(SS));
5766
5767 auto LO = Info.getASTContext().getLangOpts();
5768 if (LO.CXXAssumptions && !LO.MSVCCompat) {
5769 for (auto *Attr : AS->getAttrs()) {
5770 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
5771 if (!AA)
5772 continue;
5773
5774 auto *Assumption = AA->getAssumption();
5775 if (Assumption->isValueDependent())
5776 return ESR_Failed;
5777
5778 if (Assumption->HasSideEffects(Info.getASTContext()))
5779 continue;
5780
5781 bool Value;
5782 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
5783 return ESR_Failed;
5784 if (!Value) {
5785 Info.CCEDiag(Assumption->getExprLoc(),
5786 diag::note_constexpr_assumption_failed);
5787 return ESR_Failed;
5788 }
5789 }
5790 }
5791
5792 return EvaluateStmt(Result, Info, SS, Case);
5793 }
5794
5795 case Stmt::CaseStmtClass:
5796 case Stmt::DefaultStmtClass:
5797 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5798 case Stmt::CXXTryStmtClass:
5799 // Evaluate try blocks by evaluating all sub statements.
5800 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5801 }
5802}
5803
5804/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5805/// default constructor. If so, we'll fold it whether or not it's marked as
5806/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5807/// so we need special handling.
5809 const CXXConstructorDecl *CD,
5810 bool IsValueInitialization) {
5811 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5812 return false;
5813
5814 // Value-initialization does not call a trivial default constructor, so such a
5815 // call is a core constant expression whether or not the constructor is
5816 // constexpr.
5817 if (!CD->isConstexpr() && !IsValueInitialization) {
5818 if (Info.getLangOpts().CPlusPlus11) {
5819 // FIXME: If DiagDecl is an implicitly-declared special member function,
5820 // we should be much more explicit about why it's not constexpr.
5821 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5822 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5823 Info.Note(CD->getLocation(), diag::note_declared_at);
5824 } else {
5825 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5826 }
5827 }
5828 return true;
5829}
5830
5831/// CheckConstexprFunction - Check that a function can be called in a constant
5832/// expression.
5833static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5835 const FunctionDecl *Definition,
5836 const Stmt *Body) {
5837 // Potential constant expressions can contain calls to declared, but not yet
5838 // defined, constexpr functions.
5839 if (Info.checkingPotentialConstantExpression() && !Definition &&
5840 Declaration->isConstexpr())
5841 return false;
5842
5843 // Bail out if the function declaration itself is invalid. We will
5844 // have produced a relevant diagnostic while parsing it, so just
5845 // note the problematic sub-expression.
5846 if (Declaration->isInvalidDecl()) {
5847 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5848 return false;
5849 }
5850
5851 // DR1872: An instantiated virtual constexpr function can't be called in a
5852 // constant expression (prior to C++20). We can still constant-fold such a
5853 // call.
5854 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5855 cast<CXXMethodDecl>(Declaration)->isVirtual())
5856 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5857
5858 if (Definition && Definition->isInvalidDecl()) {
5859 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5860 return false;
5861 }
5862
5863 // Can we evaluate this function call?
5864 if (Definition && Body &&
5865 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
5866 Definition->hasAttr<MSConstexprAttr>())))
5867 return true;
5868
5869 if (Info.getLangOpts().CPlusPlus11) {
5870 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5871
5872 // If this function is not constexpr because it is an inherited
5873 // non-constexpr constructor, diagnose that directly.
5874 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5875 if (CD && CD->isInheritingConstructor()) {
5876 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5877 if (!Inherited->isConstexpr())
5878 DiagDecl = CD = Inherited;
5879 }
5880
5881 // FIXME: If DiagDecl is an implicitly-declared special member function
5882 // or an inheriting constructor, we should be much more explicit about why
5883 // it's not constexpr.
5884 if (CD && CD->isInheritingConstructor())
5885 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5886 << CD->getInheritedConstructor().getConstructor()->getParent();
5887 else
5888 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5889 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5890 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5891 } else {
5892 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5893 }
5894 return false;
5895}
5896
5897namespace {
5898struct CheckDynamicTypeHandler {
5899 AccessKinds AccessKind;
5900 typedef bool result_type;
5901 bool failed() { return false; }
5902 bool found(APValue &Subobj, QualType SubobjType) { return true; }
5903 bool found(APSInt &Value, QualType SubobjType) { return true; }
5904 bool found(APFloat &Value, QualType SubobjType) { return true; }
5905};
5906} // end anonymous namespace
5907
5908/// Check that we can access the notional vptr of an object / determine its
5909/// dynamic type.
5910static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5911 AccessKinds AK, bool Polymorphic) {
5912 if (This.Designator.Invalid)
5913 return false;
5914
5915 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5916
5917 if (!Obj)
5918 return false;
5919
5920 if (!Obj.Value) {
5921 // The object is not usable in constant expressions, so we can't inspect
5922 // its value to see if it's in-lifetime or what the active union members
5923 // are. We can still check for a one-past-the-end lvalue.
5924 if (This.Designator.isOnePastTheEnd() ||
5925 This.Designator.isMostDerivedAnUnsizedArray()) {
5926 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5927 ? diag::note_constexpr_access_past_end
5928 : diag::note_constexpr_access_unsized_array)
5929 << AK;
5930 return false;
5931 } else if (Polymorphic) {
5932 // Conservatively refuse to perform a polymorphic operation if we would
5933 // not be able to read a notional 'vptr' value.
5934 APValue Val;
5935 This.moveInto(Val);
5936 QualType StarThisType =
5937 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5938 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5939 << AK << Val.getAsString(Info.Ctx, StarThisType);
5940 return false;
5941 }
5942 return true;
5943 }
5944
5945 CheckDynamicTypeHandler Handler{AK};
5946 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5947}
5948
5949/// Check that the pointee of the 'this' pointer in a member function call is
5950/// either within its lifetime or in its period of construction or destruction.
5951static bool
5953 const LValue &This,
5954 const CXXMethodDecl *NamedMember) {
5955 return checkDynamicType(
5956 Info, E, This,
5957 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5958}
5959
5961 /// The dynamic class type of the object.
5963 /// The corresponding path length in the lvalue.
5964 unsigned PathLength;
5965};
5966
5967static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5968 unsigned PathLength) {
5969 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5970 Designator.Entries.size() && "invalid path length");
5971 return (PathLength == Designator.MostDerivedPathLength)
5972 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5973 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5974}
5975
5976/// Determine the dynamic type of an object.
5977static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5978 const Expr *E,
5979 LValue &This,
5980 AccessKinds AK) {
5981 // If we don't have an lvalue denoting an object of class type, there is no
5982 // meaningful dynamic type. (We consider objects of non-class type to have no
5983 // dynamic type.)
5984 if (!checkDynamicType(Info, E, This, AK, true))
5985 return std::nullopt;
5986
5987 // Refuse to compute a dynamic type in the presence of virtual bases. This
5988 // shouldn't happen other than in constant-folding situations, since literal
5989 // types can't have virtual bases.
5990 //
5991 // Note that consumers of DynamicType assume that the type has no virtual
5992 // bases, and will need modifications if this restriction is relaxed.
5993 const CXXRecordDecl *Class =
5994 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5995 if (!Class || Class->getNumVBases()) {
5996 Info.FFDiag(E);
5997 return std::nullopt;
5998 }
5999
6000 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6001 // binary search here instead. But the overwhelmingly common case is that
6002 // we're not in the middle of a constructor, so it probably doesn't matter
6003 // in practice.
6004 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6005 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6006 PathLength <= Path.size(); ++PathLength) {
6007 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6008 Path.slice(0, PathLength))) {
6009 case ConstructionPhase::Bases:
6010 case ConstructionPhase::DestroyingBases:
6011 // We're constructing or destroying a base class. This is not the dynamic
6012 // type.
6013 break;
6014
6015 case ConstructionPhase::None:
6016 case ConstructionPhase::AfterBases:
6017 case ConstructionPhase::AfterFields:
6018 case ConstructionPhase::Destroying:
6019 // We've finished constructing the base classes and not yet started
6020 // destroying them again, so this is the dynamic type.
6021 return DynamicType{getBaseClassType(This.Designator, PathLength),
6022 PathLength};
6023 }
6024 }
6025
6026 // CWG issue 1517: we're constructing a base class of the object described by
6027 // 'This', so that object has not yet begun its period of construction and
6028 // any polymorphic operation on it results in undefined behavior.
6029 Info.FFDiag(E);
6030 return std::nullopt;
6031}
6032
6033/// Perform virtual dispatch.
6035 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6036 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6037 std::optional<DynamicType> DynType = ComputeDynamicType(
6038 Info, E, This,
6039 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
6040 if (!DynType)
6041 return nullptr;
6042
6043 // Find the final overrider. It must be declared in one of the classes on the
6044 // path from the dynamic type to the static type.
6045 // FIXME: If we ever allow literal types to have virtual base classes, that
6046 // won't be true.
6047 const CXXMethodDecl *Callee = Found;
6048 unsigned PathLength = DynType->PathLength;
6049 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6050 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6051 const CXXMethodDecl *Overrider =
6052 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6053 if (Overrider) {
6054 Callee = Overrider;
6055 break;
6056 }
6057 }
6058
6059 // C++2a [class.abstract]p6:
6060 // the effect of making a virtual call to a pure virtual function [...] is
6061 // undefined
6062 if (Callee->isPureVirtual()) {
6063 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6064 Info.Note(Callee->getLocation(), diag::note_declared_at);
6065 return nullptr;
6066 }
6067
6068 // If necessary, walk the rest of the path to determine the sequence of
6069 // covariant adjustment steps to apply.
6070 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6071 Found->getReturnType())) {
6072 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6073 for (unsigned CovariantPathLength = PathLength + 1;
6074 CovariantPathLength != This.Designator.Entries.size();
6075 ++CovariantPathLength) {
6076 const CXXRecordDecl *NextClass =
6077 getBaseClassType(This.Designator, CovariantPathLength);
6078 const CXXMethodDecl *Next =
6079 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6080 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6081 Next->getReturnType(), CovariantAdjustmentPath.back()))
6082 CovariantAdjustmentPath.push_back(Next->getReturnType());
6083 }
6084 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6085 CovariantAdjustmentPath.back()))
6086 CovariantAdjustmentPath.push_back(Found->getReturnType());
6087 }
6088
6089 // Perform 'this' adjustment.
6090 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6091 return nullptr;
6092
6093 return Callee;
6094}
6095
6096/// Perform the adjustment from a value returned by a virtual function to
6097/// a value of the statically expected type, which may be a pointer or
6098/// reference to a base class of the returned type.
6099static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6100 APValue &Result,
6102 assert(Result.isLValue() &&
6103 "unexpected kind of APValue for covariant return");
6104 if (Result.isNullPointer())
6105 return true;
6106
6107 LValue LVal;
6108 LVal.setFrom(Info.Ctx, Result);
6109
6110 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6111 for (unsigned I = 1; I != Path.size(); ++I) {
6112 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6113 assert(OldClass && NewClass && "unexpected kind of covariant return");
6114 if (OldClass != NewClass &&
6115 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6116 return false;
6117 OldClass = NewClass;
6118 }
6119
6120 LVal.moveInto(Result);
6121 return true;
6122}
6123
6124/// Determine whether \p Base, which is known to be a direct base class of
6125/// \p Derived, is a public base class.
6126static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6127 const CXXRecordDecl *Base) {
6128 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6129 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6130 if (BaseClass && declaresSameEntity(BaseClass, Base))
6131 return BaseSpec.getAccessSpecifier() == AS_public;
6132 }
6133 llvm_unreachable("Base is not a direct base of Derived");
6134}
6135
6136/// Apply the given dynamic cast operation on the provided lvalue.
6137///
6138/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6139/// to find a suitable target subobject.
6140static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6141 LValue &Ptr) {
6142 // We can't do anything with a non-symbolic pointer value.
6143 SubobjectDesignator &D = Ptr.Designator;
6144 if (D.Invalid)
6145 return false;
6146
6147 // C++ [expr.dynamic.cast]p6:
6148 // If v is a null pointer value, the result is a null pointer value.
6149 if (Ptr.isNullPointer() && !E->isGLValue())
6150 return true;
6151
6152 // For all the other cases, we need the pointer to point to an object within
6153 // its lifetime / period of construction / destruction, and we need to know
6154 // its dynamic type.
6155 std::optional<DynamicType> DynType =
6156 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6157 if (!DynType)
6158 return false;
6159
6160 // C++ [expr.dynamic.cast]p7:
6161 // If T is "pointer to cv void", then the result is a pointer to the most
6162 // derived object
6163 if (E->getType()->isVoidPointerType())
6164 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6165
6166 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
6167 assert(C && "dynamic_cast target is not void pointer nor class");
6168 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
6169
6170 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6171 // C++ [expr.dynamic.cast]p9:
6172 if (!E->isGLValue()) {
6173 // The value of a failed cast to pointer type is the null pointer value
6174 // of the required result type.
6175 Ptr.setNull(Info.Ctx, E->getType());
6176 return true;
6177 }
6178
6179 // A failed cast to reference type throws [...] std::bad_cast.
6180 unsigned DiagKind;
6181 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6182 DynType->Type->isDerivedFrom(C)))
6183 DiagKind = 0;
6184 else if (!Paths || Paths->begin() == Paths->end())
6185 DiagKind = 1;
6186 else if (Paths->isAmbiguous(CQT))
6187 DiagKind = 2;
6188 else {
6189 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6190 DiagKind = 3;
6191 }
6192 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6193 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6194 << Info.Ctx.getRecordType(DynType->Type)
6196 return false;
6197 };
6198
6199 // Runtime check, phase 1:
6200 // Walk from the base subobject towards the derived object looking for the
6201 // target type.
6202 for (int PathLength = Ptr.Designator.Entries.size();
6203 PathLength >= (int)DynType->PathLength; --PathLength) {
6204 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6206 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6207 // We can only walk across public inheritance edges.
6208 if (PathLength > (int)DynType->PathLength &&
6209 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6210 Class))
6211 return RuntimeCheckFailed(nullptr);
6212 }
6213
6214 // Runtime check, phase 2:
6215 // Search the dynamic type for an unambiguous public base of type C.
6216 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6217 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6218 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6219 Paths.front().Access == AS_public) {
6220 // Downcast to the dynamic type...
6221 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6222 return false;
6223 // ... then upcast to the chosen base class subobject.
6224 for (CXXBasePathElement &Elem : Paths.front())
6225 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6226 return false;
6227 return true;
6228 }
6229
6230 // Otherwise, the runtime check fails.
6231 return RuntimeCheckFailed(&Paths);
6232}
6233
6234namespace {
6235struct StartLifetimeOfUnionMemberHandler {
6236 EvalInfo &Info;
6237 const Expr *LHSExpr;
6238 const FieldDecl *Field;
6239 bool DuringInit;
6240 bool Failed = false;
6241 static const AccessKinds AccessKind = AK_Assign;
6242
6243 typedef bool result_type;
6244 bool failed() { return Failed; }
6245 bool found(APValue &Subobj, QualType SubobjType) {
6246 // We are supposed to perform no initialization but begin the lifetime of
6247 // the object. We interpret that as meaning to do what default
6248 // initialization of the object would do if all constructors involved were
6249 // trivial:
6250 // * All base, non-variant member, and array element subobjects' lifetimes
6251 // begin
6252 // * No variant members' lifetimes begin
6253 // * All scalar subobjects whose lifetimes begin have indeterminate values
6254 assert(SubobjType->isUnionType());
6255 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6256 // This union member is already active. If it's also in-lifetime, there's
6257 // nothing to do.
6258 if (Subobj.getUnionValue().hasValue())
6259 return true;
6260 } else if (DuringInit) {
6261 // We're currently in the process of initializing a different union
6262 // member. If we carried on, that initialization would attempt to
6263 // store to an inactive union member, resulting in undefined behavior.
6264 Info.FFDiag(LHSExpr,
6265 diag::note_constexpr_union_member_change_during_init);
6266 return false;
6267 }
6268 APValue Result;
6269 Failed = !handleDefaultInitValue(Field->getType(), Result);
6270 Subobj.setUnion(Field, Result);
6271 return true;
6272 }
6273 bool found(APSInt &Value, QualType SubobjType) {
6274 llvm_unreachable("wrong value kind for union object");
6275 }
6276 bool found(APFloat &Value, QualType SubobjType) {
6277 llvm_unreachable("wrong value kind for union object");
6278 }
6279};
6280} // end anonymous namespace
6281
6282const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6283
6284/// Handle a builtin simple-assignment or a call to a trivial assignment
6285/// operator whose left-hand side might involve a union member access. If it
6286/// does, implicitly start the lifetime of any accessed union elements per
6287/// C++20 [class.union]5.
6288static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6289 const Expr *LHSExpr,
6290 const LValue &LHS) {
6291 if (LHS.InvalidBase || LHS.Designator.Invalid)
6292 return false;
6293
6295 // C++ [class.union]p5:
6296 // define the set S(E) of subexpressions of E as follows:
6297 unsigned PathLength = LHS.Designator.Entries.size();
6298 for (const Expr *E = LHSExpr; E != nullptr;) {
6299 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6300 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6301 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6302 // Note that we can't implicitly start the lifetime of a reference,
6303 // so we don't need to proceed any further if we reach one.
6304 if (!FD || FD->getType()->isReferenceType())
6305 break;
6306
6307 // ... and also contains A.B if B names a union member ...
6308 if (FD->getParent()->isUnion()) {
6309 // ... of a non-class, non-array type, or of a class type with a
6310 // trivial default constructor that is not deleted, or an array of
6311 // such types.
6312 auto *RD =
6313 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6314 if (!RD || RD->hasTrivialDefaultConstructor())
6315 UnionPathLengths.push_back({PathLength - 1, FD});
6316 }
6317
6318 E = ME->getBase();
6319 --PathLength;
6320 assert(declaresSameEntity(FD,
6321 LHS.Designator.Entries[PathLength]
6322 .getAsBaseOrMember().getPointer()));
6323
6324 // -- If E is of the form A[B] and is interpreted as a built-in array
6325 // subscripting operator, S(E) is [S(the array operand, if any)].
6326 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6327 // Step over an ArrayToPointerDecay implicit cast.
6328 auto *Base = ASE->getBase()->IgnoreImplicit();
6329 if (!Base->getType()->isArrayType())
6330 break;
6331
6332 E = Base;
6333 --PathLength;
6334
6335 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6336 // Step over a derived-to-base conversion.
6337 E = ICE->getSubExpr();
6338 if (ICE->getCastKind() == CK_NoOp)
6339 continue;
6340 if (ICE->getCastKind() != CK_DerivedToBase &&
6341 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6342 break;
6343 // Walk path backwards as we walk up from the base to the derived class.
6344 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6345 if (Elt->isVirtual()) {
6346 // A class with virtual base classes never has a trivial default
6347 // constructor, so S(E) is empty in this case.
6348 E = nullptr;
6349 break;
6350 }
6351
6352 --PathLength;
6353 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6354 LHS.Designator.Entries[PathLength]
6355 .getAsBaseOrMember().getPointer()));
6356 }
6357
6358 // -- Otherwise, S(E) is empty.
6359 } else {
6360 break;
6361 }
6362 }
6363
6364 // Common case: no unions' lifetimes are started.
6365 if (UnionPathLengths.empty())
6366 return true;
6367
6368 // if modification of X [would access an inactive union member], an object
6369 // of the type of X is implicitly created
6370 CompleteObject Obj =
6371 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6372 if (!Obj)
6373 return false;
6374 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6375 llvm::reverse(UnionPathLengths)) {
6376 // Form a designator for the union object.
6377 SubobjectDesignator D = LHS.Designator;
6378 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6379
6380 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6381 ConstructionPhase::AfterBases;
6382 StartLifetimeOfUnionMemberHandler StartLifetime{
6383 Info, LHSExpr, LengthAndField.second, DuringInit};
6384 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6385 return false;
6386 }
6387
6388 return true;
6389}
6390
6391static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6392 CallRef Call, EvalInfo &Info,
6393 bool NonNull = false) {
6394 LValue LV;
6395 // Create the parameter slot and register its destruction. For a vararg
6396 // argument, create a temporary.
6397 // FIXME: For calling conventions that destroy parameters in the callee,
6398 // should we consider performing destruction when the function returns
6399 // instead?
6400 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6401 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6402 ScopeKind::Call, LV);
6403 if (!EvaluateInPlace(V, Info, LV, Arg))
6404 return false;
6405
6406 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6407 // undefined behavior, so is non-constant.
6408 if (NonNull && V.isLValue() && V.isNullPointer()) {
6409 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6410 return false;
6411 }
6412
6413 return true;
6414}
6415
6416/// Evaluate the arguments to a function call.
6417static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6418 EvalInfo &Info, const FunctionDecl *Callee,
6419 bool RightToLeft = false) {
6420 bool Success = true;
6421 llvm::SmallBitVector ForbiddenNullArgs;
6422 if (Callee->hasAttr<NonNullAttr>()) {
6423 ForbiddenNullArgs.resize(Args.size());
6424 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6425 if (!Attr->args_size()) {
6426 ForbiddenNullArgs.set();
6427 break;
6428 } else
6429 for (auto Idx : Attr->args()) {
6430 unsigned ASTIdx = Idx.getASTIndex();
6431 if (ASTIdx >= Args.size())
6432 continue;
6433 ForbiddenNullArgs[ASTIdx] = true;
6434 }
6435 }
6436 }
6437 for (unsigned I = 0; I < Args.size(); I++) {
6438 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6439 const ParmVarDecl *PVD =
6440 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6441 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6442 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6443 // If we're checking for a potential constant expression, evaluate all
6444 // initializers even if some of them fail.
6445 if (!Info.noteFailure())
6446 return false;
6447 Success = false;
6448 }
6449 }
6450 return Success;
6451}
6452
6453/// Perform a trivial copy from Param, which is the parameter of a copy or move
6454/// constructor or assignment operator.
6455static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6456 const Expr *E, APValue &Result,
6457 bool CopyObjectRepresentation) {
6458 // Find the reference argument.
6459 CallStackFrame *Frame = Info.CurrentCall;
6460 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6461 if (!RefValue) {
6462 Info.FFDiag(E);
6463 return false;
6464 }
6465
6466 // Copy out the contents of the RHS object.
6467 LValue RefLValue;
6468 RefLValue.setFrom(Info.Ctx, *RefValue);
6470 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6471 CopyObjectRepresentation);
6472}
6473
6474/// Evaluate a function call.
6476 const FunctionDecl *Callee, const LValue *This,
6477 const Expr *E, ArrayRef<const Expr *> Args,
6478 CallRef Call, const Stmt *Body, EvalInfo &Info,
6479 APValue &Result, const LValue *ResultSlot) {
6480 if (!Info.CheckCallLimit(CallLoc))
6481 return false;
6482
6483 CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);
6484
6485 // For a trivial copy or move assignment, perform an APValue copy. This is
6486 // essential for unions, where the operations performed by the assignment
6487 // operator cannot be represented as statements.
6488 //
6489 // Skip this for non-union classes with no fields; in that case, the defaulted
6490 // copy/move does not actually read the object.
6491 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6492 if (MD && MD->isDefaulted() &&
6493 (MD->getParent()->isUnion() ||
6494 (MD->isTrivial() &&
6496 assert(This &&
6498 APValue RHSValue;
6499 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6500 MD->getParent()->isUnion()))
6501 return false;
6502 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6503 RHSValue))
6504 return false;
6505 This->moveInto(Result);
6506 return true;
6507 } else if (MD && isLambdaCallOperator(MD)) {
6508 // We're in a lambda; determine the lambda capture field maps unless we're
6509 // just constexpr checking a lambda's call operator. constexpr checking is
6510 // done before the captures have been added to the closure object (unless
6511 // we're inferring constexpr-ness), so we don't have access to them in this
6512 // case. But since we don't need the captures to constexpr check, we can
6513 // just ignore them.
6514 if (!Info.checkingPotentialConstantExpression())
6515 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6516 Frame.LambdaThisCaptureField);
6517 }
6518
6519 StmtResult Ret = {Result, ResultSlot};
6520 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6521 if (ESR == ESR_Succeeded) {
6522 if (Callee->getReturnType()->isVoidType())
6523 return true;
6524 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6525 }
6526 return ESR == ESR_Returned;
6527}
6528
6529/// Evaluate a constructor call.
6530static bool HandleConstructorCall(const Expr *E, const LValue &This,
6531 CallRef Call,
6533 EvalInfo &Info, APValue &Result) {
6534 SourceLocation CallLoc = E->getExprLoc();
6535 if (!Info.CheckCallLimit(CallLoc))
6536 return false;
6537
6538 const CXXRecordDecl *RD = Definition->getParent();
6539 if (RD->getNumVBases()) {
6540 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6541 return false;
6542 }
6543
6544 EvalInfo::EvaluatingConstructorRAII EvalObj(
6545 Info,
6546 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6547 RD->getNumBases());
6548 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6549
6550 // FIXME: Creating an APValue just to hold a nonexistent return value is
6551 // wasteful.
6552 APValue RetVal;
6553 StmtResult Ret = {RetVal, nullptr};
6554
6555 // If it's a delegating constructor, delegate.
6556 if (Definition->isDelegatingConstructor()) {
6558 if ((*I)->getInit()->isValueDependent()) {
6559 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6560 return false;
6561 } else {
6562 FullExpressionRAII InitScope(Info);
6563 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6564 !InitScope.destroy())
6565 return false;
6566 }
6567 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6568 }
6569
6570 // For a trivial copy or move constructor, perform an APValue copy. This is
6571 // essential for unions (or classes with anonymous union members), where the
6572 // operations performed by the constructor cannot be represented by
6573 // ctor-initializers.
6574 //
6575 // Skip this for empty non-union classes; we should not perform an
6576 // lvalue-to-rvalue conversion on them because their copy constructor does not
6577 // actually read them.
6578 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6579 (Definition->getParent()->isUnion() ||
6580 (Definition->isTrivial() &&
6582 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6583 Definition->getParent()->isUnion());
6584 }
6585
6586 // Reserve space for the struct members.
6587 if (!Result.hasValue()) {
6588 if (!RD->isUnion())
6589 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6590 std::distance(RD->field_begin(), RD->field_end()));
6591 else
6592 // A union starts with no active member.
6593 Result = APValue((const FieldDecl*)nullptr);
6594 }
6595
6596 if (RD->isInvalidDecl()) return false;
6597 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6598
6599 // A scope for temporaries lifetime-extended by reference members.
6600 BlockScopeRAII LifetimeExtendedScope(Info);
6601
6602 bool Success = true;
6603 unsigned BasesSeen = 0;
6604#ifndef NDEBUG
6606#endif
6608 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6609 // We might be initializing the same field again if this is an indirect
6610 // field initialization.
6611 if (FieldIt == RD->field_end() ||
6612 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6613 assert(Indirect && "fields out of order?");
6614 return;
6615 }
6616
6617 // Default-initialize any fields with no explicit initializer.
6618 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6619 assert(FieldIt != RD->field_end() && "missing field?");
6620 if (!FieldIt->isUnnamedBitField())
6622 FieldIt->getType(),
6623 Result.getStructField(FieldIt->getFieldIndex()));
6624 }
6625 ++FieldIt;
6626 };
6627 for (const auto *I : Definition->inits()) {
6628 LValue Subobject = This;
6629 LValue SubobjectParent = This;
6630 APValue *Value = &Result;
6631
6632 // Determine the subobject to initialize.
6633 FieldDecl *FD = nullptr;
6634 if (I->isBaseInitializer()) {
6635 QualType BaseType(I->getBaseClass(), 0);
6636#ifndef NDEBUG
6637 // Non-virtual base classes are initialized in the order in the class
6638 // definition. We have already checked for virtual base classes.
6639 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6640 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6641 "base class initializers not in expected order");
6642 ++BaseIt;
6643#endif
6644 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6645 BaseType->getAsCXXRecordDecl(), &Layout))
6646 return false;
6647 Value = &Result.getStructBase(BasesSeen++);
6648 } else if ((FD = I->getMember())) {
6649 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6650 return false;
6651 if (RD->isUnion()) {
6652 Result = APValue(FD);
6653 Value = &Result.getUnionValue();
6654 } else {
6655 SkipToField(FD, false);
6656 Value = &Result.getStructField(FD->getFieldIndex());
6657 }
6658 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6659 // Walk the indirect field decl's chain to find the object to initialize,
6660 // and make sure we've initialized every step along it.
6661 auto IndirectFieldChain = IFD->chain();
6662 for (auto *C : IndirectFieldChain) {
6663 FD = cast<FieldDecl>(C);
6664 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6665 // Switch the union field if it differs. This happens if we had
6666 // preceding zero-initialization, and we're now initializing a union
6667 // subobject other than the first.
6668 // FIXME: In this case, the values of the other subobjects are
6669 // specified, since zero-initialization sets all padding bits to zero.
6670 if (!Value->hasValue() ||
6671 (Value->isUnion() && Value->getUnionField() != FD)) {
6672 if (CD->isUnion())
6673 *Value = APValue(FD);
6674 else
6675 // FIXME: This immediately starts the lifetime of all members of
6676 // an anonymous struct. It would be preferable to strictly start
6677 // member lifetime in initialization order.
6678 Success &=
6679 handleDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6680 }
6681 // Store Subobject as its parent before updating it for the last element
6682 // in the chain.
6683 if (C == IndirectFieldChain.back())
6684 SubobjectParent = Subobject;
6685 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6686 return false;
6687 if (CD->isUnion())
6688 Value = &Value->getUnionValue();
6689 else {
6690 if (C == IndirectFieldChain.front() && !RD->isUnion())
6691 SkipToField(FD, true);
6692 Value = &Value->getStructField(FD->getFieldIndex());
6693 }
6694 }
6695 } else {
6696 llvm_unreachable("unknown base initializer kind");
6697 }
6698
6699 // Need to override This for implicit field initializers as in this case
6700 // This refers to innermost anonymous struct/union containing initializer,
6701 // not to currently constructed class.
6702 const Expr *Init = I->getInit();
6703 if (Init->isValueDependent()) {
6704 if (!EvaluateDependentExpr(Init, Info))
6705 return false;
6706 } else {
6707 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6708 isa<CXXDefaultInitExpr>(Init));
6709 FullExpressionRAII InitScope(Info);
6710 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6711 (FD && FD->isBitField() &&
6712 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6713 // If we're checking for a potential constant expression, evaluate all
6714 // initializers even if some of them fail.
6715 if (!Info.noteFailure())
6716 return false;
6717 Success = false;
6718 }
6719 }
6720
6721 // This is the point at which the dynamic type of the object becomes this
6722 // class type.
6723 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6724 EvalObj.finishedConstructingBases();
6725 }
6726
6727 // Default-initialize any remaining fields.
6728 if (!RD->isUnion()) {
6729 for (; FieldIt != RD->field_end(); ++FieldIt) {
6730 if (!FieldIt->isUnnamedBitField())
6732 FieldIt->getType(),
6733 Result.getStructField(FieldIt->getFieldIndex()));
6734 }
6735 }
6736
6737 EvalObj.finishedConstructingFields();
6738
6739 return Success &&
6740 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6741 LifetimeExtendedScope.destroy();
6742}
6743
6744static bool HandleConstructorCall(const Expr *E, const LValue &This,
6747 EvalInfo &Info, APValue &Result) {
6748 CallScopeRAII CallScope(Info);
6749 CallRef Call = Info.CurrentCall->createCall(Definition);
6750 if (!EvaluateArgs(Args, Call, Info, Definition))
6751 return false;
6752
6753 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6754 CallScope.destroy();
6755}
6756
6757static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6758 const LValue &This, APValue &Value,
6759 QualType T) {
6760 // Objects can only be destroyed while they're within their lifetimes.
6761 // FIXME: We have no representation for whether an object of type nullptr_t
6762 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6763 // as indeterminate instead?
6764 if (Value.isAbsent() && !T->isNullPtrType()) {
6765 APValue Printable;
6766 This.moveInto(Printable);
6767 Info.FFDiag(CallRange.getBegin(),
6768 diag::note_constexpr_destroy_out_of_lifetime)
6769 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6770 return false;
6771 }
6772
6773 // Invent an expression for location purposes.
6774 // FIXME: We shouldn't need to do this.
6775 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
6776
6777 // For arrays, destroy elements right-to-left.
6778 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6779 uint64_t Size = CAT->getZExtSize();
6780 QualType ElemT = CAT->getElementType();
6781
6782 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
6783 return false;
6784
6785 LValue ElemLV = This;
6786 ElemLV.addArray(Info, &LocE, CAT);
6787 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6788 return false;
6789
6790 // Ensure that we have actual array elements available to destroy; the
6791 // destructors might mutate the value, so we can't run them on the array
6792 // filler.
6793 if (Size && Size > Value.getArrayInitializedElts())
6794 expandArray(Value, Value.getArraySize() - 1);
6795
6796 // The size of the array might have been reduced by
6797 // a placement new.
6798 for (Size = Value.getArraySize(); Size != 0; --Size) {
6799 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6800 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6801 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
6802 return false;
6803 }
6804
6805 // End the lifetime of this array now.
6806 Value = APValue();
6807 return true;
6808 }
6809
6810 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6811 if (!RD) {
6812 if (T.isDestructedType()) {
6813 Info.FFDiag(CallRange.getBegin(),
6814 diag::note_constexpr_unsupported_destruction)
6815 << T;
6816 return false;
6817 }
6818
6819 Value = APValue();
6820 return true;
6821 }
6822
6823 if (RD->getNumVBases()) {
6824 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
6825 return false;
6826 }
6827
6828 const CXXDestructorDecl *DD = RD->getDestructor();
6829 if (!DD && !RD->hasTrivialDestructor()) {
6830 Info.FFDiag(CallRange.getBegin());
6831 return false;
6832 }
6833
6834 if (!DD || DD->isTrivial() ||
6835 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6836 // A trivial destructor just ends the lifetime of the object. Check for
6837 // this case before checking for a body, because we might not bother
6838 // building a body for a trivial destructor. Note that it doesn't matter
6839 // whether the destructor is constexpr in this case; all trivial
6840 // destructors are constexpr.
6841 //
6842 // If an anonymous union would be destroyed, some enclosing destructor must
6843 // have been explicitly defined, and the anonymous union destruction should
6844 // have no effect.
6845 Value = APValue();
6846 return true;
6847 }
6848
6849 if (!Info.CheckCallLimit(CallRange.getBegin()))
6850 return false;
6851
6852 const FunctionDecl *Definition = nullptr;
6853 const Stmt *Body = DD->getBody(Definition);
6854
6855 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
6856 return false;
6857
6858 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
6859 CallRef());
6860
6861 // We're now in the period of destruction of this object.
6862 unsigned BasesLeft = RD->getNumBases();
6863 EvalInfo::EvaluatingDestructorRAII EvalObj(
6864 Info,
6865 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6866 if (!EvalObj.DidInsert) {
6867 // C++2a [class.dtor]p19:
6868 // the behavior is undefined if the destructor is invoked for an object
6869 // whose lifetime has ended
6870 // (Note that formally the lifetime ends when the period of destruction
6871 // begins, even though certain uses of the object remain valid until the
6872 // period of destruction ends.)
6873 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
6874 return false;
6875 }
6876
6877 // FIXME: Creating an APValue just to hold a nonexistent return value is
6878 // wasteful.
6879 APValue RetVal;
6880 StmtResult Ret = {RetVal, nullptr};
6881 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6882 return false;
6883
6884 // A union destructor does not implicitly destroy its members.
6885 if (RD->isUnion())
6886 return true;
6887
6888 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6889
6890 // We don't have a good way to iterate fields in reverse, so collect all the
6891 // fields first and then walk them backwards.
6892 SmallVector<FieldDecl*, 16> Fields(RD->fields());
6893 for (const FieldDecl *FD : llvm::reverse(Fields)) {
6894 if (FD->isUnnamedBitField())
6895 continue;
6896
6897 LValue Subobject = This;
6898 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6899 return false;
6900
6901 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6902 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6903 FD->getType()))
6904 return false;
6905 }
6906
6907 if (BasesLeft != 0)
6908 EvalObj.startedDestroyingBases();
6909
6910 // Destroy base classes in reverse order.
6911 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6912 --BasesLeft;
6913
6914 QualType BaseType = Base.getType();
6915 LValue Subobject = This;
6916 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6917 BaseType->getAsCXXRecordDecl(), &Layout))
6918 return false;
6919
6920 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6921 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6922 BaseType))
6923 return false;
6924 }
6925 assert(BasesLeft == 0 && "NumBases was wrong?");
6926
6927 // The period of destruction ends now. The object is gone.
6928 Value = APValue();
6929 return true;
6930}
6931
6932namespace {
6933struct DestroyObjectHandler {
6934 EvalInfo &Info;
6935 const Expr *E;
6936 const LValue &This;
6937 const AccessKinds AccessKind;
6938
6939 typedef bool result_type;
6940 bool failed() { return false; }
6941 bool found(APValue &Subobj, QualType SubobjType) {
6942 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
6943 SubobjType);
6944 }
6945 bool found(APSInt &Value, QualType SubobjType) {
6946 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6947 return false;
6948 }
6949 bool found(APFloat &Value, QualType SubobjType) {
6950 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6951 return false;
6952 }
6953};
6954}
6955
6956/// Perform a destructor or pseudo-destructor call on the given object, which
6957/// might in general not be a complete object.
6958static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6959 const LValue &This, QualType ThisType) {
6960 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6961 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6962 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6963}
6964
6965/// Destroy and end the lifetime of the given complete object.
6966static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6968 QualType T) {
6969 // If we've had an unmodeled side-effect, we can't rely on mutable state
6970 // (such as the object we're about to destroy) being correct.
6971 if (Info.EvalStatus.HasSideEffects)
6972 return false;
6973
6974 LValue LV;
6975 LV.set({LVBase});
6976 return HandleDestructionImpl(Info, Loc, LV, Value, T);
6977}
6978
6979/// Perform a call to 'operator new' or to `__builtin_operator_new'.
6980static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6981 LValue &Result) {
6982 if (Info.checkingPotentialConstantExpression() ||
6983 Info.SpeculativeEvaluationDepth)
6984 return false;
6985
6986 // This is permitted only within a call to std::allocator<T>::allocate.
6987 auto Caller = Info.getStdAllocatorCaller("allocate");
6988 if (!Caller) {
6989 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6990 ? diag::note_constexpr_new_untyped
6991 : diag::note_constexpr_new);
6992 return false;
6993 }
6994
6995 QualType ElemType = Caller.ElemType;
6996 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6997 Info.FFDiag(E->getExprLoc(),
6998 diag::note_constexpr_new_not_complete_object_type)
6999 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7000 return false;
7001 }
7002
7003 APSInt ByteSize;
7004 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7005 return false;
7006 bool IsNothrow = false;
7007 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7008 EvaluateIgnoredValue(Info, E->getArg(I));
7009 IsNothrow |= E->getType()->isNothrowT();
7010 }
7011
7012 CharUnits ElemSize;
7013 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7014 return false;
7015 APInt Size, Remainder;
7016 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7017 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7018 if (Remainder != 0) {
7019 // This likely indicates a bug in the implementation of 'std::allocator'.
7020 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7021 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7022 return false;
7023 }
7024
7025 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7026 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7027 if (IsNothrow) {
7028 Result.setNull(Info.Ctx, E->getType());
7029 return true;
7030 }
7031 return false;
7032 }
7033
7034 QualType AllocType = Info.Ctx.getConstantArrayType(
7035 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7036 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
7037 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7038 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7039 return true;
7040}
7041
7043 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7044 if (CXXDestructorDecl *DD = RD->getDestructor())
7045 return DD->isVirtual();
7046 return false;
7047}
7048
7050 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7051 if (CXXDestructorDecl *DD = RD->getDestructor())
7052 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7053 return nullptr;
7054}
7055
7056/// Check that the given object is a suitable pointer to a heap allocation that
7057/// still exists and is of the right kind for the purpose of a deletion.
7058///
7059/// On success, returns the heap allocation to deallocate. On failure, produces
7060/// a diagnostic and returns std::nullopt.
7061static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7062 const LValue &Pointer,
7063 DynAlloc::Kind DeallocKind) {
7064 auto PointerAsString = [&] {
7065 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7066 };
7067
7068 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7069 if (!DA) {
7070 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7071 << PointerAsString();
7072 if (Pointer.Base)
7073 NoteLValueLocation(Info, Pointer.Base);
7074 return std::nullopt;
7075 }
7076
7077 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7078 if (!Alloc) {
7079 Info.FFDiag(E, diag::note_constexpr_double_delete);
7080 return std::nullopt;
7081 }
7082
7083 if (DeallocKind != (*Alloc)->getKind()) {
7084 QualType AllocType = Pointer.Base.getDynamicAllocType();
7085 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7086 << DeallocKind << (*Alloc)->getKind() << AllocType;
7087 NoteLValueLocation(Info, Pointer.Base);
7088 return std::nullopt;
7089 }
7090
7091 bool Subobject = false;
7092 if (DeallocKind == DynAlloc::New) {
7093 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7094 Pointer.Designator.isOnePastTheEnd();
7095 } else {
7096 Subobject = Pointer.Designator.Entries.size() != 1 ||
7097 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7098 }
7099 if (Subobject) {
7100 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7101 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7102 return std::nullopt;
7103 }
7104
7105 return Alloc;
7106}
7107
7108// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7109static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7110 if (Info.checkingPotentialConstantExpression() ||
7111 Info.SpeculativeEvaluationDepth)
7112 return false;
7113
7114 // This is permitted only within a call to std::allocator<T>::deallocate.
7115 if (!Info.getStdAllocatorCaller("deallocate")) {
7116 Info.FFDiag(E->getExprLoc());
7117 return true;
7118 }
7119
7120 LValue Pointer;
7121 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7122 return false;
7123 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7124 EvaluateIgnoredValue(Info, E->getArg(I));
7125
7126 if (Pointer.Designator.Invalid)
7127 return false;
7128
7129 // Deleting a null pointer would have no effect, but it's not permitted by
7130 // std::allocator<T>::deallocate's contract.
7131 if (Pointer.isNullPointer()) {
7132 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7133 return true;
7134 }
7135
7136 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7137 return false;
7138
7139 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7140 return true;
7141}
7142
7143//===----------------------------------------------------------------------===//
7144// Generic Evaluation
7145//===----------------------------------------------------------------------===//
7146namespace {
7147
7148class BitCastBuffer {
7149 // FIXME: We're going to need bit-level granularity when we support
7150 // bit-fields.
7151 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7152 // we don't support a host or target where that is the case. Still, we should
7153 // use a more generic type in case we ever do.
7155
7156 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7157 "Need at least 8 bit unsigned char");
7158
7159 bool TargetIsLittleEndian;
7160
7161public:
7162 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7163 : Bytes(Width.getQuantity()),
7164 TargetIsLittleEndian(TargetIsLittleEndian) {}
7165
7166 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7167 SmallVectorImpl<unsigned char> &Output) const {
7168 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7169 // If a byte of an integer is uninitialized, then the whole integer is
7170 // uninitialized.
7171 if (!Bytes[I.getQuantity()])
7172 return false;
7173 Output.push_back(*Bytes[I.getQuantity()]);
7174 }
7175 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7176 std::reverse(Output.begin(), Output.end());
7177 return true;
7178 }
7179
7180 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7181 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7182 std::reverse(Input.begin(), Input.end());
7183
7184 size_t Index = 0;
7185 for (unsigned char Byte : Input) {
7186 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7187 Bytes[Offset.getQuantity() + Index] = Byte;
7188 ++Index;
7189 }
7190 }
7191
7192 size_t size() { return Bytes.size(); }
7193};
7194
7195/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7196/// target would represent the value at runtime.
7197class APValueToBufferConverter {
7198 EvalInfo &Info;
7199 BitCastBuffer Buffer;
7200 const CastExpr *BCE;
7201
7202 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7203 const CastExpr *BCE)
7204 : Info(Info),
7205 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7206 BCE(BCE) {}
7207
7208 bool visit(const APValue &Val, QualType Ty) {
7209 return visit(Val, Ty, CharUnits::fromQuantity(0));
7210 }
7211
7212 // Write out Val with type Ty into Buffer starting at Offset.
7213 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7214 assert((size_t)Offset.getQuantity() <= Buffer.size());
7215
7216 // As a special case, nullptr_t has an indeterminate value.
7217 if (Ty->isNullPtrType())
7218 return true;
7219
7220 // Dig through Src to find the byte at SrcOffset.
7221 switch (Val.getKind()) {
7223 case APValue::None:
7224 return true;
7225
7226 case APValue::Int:
7227 return visitInt(Val.getInt(), Ty, Offset);
7228 case APValue::Float:
7229 return visitFloat(Val.getFloat(), Ty, Offset);
7230 case APValue::Array:
7231 return visitArray(Val, Ty, Offset);
7232 case APValue::Struct:
7233 return visitRecord(Val, Ty, Offset);
7234 case APValue::Vector:
7235 return visitVector(Val, Ty, Offset);
7236
7239 return visitComplex(Val, Ty, Offset);
7241 // FIXME: We should support these.
7242
7243 case APValue::Union:
7246 Info.FFDiag(BCE->getBeginLoc(),
7247 diag::note_constexpr_bit_cast_unsupported_type)
7248 << Ty;
7249 return false;
7250 }
7251
7252 case APValue::LValue:
7253 llvm_unreachable("LValue subobject in bit_cast?");
7254 }
7255 llvm_unreachable("Unhandled APValue::ValueKind");
7256 }
7257
7258 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7259 const RecordDecl *RD = Ty->getAsRecordDecl();
7260 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7261
7262 // Visit the base classes.
7263 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7264 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7265 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7266 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7267
7268 if (!visitRecord(Val.getStructBase(I), BS.getType(),
7269 Layout.getBaseClassOffset(BaseDecl) + Offset))
7270 return false;
7271 }
7272 }
7273
7274 // Visit the fields.
7275 unsigned FieldIdx = 0;
7276 for (FieldDecl *FD : RD->fields()) {
7277 if (FD->isBitField()) {
7278 Info.FFDiag(BCE->getBeginLoc(),
7279 diag::note_constexpr_bit_cast_unsupported_bitfield);
7280 return false;
7281 }
7282
7283 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7284
7285 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7286 "only bit-fields can have sub-char alignment");
7287 CharUnits FieldOffset =
7288 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7289 QualType FieldTy = FD->getType();
7290 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7291 return false;
7292 ++FieldIdx;
7293 }
7294
7295 return true;
7296 }
7297
7298 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7299 const auto *CAT =
7300 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7301 if (!CAT)
7302 return false;
7303
7304 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7305 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7306 unsigned ArraySize = Val.getArraySize();
7307 // First, initialize the initialized elements.
7308 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7309 const APValue &SubObj = Val.getArrayInitializedElt(I);
7310 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7311 return false;
7312 }
7313
7314 // Next, initialize the rest of the array using the filler.
7315 if (Val.hasArrayFiller()) {
7316 const APValue &Filler = Val.getArrayFiller();
7317 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7318 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7319 return false;
7320 }
7321 }
7322
7323 return true;
7324 }
7325
7326 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7327 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7328 QualType EltTy = ComplexTy->getElementType();
7329 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7330 bool IsInt = Val.isComplexInt();
7331
7332 if (IsInt) {
7333 if (!visitInt(Val.getComplexIntReal(), EltTy,
7334 Offset + (0 * EltSizeChars)))
7335 return false;
7336 if (!visitInt(Val.getComplexIntImag(), EltTy,
7337 Offset + (1 * EltSizeChars)))
7338 return false;
7339 } else {
7340 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7341 Offset + (0 * EltSizeChars)))
7342 return false;
7343 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7344 Offset + (1 * EltSizeChars)))
7345 return false;
7346 }
7347
7348 return true;
7349 }
7350
7351 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7352 const VectorType *VTy = Ty->castAs<VectorType>();
7353 QualType EltTy = VTy->getElementType();
7354 unsigned NElts = VTy->getNumElements();
7355
7356 if (VTy->isExtVectorBoolType()) {
7357 // Special handling for OpenCL bool vectors:
7358 // Since these vectors are stored as packed bits, but we can't write
7359 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7360 // together into an appropriately sized APInt and write them all out at
7361 // once. Because we don't accept vectors where NElts * EltSize isn't a
7362 // multiple of the char size, there will be no padding space, so we don't
7363 // have to worry about writing data which should have been left
7364 // uninitialized.
7365 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7366
7367 llvm::APInt Res = llvm::APInt::getZero(NElts);
7368 for (unsigned I = 0; I < NElts; ++I) {
7369 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7370 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7371 "bool vector element must be 1-bit unsigned integer!");
7372
7373 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7374 }
7375
7376 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7377 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7378 Buffer.writeObject(Offset, Bytes);
7379 } else {
7380 // Iterate over each of the elements and write them out to the buffer at
7381 // the appropriate offset.
7382 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7383 for (unsigned I = 0; I < NElts; ++I) {
7384 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7385 return false;
7386 }
7387 }
7388
7389 return true;
7390 }
7391
7392 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7393 APSInt AdjustedVal = Val;
7394 unsigned Width = AdjustedVal.getBitWidth();
7395 if (Ty->isBooleanType()) {
7396 Width = Info.Ctx.getTypeSize(Ty);
7397 AdjustedVal = AdjustedVal.extend(Width);
7398 }
7399
7400 SmallVector<uint8_t, 8> Bytes(Width / 8);
7401 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7402 Buffer.writeObject(Offset, Bytes);
7403 return true;
7404 }
7405
7406 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7407 APSInt AsInt(Val.bitcastToAPInt());
7408 return visitInt(AsInt, Ty, Offset);
7409 }
7410
7411public:
7412 static std::optional<BitCastBuffer>
7413 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7414 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7415 APValueToBufferConverter Converter(Info, DstSize, BCE);
7416 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7417 return std::nullopt;
7418 return Converter.Buffer;
7419 }
7420};
7421
7422/// Write an BitCastBuffer into an APValue.
7423class BufferToAPValueConverter {
7424 EvalInfo &Info;
7425 const BitCastBuffer &Buffer;
7426 const CastExpr *BCE;
7427
7428 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7429 const CastExpr *BCE)
7430 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7431
7432 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7433 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7434 // Ideally this will be unreachable.
7435 std::nullopt_t unsupportedType(QualType Ty) {
7436 Info.FFDiag(BCE->getBeginLoc(),
7437 diag::note_constexpr_bit_cast_unsupported_type)
7438 << Ty;
7439 return std::nullopt;
7440 }
7441
7442 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7443 Info.FFDiag(BCE->getBeginLoc(),
7444 diag::note_constexpr_bit_cast_unrepresentable_value)
7445 << Ty << toString(Val, /*Radix=*/10);
7446 return std::nullopt;
7447 }
7448
7449 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7450 const EnumType *EnumSugar = nullptr) {
7451 if (T->isNullPtrType()) {
7452 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7453 return APValue((Expr *)nullptr,
7454 /*Offset=*/CharUnits::fromQuantity(NullValue),
7455 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7456 }
7457
7458 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7459
7460 // Work around floating point types that contain unused padding bytes. This
7461 // is really just `long double` on x86, which is the only fundamental type
7462 // with padding bytes.
7463 if (T->isRealFloatingType()) {
7464 const llvm::fltSemantics &Semantics =
7465 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7466 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7467 assert(NumBits % 8 == 0);
7468 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7469 if (NumBytes != SizeOf)
7470 SizeOf = NumBytes;
7471 }
7472
7474 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7475 // If this is std::byte or unsigned char, then its okay to store an
7476 // indeterminate value.
7477 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7478 bool IsUChar =
7479 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7480 T->isSpecificBuiltinType(BuiltinType::Char_U));
7481 if (!IsStdByte && !IsUChar) {
7482 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7483 Info.FFDiag(BCE->getExprLoc(),
7484 diag::note_constexpr_bit_cast_indet_dest)
7485 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7486 return std::nullopt;
7487 }
7488
7490 }
7491
7492 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7493 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7494
7496 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7497
7498 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7499 if (IntWidth != Val.getBitWidth()) {
7500 APSInt Truncated = Val.trunc(IntWidth);
7501 if (Truncated.extend(Val.getBitWidth()) != Val)
7502 return unrepresentableValue(QualType(T, 0), Val);
7503 Val = Truncated;
7504 }
7505
7506 return APValue(Val);
7507 }
7508
7509 if (T->isRealFloatingType()) {
7510 const llvm::fltSemantics &Semantics =
7511 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7512 return APValue(APFloat(Semantics, Val));
7513 }
7514
7515 return unsupportedType(QualType(T, 0));
7516 }
7517
7518 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7519 const RecordDecl *RD = RTy->getAsRecordDecl();
7520 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7521
7522 unsigned NumBases = 0;
7523 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7524 NumBases = CXXRD->getNumBases();
7525
7526 APValue ResultVal(APValue::UninitStruct(), NumBases,
7527 std::distance(RD->field_begin(), RD->field_end()));
7528
7529 // Visit the base classes.
7530 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7531 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7532 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7533 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7534
7535 std::optional<APValue> SubObj = visitType(
7536 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7537 if (!SubObj)
7538 return std::nullopt;
7539 ResultVal.getStructBase(I) = *SubObj;
7540 }
7541 }
7542
7543 // Visit the fields.
7544 unsigned FieldIdx = 0;
7545 for (FieldDecl *FD : RD->fields()) {
7546 // FIXME: We don't currently support bit-fields. A lot of the logic for
7547 // this is in CodeGen, so we need to factor it around.
7548 if (FD->isBitField()) {
7549 Info.FFDiag(BCE->getBeginLoc(),
7550 diag::note_constexpr_bit_cast_unsupported_bitfield);
7551 return std::nullopt;
7552 }
7553
7554 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7555 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7556
7557 CharUnits FieldOffset =
7558 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7559 Offset;
7560 QualType FieldTy = FD->getType();
7561 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7562 if (!SubObj)
7563 return std::nullopt;
7564 ResultVal.getStructField(FieldIdx) = *SubObj;
7565 ++FieldIdx;
7566 }
7567
7568 return ResultVal;
7569 }
7570
7571 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7572 QualType RepresentationType = Ty->getDecl()->getIntegerType();
7573 assert(!RepresentationType.isNull() &&
7574 "enum forward decl should be caught by Sema");
7575 const auto *AsBuiltin =
7576 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7577 // Recurse into the underlying type. Treat std::byte transparently as
7578 // unsigned char.
7579 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7580 }
7581
7582 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7583 size_t Size = Ty->getLimitedSize();
7584 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7585
7586 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7587 for (size_t I = 0; I != Size; ++I) {
7588 std::optional<APValue> ElementValue =
7589 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7590 if (!ElementValue)
7591 return std::nullopt;
7592 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7593 }
7594
7595 return ArrayValue;
7596 }
7597
7598 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
7599 QualType ElementType = Ty->getElementType();
7600 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
7601 bool IsInt = ElementType->isIntegerType();
7602
7603 std::optional<APValue> Values[2];
7604 for (unsigned I = 0; I != 2; ++I) {
7605 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
7606 if (!Values[I])
7607 return std::nullopt;
7608 }
7609
7610 if (IsInt)
7611 return APValue(Values[0]->getInt(), Values[1]->getInt());
7612 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
7613 }
7614
7615 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7616 QualType EltTy = VTy->getElementType();
7617 unsigned NElts = VTy->getNumElements();
7618 unsigned EltSize =
7619 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7620
7622 Elts.reserve(NElts);
7623 if (VTy->isExtVectorBoolType()) {
7624 // Special handling for OpenCL bool vectors:
7625 // Since these vectors are stored as packed bits, but we can't read
7626 // individual bits from the BitCastBuffer, we'll buffer all of the
7627 // elements together into an appropriately sized APInt and write them all
7628 // out at once. Because we don't accept vectors where NElts * EltSize
7629 // isn't a multiple of the char size, there will be no padding space, so
7630 // we don't have to worry about reading any padding data which didn't
7631 // actually need to be accessed.
7632 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7633
7635 Bytes.reserve(NElts / 8);
7636 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7637 return std::nullopt;
7638
7639 APSInt SValInt(NElts, true);
7640 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7641
7642 for (unsigned I = 0; I < NElts; ++I) {
7643 llvm::APInt Elt =
7644 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7645 Elts.emplace_back(
7646 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7647 }
7648 } else {
7649 // Iterate over each of the elements and read them from the buffer at
7650 // the appropriate offset.
7651 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7652 for (unsigned I = 0; I < NElts; ++I) {
7653 std::optional<APValue> EltValue =
7654 visitType(EltTy, Offset + I * EltSizeChars);
7655 if (!EltValue)
7656 return std::nullopt;
7657 Elts.push_back(std::move(*EltValue));
7658 }
7659 }
7660
7661 return APValue(Elts.data(), Elts.size());
7662 }
7663
7664 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7665 return unsupportedType(QualType(Ty, 0));
7666 }
7667
7668 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7669 QualType Can = Ty.getCanonicalType();
7670
7671 switch (Can->getTypeClass()) {
7672#define TYPE(Class, Base) \
7673 case Type::Class: \
7674 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7675#define ABSTRACT_TYPE(Class, Base)
7676#define NON_CANONICAL_TYPE(Class, Base) \
7677 case Type::Class: \
7678 llvm_unreachable("non-canonical type should be impossible!");
7679#define DEPENDENT_TYPE(Class, Base) \
7680 case Type::Class: \
7681 llvm_unreachable( \
7682 "dependent types aren't supported in the constant evaluator!");
7683#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7684 case Type::Class: \
7685 llvm_unreachable("either dependent or not canonical!");
7686#include "clang/AST/TypeNodes.inc"
7687 }
7688 llvm_unreachable("Unhandled Type::TypeClass");
7689 }
7690
7691public:
7692 // Pull out a full value of type DstType.
7693 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7694 const CastExpr *BCE) {
7695 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7696 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7697 }
7698};
7699
7700static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7701 QualType Ty, EvalInfo *Info,
7702 const ASTContext &Ctx,
7703 bool CheckingDest) {
7704 Ty = Ty.getCanonicalType();
7705
7706 auto diag = [&](int Reason) {
7707 if (Info)
7708 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7709 << CheckingDest << (Reason == 4) << Reason;
7710 return false;
7711 };
7712 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7713 if (Info)
7714 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7715 << NoteTy << Construct << Ty;
7716 return false;
7717 };
7718
7719 if (Ty->isUnionType())
7720 return diag(0);
7721 if (Ty->isPointerType())
7722 return diag(1);
7723 if (Ty->isMemberPointerType())
7724 return diag(2);
7725 if (Ty.isVolatileQualified())
7726 return diag(3);
7727
7728 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7729 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7730 for (CXXBaseSpecifier &BS : CXXRD->bases())
7731 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7732 CheckingDest))
7733 return note(1, BS.getType(), BS.getBeginLoc());
7734 }
7735 for (FieldDecl *FD : Record->fields()) {
7736 if (FD->getType()->isReferenceType())
7737 return diag(4);
7738 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7739 CheckingDest))
7740 return note(0, FD->getType(), FD->getBeginLoc());
7741 }
7742 }
7743
7744 if (Ty->isArrayType() &&
7745 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7746 Info, Ctx, CheckingDest))
7747 return false;
7748
7749 if (const auto *VTy = Ty->getAs<VectorType>()) {
7750 QualType EltTy = VTy->getElementType();
7751 unsigned NElts = VTy->getNumElements();
7752 unsigned EltSize = VTy->isExtVectorBoolType() ? 1 : Ctx.getTypeSize(EltTy);
7753
7754 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
7755 // The vector's size in bits is not a multiple of the target's byte size,
7756 // so its layout is unspecified. For now, we'll simply treat these cases
7757 // as unsupported (this should only be possible with OpenCL bool vectors
7758 // whose element count isn't a multiple of the byte size).
7759 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
7760 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
7761 return false;
7762 }
7763
7764 if (EltTy->isRealFloatingType() &&
7765 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
7766 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7767 // by both clang and LLVM, so for now we won't allow bit_casts involving
7768 // it in a constexpr context.
7769 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
7770 << EltTy;
7771 return false;
7772 }
7773 }
7774
7775 return true;
7776}
7777
7778static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7779 const ASTContext &Ctx,
7780 const CastExpr *BCE) {
7781 bool DestOK = checkBitCastConstexprEligibilityType(
7782 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7783 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7784 BCE->getBeginLoc(),
7785 BCE->getSubExpr()->getType(), Info, Ctx, false);
7786 return SourceOK;
7787}
7788
7789static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7790 const APValue &SourceRValue,
7791 const CastExpr *BCE) {
7792 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7793 "no host or target supports non 8-bit chars");
7794
7795 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7796 return false;
7797
7798 // Read out SourceValue into a char buffer.
7799 std::optional<BitCastBuffer> Buffer =
7800 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7801 if (!Buffer)
7802 return false;
7803
7804 // Write out the buffer into a new APValue.
7805 std::optional<APValue> MaybeDestValue =
7806 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7807 if (!MaybeDestValue)
7808 return false;
7809
7810 DestValue = std::move(*MaybeDestValue);
7811 return true;
7812}
7813
7814static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7815 APValue &SourceValue,
7816 const CastExpr *BCE) {
7817 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7818 "no host or target supports non 8-bit chars");
7819 assert(SourceValue.isLValue() &&
7820 "LValueToRValueBitcast requires an lvalue operand!");
7821
7822 LValue SourceLValue;
7823 APValue SourceRValue;
7824 SourceLValue.setFrom(Info.Ctx, SourceValue);
7826 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7827 SourceRValue, /*WantObjectRepresentation=*/true))
7828 return false;
7829
7830 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
7831}
7832
7833template <class Derived>
7834class ExprEvaluatorBase
7835 : public ConstStmtVisitor<Derived, bool> {
7836private:
7837 Derived &getDerived() { return static_cast<Derived&>(*this); }
7838 bool DerivedSuccess(const APValue &V, const Expr *E) {
7839 return getDerived().Success(V, E);
7840 }
7841 bool DerivedZeroInitialization(const Expr *E) {
7842 return getDerived().ZeroInitialization(E);
7843 }
7844
7845 // Check whether a conditional operator with a non-constant condition is a
7846 // potential constant expression. If neither arm is a potential constant
7847 // expression, then the conditional operator is not either.
7848 template<typename ConditionalOperator>
7849 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7850 assert(Info.checkingPotentialConstantExpression());
7851
7852 // Speculatively evaluate both arms.
7854 {
7855 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7856 StmtVisitorTy::Visit(E->getFalseExpr());
7857 if (Diag.empty())
7858 return;
7859 }
7860
7861 {
7862 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7863 Diag.clear();
7864 StmtVisitorTy::Visit(E->getTrueExpr());
7865 if (Diag.empty())
7866 return;
7867 }
7868
7869 Error(E, diag::note_constexpr_conditional_never_const);
7870 }
7871
7872
7873 template<typename ConditionalOperator>
7874 bool HandleConditionalOperator(const ConditionalOperator *E) {
7875 bool BoolResult;
7876 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7877 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7878 CheckPotentialConstantConditional(E);
7879 return false;
7880 }
7881 if (Info.noteFailure()) {
7882 StmtVisitorTy::Visit(E->getTrueExpr());
7883 StmtVisitorTy::Visit(E->getFalseExpr());
7884 }
7885 return false;
7886 }
7887
7888 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7889 return StmtVisitorTy::Visit(EvalExpr);
7890 }
7891
7892protected:
7893 EvalInfo &Info;
7894 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7895 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7896
7897 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7898 return Info.CCEDiag(E, D);
7899 }
7900
7901 bool ZeroInitialization(const Expr *E) { return Error(E); }
7902
7903 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7904 unsigned BuiltinOp = E->getBuiltinCallee();
7905 return BuiltinOp != 0 &&
7906 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7907 }
7908
7909public:
7910 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7911
7912 EvalInfo &getEvalInfo() { return Info; }
7913
7914 /// Report an evaluation error. This should only be called when an error is
7915 /// first discovered. When propagating an error, just return false.
7916 bool Error(const Expr *E, diag::kind D) {
7917 Info.FFDiag(E, D) << E->getSourceRange();
7918 return false;
7919 }
7920 bool Error(const Expr *E) {
7921 return Error(E, diag::note_invalid_subexpr_in_const_expr);
7922 }
7923
7924 bool VisitStmt(const Stmt *) {
7925 llvm_unreachable("Expression evaluator should not be called on stmts");
7926 }
7927 bool VisitExpr(const Expr *E) {
7928 return Error(E);
7929 }
7930
7931 bool VisitEmbedExpr(const EmbedExpr *E) {
7932 const auto It = E->begin();
7933 return StmtVisitorTy::Visit(*It);
7934 }
7935
7936 bool VisitPredefinedExpr(const PredefinedExpr *E) {
7937 return StmtVisitorTy::Visit(E->getFunctionName());
7938 }
7939 bool VisitConstantExpr(const ConstantExpr *E) {
7940 if (E->hasAPValueResult())
7941 return DerivedSuccess(E->getAPValueResult(), E);
7942
7943 return StmtVisitorTy::Visit(E->getSubExpr());
7944 }
7945
7946 bool VisitParenExpr(const ParenExpr *E)
7947 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7948 bool VisitUnaryExtension(const UnaryOperator *E)
7949 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7950 bool VisitUnaryPlus(const UnaryOperator *E)
7951 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7952 bool VisitChooseExpr(const ChooseExpr *E)
7953 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7954 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7955 { return StmtVisitorTy::Visit(E->getResultExpr()); }
7956 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7957 { return StmtVisitorTy::Visit(E->getReplacement()); }
7958 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7959 TempVersionRAII RAII(*Info.CurrentCall);
7960 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7961 return StmtVisitorTy::Visit(E->getExpr());
7962 }
7963 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7964 TempVersionRAII RAII(*Info.CurrentCall);
7965 // The initializer may not have been parsed yet, or might be erroneous.
7966 if (!E->getExpr())
7967 return Error(E);
7968 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7969 return StmtVisitorTy::Visit(E->getExpr());
7970 }
7971
7972 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7973 FullExpressionRAII Scope(Info);
7974 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7975 }
7976
7977 // Temporaries are registered when created, so we don't care about
7978 // CXXBindTemporaryExpr.
7979 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7980 return StmtVisitorTy::Visit(E->getSubExpr());
7981 }
7982
7983 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7984 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7985 return static_cast<Derived*>(this)->VisitCastExpr(E);
7986 }
7987 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7988 if (!Info.Ctx.getLangOpts().CPlusPlus20)
7989 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7990 return static_cast<Derived*>(this)->VisitCastExpr(E);
7991 }
7992 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7993 return static_cast<Derived*>(this)->VisitCastExpr(E);
7994 }
7995
7996 bool VisitBinaryOperator(const BinaryOperator *E) {
7997 switch (E->getOpcode()) {
7998 default:
7999 return Error(E);
8000
8001 case BO_Comma:
8002 VisitIgnoredValue(E->getLHS());
8003 return StmtVisitorTy::Visit(E->getRHS());
8004
8005 case BO_PtrMemD:
8006 case BO_PtrMemI: {
8007 LValue Obj;
8008 if (!HandleMemberPointerAccess(Info, E, Obj))
8009 return false;
8010 APValue Result;
8011 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8012 return false;
8013 return DerivedSuccess(Result, E);
8014 }
8015 }
8016 }
8017
8018 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8019 return StmtVisitorTy::Visit(E->getSemanticForm());
8020 }
8021
8022 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8023 // Evaluate and cache the common expression. We treat it as a temporary,
8024 // even though it's not quite the same thing.
8025 LValue CommonLV;
8026 if (!Evaluate(Info.CurrentCall->createTemporary(
8027 E->getOpaqueValue(),
8028 getStorageType(Info.Ctx, E->getOpaqueValue()),
8029 ScopeKind::FullExpression, CommonLV),
8030 Info, E->getCommon()))
8031 return false;
8032
8033 return HandleConditionalOperator(E);
8034 }
8035
8036 bool VisitConditionalOperator(const ConditionalOperator *E) {
8037 bool IsBcpCall = false;
8038 // If the condition (ignoring parens) is a __builtin_constant_p call,
8039 // the result is a constant expression if it can be folded without
8040 // side-effects. This is an important GNU extension. See GCC PR38377
8041 // for discussion.
8042 if (const CallExpr *CallCE =
8043 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8044 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8045 IsBcpCall = true;
8046
8047 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8048 // constant expression; we can't check whether it's potentially foldable.
8049 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8050 // it would return 'false' in this mode.
8051 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8052 return false;
8053
8054 FoldConstant Fold(Info, IsBcpCall);
8055 if (!HandleConditionalOperator(E)) {
8056 Fold.keepDiagnostics();
8057 return false;
8058 }
8059
8060 return true;
8061 }
8062
8063 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8064 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8065 Value && !Value->isAbsent())
8066 return DerivedSuccess(*Value, E);
8067
8068 const Expr *Source = E->getSourceExpr();
8069 if (!Source)
8070 return Error(E);
8071 if (Source == E) {
8072 assert(0 && "OpaqueValueExpr recursively refers to itself");
8073 return Error(E);
8074 }
8075 return StmtVisitorTy::Visit(Source);
8076 }
8077
8078 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8079 for (const Expr *SemE : E->semantics()) {
8080 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8081 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8082 // result expression: there could be two different LValues that would
8083 // refer to the same object in that case, and we can't model that.
8084 if (SemE == E->getResultExpr())
8085 return Error(E);
8086
8087 // Unique OVEs get evaluated if and when we encounter them when
8088 // emitting the rest of the semantic form, rather than eagerly.
8089 if (OVE->isUnique())
8090 continue;
8091
8092 LValue LV;
8093 if (!Evaluate(Info.CurrentCall->createTemporary(
8094 OVE, getStorageType(Info.Ctx, OVE),
8095 ScopeKind::FullExpression, LV),
8096 Info, OVE->getSourceExpr()))
8097 return false;
8098 } else if (SemE == E->getResultExpr()) {
8099 if (!StmtVisitorTy::Visit(SemE))
8100 return false;
8101 } else {
8102 if (!EvaluateIgnoredValue(Info, SemE))
8103 return false;
8104 }
8105 }
8106 return true;
8107 }
8108
8109 bool VisitCallExpr(const CallExpr *E) {
8110 APValue Result;
8111 if (!handleCallExpr(E, Result, nullptr))
8112 return false;
8113 return DerivedSuccess(Result, E);
8114 }
8115
8116 bool handleCallExpr(const CallExpr *E, APValue &Result,
8117 const LValue *ResultSlot) {
8118 CallScopeRAII CallScope(Info);
8119
8120 const Expr *Callee = E->getCallee()->IgnoreParens();
8121 QualType CalleeType = Callee->getType();
8122
8123 const FunctionDecl *FD = nullptr;
8124 LValue *This = nullptr, ThisVal;
8125 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
8126 bool HasQualifier = false;
8127
8128 CallRef Call;
8129
8130 // Extract function decl and 'this' pointer from the callee.
8131 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8132 const CXXMethodDecl *Member = nullptr;
8133 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8134 // Explicit bound member calls, such as x.f() or p->g();
8135 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
8136 return false;
8137 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8138 if (!Member)
8139 return Error(Callee);
8140 This = &ThisVal;
8141 HasQualifier = ME->hasQualifier();
8142 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8143 // Indirect bound member calls ('.*' or '->*').
8144 const ValueDecl *D =
8145 HandleMemberPointerAccess(Info, BE, ThisVal, false);
8146 if (!D)
8147 return false;
8148 Member = dyn_cast<CXXMethodDecl>(D);
8149 if (!Member)
8150 return Error(Callee);
8151 This = &ThisVal;
8152 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8153 if (!Info.getLangOpts().CPlusPlus20)
8154 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8155 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
8156 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
8157 } else
8158 return Error(Callee);
8159 FD = Member;
8160 } else if (CalleeType->isFunctionPointerType()) {
8161 LValue CalleeLV;
8162 if (!EvaluatePointer(Callee, CalleeLV, Info))
8163 return false;
8164
8165 if (!CalleeLV.getLValueOffset().isZero())
8166 return Error(Callee);
8167 if (CalleeLV.isNullPointer()) {
8168 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8169 << const_cast<Expr *>(Callee);
8170 return false;
8171 }
8172 FD = dyn_cast_or_null<FunctionDecl>(
8173 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8174 if (!FD)
8175 return Error(Callee);
8176 // Don't call function pointers which have been cast to some other type.
8177 // Per DR (no number yet), the caller and callee can differ in noexcept.
8178 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8179 CalleeType->getPointeeType(), FD->getType())) {
8180 return Error(E);
8181 }
8182
8183 // For an (overloaded) assignment expression, evaluate the RHS before the
8184 // LHS.
8185 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8186 if (OCE && OCE->isAssignmentOp()) {
8187 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8188 Call = Info.CurrentCall->createCall(FD);
8189 bool HasThis = false;
8190 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8191 HasThis = MD->isImplicitObjectMemberFunction();
8192 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8193 /*RightToLeft=*/true))
8194 return false;
8195 }
8196
8197 // Overloaded operator calls to member functions are represented as normal
8198 // calls with '*this' as the first argument.
8199 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8200 if (MD &&
8201 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8202 // FIXME: When selecting an implicit conversion for an overloaded
8203 // operator delete, we sometimes try to evaluate calls to conversion
8204 // operators without a 'this' parameter!
8205 if (Args.empty())
8206 return Error(E);
8207
8208 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
8209 return false;
8210
8211 // If we are calling a static operator, the 'this' argument needs to be
8212 // ignored after being evaluated.
8213 if (MD->isInstance())
8214 This = &ThisVal;
8215
8216 // If this is syntactically a simple assignment using a trivial
8217 // assignment operator, start the lifetimes of union members as needed,
8218 // per C++20 [class.union]5.
8219 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8220 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8221 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))
8222 return false;
8223
8224 Args = Args.slice(1);
8225 } else if (MD && MD->isLambdaStaticInvoker()) {
8226 // Map the static invoker for the lambda back to the call operator.
8227 // Conveniently, we don't have to slice out the 'this' argument (as is
8228 // being done for the non-static case), since a static member function
8229 // doesn't have an implicit argument passed in.
8230 const CXXRecordDecl *ClosureClass = MD->getParent();
8231 assert(
8232 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
8233 "Number of captures must be zero for conversion to function-ptr");
8234
8235 const CXXMethodDecl *LambdaCallOp =
8236 ClosureClass->getLambdaCallOperator();
8237
8238 // Set 'FD', the function that will be called below, to the call
8239 // operator. If the closure object represents a generic lambda, find
8240 // the corresponding specialization of the call operator.
8241
8242 if (ClosureClass->isGenericLambda()) {
8243 assert(MD->isFunctionTemplateSpecialization() &&
8244 "A generic lambda's static-invoker function must be a "
8245 "template specialization");
8247 FunctionTemplateDecl *CallOpTemplate =
8248 LambdaCallOp->getDescribedFunctionTemplate();
8249 void *InsertPos = nullptr;
8250 FunctionDecl *CorrespondingCallOpSpecialization =
8251 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8252 assert(CorrespondingCallOpSpecialization &&
8253 "We must always have a function call operator specialization "
8254 "that corresponds to our static invoker specialization");
8255 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8256 FD = CorrespondingCallOpSpecialization;
8257 } else
8258 FD = LambdaCallOp;
8259 } else if (FD->isReplaceableGlobalAllocationFunction()) {
8260 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
8261 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
8262 LValue Ptr;
8263 if (!HandleOperatorNewCall(Info, E, Ptr))
8264 return false;
8265 Ptr.moveInto(Result);
8266 return CallScope.destroy();
8267 } else {
8268 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8269 }
8270 }
8271 } else
8272 return Error(E);
8273
8274 // Evaluate the arguments now if we've not already done so.
8275 if (!Call) {
8276 Call = Info.CurrentCall->createCall(FD);
8277 if (!EvaluateArgs(Args, Call, Info, FD))
8278 return false;
8279 }
8280
8281 SmallVector<QualType, 4> CovariantAdjustmentPath;
8282 if (This) {
8283 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8284 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8285 // Perform virtual dispatch, if necessary.
8286 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8287 CovariantAdjustmentPath);
8288 if (!FD)
8289 return false;
8290 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8291 // Check that the 'this' pointer points to an object of the right type.
8292 // FIXME: If this is an assignment operator call, we may need to change
8293 // the active union member before we check this.
8294 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8295 return false;
8296 }
8297 }
8298
8299 // Destructor calls are different enough that they have their own codepath.
8300 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8301 assert(This && "no 'this' pointer for destructor call");
8302 return HandleDestruction(Info, E, *This,
8303 Info.Ctx.getRecordType(DD->getParent())) &&
8304 CallScope.destroy();
8305 }
8306
8307 const FunctionDecl *Definition = nullptr;
8308 Stmt *Body = FD->getBody(Definition);
8309
8310 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8311 !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8312 Body, Info, Result, ResultSlot))
8313 return false;
8314
8315 if (!CovariantAdjustmentPath.empty() &&
8316 !HandleCovariantReturnAdjustment(Info, E, Result,
8317 CovariantAdjustmentPath))
8318 return false;
8319
8320 return CallScope.destroy();
8321 }
8322
8323 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8324 return StmtVisitorTy::Visit(E->getInitializer());
8325 }
8326 bool VisitInitListExpr(const InitListExpr *E) {
8327 if (E->getNumInits() == 0)
8328 return DerivedZeroInitialization(E);
8329 if (E->getNumInits() == 1)
8330 return StmtVisitorTy::Visit(E->getInit(0));
8331 return Error(E);
8332 }
8333 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8334 return DerivedZeroInitialization(E);
8335 }
8336 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8337 return DerivedZeroInitialization(E);
8338 }
8339 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8340 return DerivedZeroInitialization(E);
8341 }
8342
8343 /// A member expression where the object is a prvalue is itself a prvalue.
8344 bool VisitMemberExpr(const MemberExpr *E) {
8345 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8346 "missing temporary materialization conversion");
8347 assert(!E->isArrow() && "missing call to bound member function?");
8348
8349 APValue Val;
8350 if (!Evaluate(Val, Info, E->getBase()))
8351 return false;
8352
8353 QualType BaseTy = E->getBase()->getType();
8354
8355 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8356 if (!FD) return Error(E);
8357 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8358 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8359 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8360
8361 // Note: there is no lvalue base here. But this case should only ever
8362 // happen in C or in C++98, where we cannot be evaluating a constexpr
8363 // constructor, which is the only case the base matters.
8364 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8365 SubobjectDesignator Designator(BaseTy);
8366 Designator.addDeclUnchecked(FD);
8367
8368 APValue Result;
8369 return extractSubobject(Info, E, Obj, Designator, Result) &&
8370 DerivedSuccess(Result, E);
8371 }
8372
8373 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8374 APValue Val;
8375 if (!Evaluate(Val, Info, E->getBase()))
8376 return false;
8377
8378 if (Val.isVector()) {
8380 E->getEncodedElementAccess(Indices);
8381 if (Indices.size() == 1) {
8382 // Return scalar.
8383 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8384 } else {
8385 // Construct new APValue vector.
8387 for (unsigned I = 0; I < Indices.size(); ++I) {
8388 Elts.push_back(Val.getVectorElt(Indices[I]));
8389 }
8390 APValue VecResult(Elts.data(), Indices.size());
8391 return DerivedSuccess(VecResult, E);
8392 }
8393 }
8394
8395 return false;
8396 }
8397
8398 bool VisitCastExpr(const CastExpr *E) {
8399 switch (E->getCastKind()) {
8400 default:
8401 break;
8402
8403 case CK_AtomicToNonAtomic: {
8404 APValue AtomicVal;
8405 // This does not need to be done in place even for class/array types:
8406 // atomic-to-non-atomic conversion implies copying the object
8407 // representation.
8408 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8409 return false;
8410 return DerivedSuccess(AtomicVal, E);
8411 }
8412
8413 case CK_NoOp:
8414 case CK_UserDefinedConversion:
8415 return StmtVisitorTy::Visit(E->getSubExpr());
8416
8417 case CK_LValueToRValue: {
8418 LValue LVal;
8419 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8420 return false;
8421 APValue RVal;
8422 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8423 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8424 LVal, RVal))
8425 return false;
8426 return DerivedSuccess(RVal, E);
8427 }
8428 case CK_LValueToRValueBitCast: {
8429 APValue DestValue, SourceValue;
8430 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8431 return false;
8432 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8433 return false;
8434 return DerivedSuccess(DestValue, E);
8435 }
8436
8437 case CK_AddressSpaceConversion: {
8438 APValue Value;
8439 if (!Evaluate(Value, Info, E->getSubExpr()))
8440 return false;
8441 return DerivedSuccess(Value, E);
8442 }
8443 }
8444
8445 return Error(E);
8446 }
8447
8448 bool VisitUnaryPostInc(const UnaryOperator *UO) {
8449 return VisitUnaryPostIncDec(UO);
8450 }
8451 bool VisitUnaryPostDec(const UnaryOperator *UO) {
8452 return VisitUnaryPostIncDec(UO);
8453 }
8454 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8455 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8456 return Error(UO);
8457
8458 LValue LVal;
8459 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8460 return false;
8461 APValue RVal;
8462 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8463 UO->isIncrementOp(), &RVal))
8464 return false;
8465 return DerivedSuccess(RVal, UO);
8466 }
8467
8468 bool VisitStmtExpr(const StmtExpr *E) {
8469 // We will have checked the full-expressions inside the statement expression
8470 // when they were completed, and don't need to check them again now.
8471 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8472 false);
8473
8474 const CompoundStmt *CS = E->getSubStmt();
8475 if (CS->body_empty())
8476 return true;
8477
8478 BlockScopeRAII Scope(Info);
8480 BE = CS->body_end();
8481 /**/; ++BI) {
8482 if (BI + 1 == BE) {
8483 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8484 if (!FinalExpr) {
8485 Info.FFDiag((*BI)->getBeginLoc(),
8486 diag::note_constexpr_stmt_expr_unsupported);
8487 return false;
8488 }
8489 return this->Visit(FinalExpr) && Scope.destroy();
8490 }
8491
8493 StmtResult Result = { ReturnValue, nullptr };
8494 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8495 if (ESR != ESR_Succeeded) {
8496 // FIXME: If the statement-expression terminated due to 'return',
8497 // 'break', or 'continue', it would be nice to propagate that to
8498 // the outer statement evaluation rather than bailing out.
8499 if (ESR != ESR_Failed)
8500 Info.FFDiag((*BI)->getBeginLoc(),
8501 diag::note_constexpr_stmt_expr_unsupported);
8502 return false;
8503 }
8504 }
8505
8506 llvm_unreachable("Return from function from the loop above.");
8507 }
8508
8509 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8510 return StmtVisitorTy::Visit(E->getSelectedExpr());
8511 }
8512
8513 /// Visit a value which is evaluated, but whose value is ignored.
8514 void VisitIgnoredValue(const Expr *E) {
8515 EvaluateIgnoredValue(Info, E);
8516 }
8517
8518 /// Potentially visit a MemberExpr's base expression.
8519 void VisitIgnoredBaseExpression(const Expr *E) {
8520 // While MSVC doesn't evaluate the base expression, it does diagnose the
8521 // presence of side-effecting behavior.
8522 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8523 return;
8524 VisitIgnoredValue(E);
8525 }
8526};
8527
8528} // namespace
8529
8530//===----------------------------------------------------------------------===//
8531// Common base class for lvalue and temporary evaluation.
8532//===----------------------------------------------------------------------===//
8533namespace {
8534template<class Derived>
8535class LValueExprEvaluatorBase
8536 : public ExprEvaluatorBase<Derived> {
8537protected:
8538 LValue &Result;
8539 bool InvalidBaseOK;
8540 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8541 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8542
8544 Result.set(B);
8545 return true;
8546 }
8547
8548 bool evaluatePointer(const Expr *E, LValue &Result) {
8549 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8550 }
8551
8552public:
8553 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8554 : ExprEvaluatorBaseTy(Info), Result(Result),
8555 InvalidBaseOK(InvalidBaseOK) {}
8556
8557 bool Success(const APValue &V, const Expr *E) {
8558 Result.setFrom(this->Info.Ctx, V);
8559 return true;
8560 }
8561
8562 bool VisitMemberExpr(const MemberExpr *E) {
8563 // Handle non-static data members.
8564 QualType BaseTy;
8565 bool EvalOK;
8566 if (E->isArrow()) {
8567 EvalOK = evaluatePointer(E->getBase(), Result);
8568 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8569 } else if (E->getBase()->isPRValue()) {
8570 assert(E->getBase()->getType()->isRecordType());
8571 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8572 BaseTy = E->getBase()->getType();
8573 } else {
8574 EvalOK = this->Visit(E->getBase());
8575 BaseTy = E->getBase()->getType();
8576 }
8577 if (!EvalOK) {
8578 if (!InvalidBaseOK)
8579 return false;
8580 Result.setInvalid(E);
8581 return true;
8582 }
8583
8584 const ValueDecl *MD = E->getMemberDecl();
8585 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8586 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8587 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8588 (void)BaseTy;
8589 if (!HandleLValueMember(this->Info, E, Result, FD))
8590 return false;
8591 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8592 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8593 return false;
8594 } else
8595 return this->Error(E);
8596
8597 if (MD->getType()->isReferenceType()) {
8598 APValue RefValue;
8599 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8600 RefValue))
8601 return false;
8602 return Success(RefValue, E);
8603 }
8604 return true;
8605 }
8606
8607 bool VisitBinaryOperator(const BinaryOperator *E) {
8608 switch (E->getOpcode()) {
8609 default:
8610 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8611
8612 case BO_PtrMemD:
8613 case BO_PtrMemI:
8614 return HandleMemberPointerAccess(this->Info, E, Result);
8615 }
8616 }
8617
8618 bool VisitCastExpr(const CastExpr *E) {
8619 switch (E->getCastKind()) {
8620 default:
8621 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8622
8623 case CK_DerivedToBase:
8624 case CK_UncheckedDerivedToBase:
8625 if (!this->Visit(E->getSubExpr()))
8626 return false;
8627
8628 // Now figure out the necessary offset to add to the base LV to get from
8629 // the derived class to the base class.
8630 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8631 Result);
8632 }
8633 }
8634};
8635}
8636
8637//===----------------------------------------------------------------------===//
8638// LValue Evaluation
8639//
8640// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8641// function designators (in C), decl references to void objects (in C), and
8642// temporaries (if building with -Wno-address-of-temporary).
8643//
8644// LValue evaluation produces values comprising a base expression of one of the
8645// following types:
8646// - Declarations
8647// * VarDecl
8648// * FunctionDecl
8649// - Literals
8650// * CompoundLiteralExpr in C (and in global scope in C++)
8651// * StringLiteral
8652// * PredefinedExpr
8653// * ObjCStringLiteralExpr
8654// * ObjCEncodeExpr
8655// * AddrLabelExpr
8656// * BlockExpr
8657// * CallExpr for a MakeStringConstant builtin
8658// - typeid(T) expressions, as TypeInfoLValues
8659// - Locals and temporaries
8660// * MaterializeTemporaryExpr
8661// * Any Expr, with a CallIndex indicating the function in which the temporary
8662// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8663// from the AST (FIXME).
8664// * A MaterializeTemporaryExpr that has static storage duration, with no
8665// CallIndex, for a lifetime-extended temporary.
8666// * The ConstantExpr that is currently being evaluated during evaluation of an
8667// immediate invocation.
8668// plus an offset in bytes.
8669//===----------------------------------------------------------------------===//
8670namespace {
8671class LValueExprEvaluator
8672 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8673public:
8674 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8675 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8676
8677 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8678 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8679
8680 bool VisitCallExpr(const CallExpr *E);
8681 bool VisitDeclRefExpr(const DeclRefExpr *E);
8682 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8683 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8684 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8685 bool VisitMemberExpr(const MemberExpr *E);
8686 bool VisitStringLiteral(const StringLiteral *E) {
8688 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
8689 }
8690 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8691 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8692 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8693 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8694 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
8695 bool VisitUnaryDeref(const UnaryOperator *E);
8696 bool VisitUnaryReal(const UnaryOperator *E);
8697 bool VisitUnaryImag(const UnaryOperator *E);
8698 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8699 return VisitUnaryPreIncDec(UO);
8700 }
8701 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8702 return VisitUnaryPreIncDec(UO);
8703 }
8704 bool VisitBinAssign(const BinaryOperator *BO);
8705 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8706
8707 bool VisitCastExpr(const CastExpr *E) {
8708 switch (E->getCastKind()) {
8709 default:
8710 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8711
8712 case CK_LValueBitCast:
8713 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8714 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8715 if (!Visit(E->getSubExpr()))
8716 return false;
8717 Result.Designator.setInvalid();
8718 return true;
8719
8720 case CK_BaseToDerived:
8721 if (!Visit(E->getSubExpr()))
8722 return false;
8723 return HandleBaseToDerivedCast(Info, E, Result);
8724
8725 case CK_Dynamic:
8726 if (!Visit(E->getSubExpr()))
8727 return false;
8728 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8729 }
8730 }
8731};
8732} // end anonymous namespace
8733
8734/// Get an lvalue to a field of a lambda's closure type.
8735static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8736 const CXXMethodDecl *MD, const FieldDecl *FD,
8737 bool LValueToRValueConversion) {
8738 // Static lambda function call operators can't have captures. We already
8739 // diagnosed this, so bail out here.
8740 if (MD->isStatic()) {
8741 assert(Info.CurrentCall->This == nullptr &&
8742 "This should not be set for a static call operator");
8743 return false;
8744 }
8745
8746 // Start with 'Result' referring to the complete closure object...
8748 // Self may be passed by reference or by value.
8749 const ParmVarDecl *Self = MD->getParamDecl(0);
8750 if (Self->getType()->isReferenceType()) {
8751 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
8752 Result.setFrom(Info.Ctx, *RefValue);
8753 } else {
8754 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
8755 CallStackFrame *Frame =
8756 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
8757 .first;
8758 unsigned Version = Info.CurrentCall->Arguments.Version;
8759 Result.set({VD, Frame->Index, Version});
8760 }
8761 } else
8762 Result = *Info.CurrentCall->This;
8763
8764 // ... then update it to refer to the field of the closure object
8765 // that represents the capture.
8766 if (!HandleLValueMember(Info, E, Result, FD))
8767 return false;
8768
8769 // And if the field is of reference type (or if we captured '*this' by
8770 // reference), update 'Result' to refer to what
8771 // the field refers to.
8772 if (LValueToRValueConversion) {
8773 APValue RVal;
8774 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
8775 return false;
8776 Result.setFrom(Info.Ctx, RVal);
8777 }
8778 return true;
8779}
8780
8781/// Evaluate an expression as an lvalue. This can be legitimately called on
8782/// expressions which are not glvalues, in three cases:
8783/// * function designators in C, and
8784/// * "extern void" objects
8785/// * @selector() expressions in Objective-C
8786static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8787 bool InvalidBaseOK) {
8788 assert(!E->isValueDependent());
8789 assert(E->isGLValue() || E->getType()->isFunctionType() ||
8790 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8791 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8792}
8793
8794bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8795 const NamedDecl *D = E->getDecl();
8798 return Success(cast<ValueDecl>(D));
8799 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8800 return VisitVarDecl(E, VD);
8801 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8802 return Visit(BD->getBinding());
8803 return Error(E);
8804}
8805
8806
8807bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8808
8809 // If we are within a lambda's call operator, check whether the 'VD' referred
8810 // to within 'E' actually represents a lambda-capture that maps to a
8811 // data-member/field within the closure object, and if so, evaluate to the
8812 // field or what the field refers to.
8813 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8814 isa<DeclRefExpr>(E) &&
8815 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8816 // We don't always have a complete capture-map when checking or inferring if
8817 // the function call operator meets the requirements of a constexpr function
8818 // - but we don't need to evaluate the captures to determine constexprness
8819 // (dcl.constexpr C++17).
8820 if (Info.checkingPotentialConstantExpression())
8821 return false;
8822
8823 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8824 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
8825 return HandleLambdaCapture(Info, E, Result, MD, FD,
8826 FD->getType()->isReferenceType());
8827 }
8828 }
8829
8830 CallStackFrame *Frame = nullptr;
8831 unsigned Version = 0;
8832 if (VD->hasLocalStorage()) {
8833 // Only if a local variable was declared in the function currently being
8834 // evaluated, do we expect to be able to find its value in the current
8835 // frame. (Otherwise it was likely declared in an enclosing context and
8836 // could either have a valid evaluatable value (for e.g. a constexpr
8837 // variable) or be ill-formed (and trigger an appropriate evaluation
8838 // diagnostic)).
8839 CallStackFrame *CurrFrame = Info.CurrentCall;
8840 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8841 // Function parameters are stored in some caller's frame. (Usually the
8842 // immediate caller, but for an inherited constructor they may be more
8843 // distant.)
8844 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8845 if (CurrFrame->Arguments) {
8846 VD = CurrFrame->Arguments.getOrigParam(PVD);
8847 Frame =
8848 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8849 Version = CurrFrame->Arguments.Version;
8850 }
8851 } else {
8852 Frame = CurrFrame;
8853 Version = CurrFrame->getCurrentTemporaryVersion(VD);
8854 }
8855 }
8856 }
8857
8858 if (!VD->getType()->isReferenceType()) {
8859 if (Frame) {
8860 Result.set({VD, Frame->Index, Version});
8861 return true;
8862 }
8863 return Success(VD);
8864 }
8865
8866 if (!Info.getLangOpts().CPlusPlus11) {
8867 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8868 << VD << VD->getType();
8869 Info.Note(VD->getLocation(), diag::note_declared_at);
8870 }
8871
8872 APValue *V;
8873 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8874 return false;
8875 if (!V->hasValue()) {
8876 // FIXME: Is it possible for V to be indeterminate here? If so, we should
8877 // adjust the diagnostic to say that.
8878 if (!Info.checkingPotentialConstantExpression())
8879 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8880 return false;
8881 }
8882 return Success(*V, E);
8883}
8884
8885bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8886 if (!IsConstantEvaluatedBuiltinCall(E))
8887 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8888
8889 switch (E->getBuiltinCallee()) {
8890 default:
8891 return false;
8892 case Builtin::BIas_const:
8893 case Builtin::BIforward:
8894 case Builtin::BIforward_like:
8895 case Builtin::BImove:
8896 case Builtin::BImove_if_noexcept:
8897 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8898 return Visit(E->getArg(0));
8899 break;
8900 }
8901
8902 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8903}
8904
8905bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8906 const MaterializeTemporaryExpr *E) {
8907 // Walk through the expression to find the materialized temporary itself.
8910 const Expr *Inner =
8911 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8912
8913 // If we passed any comma operators, evaluate their LHSs.
8914 for (const Expr *E : CommaLHSs)
8915 if (!EvaluateIgnoredValue(Info, E))
8916 return false;
8917
8918 // A materialized temporary with static storage duration can appear within the
8919 // result of a constant expression evaluation, so we need to preserve its
8920 // value for use outside this evaluation.
8921 APValue *Value;
8922 if (E->getStorageDuration() == SD_Static) {
8923 if (Info.EvalMode == EvalInfo::EM_ConstantFold)
8924 return false;
8925 // FIXME: What about SD_Thread?
8926 Value = E->getOrCreateValue(true);
8927 *Value = APValue();
8928 Result.set(E);
8929 } else {
8930 Value = &Info.CurrentCall->createTemporary(
8931 E, Inner->getType(),
8932 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8933 : ScopeKind::Block,
8934 Result);
8935 }
8936
8937 QualType Type = Inner->getType();
8938
8939 // Materialize the temporary itself.
8940 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8941 *Value = APValue();
8942 return false;
8943 }
8944
8945 // Adjust our lvalue to refer to the desired subobject.
8946 for (unsigned I = Adjustments.size(); I != 0; /**/) {
8947 --I;
8948 switch (Adjustments[I].Kind) {
8950 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8951 Type, Result))
8952 return false;
8953 Type = Adjustments[I].DerivedToBase.BasePath->getType();
8954 break;
8955
8957 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8958 return false;
8959 Type = Adjustments[I].Field->getType();
8960 break;
8961
8963 if (!HandleMemberPointerAccess(this->Info, Type, Result,
8964 Adjustments[I].Ptr.RHS))
8965 return false;
8966 Type = Adjustments[I].Ptr.MPT->getPointeeType();
8967 break;
8968 }
8969 }
8970
8971 return true;
8972}
8973
8974bool
8975LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8976 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8977 "lvalue compound literal in c++?");
8978 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8979 // only see this when folding in C, so there's no standard to follow here.
8980 return Success(E);
8981}
8982
8983bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8985
8986 if (!E->isPotentiallyEvaluated()) {
8987 if (E->isTypeOperand())
8988 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8989 else
8990 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8991 } else {
8992 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8993 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8994 << E->getExprOperand()->getType()
8995 << E->getExprOperand()->getSourceRange();
8996 }
8997
8998 if (!Visit(E->getExprOperand()))
8999 return false;
9000
9001 std::optional<DynamicType> DynType =
9002 ComputeDynamicType(Info, E, Result, AK_TypeId);
9003 if (!DynType)
9004 return false;
9005
9006 TypeInfo =
9007 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
9008 }
9009
9011}
9012
9013bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9014 return Success(E->getGuidDecl());
9015}
9016
9017bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9018 // Handle static data members.
9019 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9020 VisitIgnoredBaseExpression(E->getBase());
9021 return VisitVarDecl(E, VD);
9022 }
9023
9024 // Handle static member functions.
9025 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9026 if (MD->isStatic()) {
9027 VisitIgnoredBaseExpression(E->getBase());
9028 return Success(MD);
9029 }
9030 }
9031
9032 // Handle non-static data members.
9033 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9034}
9035
9036bool LValueExprEvaluator::VisitExtVectorElementExpr(
9037 const ExtVectorElementExpr *E) {
9038 bool Success = true;
9039
9040 APValue Val;
9041 if (!Evaluate(Val, Info, E->getBase())) {
9042 if (!Info.noteFailure())
9043 return false;
9044 Success = false;
9045 }
9046
9048 E->getEncodedElementAccess(Indices);
9049 // FIXME: support accessing more than one element
9050 if (Indices.size() > 1)
9051 return false;
9052
9053 if (Success) {
9054 Result.setFrom(Info.Ctx, Val);
9055 const auto *VT = E->getBase()->getType()->castAs<VectorType>();
9056 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9057 VT->getNumElements(), Indices[0]);
9058 }
9059
9060 return Success;
9061}
9062
9063bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9064 if (E->getBase()->getType()->isSveVLSBuiltinType())
9065 return Error(E);
9066
9067 APSInt Index;
9068 bool Success = true;
9069
9070 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9071 APValue Val;
9072 if (!Evaluate(Val, Info, E->getBase())) {
9073 if (!Info.noteFailure())
9074 return false;
9075 Success = false;
9076 }
9077
9078 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9079 if (!Info.noteFailure())
9080 return false;
9081 Success = false;
9082 }
9083
9084 if (Success) {
9085 Result.setFrom(Info.Ctx, Val);
9086 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9087 VT->getNumElements(), Index.getExtValue());
9088 }
9089
9090 return Success;
9091 }
9092
9093 // C++17's rules require us to evaluate the LHS first, regardless of which
9094 // side is the base.
9095 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9096 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9097 : !EvaluateInteger(SubExpr, Index, Info)) {
9098 if (!Info.noteFailure())
9099 return false;
9100 Success = false;
9101 }
9102 }
9103
9104 return Success &&
9105 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9106}
9107
9108bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9109 return evaluatePointer(E->getSubExpr(), Result);
9110}
9111
9112bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9113 if (!Visit(E->getSubExpr()))
9114 return false;
9115 // __real is a no-op on scalar lvalues.
9116 if (E->getSubExpr()->getType()->isAnyComplexType())
9117 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9118 return true;
9119}
9120
9121bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9122 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9123 "lvalue __imag__ on scalar?");
9124 if (!Visit(E->getSubExpr()))
9125 return false;
9126 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9127 return true;
9128}
9129
9130bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9131 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9132 return Error(UO);
9133
9134 if (!this->Visit(UO->getSubExpr()))
9135 return false;
9136
9137 return handleIncDec(
9138 this->Info, UO, Result, UO->getSubExpr()->getType(),
9139 UO->isIncrementOp(), nullptr);
9140}
9141
9142bool LValueExprEvaluator::VisitCompoundAssignOperator(
9143 const CompoundAssignOperator *CAO) {
9144 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9145 return Error(CAO);
9146
9147 bool Success = true;
9148
9149 // C++17 onwards require that we evaluate the RHS first.
9150 APValue RHS;
9151 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9152 if (!Info.noteFailure())
9153 return false;
9154 Success = false;
9155 }
9156
9157 // The overall lvalue result is the result of evaluating the LHS.
9158 if (!this->Visit(CAO->getLHS()) || !Success)
9159 return false;
9160
9162 this->Info, CAO,
9163 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9164 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9165}
9166
9167bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9168 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9169 return Error(E);
9170
9171 bool Success = true;
9172
9173 // C++17 onwards require that we evaluate the RHS first.
9174 APValue NewVal;
9175 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9176 if (!Info.noteFailure())
9177 return false;
9178 Success = false;
9179 }
9180
9181 if (!this->Visit(E->getLHS()) || !Success)
9182 return false;
9183
9184 if (Info.getLangOpts().CPlusPlus20 &&
9185 !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
9186 return false;
9187
9188 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9189 NewVal);
9190}
9191
9192//===----------------------------------------------------------------------===//
9193// Pointer Evaluation
9194//===----------------------------------------------------------------------===//
9195
9196/// Attempts to compute the number of bytes available at the pointer
9197/// returned by a function with the alloc_size attribute. Returns true if we
9198/// were successful. Places an unsigned number into `Result`.
9199///
9200/// This expects the given CallExpr to be a call to a function with an
9201/// alloc_size attribute.
9203 const CallExpr *Call,
9204 llvm::APInt &Result) {
9205 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
9206
9207 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
9208 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
9209 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
9210 if (Call->getNumArgs() <= SizeArgNo)
9211 return false;
9212
9213 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
9216 return false;
9217 Into = ExprResult.Val.getInt();
9218 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
9219 return false;
9220 Into = Into.zext(BitsInSizeT);
9221 return true;
9222 };
9223
9224 APSInt SizeOfElem;
9225 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
9226 return false;
9227
9228 if (!AllocSize->getNumElemsParam().isValid()) {
9229 Result = std::move(SizeOfElem);
9230 return true;
9231 }
9232
9233 APSInt NumberOfElems;
9234 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
9235 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
9236 return false;
9237
9238 bool Overflow;
9239 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
9240 if (Overflow)
9241 return false;
9242
9243 Result = std::move(BytesAvailable);
9244 return true;
9245}
9246
9247/// Convenience function. LVal's base must be a call to an alloc_size
9248/// function.
9250 const LValue &LVal,
9251 llvm::APInt &Result) {
9252 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9253 "Can't get the size of a non alloc_size function");
9254 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9255 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9256 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
9257}
9258
9259/// Attempts to evaluate the given LValueBase as the result of a call to
9260/// a function with the alloc_size attribute. If it was possible to do so, this
9261/// function will return true, make Result's Base point to said function call,
9262/// and mark Result's Base as invalid.
9264 LValue &Result) {
9265 if (Base.isNull())
9266 return false;
9267
9268 // Because we do no form of static analysis, we only support const variables.
9269 //
9270 // Additionally, we can't support parameters, nor can we support static
9271 // variables (in the latter case, use-before-assign isn't UB; in the former,
9272 // we have no clue what they'll be assigned to).
9273 const auto *VD =
9274 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9275 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9276 return false;
9277
9278 const Expr *Init = VD->getAnyInitializer();
9279 if (!Init || Init->getType().isNull())
9280 return false;
9281
9282 const Expr *E = Init->IgnoreParens();
9283 if (!tryUnwrapAllocSizeCall(E))
9284 return false;
9285
9286 // Store E instead of E unwrapped so that the type of the LValue's base is
9287 // what the user wanted.
9288 Result.setInvalid(E);
9289
9290 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9291 Result.addUnsizedArray(Info, E, Pointee);
9292 return true;
9293}
9294
9295namespace {
9296class PointerExprEvaluator
9297 : public ExprEvaluatorBase<PointerExprEvaluator> {
9298 LValue &Result;
9299 bool InvalidBaseOK;
9300
9301 bool Success(const Expr *E) {
9302 Result.set(E);
9303 return true;
9304 }
9305
9306 bool evaluateLValue(const Expr *E, LValue &Result) {
9307 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9308 }
9309
9310 bool evaluatePointer(const Expr *E, LValue &Result) {
9311 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9312 }
9313
9314 bool visitNonBuiltinCallExpr(const CallExpr *E);
9315public:
9316
9317 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9318 : ExprEvaluatorBaseTy(info), Result(Result),
9319 InvalidBaseOK(InvalidBaseOK) {}
9320
9321 bool Success(const APValue &V, const Expr *E) {
9322 Result.setFrom(Info.Ctx, V);
9323 return true;
9324 }
9325 bool ZeroInitialization(const Expr *E) {
9326 Result.setNull(Info.Ctx, E->getType());
9327 return true;
9328 }
9329
9330 bool VisitBinaryOperator(const BinaryOperator *E);
9331 bool VisitCastExpr(const CastExpr* E);
9332 bool VisitUnaryAddrOf(const UnaryOperator *E);
9333 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9334 { return Success(E); }
9335 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9336 if (E->isExpressibleAsConstantInitializer())
9337 return Success(E);
9338 if (Info.noteFailure())
9339 EvaluateIgnoredValue(Info, E->getSubExpr());
9340 return Error(E);
9341 }
9342 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9343 { return Success(E); }
9344 bool VisitCallExpr(const CallExpr *E);
9345 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9346 bool VisitBlockExpr(const BlockExpr *E) {
9347 if (!E->getBlockDecl()->hasCaptures())
9348 return Success(E);
9349 return Error(E);
9350 }
9351 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9352 auto DiagnoseInvalidUseOfThis = [&] {
9353 if (Info.getLangOpts().CPlusPlus11)
9354 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9355 else
9356 Info.FFDiag(E);
9357 };
9358
9359 // Can't look at 'this' when checking a potential constant expression.
9360 if (Info.checkingPotentialConstantExpression())
9361 return false;
9362
9363 bool IsExplicitLambda =
9364 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9365 if (!IsExplicitLambda) {
9366 if (!Info.CurrentCall->This) {
9367 DiagnoseInvalidUseOfThis();
9368 return false;
9369 }
9370
9371 Result = *Info.CurrentCall->This;
9372 }
9373
9374 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9375 // Ensure we actually have captured 'this'. If something was wrong with
9376 // 'this' capture, the error would have been previously reported.
9377 // Otherwise we can be inside of a default initialization of an object
9378 // declared by lambda's body, so no need to return false.
9379 if (!Info.CurrentCall->LambdaThisCaptureField) {
9380 if (IsExplicitLambda && !Info.CurrentCall->This) {
9381 DiagnoseInvalidUseOfThis();
9382 return false;
9383 }
9384
9385 return true;
9386 }
9387
9388 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9389 return HandleLambdaCapture(
9390 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9391 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9392 }
9393 return true;
9394 }
9395
9396 bool VisitCXXNewExpr(const CXXNewExpr *E);
9397
9398 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9399 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9400 APValue LValResult = E->EvaluateInContext(
9401 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9402 Result.setFrom(Info.Ctx, LValResult);
9403 return true;
9404 }
9405
9406 bool VisitEmbedExpr(const EmbedExpr *E) {
9407 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9408 return true;
9409 }
9410
9411 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9412 std::string ResultStr = E->ComputeName(Info.Ctx);
9413
9414 QualType CharTy = Info.Ctx.CharTy.withConst();
9415 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9416 ResultStr.size() + 1);
9417 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9418 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9419
9420 StringLiteral *SL =
9421 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9422 /*Pascal*/ false, ArrayTy, E->getLocation());
9423
9424 evaluateLValue(SL, Result);
9425 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9426 return true;
9427 }
9428
9429 // FIXME: Missing: @protocol, @selector
9430};
9431} // end anonymous namespace
9432
9433static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9434 bool InvalidBaseOK) {
9435 assert(!E->isValueDependent());
9436 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9437 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9438}
9439
9440bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9441 if (E->getOpcode() != BO_Add &&
9442 E->getOpcode() != BO_Sub)
9443 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9444
9445 const Expr *PExp = E->getLHS();
9446 const Expr *IExp = E->getRHS();
9447 if (IExp->getType()->isPointerType())
9448 std::swap(PExp, IExp);
9449
9450 bool EvalPtrOK = evaluatePointer(PExp, Result);
9451 if (!EvalPtrOK && !Info.noteFailure())
9452 return false;
9453
9454 llvm::APSInt Offset;
9455 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9456 return false;
9457
9458 if (E->getOpcode() == BO_Sub)
9459 negateAsSigned(Offset);
9460
9461 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9462 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9463}
9464
9465bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9466 return evaluateLValue(E->getSubExpr(), Result);
9467}
9468
9469// Is the provided decl 'std::source_location::current'?
9471 if (!FD)
9472 return false;
9473 const IdentifierInfo *FnII = FD->getIdentifier();
9474 if (!FnII || !FnII->isStr("current"))
9475 return false;
9476
9477 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9478 if (!RD)
9479 return false;
9480
9481 const IdentifierInfo *ClassII = RD->getIdentifier();
9482 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9483}
9484
9485bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9486 const Expr *SubExpr = E->getSubExpr();
9487
9488 switch (E->getCastKind()) {
9489 default:
9490 break;
9491 case CK_BitCast:
9492 case CK_CPointerToObjCPointerCast:
9493 case CK_BlockPointerToObjCPointerCast:
9494 case CK_AnyPointerToBlockPointerCast:
9495 case CK_AddressSpaceConversion:
9496 if (!Visit(SubExpr))
9497 return false;
9498 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9499 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9500 // also static_casts, but we disallow them as a resolution to DR1312.
9501 if (!E->getType()->isVoidPointerType()) {
9502 // In some circumstances, we permit casting from void* to cv1 T*, when the
9503 // actual pointee object is actually a cv2 T.
9504 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9505 !Result.IsNullPtr;
9506 bool VoidPtrCastMaybeOK =
9507 Result.IsNullPtr ||
9508 (HasValidResult &&
9509 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9510 E->getType()->getPointeeType()));
9511 // 1. We'll allow it in std::allocator::allocate, and anything which that
9512 // calls.
9513 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9514 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9515 // We'll allow it in the body of std::source_location::current. GCC's
9516 // implementation had a parameter of type `void*`, and casts from
9517 // that back to `const __impl*` in its body.
9518 if (VoidPtrCastMaybeOK &&
9519 (Info.getStdAllocatorCaller("allocate") ||
9520 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9521 Info.getLangOpts().CPlusPlus26)) {
9522 // Permitted.
9523 } else {
9524 if (SubExpr->getType()->isVoidPointerType() &&
9525 Info.getLangOpts().CPlusPlus) {
9526 if (HasValidResult)
9527 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9528 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9529 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9530 << E->getType()->getPointeeType();
9531 else
9532 CCEDiag(E, diag::note_constexpr_invalid_cast)
9533 << 3 << SubExpr->getType();
9534 } else
9535 CCEDiag(E, diag::note_constexpr_invalid_cast)
9536 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9537 Result.Designator.setInvalid();
9538 }
9539 }
9540 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9541 ZeroInitialization(E);
9542 return true;
9543
9544 case CK_DerivedToBase:
9545 case CK_UncheckedDerivedToBase:
9546 if (!evaluatePointer(E->getSubExpr(), Result))
9547 return false;
9548 if (!Result.Base && Result.Offset.isZero())
9549 return true;
9550
9551 // Now figure out the necessary offset to add to the base LV to get from
9552 // the derived class to the base class.
9553 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9554 castAs<PointerType>()->getPointeeType(),
9555 Result);
9556
9557 case CK_BaseToDerived:
9558 if (!Visit(E->getSubExpr()))
9559 return false;
9560 if (!Result.Base && Result.Offset.isZero())
9561 return true;
9562 return HandleBaseToDerivedCast(Info, E, Result);
9563
9564 case CK_Dynamic:
9565 if (!Visit(E->getSubExpr()))
9566 return false;
9567 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9568
9569 case CK_NullToPointer:
9570 VisitIgnoredValue(E->getSubExpr());
9571 return ZeroInitialization(E);
9572
9573 case CK_IntegralToPointer: {
9574 CCEDiag(E, diag::note_constexpr_invalid_cast)
9575 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9576
9577 APValue Value;
9578 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9579 break;
9580
9581 if (Value.isInt()) {
9582 unsigned Size = Info.Ctx.getTypeSize(E->getType());
9583 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9584 Result.Base = (Expr*)nullptr;
9585 Result.InvalidBase = false;
9586 Result.Offset = CharUnits::fromQuantity(N);
9587 Result.Designator.setInvalid();
9588 Result.IsNullPtr = false;
9589 return true;
9590 } else {
9591 // In rare instances, the value isn't an lvalue.
9592 // For example, when the value is the difference between the addresses of
9593 // two labels. We reject that as a constant expression because we can't
9594 // compute a valid offset to convert into a pointer.
9595 if (!Value.isLValue())
9596 return false;
9597
9598 // Cast is of an lvalue, no need to change value.
9599 Result.setFrom(Info.Ctx, Value);
9600 return true;
9601 }
9602 }
9603
9604 case CK_ArrayToPointerDecay: {
9605 if (SubExpr->isGLValue()) {
9606 if (!evaluateLValue(SubExpr, Result))
9607 return false;
9608 } else {
9609 APValue &Value = Info.CurrentCall->createTemporary(
9610 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9611 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9612 return false;
9613 }
9614 // The result is a pointer to the first element of the array.
9615 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9616 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9617 Result.addArray(Info, E, CAT);
9618 else
9619 Result.addUnsizedArray(Info, E, AT->getElementType());
9620 return true;
9621 }
9622
9623 case CK_FunctionToPointerDecay:
9624 return evaluateLValue(SubExpr, Result);
9625
9626 case CK_LValueToRValue: {
9627 LValue LVal;
9628 if (!evaluateLValue(E->getSubExpr(), LVal))
9629 return false;
9630
9631 APValue RVal;
9632 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9633 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9634 LVal, RVal))
9635 return InvalidBaseOK &&
9636 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9637 return Success(RVal, E);
9638 }
9639 }
9640
9641 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9642}
9643
9645 UnaryExprOrTypeTrait ExprKind) {
9646 // C++ [expr.alignof]p3:
9647 // When alignof is applied to a reference type, the result is the
9648 // alignment of the referenced type.
9649 T = T.getNonReferenceType();
9650
9651 if (T.getQualifiers().hasUnaligned())
9652 return CharUnits::One();
9653
9654 const bool AlignOfReturnsPreferred =
9655 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9656
9657 // __alignof is defined to return the preferred alignment.
9658 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9659 // as well.
9660 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9661 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
9662 // alignof and _Alignof are defined to return the ABI alignment.
9663 else if (ExprKind == UETT_AlignOf)
9664 return Ctx.getTypeAlignInChars(T.getTypePtr());
9665 else
9666 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9667}
9668
9670 UnaryExprOrTypeTrait ExprKind) {
9671 E = E->IgnoreParens();
9672
9673 // The kinds of expressions that we have special-case logic here for
9674 // should be kept up to date with the special checks for those
9675 // expressions in Sema.
9676
9677 // alignof decl is always accepted, even if it doesn't make sense: we default
9678 // to 1 in those cases.
9679 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9680 return Ctx.getDeclAlign(DRE->getDecl(),
9681 /*RefAsPointee*/ true);
9682
9683 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9684 return Ctx.getDeclAlign(ME->getMemberDecl(),
9685 /*RefAsPointee*/ true);
9686
9687 return GetAlignOfType(Ctx, E->getType(), ExprKind);
9688}
9689
9690static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9691 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9692 return Info.Ctx.getDeclAlign(VD);
9693 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9694 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
9695 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
9696}
9697
9698/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9699/// __builtin_is_aligned and __builtin_assume_aligned.
9700static bool getAlignmentArgument(const Expr *E, QualType ForType,
9701 EvalInfo &Info, APSInt &Alignment) {
9702 if (!EvaluateInteger(E, Alignment, Info))
9703 return false;
9704 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9705 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9706 return false;
9707 }
9708 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9709 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9710 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9711 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9712 << MaxValue << ForType << Alignment;
9713 return false;
9714 }
9715 // Ensure both alignment and source value have the same bit width so that we
9716 // don't assert when computing the resulting value.
9717 APSInt ExtAlignment =
9718 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9719 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9720 "Alignment should not be changed by ext/trunc");
9721 Alignment = ExtAlignment;
9722 assert(Alignment.getBitWidth() == SrcWidth);
9723 return true;
9724}
9725
9726// To be clear: this happily visits unsupported builtins. Better name welcomed.
9727bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9728 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9729 return true;
9730
9731 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9732 return false;
9733
9734 Result.setInvalid(E);
9735 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9736 Result.addUnsizedArray(Info, E, PointeeTy);
9737 return true;
9738}
9739
9740bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9741 if (!IsConstantEvaluatedBuiltinCall(E))
9742 return visitNonBuiltinCallExpr(E);
9743 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9744}
9745
9746// Determine if T is a character type for which we guarantee that
9747// sizeof(T) == 1.
9749 return T->isCharType() || T->isChar8Type();
9750}
9751
9752bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9753 unsigned BuiltinOp) {
9755 return Success(E);
9756
9757 switch (BuiltinOp) {
9758 case Builtin::BIaddressof:
9759 case Builtin::BI__addressof:
9760 case Builtin::BI__builtin_addressof:
9761 return evaluateLValue(E->getArg(0), Result);
9762 case Builtin::BI__builtin_assume_aligned: {
9763 // We need to be very careful here because: if the pointer does not have the
9764 // asserted alignment, then the behavior is undefined, and undefined
9765 // behavior is non-constant.
9766 if (!evaluatePointer(E->getArg(0), Result))
9767 return false;
9768
9769 LValue OffsetResult(Result);
9770 APSInt Alignment;
9771 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9772 Alignment))
9773 return false;
9774 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9775
9776 if (E->getNumArgs() > 2) {
9777 APSInt Offset;
9778 if (!EvaluateInteger(E->getArg(2), Offset, Info))
9779 return false;
9780
9781 int64_t AdditionalOffset = -Offset.getZExtValue();
9782 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9783 }
9784
9785 // If there is a base object, then it must have the correct alignment.
9786 if (OffsetResult.Base) {
9787 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9788
9789 if (BaseAlignment < Align) {
9790 Result.Designator.setInvalid();
9791 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
9792 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
9793 return false;
9794 }
9795 }
9796
9797 // The offset must also have the correct alignment.
9798 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9799 Result.Designator.setInvalid();
9800
9801 (OffsetResult.Base
9802 ? CCEDiag(E->getArg(0),
9803 diag::note_constexpr_baa_insufficient_alignment)
9804 << 1
9805 : CCEDiag(E->getArg(0),
9806 diag::note_constexpr_baa_value_insufficient_alignment))
9807 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
9808 return false;
9809 }
9810
9811 return true;
9812 }
9813 case Builtin::BI__builtin_align_up:
9814 case Builtin::BI__builtin_align_down: {
9815 if (!evaluatePointer(E->getArg(0), Result))
9816 return false;
9817 APSInt Alignment;
9818 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9819 Alignment))
9820 return false;
9821 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9822 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9823 // For align_up/align_down, we can return the same value if the alignment
9824 // is known to be greater or equal to the requested value.
9825 if (PtrAlign.getQuantity() >= Alignment)
9826 return true;
9827
9828 // The alignment could be greater than the minimum at run-time, so we cannot
9829 // infer much about the resulting pointer value. One case is possible:
9830 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9831 // can infer the correct index if the requested alignment is smaller than
9832 // the base alignment so we can perform the computation on the offset.
9833 if (BaseAlignment.getQuantity() >= Alignment) {
9834 assert(Alignment.getBitWidth() <= 64 &&
9835 "Cannot handle > 64-bit address-space");
9836 uint64_t Alignment64 = Alignment.getZExtValue();
9838 BuiltinOp == Builtin::BI__builtin_align_down
9839 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9840 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9841 Result.adjustOffset(NewOffset - Result.Offset);
9842 // TODO: diagnose out-of-bounds values/only allow for arrays?
9843 return true;
9844 }
9845 // Otherwise, we cannot constant-evaluate the result.
9846 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9847 << Alignment;
9848 return false;
9849 }
9850 case Builtin::BI__builtin_operator_new:
9851 return HandleOperatorNewCall(Info, E, Result);
9852 case Builtin::BI__builtin_launder:
9853 return evaluatePointer(E->getArg(0), Result);
9854 case Builtin::BIstrchr:
9855 case Builtin::BIwcschr:
9856 case Builtin::BImemchr:
9857 case Builtin::BIwmemchr:
9858 if (Info.getLangOpts().CPlusPlus11)
9859 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9860 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9861 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9862 else
9863 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9864 [[fallthrough]];
9865 case Builtin::BI__builtin_strchr:
9866 case Builtin::BI__builtin_wcschr:
9867 case Builtin::BI__builtin_memchr:
9868 case Builtin::BI__builtin_char_memchr:
9869 case Builtin::BI__builtin_wmemchr: {
9870 if (!Visit(E->getArg(0)))
9871 return false;
9872 APSInt Desired;
9873 if (!EvaluateInteger(E->getArg(1), Desired, Info))
9874 return false;
9875 uint64_t MaxLength = uint64_t(-1);
9876 if (BuiltinOp != Builtin::BIstrchr &&
9877 BuiltinOp != Builtin::BIwcschr &&
9878 BuiltinOp != Builtin::BI__builtin_strchr &&
9879 BuiltinOp != Builtin::BI__builtin_wcschr) {
9880 APSInt N;
9881 if (!EvaluateInteger(E->getArg(2), N, Info))
9882 return false;
9883 MaxLength = N.getZExtValue();
9884 }
9885 // We cannot find the value if there are no candidates to match against.
9886 if (MaxLength == 0u)
9887 return ZeroInitialization(E);
9888 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9889 Result.Designator.Invalid)
9890 return false;
9891 QualType CharTy = Result.Designator.getType(Info.Ctx);
9892 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9893 BuiltinOp == Builtin::BI__builtin_memchr;
9894 assert(IsRawByte ||
9895 Info.Ctx.hasSameUnqualifiedType(
9896 CharTy, E->getArg(0)->getType()->getPointeeType()));
9897 // Pointers to const void may point to objects of incomplete type.
9898 if (IsRawByte && CharTy->isIncompleteType()) {
9899 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9900 return false;
9901 }
9902 // Give up on byte-oriented matching against multibyte elements.
9903 // FIXME: We can compare the bytes in the correct order.
9904 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9905 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9906 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
9907 << CharTy;
9908 return false;
9909 }
9910 // Figure out what value we're actually looking for (after converting to
9911 // the corresponding unsigned type if necessary).
9912 uint64_t DesiredVal;
9913 bool StopAtNull = false;
9914 switch (BuiltinOp) {
9915 case Builtin::BIstrchr:
9916 case Builtin::BI__builtin_strchr:
9917 // strchr compares directly to the passed integer, and therefore
9918 // always fails if given an int that is not a char.
9919 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9920 E->getArg(1)->getType(),
9921 Desired),
9922 Desired))
9923 return ZeroInitialization(E);
9924 StopAtNull = true;
9925 [[fallthrough]];
9926 case Builtin::BImemchr:
9927 case Builtin::BI__builtin_memchr:
9928 case Builtin::BI__builtin_char_memchr:
9929 // memchr compares by converting both sides to unsigned char. That's also
9930 // correct for strchr if we get this far (to cope with plain char being
9931 // unsigned in the strchr case).
9932 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9933 break;
9934
9935 case Builtin::BIwcschr:
9936 case Builtin::BI__builtin_wcschr:
9937 StopAtNull = true;
9938 [[fallthrough]];
9939 case Builtin::BIwmemchr:
9940 case Builtin::BI__builtin_wmemchr:
9941 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9942 DesiredVal = Desired.getZExtValue();
9943 break;
9944 }
9945
9946 for (; MaxLength; --MaxLength) {
9947 APValue Char;
9948 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9949 !Char.isInt())
9950 return false;
9951 if (Char.getInt().getZExtValue() == DesiredVal)
9952 return true;
9953 if (StopAtNull && !Char.getInt())
9954 break;
9955 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9956 return false;
9957 }
9958 // Not found: return nullptr.
9959 return ZeroInitialization(E);
9960 }
9961
9962 case Builtin::BImemcpy:
9963 case Builtin::BImemmove:
9964 case Builtin::BIwmemcpy:
9965 case Builtin::BIwmemmove:
9966 if (Info.getLangOpts().CPlusPlus11)
9967 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9968 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9969 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9970 else
9971 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9972 [[fallthrough]];
9973 case Builtin::BI__builtin_memcpy:
9974 case Builtin::BI__builtin_memmove:
9975 case Builtin::BI__builtin_wmemcpy:
9976 case Builtin::BI__builtin_wmemmove: {
9977 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9978 BuiltinOp == Builtin::BIwmemmove ||
9979 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9980 BuiltinOp == Builtin::BI__builtin_wmemmove;
9981 bool Move = BuiltinOp == Builtin::BImemmove ||
9982 BuiltinOp == Builtin::BIwmemmove ||
9983 BuiltinOp == Builtin::BI__builtin_memmove ||
9984 BuiltinOp == Builtin::BI__builtin_wmemmove;
9985
9986 // The result of mem* is the first argument.
9987 if (!Visit(E->getArg(0)))
9988 return false;
9989 LValue Dest = Result;
9990
9991 LValue Src;
9992 if (!EvaluatePointer(E->getArg(1), Src, Info))
9993 return false;
9994
9995 APSInt N;
9996 if (!EvaluateInteger(E->getArg(2), N, Info))
9997 return false;
9998 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9999
10000 // If the size is zero, we treat this as always being a valid no-op.
10001 // (Even if one of the src and dest pointers is null.)
10002 if (!N)
10003 return true;
10004
10005 // Otherwise, if either of the operands is null, we can't proceed. Don't
10006 // try to determine the type of the copied objects, because there aren't
10007 // any.
10008 if (!Src.Base || !Dest.Base) {
10009 APValue Val;
10010 (!Src.Base ? Src : Dest).moveInto(Val);
10011 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10012 << Move << WChar << !!Src.Base
10013 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10014 return false;
10015 }
10016 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10017 return false;
10018
10019 // We require that Src and Dest are both pointers to arrays of
10020 // trivially-copyable type. (For the wide version, the designator will be
10021 // invalid if the designated object is not a wchar_t.)
10022 QualType T = Dest.Designator.getType(Info.Ctx);
10023 QualType SrcT = Src.Designator.getType(Info.Ctx);
10024 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10025 // FIXME: Consider using our bit_cast implementation to support this.
10026 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10027 return false;
10028 }
10029 if (T->isIncompleteType()) {
10030 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10031 return false;
10032 }
10033 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10034 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10035 return false;
10036 }
10037
10038 // Figure out how many T's we're copying.
10039 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10040 if (TSize == 0)
10041 return false;
10042 if (!WChar) {
10043 uint64_t Remainder;
10044 llvm::APInt OrigN = N;
10045 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10046 if (Remainder) {
10047 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10048 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10049 << (unsigned)TSize;
10050 return false;
10051 }
10052 }
10053
10054 // Check that the copying will remain within the arrays, just so that we
10055 // can give a more meaningful diagnostic. This implicitly also checks that
10056 // N fits into 64 bits.
10057 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10058 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10059 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10060 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10061 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10062 << toString(N, 10, /*Signed*/false);
10063 return false;
10064 }
10065 uint64_t NElems = N.getZExtValue();
10066 uint64_t NBytes = NElems * TSize;
10067
10068 // Check for overlap.
10069 int Direction = 1;
10070 if (HasSameBase(Src, Dest)) {
10071 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10072 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10073 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10074 // Dest is inside the source region.
10075 if (!Move) {
10076 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10077 return false;
10078 }
10079 // For memmove and friends, copy backwards.
10080 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10081 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10082 return false;
10083 Direction = -1;
10084 } else if (!Move && SrcOffset >= DestOffset &&
10085 SrcOffset - DestOffset < NBytes) {
10086 // Src is inside the destination region for memcpy: invalid.
10087 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10088 return false;
10089 }
10090 }
10091
10092 while (true) {
10093 APValue Val;
10094 // FIXME: Set WantObjectRepresentation to true if we're copying a
10095 // char-like type?
10096 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10097 !handleAssignment(Info, E, Dest, T, Val))
10098 return false;
10099 // Do not iterate past the last element; if we're copying backwards, that
10100 // might take us off the start of the array.
10101 if (--NElems == 0)
10102 return true;
10103 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10104 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10105 return false;
10106 }
10107 }
10108
10109 default:
10110 return false;
10111 }
10112}
10113
10114static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10115 APValue &Result, const InitListExpr *ILE,
10116 QualType AllocType);
10117static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10118 APValue &Result,
10119 const CXXConstructExpr *CCE,
10120 QualType AllocType);
10121
10122bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10123 if (!Info.getLangOpts().CPlusPlus20)
10124 Info.CCEDiag(E, diag::note_constexpr_new);
10125
10126 // We cannot speculatively evaluate a delete expression.
10127 if (Info.SpeculativeEvaluationDepth)
10128 return false;
10129
10130 FunctionDecl *OperatorNew = E->getOperatorNew();
10131 QualType AllocType = E->getAllocatedType();
10132 QualType TargetType = AllocType;
10133
10134 bool IsNothrow = false;
10135 bool IsPlacement = false;
10136
10137 if (E->getNumPlacementArgs() == 1 &&
10138 E->getPlacementArg(0)->getType()->isNothrowT()) {
10139 // The only new-placement list we support is of the form (std::nothrow).
10140 //
10141 // FIXME: There is no restriction on this, but it's not clear that any
10142 // other form makes any sense. We get here for cases such as:
10143 //
10144 // new (std::align_val_t{N}) X(int)
10145 //
10146 // (which should presumably be valid only if N is a multiple of
10147 // alignof(int), and in any case can't be deallocated unless N is
10148 // alignof(X) and X has new-extended alignment).
10149 LValue Nothrow;
10150 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10151 return false;
10152 IsNothrow = true;
10153 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10154 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10155 (Info.CurrentCall->CanEvalMSConstexpr &&
10156 OperatorNew->hasAttr<MSConstexprAttr>())) {
10157 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10158 return false;
10159 if (Result.Designator.Invalid)
10160 return false;
10161 TargetType = E->getPlacementArg(0)->getType();
10162 IsPlacement = true;
10163 } else {
10164 Info.FFDiag(E, diag::note_constexpr_new_placement)
10165 << /*C++26 feature*/ 1 << E->getSourceRange();
10166 return false;
10167 }
10168 } else if (E->getNumPlacementArgs()) {
10169 Info.FFDiag(E, diag::note_constexpr_new_placement)
10170 << /*Unsupported*/ 0 << E->getSourceRange();
10171 return false;
10172 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
10173 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10174 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10175 return false;
10176 }
10177
10178 const Expr *Init = E->getInitializer();
10179 const InitListExpr *ResizedArrayILE = nullptr;
10180 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10181 bool ValueInit = false;
10182
10183 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10184 const Expr *Stripped = *ArraySize;
10185 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10186 Stripped = ICE->getSubExpr())
10187 if (ICE->getCastKind() != CK_NoOp &&
10188 ICE->getCastKind() != CK_IntegralCast)
10189 break;
10190
10191 llvm::APSInt ArrayBound;
10192 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10193 return false;
10194
10195 // C++ [expr.new]p9:
10196 // The expression is erroneous if:
10197 // -- [...] its value before converting to size_t [or] applying the
10198 // second standard conversion sequence is less than zero
10199 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10200 if (IsNothrow)
10201 return ZeroInitialization(E);
10202
10203 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10204 << ArrayBound << (*ArraySize)->getSourceRange();
10205 return false;
10206 }
10207
10208 // -- its value is such that the size of the allocated object would
10209 // exceed the implementation-defined limit
10210 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10212 Info.Ctx, AllocType, ArrayBound),
10213 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10214 if (IsNothrow)
10215 return ZeroInitialization(E);
10216 return false;
10217 }
10218
10219 // -- the new-initializer is a braced-init-list and the number of
10220 // array elements for which initializers are provided [...]
10221 // exceeds the number of elements to initialize
10222 if (!Init) {
10223 // No initialization is performed.
10224 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10225 isa<ImplicitValueInitExpr>(Init)) {
10226 ValueInit = true;
10227 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10228 ResizedArrayCCE = CCE;
10229 } else {
10230 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10231 assert(CAT && "unexpected type for array initializer");
10232
10233 unsigned Bits =
10234 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10235 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10236 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10237 if (InitBound.ugt(AllocBound)) {
10238 if (IsNothrow)
10239 return ZeroInitialization(E);
10240
10241 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10242 << toString(AllocBound, 10, /*Signed=*/false)
10243 << toString(InitBound, 10, /*Signed=*/false)
10244 << (*ArraySize)->getSourceRange();
10245 return false;
10246 }
10247
10248 // If the sizes differ, we must have an initializer list, and we need
10249 // special handling for this case when we initialize.
10250 if (InitBound != AllocBound)
10251 ResizedArrayILE = cast<InitListExpr>(Init);
10252 }
10253
10254 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10255 ArraySizeModifier::Normal, 0);
10256 } else {
10257 assert(!AllocType->isArrayType() &&
10258 "array allocation with non-array new");
10259 }
10260
10261 APValue *Val;
10262 if (IsPlacement) {
10264 struct FindObjectHandler {
10265 EvalInfo &Info;
10266 const Expr *E;
10267 QualType AllocType;
10268 const AccessKinds AccessKind;
10269 APValue *Value;
10270
10271 typedef bool result_type;
10272 bool failed() { return false; }
10273 bool found(APValue &Subobj, QualType SubobjType) {
10274 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10275 // old name of the object to be used to name the new object.
10276 unsigned SubobjectSize = 1;
10277 unsigned AllocSize = 1;
10278 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10279 AllocSize = CAT->getZExtSize();
10280 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10281 SubobjectSize = CAT->getZExtSize();
10282 if (SubobjectSize < AllocSize ||
10283 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10284 Info.Ctx.getBaseElementType(AllocType))) {
10285 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10286 << SubobjType << AllocType;
10287 return false;
10288 }
10289 Value = &Subobj;
10290 return true;
10291 }
10292 bool found(APSInt &Value, QualType SubobjType) {
10293 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10294 return false;
10295 }
10296 bool found(APFloat &Value, QualType SubobjType) {
10297 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10298 return false;
10299 }
10300 } Handler = {Info, E, AllocType, AK, nullptr};
10301
10302 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10303 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10304 return false;
10305
10306 Val = Handler.Value;
10307
10308 // [basic.life]p1:
10309 // The lifetime of an object o of type T ends when [...] the storage
10310 // which the object occupies is [...] reused by an object that is not
10311 // nested within o (6.6.2).
10312 *Val = APValue();
10313 } else {
10314 // Perform the allocation and obtain a pointer to the resulting object.
10315 Val = Info.createHeapAlloc(E, AllocType, Result);
10316 if (!Val)
10317 return false;
10318 }
10319
10320 if (ValueInit) {
10321 ImplicitValueInitExpr VIE(AllocType);
10322 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10323 return false;
10324 } else if (ResizedArrayILE) {
10325 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10326 AllocType))
10327 return false;
10328 } else if (ResizedArrayCCE) {
10329 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10330 AllocType))
10331 return false;
10332 } else if (Init) {
10333 if (!EvaluateInPlace(*Val, Info, Result, Init))
10334 return false;
10335 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10336 return false;
10337 }
10338
10339 // Array new returns a pointer to the first element, not a pointer to the
10340 // array.
10341 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10342 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10343
10344 return true;
10345}
10346//===----------------------------------------------------------------------===//
10347// Member Pointer Evaluation
10348//===----------------------------------------------------------------------===//
10349
10350namespace {
10351class MemberPointerExprEvaluator
10352 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10353 MemberPtr &Result;
10354
10355 bool Success(const ValueDecl *D) {
10356 Result = MemberPtr(D);
10357 return true;
10358 }
10359public:
10360
10361 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10362 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10363
10364 bool Success(const APValue &V, const Expr *E) {
10365 Result.setFrom(V);
10366 return true;
10367 }
10368 bool ZeroInitialization(const Expr *E) {
10369 return Success((const ValueDecl*)nullptr);
10370 }
10371
10372 bool VisitCastExpr(const CastExpr *E);
10373 bool VisitUnaryAddrOf(const UnaryOperator *E);
10374};
10375} // end anonymous namespace
10376
10377static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10378 EvalInfo &Info) {
10379 assert(!E->isValueDependent());
10380 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10381 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10382}
10383
10384bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10385 switch (E->getCastKind()) {
10386 default:
10387 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10388
10389 case CK_NullToMemberPointer:
10390 VisitIgnoredValue(E->getSubExpr());
10391 return ZeroInitialization(E);
10392
10393 case CK_BaseToDerivedMemberPointer: {
10394 if (!Visit(E->getSubExpr()))
10395 return false;
10396 if (E->path_empty())
10397 return true;
10398 // Base-to-derived member pointer casts store the path in derived-to-base
10399 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10400 // the wrong end of the derived->base arc, so stagger the path by one class.
10401 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10402 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10403 PathI != PathE; ++PathI) {
10404 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10405 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10406 if (!Result.castToDerived(Derived))
10407 return Error(E);
10408 }
10409 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
10410 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
10411 return Error(E);
10412 return true;
10413 }
10414
10415 case CK_DerivedToBaseMemberPointer:
10416 if (!Visit(E->getSubExpr()))
10417 return false;
10418 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10419 PathE = E->path_end(); PathI != PathE; ++PathI) {
10420 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10421 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10422 if (!Result.castToBase(Base))
10423 return Error(E);
10424 }
10425 return true;
10426 }
10427}
10428
10429bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10430 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10431 // member can be formed.
10432 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10433}
10434
10435//===----------------------------------------------------------------------===//
10436// Record Evaluation
10437//===----------------------------------------------------------------------===//
10438
10439namespace {
10440 class RecordExprEvaluator
10441 : public ExprEvaluatorBase<RecordExprEvaluator> {
10442 const LValue &This;
10443 APValue &Result;
10444 public:
10445
10446 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10447 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10448
10449 bool Success(const APValue &V, const Expr *E) {
10450 Result = V;
10451 return true;
10452 }
10453 bool ZeroInitialization(const Expr *E) {
10454 return ZeroInitialization(E, E->getType());
10455 }
10456 bool ZeroInitialization(const Expr *E, QualType T);
10457
10458 bool VisitCallExpr(const CallExpr *E) {
10459 return handleCallExpr(E, Result, &This);
10460 }
10461 bool VisitCastExpr(const CastExpr *E);
10462 bool VisitInitListExpr(const InitListExpr *E);
10463 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10464 return VisitCXXConstructExpr(E, E->getType());
10465 }
10466 bool VisitLambdaExpr(const LambdaExpr *E);
10467 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10468 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10469 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10470 bool VisitBinCmp(const BinaryOperator *E);
10471 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10472 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10473 ArrayRef<Expr *> Args);
10474 };
10475}
10476
10477/// Perform zero-initialization on an object of non-union class type.
10478/// C++11 [dcl.init]p5:
10479/// To zero-initialize an object or reference of type T means:
10480/// [...]
10481/// -- if T is a (possibly cv-qualified) non-union class type,
10482/// each non-static data member and each base-class subobject is
10483/// zero-initialized
10484static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10485 const RecordDecl *RD,
10486 const LValue &This, APValue &Result) {
10487 assert(!RD->isUnion() && "Expected non-union class type");
10488 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10489 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10490 std::distance(RD->field_begin(), RD->field_end()));
10491
10492 if (RD->isInvalidDecl()) return false;
10493 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10494
10495 if (CD) {
10496 unsigned Index = 0;
10498 End = CD->bases_end(); I != End; ++I, ++Index) {
10499 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10500 LValue Subobject = This;
10501 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10502 return false;
10503 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10504 Result.getStructBase(Index)))
10505 return false;
10506 }
10507 }
10508
10509 for (const auto *I : RD->fields()) {
10510 // -- if T is a reference type, no initialization is performed.
10511 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10512 continue;
10513
10514 LValue Subobject = This;
10515 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10516 return false;
10517
10518 ImplicitValueInitExpr VIE(I->getType());
10519 if (!EvaluateInPlace(
10520 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10521 return false;
10522 }
10523
10524 return true;
10525}
10526
10527bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10528 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
10529 if (RD->isInvalidDecl()) return false;
10530 if (RD->isUnion()) {
10531 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10532 // object's first non-static named data member is zero-initialized
10534 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10535 ++I;
10536 if (I == RD->field_end()) {
10537 Result = APValue((const FieldDecl*)nullptr);
10538 return true;
10539 }
10540
10541 LValue Subobject = This;
10542 if (!HandleLValueMember(Info, E, Subobject, *I))
10543 return false;
10544 Result = APValue(*I);
10545 ImplicitValueInitExpr VIE(I->getType());
10546 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10547 }
10548
10549 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10550 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10551 return false;
10552 }
10553
10554 return HandleClassZeroInitialization(Info, E, RD, This, Result);
10555}
10556
10557bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10558 switch (E->getCastKind()) {
10559 default:
10560 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10561
10562 case CK_ConstructorConversion:
10563 return Visit(E->getSubExpr());
10564
10565 case CK_DerivedToBase:
10566 case CK_UncheckedDerivedToBase: {
10567 APValue DerivedObject;
10568 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10569 return false;
10570 if (!DerivedObject.isStruct())
10571 return Error(E->getSubExpr());
10572
10573 // Derived-to-base rvalue conversion: just slice off the derived part.
10574 APValue *Value = &DerivedObject;
10575 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10576 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10577 PathE = E->path_end(); PathI != PathE; ++PathI) {
10578 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10579 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10580 Value = &Value->getStructBase(getBaseIndex(RD, Base));
10581 RD = Base;
10582 }
10583 Result = *Value;
10584 return true;
10585 }
10586 }
10587}
10588
10589bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10590 if (E->isTransparent())
10591 return Visit(E->getInit(0));
10592 return VisitCXXParenListOrInitListExpr(E, E->inits());
10593}
10594
10595bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10596 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10597 const RecordDecl *RD =
10598 ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10599 if (RD->isInvalidDecl()) return false;
10600 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10601 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10602
10603 EvalInfo::EvaluatingConstructorRAII EvalObj(
10604 Info,
10605 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10606 CXXRD && CXXRD->getNumBases());
10607
10608 if (RD->isUnion()) {
10609 const FieldDecl *Field;
10610 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10611 Field = ILE->getInitializedFieldInUnion();
10612 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10613 Field = PLIE->getInitializedFieldInUnion();
10614 } else {
10615 llvm_unreachable(
10616 "Expression is neither an init list nor a C++ paren list");
10617 }
10618
10619 Result = APValue(Field);
10620 if (!Field)
10621 return true;
10622
10623 // If the initializer list for a union does not contain any elements, the
10624 // first element of the union is value-initialized.
10625 // FIXME: The element should be initialized from an initializer list.
10626 // Is this difference ever observable for initializer lists which
10627 // we don't build?
10628 ImplicitValueInitExpr VIE(Field->getType());
10629 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10630
10631 LValue Subobject = This;
10632 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10633 return false;
10634
10635 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10636 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10637 isa<CXXDefaultInitExpr>(InitExpr));
10638
10639 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10640 if (Field->isBitField())
10641 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10642 Field);
10643 return true;
10644 }
10645
10646 return false;
10647 }
10648
10649 if (!Result.hasValue())
10650 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10651 std::distance(RD->field_begin(), RD->field_end()));
10652 unsigned ElementNo = 0;
10653 bool Success = true;
10654
10655 // Initialize base classes.
10656 if (CXXRD && CXXRD->getNumBases()) {
10657 for (const auto &Base : CXXRD->bases()) {
10658 assert(ElementNo < Args.size() && "missing init for base class");
10659 const Expr *Init = Args[ElementNo];
10660
10661 LValue Subobject = This;
10662 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10663 return false;
10664
10665 APValue &FieldVal = Result.getStructBase(ElementNo);
10666 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10667 if (!Info.noteFailure())
10668 return false;
10669 Success = false;
10670 }
10671 ++ElementNo;
10672 }
10673
10674 EvalObj.finishedConstructingBases();
10675 }
10676
10677 // Initialize members.
10678 for (const auto *Field : RD->fields()) {
10679 // Anonymous bit-fields are not considered members of the class for
10680 // purposes of aggregate initialization.
10681 if (Field->isUnnamedBitField())
10682 continue;
10683
10684 LValue Subobject = This;
10685
10686 bool HaveInit = ElementNo < Args.size();
10687
10688 // FIXME: Diagnostics here should point to the end of the initializer
10689 // list, not the start.
10690 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10691 Subobject, Field, &Layout))
10692 return false;
10693
10694 // Perform an implicit value-initialization for members beyond the end of
10695 // the initializer list.
10696 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10697 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10698
10699 if (Field->getType()->isIncompleteArrayType()) {
10700 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10701 if (!CAT->isZeroSize()) {
10702 // Bail out for now. This might sort of "work", but the rest of the
10703 // code isn't really prepared to handle it.
10704 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10705 return false;
10706 }
10707 }
10708 }
10709
10710 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10711 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10712 isa<CXXDefaultInitExpr>(Init));
10713
10714 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10715 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10716 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10717 FieldVal, Field))) {
10718 if (!Info.noteFailure())
10719 return false;
10720 Success = false;
10721 }
10722 }
10723
10724 EvalObj.finishedConstructingFields();
10725
10726 return Success;
10727}
10728
10729bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10730 QualType T) {
10731 // Note that E's type is not necessarily the type of our class here; we might
10732 // be initializing an array element instead.
10733 const CXXConstructorDecl *FD = E->getConstructor();
10734 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10735
10736 bool ZeroInit = E->requiresZeroInitialization();
10737 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10738 // If we've already performed zero-initialization, we're already done.
10739 if (Result.hasValue())
10740 return true;
10741
10742 if (ZeroInit)
10743 return ZeroInitialization(E, T);
10744
10745 return handleDefaultInitValue(T, Result);
10746 }
10747
10748 const FunctionDecl *Definition = nullptr;
10749 auto Body = FD->getBody(Definition);
10750
10751 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10752 return false;
10753
10754 // Avoid materializing a temporary for an elidable copy/move constructor.
10755 if (E->isElidable() && !ZeroInit) {
10756 // FIXME: This only handles the simplest case, where the source object
10757 // is passed directly as the first argument to the constructor.
10758 // This should also handle stepping though implicit casts and
10759 // and conversion sequences which involve two steps, with a
10760 // conversion operator followed by a converting constructor.
10761 const Expr *SrcObj = E->getArg(0);
10762 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10763 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10764 if (const MaterializeTemporaryExpr *ME =
10765 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10766 return Visit(ME->getSubExpr());
10767 }
10768
10769 if (ZeroInit && !ZeroInitialization(E, T))
10770 return false;
10771
10772 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10773 return HandleConstructorCall(E, This, Args,
10774 cast<CXXConstructorDecl>(Definition), Info,
10775 Result);
10776}
10777
10778bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10779 const CXXInheritedCtorInitExpr *E) {
10780 if (!Info.CurrentCall) {
10781 assert(Info.checkingPotentialConstantExpression());
10782 return false;
10783 }
10784
10785 const CXXConstructorDecl *FD = E->getConstructor();
10786 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10787 return false;
10788
10789 const FunctionDecl *Definition = nullptr;
10790 auto Body = FD->getBody(Definition);
10791
10792 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10793 return false;
10794
10795 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10796 cast<CXXConstructorDecl>(Definition), Info,
10797 Result);
10798}
10799
10800bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10803 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10804
10805 LValue Array;
10806 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10807 return false;
10808
10809 assert(ArrayType && "unexpected type for array initializer");
10810
10811 // Get a pointer to the first element of the array.
10812 Array.addArray(Info, E, ArrayType);
10813
10814 // FIXME: What if the initializer_list type has base classes, etc?
10815 Result = APValue(APValue::UninitStruct(), 0, 2);
10816 Array.moveInto(Result.getStructField(0));
10817
10818 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10819 RecordDecl::field_iterator Field = Record->field_begin();
10820 assert(Field != Record->field_end() &&
10821 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10823 "Expected std::initializer_list first field to be const E *");
10824 ++Field;
10825 assert(Field != Record->field_end() &&
10826 "Expected std::initializer_list to have two fields");
10827
10828 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
10829 // Length.
10830 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10831 } else {
10832 // End pointer.
10833 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10835 "Expected std::initializer_list second field to be const E *");
10836 if (!HandleLValueArrayAdjustment(Info, E, Array,
10838 ArrayType->getZExtSize()))
10839 return false;
10840 Array.moveInto(Result.getStructField(1));
10841 }
10842
10843 assert(++Field == Record->field_end() &&
10844 "Expected std::initializer_list to only have two fields");
10845
10846 return true;
10847}
10848
10849bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10850 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10851 if (ClosureClass->isInvalidDecl())
10852 return false;
10853
10854 const size_t NumFields =
10855 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10856
10857 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10858 E->capture_init_end()) &&
10859 "The number of lambda capture initializers should equal the number of "
10860 "fields within the closure type");
10861
10862 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10863 // Iterate through all the lambda's closure object's fields and initialize
10864 // them.
10865 auto *CaptureInitIt = E->capture_init_begin();
10866 bool Success = true;
10867 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10868 for (const auto *Field : ClosureClass->fields()) {
10869 assert(CaptureInitIt != E->capture_init_end());
10870 // Get the initializer for this field
10871 Expr *const CurFieldInit = *CaptureInitIt++;
10872
10873 // If there is no initializer, either this is a VLA or an error has
10874 // occurred.
10875 if (!CurFieldInit)
10876 return Error(E);
10877
10878 LValue Subobject = This;
10879
10880 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10881 return false;
10882
10883 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10884 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10885 if (!Info.keepEvaluatingAfterFailure())
10886 return false;
10887 Success = false;
10888 }
10889 }
10890 return Success;
10891}
10892
10893static bool EvaluateRecord(const Expr *E, const LValue &This,
10894 APValue &Result, EvalInfo &Info) {
10895 assert(!E->isValueDependent());
10896 assert(E->isPRValue() && E->getType()->isRecordType() &&
10897 "can't evaluate expression as a record rvalue");
10898 return RecordExprEvaluator(Info, This, Result).Visit(E);
10899}
10900
10901//===----------------------------------------------------------------------===//
10902// Temporary Evaluation
10903//
10904// Temporaries are represented in the AST as rvalues, but generally behave like
10905// lvalues. The full-object of which the temporary is a subobject is implicitly
10906// materialized so that a reference can bind to it.
10907//===----------------------------------------------------------------------===//
10908namespace {
10909class TemporaryExprEvaluator
10910 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10911public:
10912 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10913 LValueExprEvaluatorBaseTy(Info, Result, false) {}
10914
10915 /// Visit an expression which constructs the value of this temporary.
10916 bool VisitConstructExpr(const Expr *E) {
10917 APValue &Value = Info.CurrentCall->createTemporary(
10918 E, E->getType(), ScopeKind::FullExpression, Result);
10919 return EvaluateInPlace(Value, Info, Result, E);
10920 }
10921
10922 bool VisitCastExpr(const CastExpr *E) {
10923 switch (E->getCastKind()) {
10924 default:
10925 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10926
10927 case CK_ConstructorConversion:
10928 return VisitConstructExpr(E->getSubExpr());
10929 }
10930 }
10931 bool VisitInitListExpr(const InitListExpr *E) {
10932 return VisitConstructExpr(E);
10933 }
10934 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10935 return VisitConstructExpr(E);
10936 }
10937 bool VisitCallExpr(const CallExpr *E) {
10938 return VisitConstructExpr(E);
10939 }
10940 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10941 return VisitConstructExpr(E);
10942 }
10943 bool VisitLambdaExpr(const LambdaExpr *E) {
10944 return VisitConstructExpr(E);
10945 }
10946};
10947} // end anonymous namespace
10948
10949/// Evaluate an expression of record type as a temporary.
10950static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10951 assert(!E->isValueDependent());
10952 assert(E->isPRValue() && E->getType()->isRecordType());
10953 return TemporaryExprEvaluator(Info, Result).Visit(E);
10954}
10955
10956//===----------------------------------------------------------------------===//
10957// Vector Evaluation
10958//===----------------------------------------------------------------------===//
10959
10960namespace {
10961 class VectorExprEvaluator
10962 : public ExprEvaluatorBase<VectorExprEvaluator> {
10963 APValue &Result;
10964 public:
10965
10966 VectorExprEvaluator(EvalInfo &info, APValue &Result)
10967 : ExprEvaluatorBaseTy(info), Result(Result) {}
10968
10969 bool Success(ArrayRef<APValue> V, const Expr *E) {
10970 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10971 // FIXME: remove this APValue copy.
10972 Result = APValue(V.data(), V.size());
10973 return true;
10974 }
10975 bool Success(const APValue &V, const Expr *E) {
10976 assert(V.isVector());
10977 Result = V;
10978 return true;
10979 }
10980 bool ZeroInitialization(const Expr *E);
10981
10982 bool VisitUnaryReal(const UnaryOperator *E)
10983 { return Visit(E->getSubExpr()); }
10984 bool VisitCastExpr(const CastExpr* E);
10985 bool VisitInitListExpr(const InitListExpr *E);
10986 bool VisitUnaryImag(const UnaryOperator *E);
10987 bool VisitBinaryOperator(const BinaryOperator *E);
10988 bool VisitUnaryOperator(const UnaryOperator *E);
10989 bool VisitCallExpr(const CallExpr *E);
10990 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
10991 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
10992
10993 // FIXME: Missing: conditional operator (for GNU
10994 // conditional select), ExtVectorElementExpr
10995 };
10996} // end anonymous namespace
10997
10998static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10999 assert(E->isPRValue() && E->getType()->isVectorType() &&
11000 "not a vector prvalue");
11001 return VectorExprEvaluator(Info, Result).Visit(E);
11002}
11003
11004bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11005 const VectorType *VTy = E->getType()->castAs<VectorType>();
11006 unsigned NElts = VTy->getNumElements();
11007
11008 const Expr *SE = E->getSubExpr();
11009 QualType SETy = SE->getType();
11010
11011 switch (E->getCastKind()) {
11012 case CK_VectorSplat: {
11013 APValue Val = APValue();
11014 if (SETy->isIntegerType()) {
11015 APSInt IntResult;
11016 if (!EvaluateInteger(SE, IntResult, Info))
11017 return false;
11018 Val = APValue(std::move(IntResult));
11019 } else if (SETy->isRealFloatingType()) {
11020 APFloat FloatResult(0.0);
11021 if (!EvaluateFloat(SE, FloatResult, Info))
11022 return false;
11023 Val = APValue(std::move(FloatResult));
11024 } else {
11025 return Error(E);
11026 }
11027
11028 // Splat and create vector APValue.
11029 SmallVector<APValue, 4> Elts(NElts, Val);
11030 return Success(Elts, E);
11031 }
11032 case CK_BitCast: {
11033 APValue SVal;
11034 if (!Evaluate(SVal, Info, SE))
11035 return false;
11036
11037 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11038 // Give up if the input isn't an int, float, or vector. For example, we
11039 // reject "(v4i16)(intptr_t)&a".
11040 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11041 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
11042 return false;
11043 }
11044
11045 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11046 return false;
11047
11048 return true;
11049 }
11050 case CK_HLSLVectorTruncation: {
11051 APValue Val;
11052 SmallVector<APValue, 4> Elements;
11053 if (!EvaluateVector(SE, Val, Info))
11054 return Error(E);
11055 for (unsigned I = 0; I < NElts; I++)
11056 Elements.push_back(Val.getVectorElt(I));
11057 return Success(Elements, E);
11058 }
11059 default:
11060 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11061 }
11062}
11063
11064bool
11065VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11066 const VectorType *VT = E->getType()->castAs<VectorType>();
11067 unsigned NumInits = E->getNumInits();
11068 unsigned NumElements = VT->getNumElements();
11069
11070 QualType EltTy = VT->getElementType();
11071 SmallVector<APValue, 4> Elements;
11072
11073 // The number of initializers can be less than the number of
11074 // vector elements. For OpenCL, this can be due to nested vector
11075 // initialization. For GCC compatibility, missing trailing elements
11076 // should be initialized with zeroes.
11077 unsigned CountInits = 0, CountElts = 0;
11078 while (CountElts < NumElements) {
11079 // Handle nested vector initialization.
11080 if (CountInits < NumInits
11081 && E->getInit(CountInits)->getType()->isVectorType()) {
11082 APValue v;
11083 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11084 return Error(E);
11085 unsigned vlen = v.getVectorLength();
11086 for (unsigned j = 0; j < vlen; j++)
11087 Elements.push_back(v.getVectorElt(j));
11088 CountElts += vlen;
11089 } else if (EltTy->isIntegerType()) {
11090 llvm::APSInt sInt(32);
11091 if (CountInits < NumInits) {
11092 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11093 return false;
11094 } else // trailing integer zero.
11095 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11096 Elements.push_back(APValue(sInt));
11097 CountElts++;
11098 } else {
11099 llvm::APFloat f(0.0);
11100 if (CountInits < NumInits) {
11101 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11102 return false;
11103 } else // trailing float zero.
11104 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11105 Elements.push_back(APValue(f));
11106 CountElts++;
11107 }
11108 CountInits++;
11109 }
11110 return Success(Elements, E);
11111}
11112
11113bool
11114VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11115 const auto *VT = E->getType()->castAs<VectorType>();
11116 QualType EltTy = VT->getElementType();
11117 APValue ZeroElement;
11118 if (EltTy->isIntegerType())
11119 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11120 else
11121 ZeroElement =
11122 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11123
11124 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11125 return Success(Elements, E);
11126}
11127
11128bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11129 VisitIgnoredValue(E->getSubExpr());
11130 return ZeroInitialization(E);
11131}
11132
11133bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11134 BinaryOperatorKind Op = E->getOpcode();
11135 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11136 "Operation not supported on vector types");
11137
11138 if (Op == BO_Comma)
11139 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11140
11141 Expr *LHS = E->getLHS();
11142 Expr *RHS = E->getRHS();
11143
11144 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11145 "Must both be vector types");
11146 // Checking JUST the types are the same would be fine, except shifts don't
11147 // need to have their types be the same (since you always shift by an int).
11148 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11150 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11152 "All operands must be the same size.");
11153
11154 APValue LHSValue;
11155 APValue RHSValue;
11156 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11157 if (!LHSOK && !Info.noteFailure())
11158 return false;
11159 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11160 return false;
11161
11162 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11163 return false;
11164
11165 return Success(LHSValue, E);
11166}
11167
11168static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11169 QualType ResultTy,
11171 APValue Elt) {
11172 switch (Op) {
11173 case UO_Plus:
11174 // Nothing to do here.
11175 return Elt;
11176 case UO_Minus:
11177 if (Elt.getKind() == APValue::Int) {
11178 Elt.getInt().negate();
11179 } else {
11180 assert(Elt.getKind() == APValue::Float &&
11181 "Vector can only be int or float type");
11182 Elt.getFloat().changeSign();
11183 }
11184 return Elt;
11185 case UO_Not:
11186 // This is only valid for integral types anyway, so we don't have to handle
11187 // float here.
11188 assert(Elt.getKind() == APValue::Int &&
11189 "Vector operator ~ can only be int");
11190 Elt.getInt().flipAllBits();
11191 return Elt;
11192 case UO_LNot: {
11193 if (Elt.getKind() == APValue::Int) {
11194 Elt.getInt() = !Elt.getInt();
11195 // operator ! on vectors returns -1 for 'truth', so negate it.
11196 Elt.getInt().negate();
11197 return Elt;
11198 }
11199 assert(Elt.getKind() == APValue::Float &&
11200 "Vector can only be int or float type");
11201 // Float types result in an int of the same size, but -1 for true, or 0 for
11202 // false.
11203 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11204 ResultTy->isUnsignedIntegerType()};
11205 if (Elt.getFloat().isZero())
11206 EltResult.setAllBits();
11207 else
11208 EltResult.clearAllBits();
11209
11210 return APValue{EltResult};
11211 }
11212 default:
11213 // FIXME: Implement the rest of the unary operators.
11214 return std::nullopt;
11215 }
11216}
11217
11218bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11219 Expr *SubExpr = E->getSubExpr();
11220 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11221 // This result element type differs in the case of negating a floating point
11222 // vector, since the result type is the a vector of the equivilant sized
11223 // integer.
11224 const QualType ResultEltTy = VD->getElementType();
11225 UnaryOperatorKind Op = E->getOpcode();
11226
11227 APValue SubExprValue;
11228 if (!Evaluate(SubExprValue, Info, SubExpr))
11229 return false;
11230
11231 // FIXME: This vector evaluator someday needs to be changed to be LValue
11232 // aware/keep LValue information around, rather than dealing with just vector
11233 // types directly. Until then, we cannot handle cases where the operand to
11234 // these unary operators is an LValue. The only case I've been able to see
11235 // cause this is operator++ assigning to a member expression (only valid in
11236 // altivec compilations) in C mode, so this shouldn't limit us too much.
11237 if (SubExprValue.isLValue())
11238 return false;
11239
11240 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11241 "Vector length doesn't match type?");
11242
11243 SmallVector<APValue, 4> ResultElements;
11244 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11245 std::optional<APValue> Elt = handleVectorUnaryOperator(
11246 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11247 if (!Elt)
11248 return false;
11249 ResultElements.push_back(*Elt);
11250 }
11251 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11252}
11253
11254static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11255 const Expr *E, QualType SourceTy,
11256 QualType DestTy, APValue const &Original,
11257 APValue &Result) {
11258 if (SourceTy->isIntegerType()) {
11259 if (DestTy->isRealFloatingType()) {
11260 Result = APValue(APFloat(0.0));
11261 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11262 DestTy, Result.getFloat());
11263 }
11264 if (DestTy->isIntegerType()) {
11265 Result = APValue(
11266 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11267 return true;
11268 }
11269 } else if (SourceTy->isRealFloatingType()) {
11270 if (DestTy->isRealFloatingType()) {
11271 Result = Original;
11272 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11273 Result.getFloat());
11274 }
11275 if (DestTy->isIntegerType()) {
11276 Result = APValue(APSInt());
11277 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11278 DestTy, Result.getInt());
11279 }
11280 }
11281
11282 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11283 << SourceTy << DestTy;
11284 return false;
11285}
11286
11287bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
11288 if (!IsConstantEvaluatedBuiltinCall(E))
11289 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11290
11291 switch (E->getBuiltinCallee()) {
11292 default:
11293 return false;
11294 case Builtin::BI__builtin_elementwise_popcount:
11295 case Builtin::BI__builtin_elementwise_bitreverse: {
11296 APValue Source;
11297 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11298 return false;
11299
11300 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11301 unsigned SourceLen = Source.getVectorLength();
11302 SmallVector<APValue, 4> ResultElements;
11303 ResultElements.reserve(SourceLen);
11304
11305 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11306 APSInt Elt = Source.getVectorElt(EltNum).getInt();
11307 switch (E->getBuiltinCallee()) {
11308 case Builtin::BI__builtin_elementwise_popcount:
11309 ResultElements.push_back(APValue(
11310 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
11311 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11312 break;
11313 case Builtin::BI__builtin_elementwise_bitreverse:
11314 ResultElements.push_back(
11315 APValue(APSInt(Elt.reverseBits(),
11316 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11317 break;
11318 }
11319 }
11320
11321 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11322 }
11323 case Builtin::BI__builtin_elementwise_add_sat:
11324 case Builtin::BI__builtin_elementwise_sub_sat: {
11325 APValue SourceLHS, SourceRHS;
11326 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11327 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11328 return false;
11329
11330 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11331 unsigned SourceLen = SourceLHS.getVectorLength();
11332 SmallVector<APValue, 4> ResultElements;
11333 ResultElements.reserve(SourceLen);
11334
11335 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11336 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11337 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11338 switch (E->getBuiltinCallee()) {
11339 case Builtin::BI__builtin_elementwise_add_sat:
11340 ResultElements.push_back(APValue(
11341 APSInt(LHS.isSigned() ? LHS.sadd_sat(RHS) : RHS.uadd_sat(RHS),
11342 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11343 break;
11344 case Builtin::BI__builtin_elementwise_sub_sat:
11345 ResultElements.push_back(APValue(
11346 APSInt(LHS.isSigned() ? LHS.ssub_sat(RHS) : RHS.usub_sat(RHS),
11347 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11348 break;
11349 }
11350 }
11351
11352 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11353 }
11354 }
11355}
11356
11357bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
11358 APValue Source;
11359 QualType SourceVecType = E->getSrcExpr()->getType();
11360 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
11361 return false;
11362
11363 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
11364 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
11365
11366 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11367
11368 auto SourceLen = Source.getVectorLength();
11369 SmallVector<APValue, 4> ResultElements;
11370 ResultElements.reserve(SourceLen);
11371 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11372 APValue Elt;
11373 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
11374 Source.getVectorElt(EltNum), Elt))
11375 return false;
11376 ResultElements.push_back(std::move(Elt));
11377 }
11378
11379 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11380}
11381
11382static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
11383 QualType ElemType, APValue const &VecVal1,
11384 APValue const &VecVal2, unsigned EltNum,
11385 APValue &Result) {
11386 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
11387 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
11388
11389 APSInt IndexVal = E->getShuffleMaskIdx(Info.Ctx, EltNum);
11390 int64_t index = IndexVal.getExtValue();
11391 // The spec says that -1 should be treated as undef for optimizations,
11392 // but in constexpr we'd have to produce an APValue::Indeterminate,
11393 // which is prohibited from being a top-level constant value. Emit a
11394 // diagnostic instead.
11395 if (index == -1) {
11396 Info.FFDiag(
11397 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
11398 << EltNum;
11399 return false;
11400 }
11401
11402 if (index < 0 ||
11403 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
11404 llvm_unreachable("Out of bounds shuffle index");
11405
11406 if (index >= TotalElementsInInputVector1)
11407 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
11408 else
11409 Result = VecVal1.getVectorElt(index);
11410 return true;
11411}
11412
11413bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
11414 APValue VecVal1;
11415 const Expr *Vec1 = E->getExpr(0);
11416 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
11417 return false;
11418 APValue VecVal2;
11419 const Expr *Vec2 = E->getExpr(1);
11420 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
11421 return false;
11422
11423 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
11424 QualType DestElTy = DestVecTy->getElementType();
11425
11426 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
11427
11428 SmallVector<APValue, 4> ResultElements;
11429 ResultElements.reserve(TotalElementsInOutputVector);
11430 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
11431 APValue Elt;
11432 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
11433 return false;
11434 ResultElements.push_back(std::move(Elt));
11435 }
11436
11437 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11438}
11439
11440//===----------------------------------------------------------------------===//
11441// Array Evaluation
11442//===----------------------------------------------------------------------===//
11443
11444namespace {
11445 class ArrayExprEvaluator
11446 : public ExprEvaluatorBase<ArrayExprEvaluator> {
11447 const LValue &This;
11448 APValue &Result;
11449 public:
11450
11451 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
11452 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
11453
11454 bool Success(const APValue &V, const Expr *E) {
11455 assert(V.isArray() && "expected array");
11456 Result = V;
11457 return true;
11458 }
11459
11460 bool ZeroInitialization(const Expr *E) {
11461 const ConstantArrayType *CAT =
11462 Info.Ctx.getAsConstantArrayType(E->getType());
11463 if (!CAT) {
11464 if (E->getType()->isIncompleteArrayType()) {
11465 // We can be asked to zero-initialize a flexible array member; this
11466 // is represented as an ImplicitValueInitExpr of incomplete array
11467 // type. In this case, the array has zero elements.
11468 Result = APValue(APValue::UninitArray(), 0, 0);
11469 return true;
11470 }
11471 // FIXME: We could handle VLAs here.
11472 return Error(E);
11473 }
11474
11475 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
11476 if (!Result.hasArrayFiller())
11477 return true;
11478
11479 // Zero-initialize all elements.
11480 LValue Subobject = This;
11481 Subobject.addArray(Info, E, CAT);
11483 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
11484 }
11485
11486 bool VisitCallExpr(const CallExpr *E) {
11487 return handleCallExpr(E, Result, &This);
11488 }
11489 bool VisitInitListExpr(const InitListExpr *E,
11490 QualType AllocType = QualType());
11491 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
11492 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
11493 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
11494 const LValue &Subobject,
11496 bool VisitStringLiteral(const StringLiteral *E,
11497 QualType AllocType = QualType()) {
11498 expandStringLiteral(Info, E, Result, AllocType);
11499 return true;
11500 }
11501 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11502 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11503 ArrayRef<Expr *> Args,
11504 const Expr *ArrayFiller,
11505 QualType AllocType = QualType());
11506 };
11507} // end anonymous namespace
11508
11509static bool EvaluateArray(const Expr *E, const LValue &This,
11510 APValue &Result, EvalInfo &Info) {
11511 assert(!E->isValueDependent());
11512 assert(E->isPRValue() && E->getType()->isArrayType() &&
11513 "not an array prvalue");
11514 return ArrayExprEvaluator(Info, This, Result).Visit(E);
11515}
11516
11517static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
11518 APValue &Result, const InitListExpr *ILE,
11519 QualType AllocType) {
11520 assert(!ILE->isValueDependent());
11521 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
11522 "not an array prvalue");
11523 return ArrayExprEvaluator(Info, This, Result)
11524 .VisitInitListExpr(ILE, AllocType);
11525}
11526
11527static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
11528 APValue &Result,
11529 const CXXConstructExpr *CCE,
11530 QualType AllocType) {
11531 assert(!CCE->isValueDependent());
11532 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
11533 "not an array prvalue");
11534 return ArrayExprEvaluator(Info, This, Result)
11535 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
11536}
11537
11538// Return true iff the given array filler may depend on the element index.
11539static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
11540 // For now, just allow non-class value-initialization and initialization
11541 // lists comprised of them.
11542 if (isa<ImplicitValueInitExpr>(FillerExpr))
11543 return false;
11544 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
11545 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
11546 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
11547 return true;
11548 }
11549
11550 if (ILE->hasArrayFiller() &&
11551 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
11552 return true;
11553
11554 return false;
11555 }
11556 return true;
11557}
11558
11559bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
11560 QualType AllocType) {
11561 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11562 AllocType.isNull() ? E->getType() : AllocType);
11563 if (!CAT)
11564 return Error(E);
11565
11566 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
11567 // an appropriately-typed string literal enclosed in braces.
11568 if (E->isStringLiteralInit()) {
11569 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
11570 // FIXME: Support ObjCEncodeExpr here once we support it in
11571 // ArrayExprEvaluator generally.
11572 if (!SL)
11573 return Error(E);
11574 return VisitStringLiteral(SL, AllocType);
11575 }
11576 // Any other transparent list init will need proper handling of the
11577 // AllocType; we can't just recurse to the inner initializer.
11578 assert(!E->isTransparent() &&
11579 "transparent array list initialization is not string literal init?");
11580
11581 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
11582 AllocType);
11583}
11584
11585bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
11586 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
11587 QualType AllocType) {
11588 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11589 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
11590
11591 bool Success = true;
11592
11593 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
11594 "zero-initialized array shouldn't have any initialized elts");
11595 APValue Filler;
11596 if (Result.isArray() && Result.hasArrayFiller())
11597 Filler = Result.getArrayFiller();
11598
11599 unsigned NumEltsToInit = Args.size();
11600 unsigned NumElts = CAT->getZExtSize();
11601
11602 // If the initializer might depend on the array index, run it for each
11603 // array element.
11604 if (NumEltsToInit != NumElts &&
11605 MaybeElementDependentArrayFiller(ArrayFiller)) {
11606 NumEltsToInit = NumElts;
11607 } else {
11608 for (auto *Init : Args) {
11609 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
11610 NumEltsToInit += EmbedS->getDataElementCount() - 1;
11611 }
11612 if (NumEltsToInit > NumElts)
11613 NumEltsToInit = NumElts;
11614 }
11615
11616 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
11617 << NumEltsToInit << ".\n");
11618
11619 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
11620
11621 // If the array was previously zero-initialized, preserve the
11622 // zero-initialized values.
11623 if (Filler.hasValue()) {
11624 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
11625 Result.getArrayInitializedElt(I) = Filler;
11626 if (Result.hasArrayFiller())
11627 Result.getArrayFiller() = Filler;
11628 }
11629
11630 LValue Subobject = This;
11631 Subobject.addArray(Info, ExprToVisit, CAT);
11632 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
11633 if (Init->isValueDependent())
11634 return EvaluateDependentExpr(Init, Info);
11635
11636 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
11637 Subobject, Init) ||
11638 !HandleLValueArrayAdjustment(Info, Init, Subobject,
11639 CAT->getElementType(), 1)) {
11640 if (!Info.noteFailure())
11641 return false;
11642 Success = false;
11643 }
11644 return true;
11645 };
11646 unsigned ArrayIndex = 0;
11647 QualType DestTy = CAT->getElementType();
11648 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
11649 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
11650 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
11651 if (ArrayIndex >= NumEltsToInit)
11652 break;
11653 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
11654 StringLiteral *SL = EmbedS->getDataStringLiteral();
11655 for (unsigned I = EmbedS->getStartingElementPos(),
11656 N = EmbedS->getDataElementCount();
11657 I != EmbedS->getStartingElementPos() + N; ++I) {
11658 Value = SL->getCodeUnit(I);
11659 if (DestTy->isIntegerType()) {
11660 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
11661 } else {
11662 assert(DestTy->isFloatingType() && "unexpected type");
11663 const FPOptions FPO =
11664 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11665 APFloat FValue(0.0);
11666 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
11667 DestTy, FValue))
11668 return false;
11669 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
11670 }
11671 ArrayIndex++;
11672 }
11673 } else {
11674 if (!Eval(Init, ArrayIndex))
11675 return false;
11676 ++ArrayIndex;
11677 }
11678 }
11679
11680 if (!Result.hasArrayFiller())
11681 return Success;
11682
11683 // If we get here, we have a trivial filler, which we can just evaluate
11684 // once and splat over the rest of the array elements.
11685 assert(ArrayFiller && "no array filler for incomplete init list");
11686 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
11687 ArrayFiller) &&
11688 Success;
11689}
11690
11691bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
11692 LValue CommonLV;
11693 if (E->getCommonExpr() &&
11694 !Evaluate(Info.CurrentCall->createTemporary(
11695 E->getCommonExpr(),
11696 getStorageType(Info.Ctx, E->getCommonExpr()),
11697 ScopeKind::FullExpression, CommonLV),
11698 Info, E->getCommonExpr()->getSourceExpr()))
11699 return false;
11700
11701 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
11702
11703 uint64_t Elements = CAT->getZExtSize();
11704 Result = APValue(APValue::UninitArray(), Elements, Elements);
11705
11706 LValue Subobject = This;
11707 Subobject.addArray(Info, E, CAT);
11708
11709 bool Success = true;
11710 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
11711 // C++ [class.temporary]/5
11712 // There are four contexts in which temporaries are destroyed at a different
11713 // point than the end of the full-expression. [...] The second context is
11714 // when a copy constructor is called to copy an element of an array while
11715 // the entire array is copied [...]. In either case, if the constructor has
11716 // one or more default arguments, the destruction of every temporary created
11717 // in a default argument is sequenced before the construction of the next
11718 // array element, if any.
11719 FullExpressionRAII Scope(Info);
11720
11721 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11722 Info, Subobject, E->getSubExpr()) ||
11723 !HandleLValueArrayAdjustment(Info, E, Subobject,
11724 CAT->getElementType(), 1)) {
11725 if (!Info.noteFailure())
11726 return false;
11727 Success = false;
11728 }
11729
11730 // Make sure we run the destructors too.
11731 Scope.destroy();
11732 }
11733
11734 return Success;
11735}
11736
11737bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
11738 return VisitCXXConstructExpr(E, This, &Result, E->getType());
11739}
11740
11741bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11742 const LValue &Subobject,
11743 APValue *Value,
11744 QualType Type) {
11745 bool HadZeroInit = Value->hasValue();
11746
11747 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
11748 unsigned FinalSize = CAT->getZExtSize();
11749
11750 // Preserve the array filler if we had prior zero-initialization.
11751 APValue Filler =
11752 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
11753 : APValue();
11754
11755 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
11756 if (FinalSize == 0)
11757 return true;
11758
11759 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
11760 Info, E->getExprLoc(), E->getConstructor(),
11761 E->requiresZeroInitialization());
11762 LValue ArrayElt = Subobject;
11763 ArrayElt.addArray(Info, E, CAT);
11764 // We do the whole initialization in two passes, first for just one element,
11765 // then for the whole array. It's possible we may find out we can't do const
11766 // init in the first pass, in which case we avoid allocating a potentially
11767 // large array. We don't do more passes because expanding array requires
11768 // copying the data, which is wasteful.
11769 for (const unsigned N : {1u, FinalSize}) {
11770 unsigned OldElts = Value->getArrayInitializedElts();
11771 if (OldElts == N)
11772 break;
11773
11774 // Expand the array to appropriate size.
11775 APValue NewValue(APValue::UninitArray(), N, FinalSize);
11776 for (unsigned I = 0; I < OldElts; ++I)
11777 NewValue.getArrayInitializedElt(I).swap(
11778 Value->getArrayInitializedElt(I));
11779 Value->swap(NewValue);
11780
11781 if (HadZeroInit)
11782 for (unsigned I = OldElts; I < N; ++I)
11783 Value->getArrayInitializedElt(I) = Filler;
11784
11785 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
11786 // If we have a trivial constructor, only evaluate it once and copy
11787 // the result into all the array elements.
11788 APValue &FirstResult = Value->getArrayInitializedElt(0);
11789 for (unsigned I = OldElts; I < FinalSize; ++I)
11790 Value->getArrayInitializedElt(I) = FirstResult;
11791 } else {
11792 for (unsigned I = OldElts; I < N; ++I) {
11793 if (!VisitCXXConstructExpr(E, ArrayElt,
11794 &Value->getArrayInitializedElt(I),
11795 CAT->getElementType()) ||
11796 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
11797 CAT->getElementType(), 1))
11798 return false;
11799 // When checking for const initilization any diagnostic is considered
11800 // an error.
11801 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
11802 !Info.keepEvaluatingAfterFailure())
11803 return false;
11804 }
11805 }
11806 }
11807
11808 return true;
11809 }
11810
11811 if (!Type->isRecordType())
11812 return Error(E);
11813
11814 return RecordExprEvaluator(Info, Subobject, *Value)
11815 .VisitCXXConstructExpr(E, Type);
11816}
11817
11818bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
11819 const CXXParenListInitExpr *E) {
11820 assert(E->getType()->isConstantArrayType() &&
11821 "Expression result is not a constant array type");
11822
11823 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
11824 E->getArrayFiller());
11825}
11826
11827//===----------------------------------------------------------------------===//
11828// Integer Evaluation
11829//
11830// As a GNU extension, we support casting pointers to sufficiently-wide integer
11831// types and back in constant folding. Integer values are thus represented
11832// either as an integer-valued APValue, or as an lvalue-valued APValue.
11833//===----------------------------------------------------------------------===//
11834
11835namespace {
11836class IntExprEvaluator
11837 : public ExprEvaluatorBase<IntExprEvaluator> {
11838 APValue &Result;
11839public:
11840 IntExprEvaluator(EvalInfo &info, APValue &result)
11841 : ExprEvaluatorBaseTy(info), Result(result) {}
11842
11843 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
11844 assert(E->getType()->isIntegralOrEnumerationType() &&
11845 "Invalid evaluation result.");
11846 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
11847 "Invalid evaluation result.");
11848 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11849 "Invalid evaluation result.");
11850 Result = APValue(SI);
11851 return true;
11852 }
11853 bool Success(const llvm::APSInt &SI, const Expr *E) {
11854 return Success(SI, E, Result);
11855 }
11856
11857 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
11858 assert(E->getType()->isIntegralOrEnumerationType() &&
11859 "Invalid evaluation result.");
11860 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11861 "Invalid evaluation result.");
11862 Result = APValue(APSInt(I));
11863 Result.getInt().setIsUnsigned(
11865 return true;
11866 }
11867 bool Success(const llvm::APInt &I, const Expr *E) {
11868 return Success(I, E, Result);
11869 }
11870
11871 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11872 assert(E->getType()->isIntegralOrEnumerationType() &&
11873 "Invalid evaluation result.");
11874 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11875 return true;
11876 }
11877 bool Success(uint64_t Value, const Expr *E) {
11878 return Success(Value, E, Result);
11879 }
11880
11881 bool Success(CharUnits Size, const Expr *E) {
11882 return Success(Size.getQuantity(), E);
11883 }
11884
11885 bool Success(const APValue &V, const Expr *E) {
11886 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
11887 Result = V;
11888 return true;
11889 }
11890 return Success(V.getInt(), E);
11891 }
11892
11893 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11894
11895 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
11896 const CallExpr *);
11897
11898 //===--------------------------------------------------------------------===//
11899 // Visitor Methods
11900 //===--------------------------------------------------------------------===//
11901
11902 bool VisitIntegerLiteral(const IntegerLiteral *E) {
11903 return Success(E->getValue(), E);
11904 }
11905 bool VisitCharacterLiteral(const CharacterLiteral *E) {
11906 return Success(E->getValue(), E);
11907 }
11908
11909 bool CheckReferencedDecl(const Expr *E, const Decl *D);
11910 bool VisitDeclRefExpr(const DeclRefExpr *E) {
11911 if (CheckReferencedDecl(E, E->getDecl()))
11912 return true;
11913
11914 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11915 }
11916 bool VisitMemberExpr(const MemberExpr *E) {
11917 if (CheckReferencedDecl(E, E->getMemberDecl())) {
11918 VisitIgnoredBaseExpression(E->getBase());
11919 return true;
11920 }
11921
11922 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11923 }
11924
11925 bool VisitCallExpr(const CallExpr *E);
11926 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11927 bool VisitBinaryOperator(const BinaryOperator *E);
11928 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11929 bool VisitUnaryOperator(const UnaryOperator *E);
11930
11931 bool VisitCastExpr(const CastExpr* E);
11932 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11933
11934 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11935 return Success(E->getValue(), E);
11936 }
11937
11938 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11939 return Success(E->getValue(), E);
11940 }
11941
11942 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11943 if (Info.ArrayInitIndex == uint64_t(-1)) {
11944 // We were asked to evaluate this subexpression independent of the
11945 // enclosing ArrayInitLoopExpr. We can't do that.
11946 Info.FFDiag(E);
11947 return false;
11948 }
11949 return Success(Info.ArrayInitIndex, E);
11950 }
11951
11952 // Note, GNU defines __null as an integer, not a pointer.
11953 bool VisitGNUNullExpr(const GNUNullExpr *E) {
11954 return ZeroInitialization(E);
11955 }
11956
11957 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11958 return Success(E->getValue(), E);
11959 }
11960
11961 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11962 return Success(E->getValue(), E);
11963 }
11964
11965 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11966 return Success(E->getValue(), E);
11967 }
11968
11969 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
11970 // This should not be evaluated during constant expr evaluation, as it
11971 // should always be in an unevaluated context (the args list of a 'gang' or
11972 // 'tile' clause).
11973 return Error(E);
11974 }
11975
11976 bool VisitUnaryReal(const UnaryOperator *E);
11977 bool VisitUnaryImag(const UnaryOperator *E);
11978
11979 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11980 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11981 bool VisitSourceLocExpr(const SourceLocExpr *E);
11982 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11983 bool VisitRequiresExpr(const RequiresExpr *E);
11984 // FIXME: Missing: array subscript of vector, member of vector
11985};
11986
11987class FixedPointExprEvaluator
11988 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11989 APValue &Result;
11990
11991 public:
11992 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11993 : ExprEvaluatorBaseTy(info), Result(result) {}
11994
11995 bool Success(const llvm::APInt &I, const Expr *E) {
11996 return Success(
11997 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11998 }
11999
12000 bool Success(uint64_t Value, const Expr *E) {
12001 return Success(
12002 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12003 }
12004
12005 bool Success(const APValue &V, const Expr *E) {
12006 return Success(V.getFixedPoint(), E);
12007 }
12008
12009 bool Success(const APFixedPoint &V, const Expr *E) {
12010 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
12011 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12012 "Invalid evaluation result.");
12013 Result = APValue(V);
12014 return true;
12015 }
12016
12017 bool ZeroInitialization(const Expr *E) {
12018 return Success(0, E);
12019 }
12020
12021 //===--------------------------------------------------------------------===//
12022 // Visitor Methods
12023 //===--------------------------------------------------------------------===//
12024
12025 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
12026 return Success(E->getValue(), E);
12027 }
12028
12029 bool VisitCastExpr(const CastExpr *E);
12030 bool VisitUnaryOperator(const UnaryOperator *E);
12031 bool VisitBinaryOperator(const BinaryOperator *E);
12032};
12033} // end anonymous namespace
12034
12035/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
12036/// produce either the integer value or a pointer.
12037///
12038/// GCC has a heinous extension which folds casts between pointer types and
12039/// pointer-sized integral types. We support this by allowing the evaluation of
12040/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
12041/// Some simple arithmetic on such values is supported (they are treated much
12042/// like char*).
12043static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
12044 EvalInfo &Info) {
12045 assert(!E->isValueDependent());
12046 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
12047 return IntExprEvaluator(Info, Result).Visit(E);
12048}
12049
12050static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
12051 assert(!E->isValueDependent());
12052 APValue Val;
12053 if (!EvaluateIntegerOrLValue(E, Val, Info))
12054 return false;
12055 if (!Val.isInt()) {
12056 // FIXME: It would be better to produce the diagnostic for casting
12057 // a pointer to an integer.
12058 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12059 return false;
12060 }
12061 Result = Val.getInt();
12062 return true;
12063}
12064
12065bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
12066 APValue Evaluated = E->EvaluateInContext(
12067 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
12068 return Success(Evaluated, E);
12069}
12070
12071static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
12072 EvalInfo &Info) {
12073 assert(!E->isValueDependent());
12074 if (E->getType()->isFixedPointType()) {
12075 APValue Val;
12076 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
12077 return false;
12078 if (!Val.isFixedPoint())
12079 return false;
12080
12081 Result = Val.getFixedPoint();
12082 return true;
12083 }
12084 return false;
12085}
12086
12087static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
12088 EvalInfo &Info) {
12089 assert(!E->isValueDependent());
12090 if (E->getType()->isIntegerType()) {
12091 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
12092 APSInt Val;
12093 if (!EvaluateInteger(E, Val, Info))
12094 return false;
12095 Result = APFixedPoint(Val, FXSema);
12096 return true;
12097 } else if (E->getType()->isFixedPointType()) {
12098 return EvaluateFixedPoint(E, Result, Info);
12099 }
12100 return false;
12101}
12102
12103/// Check whether the given declaration can be directly converted to an integral
12104/// rvalue. If not, no diagnostic is produced; there are other things we can
12105/// try.
12106bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
12107 // Enums are integer constant exprs.
12108 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
12109 // Check for signedness/width mismatches between E type and ECD value.
12110 bool SameSign = (ECD->getInitVal().isSigned()
12112 bool SameWidth = (ECD->getInitVal().getBitWidth()
12113 == Info.Ctx.getIntWidth(E->getType()));
12114 if (SameSign && SameWidth)
12115 return Success(ECD->getInitVal(), E);
12116 else {
12117 // Get rid of mismatch (otherwise Success assertions will fail)
12118 // by computing a new value matching the type of E.
12119 llvm::APSInt Val = ECD->getInitVal();
12120 if (!SameSign)
12121 Val.setIsSigned(!ECD->getInitVal().isSigned());
12122 if (!SameWidth)
12123 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
12124 return Success(Val, E);
12125 }
12126 }
12127 return false;
12128}
12129
12130/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12131/// as GCC.
12133 const LangOptions &LangOpts) {
12134 assert(!T->isDependentType() && "unexpected dependent type");
12135
12136 QualType CanTy = T.getCanonicalType();
12137
12138 switch (CanTy->getTypeClass()) {
12139#define TYPE(ID, BASE)
12140#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
12141#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
12142#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
12143#include "clang/AST/TypeNodes.inc"
12144 case Type::Auto:
12145 case Type::DeducedTemplateSpecialization:
12146 llvm_unreachable("unexpected non-canonical or dependent type");
12147
12148 case Type::Builtin:
12149 switch (cast<BuiltinType>(CanTy)->getKind()) {
12150#define BUILTIN_TYPE(ID, SINGLETON_ID)
12151#define SIGNED_TYPE(ID, SINGLETON_ID) \
12152 case BuiltinType::ID: return GCCTypeClass::Integer;
12153#define FLOATING_TYPE(ID, SINGLETON_ID) \
12154 case BuiltinType::ID: return GCCTypeClass::RealFloat;
12155#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
12156 case BuiltinType::ID: break;
12157#include "clang/AST/BuiltinTypes.def"
12158 case BuiltinType::Void:
12159 return GCCTypeClass::Void;
12160
12161 case BuiltinType::Bool:
12162 return GCCTypeClass::Bool;
12163
12164 case BuiltinType::Char_U:
12165 case BuiltinType::UChar:
12166 case BuiltinType::WChar_U:
12167 case BuiltinType::Char8:
12168 case BuiltinType::Char16:
12169 case BuiltinType::Char32:
12170 case BuiltinType::UShort:
12171 case BuiltinType::UInt:
12172 case BuiltinType::ULong:
12173 case BuiltinType::ULongLong:
12174 case BuiltinType::UInt128:
12175 return GCCTypeClass::Integer;
12176
12177 case BuiltinType::UShortAccum:
12178 case BuiltinType::UAccum:
12179 case BuiltinType::ULongAccum:
12180 case BuiltinType::UShortFract:
12181 case BuiltinType::UFract:
12182 case BuiltinType::ULongFract:
12183 case BuiltinType::SatUShortAccum:
12184 case BuiltinType::SatUAccum:
12185 case BuiltinType::SatULongAccum:
12186 case BuiltinType::SatUShortFract:
12187 case BuiltinType::SatUFract:
12188 case BuiltinType::SatULongFract:
12189 return GCCTypeClass::None;
12190
12191 case BuiltinType::NullPtr:
12192
12193 case BuiltinType::ObjCId:
12194 case BuiltinType::ObjCClass:
12195 case BuiltinType::ObjCSel:
12196#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
12197 case BuiltinType::Id:
12198#include "clang/Basic/OpenCLImageTypes.def"
12199#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
12200 case BuiltinType::Id:
12201#include "clang/Basic/OpenCLExtensionTypes.def"
12202 case BuiltinType::OCLSampler:
12203 case BuiltinType::OCLEvent:
12204 case BuiltinType::OCLClkEvent:
12205 case BuiltinType::OCLQueue:
12206 case BuiltinType::OCLReserveID:
12207#define SVE_TYPE(Name, Id, SingletonId) \
12208 case BuiltinType::Id:
12209#include "clang/Basic/AArch64SVEACLETypes.def"
12210#define PPC_VECTOR_TYPE(Name, Id, Size) \
12211 case BuiltinType::Id:
12212#include "clang/Basic/PPCTypes.def"
12213#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12214#include "clang/Basic/RISCVVTypes.def"
12215#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12216#include "clang/Basic/WebAssemblyReferenceTypes.def"
12217#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
12218#include "clang/Basic/AMDGPUTypes.def"
12219#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12220#include "clang/Basic/HLSLIntangibleTypes.def"
12221 return GCCTypeClass::None;
12222
12223 case BuiltinType::Dependent:
12224 llvm_unreachable("unexpected dependent type");
12225 };
12226 llvm_unreachable("unexpected placeholder type");
12227
12228 case Type::Enum:
12229 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
12230
12231 case Type::Pointer:
12232 case Type::ConstantArray:
12233 case Type::VariableArray:
12234 case Type::IncompleteArray:
12235 case Type::FunctionNoProto:
12236 case Type::FunctionProto:
12237 case Type::ArrayParameter:
12238 return GCCTypeClass::Pointer;
12239
12240 case Type::MemberPointer:
12241 return CanTy->isMemberDataPointerType()
12242 ? GCCTypeClass::PointerToDataMember
12243 : GCCTypeClass::PointerToMemberFunction;
12244
12245 case Type::Complex:
12246 return GCCTypeClass::Complex;
12247
12248 case Type::Record:
12249 return CanTy->isUnionType() ? GCCTypeClass::Union
12250 : GCCTypeClass::ClassOrStruct;
12251
12252 case Type::Atomic:
12253 // GCC classifies _Atomic T the same as T.
12255 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
12256
12257 case Type::Vector:
12258 case Type::ExtVector:
12259 return GCCTypeClass::Vector;
12260
12261 case Type::BlockPointer:
12262 case Type::ConstantMatrix:
12263 case Type::ObjCObject:
12264 case Type::ObjCInterface:
12265 case Type::ObjCObjectPointer:
12266 case Type::Pipe:
12267 case Type::HLSLAttributedResource:
12268 // Classify all other types that don't fit into the regular
12269 // classification the same way.
12270 return GCCTypeClass::None;
12271
12272 case Type::BitInt:
12273 return GCCTypeClass::BitInt;
12274
12275 case Type::LValueReference:
12276 case Type::RValueReference:
12277 llvm_unreachable("invalid type for expression");
12278 }
12279
12280 llvm_unreachable("unexpected type class");
12281}
12282
12283/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12284/// as GCC.
12285static GCCTypeClass
12287 // If no argument was supplied, default to None. This isn't
12288 // ideal, however it is what gcc does.
12289 if (E->getNumArgs() == 0)
12290 return GCCTypeClass::None;
12291
12292 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
12293 // being an ICE, but still folds it to a constant using the type of the first
12294 // argument.
12295 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
12296}
12297
12298/// EvaluateBuiltinConstantPForLValue - Determine the result of
12299/// __builtin_constant_p when applied to the given pointer.
12300///
12301/// A pointer is only "constant" if it is null (or a pointer cast to integer)
12302/// or it points to the first character of a string literal.
12305 if (Base.isNull()) {
12306 // A null base is acceptable.
12307 return true;
12308 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
12309 if (!isa<StringLiteral>(E))
12310 return false;
12311 return LV.getLValueOffset().isZero();
12312 } else if (Base.is<TypeInfoLValue>()) {
12313 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
12314 // evaluate to true.
12315 return true;
12316 } else {
12317 // Any other base is not constant enough for GCC.
12318 return false;
12319 }
12320}
12321
12322/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
12323/// GCC as we can manage.
12324static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
12325 // This evaluation is not permitted to have side-effects, so evaluate it in
12326 // a speculative evaluation context.
12327 SpeculativeEvaluationRAII SpeculativeEval(Info);
12328
12329 // Constant-folding is always enabled for the operand of __builtin_constant_p
12330 // (even when the enclosing evaluation context otherwise requires a strict
12331 // language-specific constant expression).
12332 FoldConstant Fold(Info, true);
12333
12334 QualType ArgType = Arg->getType();
12335
12336 // __builtin_constant_p always has one operand. The rules which gcc follows
12337 // are not precisely documented, but are as follows:
12338 //
12339 // - If the operand is of integral, floating, complex or enumeration type,
12340 // and can be folded to a known value of that type, it returns 1.
12341 // - If the operand can be folded to a pointer to the first character
12342 // of a string literal (or such a pointer cast to an integral type)
12343 // or to a null pointer or an integer cast to a pointer, it returns 1.
12344 //
12345 // Otherwise, it returns 0.
12346 //
12347 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
12348 // its support for this did not work prior to GCC 9 and is not yet well
12349 // understood.
12350 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
12351 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
12352 ArgType->isNullPtrType()) {
12353 APValue V;
12354 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
12355 Fold.keepDiagnostics();
12356 return false;
12357 }
12358
12359 // For a pointer (possibly cast to integer), there are special rules.
12360 if (V.getKind() == APValue::LValue)
12362
12363 // Otherwise, any constant value is good enough.
12364 return V.hasValue();
12365 }
12366
12367 // Anything else isn't considered to be sufficiently constant.
12368 return false;
12369}
12370
12371/// Retrieves the "underlying object type" of the given expression,
12372/// as used by __builtin_object_size.
12374 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
12375 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
12376 return VD->getType();
12377 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
12378 if (isa<CompoundLiteralExpr>(E))
12379 return E->getType();
12380 } else if (B.is<TypeInfoLValue>()) {
12381 return B.getTypeInfoType();
12382 } else if (B.is<DynamicAllocLValue>()) {
12383 return B.getDynamicAllocType();
12384 }
12385
12386 return QualType();
12387}
12388
12389/// A more selective version of E->IgnoreParenCasts for
12390/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
12391/// to change the type of E.
12392/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
12393///
12394/// Always returns an RValue with a pointer representation.
12396 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
12397
12398 const Expr *NoParens = E->IgnoreParens();
12399 const auto *Cast = dyn_cast<CastExpr>(NoParens);
12400 if (Cast == nullptr)
12401 return NoParens;
12402
12403 // We only conservatively allow a few kinds of casts, because this code is
12404 // inherently a simple solution that seeks to support the common case.
12405 auto CastKind = Cast->getCastKind();
12406 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
12407 CastKind != CK_AddressSpaceConversion)
12408 return NoParens;
12409
12410 const auto *SubExpr = Cast->getSubExpr();
12411 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
12412 return NoParens;
12413 return ignorePointerCastsAndParens(SubExpr);
12414}
12415
12416/// Checks to see if the given LValue's Designator is at the end of the LValue's
12417/// record layout. e.g.
12418/// struct { struct { int a, b; } fst, snd; } obj;
12419/// obj.fst // no
12420/// obj.snd // yes
12421/// obj.fst.a // no
12422/// obj.fst.b // no
12423/// obj.snd.a // no
12424/// obj.snd.b // yes
12425///
12426/// Please note: this function is specialized for how __builtin_object_size
12427/// views "objects".
12428///
12429/// If this encounters an invalid RecordDecl or otherwise cannot determine the
12430/// correct result, it will always return true.
12431static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
12432 assert(!LVal.Designator.Invalid);
12433
12434 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
12435 const RecordDecl *Parent = FD->getParent();
12436 Invalid = Parent->isInvalidDecl();
12437 if (Invalid || Parent->isUnion())
12438 return true;
12439 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
12440 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
12441 };
12442
12443 auto &Base = LVal.getLValueBase();
12444 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
12445 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
12446 bool Invalid;
12447 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12448 return Invalid;
12449 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
12450 for (auto *FD : IFD->chain()) {
12451 bool Invalid;
12452 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
12453 return Invalid;
12454 }
12455 }
12456 }
12457
12458 unsigned I = 0;
12459 QualType BaseType = getType(Base);
12460 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
12461 // If we don't know the array bound, conservatively assume we're looking at
12462 // the final array element.
12463 ++I;
12464 if (BaseType->isIncompleteArrayType())
12465 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
12466 else
12467 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
12468 }
12469
12470 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
12471 const auto &Entry = LVal.Designator.Entries[I];
12472 if (BaseType->isArrayType()) {
12473 // Because __builtin_object_size treats arrays as objects, we can ignore
12474 // the index iff this is the last array in the Designator.
12475 if (I + 1 == E)
12476 return true;
12477 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
12478 uint64_t Index = Entry.getAsArrayIndex();
12479 if (Index + 1 != CAT->getZExtSize())
12480 return false;
12481 BaseType = CAT->getElementType();
12482 } else if (BaseType->isAnyComplexType()) {
12483 const auto *CT = BaseType->castAs<ComplexType>();
12484 uint64_t Index = Entry.getAsArrayIndex();
12485 if (Index != 1)
12486 return false;
12487 BaseType = CT->getElementType();
12488 } else if (auto *FD = getAsField(Entry)) {
12489 bool Invalid;
12490 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12491 return Invalid;
12492 BaseType = FD->getType();
12493 } else {
12494 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
12495 return false;
12496 }
12497 }
12498 return true;
12499}
12500
12501/// Tests to see if the LValue has a user-specified designator (that isn't
12502/// necessarily valid). Note that this always returns 'true' if the LValue has
12503/// an unsized array as its first designator entry, because there's currently no
12504/// way to tell if the user typed *foo or foo[0].
12505static bool refersToCompleteObject(const LValue &LVal) {
12506 if (LVal.Designator.Invalid)
12507 return false;
12508
12509 if (!LVal.Designator.Entries.empty())
12510 return LVal.Designator.isMostDerivedAnUnsizedArray();
12511
12512 if (!LVal.InvalidBase)
12513 return true;
12514
12515 // If `E` is a MemberExpr, then the first part of the designator is hiding in
12516 // the LValueBase.
12517 const auto *E = LVal.Base.dyn_cast<const Expr *>();
12518 return !E || !isa<MemberExpr>(E);
12519}
12520
12521/// Attempts to detect a user writing into a piece of memory that's impossible
12522/// to figure out the size of by just using types.
12523static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
12524 const SubobjectDesignator &Designator = LVal.Designator;
12525 // Notes:
12526 // - Users can only write off of the end when we have an invalid base. Invalid
12527 // bases imply we don't know where the memory came from.
12528 // - We used to be a bit more aggressive here; we'd only be conservative if
12529 // the array at the end was flexible, or if it had 0 or 1 elements. This
12530 // broke some common standard library extensions (PR30346), but was
12531 // otherwise seemingly fine. It may be useful to reintroduce this behavior
12532 // with some sort of list. OTOH, it seems that GCC is always
12533 // conservative with the last element in structs (if it's an array), so our
12534 // current behavior is more compatible than an explicit list approach would
12535 // be.
12536 auto isFlexibleArrayMember = [&] {
12538 FAMKind StrictFlexArraysLevel =
12539 Ctx.getLangOpts().getStrictFlexArraysLevel();
12540
12541 if (Designator.isMostDerivedAnUnsizedArray())
12542 return true;
12543
12544 if (StrictFlexArraysLevel == FAMKind::Default)
12545 return true;
12546
12547 if (Designator.getMostDerivedArraySize() == 0 &&
12548 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
12549 return true;
12550
12551 if (Designator.getMostDerivedArraySize() == 1 &&
12552 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
12553 return true;
12554
12555 return false;
12556 };
12557
12558 return LVal.InvalidBase &&
12559 Designator.Entries.size() == Designator.MostDerivedPathLength &&
12560 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
12561 isDesignatorAtObjectEnd(Ctx, LVal);
12562}
12563
12564/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
12565/// Fails if the conversion would cause loss of precision.
12566static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
12567 CharUnits &Result) {
12568 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
12569 if (Int.ugt(CharUnitsMax))
12570 return false;
12571 Result = CharUnits::fromQuantity(Int.getZExtValue());
12572 return true;
12573}
12574
12575/// If we're evaluating the object size of an instance of a struct that
12576/// contains a flexible array member, add the size of the initializer.
12577static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
12578 const LValue &LV, CharUnits &Size) {
12579 if (!T.isNull() && T->isStructureType() &&
12581 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
12582 if (const auto *VD = dyn_cast<VarDecl>(V))
12583 if (VD->hasInit())
12584 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
12585}
12586
12587/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
12588/// determine how many bytes exist from the beginning of the object to either
12589/// the end of the current subobject, or the end of the object itself, depending
12590/// on what the LValue looks like + the value of Type.
12591///
12592/// If this returns false, the value of Result is undefined.
12593static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
12594 unsigned Type, const LValue &LVal,
12595 CharUnits &EndOffset) {
12596 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
12597
12598 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
12599 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
12600 return false;
12601 return HandleSizeof(Info, ExprLoc, Ty, Result);
12602 };
12603
12604 // We want to evaluate the size of the entire object. This is a valid fallback
12605 // for when Type=1 and the designator is invalid, because we're asked for an
12606 // upper-bound.
12607 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
12608 // Type=3 wants a lower bound, so we can't fall back to this.
12609 if (Type == 3 && !DetermineForCompleteObject)
12610 return false;
12611
12612 llvm::APInt APEndOffset;
12613 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12614 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12615 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12616
12617 if (LVal.InvalidBase)
12618 return false;
12619
12620 QualType BaseTy = getObjectType(LVal.getLValueBase());
12621 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
12622 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
12623 return Ret;
12624 }
12625
12626 // We want to evaluate the size of a subobject.
12627 const SubobjectDesignator &Designator = LVal.Designator;
12628
12629 // The following is a moderately common idiom in C:
12630 //
12631 // struct Foo { int a; char c[1]; };
12632 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
12633 // strcpy(&F->c[0], Bar);
12634 //
12635 // In order to not break too much legacy code, we need to support it.
12636 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
12637 // If we can resolve this to an alloc_size call, we can hand that back,
12638 // because we know for certain how many bytes there are to write to.
12639 llvm::APInt APEndOffset;
12640 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12641 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12642 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12643
12644 // If we cannot determine the size of the initial allocation, then we can't
12645 // given an accurate upper-bound. However, we are still able to give
12646 // conservative lower-bounds for Type=3.
12647 if (Type == 1)
12648 return false;
12649 }
12650
12651 CharUnits BytesPerElem;
12652 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
12653 return false;
12654
12655 // According to the GCC documentation, we want the size of the subobject
12656 // denoted by the pointer. But that's not quite right -- what we actually
12657 // want is the size of the immediately-enclosing array, if there is one.
12658 int64_t ElemsRemaining;
12659 if (Designator.MostDerivedIsArrayElement &&
12660 Designator.Entries.size() == Designator.MostDerivedPathLength) {
12661 uint64_t ArraySize = Designator.getMostDerivedArraySize();
12662 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
12663 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
12664 } else {
12665 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
12666 }
12667
12668 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
12669 return true;
12670}
12671
12672/// Tries to evaluate the __builtin_object_size for @p E. If successful,
12673/// returns true and stores the result in @p Size.
12674///
12675/// If @p WasError is non-null, this will report whether the failure to evaluate
12676/// is to be treated as an Error in IntExprEvaluator.
12677static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
12678 EvalInfo &Info, uint64_t &Size) {
12679 // Determine the denoted object.
12680 LValue LVal;
12681 {
12682 // The operand of __builtin_object_size is never evaluated for side-effects.
12683 // If there are any, but we can determine the pointed-to object anyway, then
12684 // ignore the side-effects.
12685 SpeculativeEvaluationRAII SpeculativeEval(Info);
12686 IgnoreSideEffectsRAII Fold(Info);
12687
12688 if (E->isGLValue()) {
12689 // It's possible for us to be given GLValues if we're called via
12690 // Expr::tryEvaluateObjectSize.
12691 APValue RVal;
12692 if (!EvaluateAsRValue(Info, E, RVal))
12693 return false;
12694 LVal.setFrom(Info.Ctx, RVal);
12695 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
12696 /*InvalidBaseOK=*/true))
12697 return false;
12698 }
12699
12700 // If we point to before the start of the object, there are no accessible
12701 // bytes.
12702 if (LVal.getLValueOffset().isNegative()) {
12703 Size = 0;
12704 return true;
12705 }
12706
12707 CharUnits EndOffset;
12708 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
12709 return false;
12710
12711 // If we've fallen outside of the end offset, just pretend there's nothing to
12712 // write to/read from.
12713 if (EndOffset <= LVal.getLValueOffset())
12714 Size = 0;
12715 else
12716 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
12717 return true;
12718}
12719
12720bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
12721 if (!IsConstantEvaluatedBuiltinCall(E))
12722 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12723 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
12724}
12725
12726static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
12727 APValue &Val, APSInt &Alignment) {
12728 QualType SrcTy = E->getArg(0)->getType();
12729 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
12730 return false;
12731 // Even though we are evaluating integer expressions we could get a pointer
12732 // argument for the __builtin_is_aligned() case.
12733 if (SrcTy->isPointerType()) {
12734 LValue Ptr;
12735 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
12736 return false;
12737 Ptr.moveInto(Val);
12738 } else if (!SrcTy->isIntegralOrEnumerationType()) {
12739 Info.FFDiag(E->getArg(0));
12740 return false;
12741 } else {
12742 APSInt SrcInt;
12743 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
12744 return false;
12745 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
12746 "Bit widths must be the same");
12747 Val = APValue(SrcInt);
12748 }
12749 assert(Val.hasValue());
12750 return true;
12751}
12752
12753bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
12754 unsigned BuiltinOp) {
12755 switch (BuiltinOp) {
12756 default:
12757 return false;
12758
12759 case Builtin::BI__builtin_dynamic_object_size:
12760 case Builtin::BI__builtin_object_size: {
12761 // The type was checked when we built the expression.
12762 unsigned Type =
12763 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12764 assert(Type <= 3 && "unexpected type");
12765
12766 uint64_t Size;
12767 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
12768 return Success(Size, E);
12769
12770 if (E->getArg(0)->HasSideEffects(Info.Ctx))
12771 return Success((Type & 2) ? 0 : -1, E);
12772
12773 // Expression had no side effects, but we couldn't statically determine the
12774 // size of the referenced object.
12775 switch (Info.EvalMode) {
12776 case EvalInfo::EM_ConstantExpression:
12777 case EvalInfo::EM_ConstantFold:
12778 case EvalInfo::EM_IgnoreSideEffects:
12779 // Leave it to IR generation.
12780 return Error(E);
12781 case EvalInfo::EM_ConstantExpressionUnevaluated:
12782 // Reduce it to a constant now.
12783 return Success((Type & 2) ? 0 : -1, E);
12784 }
12785
12786 llvm_unreachable("unexpected EvalMode");
12787 }
12788
12789 case Builtin::BI__builtin_os_log_format_buffer_size: {
12792 return Success(Layout.size().getQuantity(), E);
12793 }
12794
12795 case Builtin::BI__builtin_is_aligned: {
12796 APValue Src;
12797 APSInt Alignment;
12798 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12799 return false;
12800 if (Src.isLValue()) {
12801 // If we evaluated a pointer, check the minimum known alignment.
12802 LValue Ptr;
12803 Ptr.setFrom(Info.Ctx, Src);
12804 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
12805 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
12806 // We can return true if the known alignment at the computed offset is
12807 // greater than the requested alignment.
12808 assert(PtrAlign.isPowerOfTwo());
12809 assert(Alignment.isPowerOf2());
12810 if (PtrAlign.getQuantity() >= Alignment)
12811 return Success(1, E);
12812 // If the alignment is not known to be sufficient, some cases could still
12813 // be aligned at run time. However, if the requested alignment is less or
12814 // equal to the base alignment and the offset is not aligned, we know that
12815 // the run-time value can never be aligned.
12816 if (BaseAlignment.getQuantity() >= Alignment &&
12817 PtrAlign.getQuantity() < Alignment)
12818 return Success(0, E);
12819 // Otherwise we can't infer whether the value is sufficiently aligned.
12820 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
12821 // in cases where we can't fully evaluate the pointer.
12822 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
12823 << Alignment;
12824 return false;
12825 }
12826 assert(Src.isInt());
12827 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
12828 }
12829 case Builtin::BI__builtin_align_up: {
12830 APValue Src;
12831 APSInt Alignment;
12832 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12833 return false;
12834 if (!Src.isInt())
12835 return Error(E);
12836 APSInt AlignedVal =
12837 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
12838 Src.getInt().isUnsigned());
12839 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12840 return Success(AlignedVal, E);
12841 }
12842 case Builtin::BI__builtin_align_down: {
12843 APValue Src;
12844 APSInt Alignment;
12845 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12846 return false;
12847 if (!Src.isInt())
12848 return Error(E);
12849 APSInt AlignedVal =
12850 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
12851 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12852 return Success(AlignedVal, E);
12853 }
12854
12855 case Builtin::BI__builtin_bitreverse8:
12856 case Builtin::BI__builtin_bitreverse16:
12857 case Builtin::BI__builtin_bitreverse32:
12858 case Builtin::BI__builtin_bitreverse64:
12859 case Builtin::BI__builtin_elementwise_bitreverse: {
12860 APSInt Val;
12861 if (!EvaluateInteger(E->getArg(0), Val, Info))
12862 return false;
12863
12864 return Success(Val.reverseBits(), E);
12865 }
12866
12867 case Builtin::BI__builtin_bswap16:
12868 case Builtin::BI__builtin_bswap32:
12869 case Builtin::BI__builtin_bswap64: {
12870 APSInt Val;
12871 if (!EvaluateInteger(E->getArg(0), Val, Info))
12872 return false;
12873
12874 return Success(Val.byteSwap(), E);
12875 }
12876
12877 case Builtin::BI__builtin_classify_type:
12878 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12879
12880 case Builtin::BI__builtin_clrsb:
12881 case Builtin::BI__builtin_clrsbl:
12882 case Builtin::BI__builtin_clrsbll: {
12883 APSInt Val;
12884 if (!EvaluateInteger(E->getArg(0), Val, Info))
12885 return false;
12886
12887 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
12888 }
12889
12890 case Builtin::BI__builtin_clz:
12891 case Builtin::BI__builtin_clzl:
12892 case Builtin::BI__builtin_clzll:
12893 case Builtin::BI__builtin_clzs:
12894 case Builtin::BI__builtin_clzg:
12895 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
12896 case Builtin::BI__lzcnt:
12897 case Builtin::BI__lzcnt64: {
12898 APSInt Val;
12899 if (!EvaluateInteger(E->getArg(0), Val, Info))
12900 return false;
12901
12902 std::optional<APSInt> Fallback;
12903 if (BuiltinOp == Builtin::BI__builtin_clzg && E->getNumArgs() > 1) {
12904 APSInt FallbackTemp;
12905 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
12906 return false;
12907 Fallback = FallbackTemp;
12908 }
12909
12910 if (!Val) {
12911 if (Fallback)
12912 return Success(*Fallback, E);
12913
12914 // When the argument is 0, the result of GCC builtins is undefined,
12915 // whereas for Microsoft intrinsics, the result is the bit-width of the
12916 // argument.
12917 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
12918 BuiltinOp != Builtin::BI__lzcnt &&
12919 BuiltinOp != Builtin::BI__lzcnt64;
12920
12921 if (ZeroIsUndefined)
12922 return Error(E);
12923 }
12924
12925 return Success(Val.countl_zero(), E);
12926 }
12927
12928 case Builtin::BI__builtin_constant_p: {
12929 const Expr *Arg = E->getArg(0);
12930 if (EvaluateBuiltinConstantP(Info, Arg))
12931 return Success(true, E);
12932 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
12933 // Outside a constant context, eagerly evaluate to false in the presence
12934 // of side-effects in order to avoid -Wunsequenced false-positives in
12935 // a branch on __builtin_constant_p(expr).
12936 return Success(false, E);
12937 }
12938 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12939 return false;
12940 }
12941
12942 case Builtin::BI__noop:
12943 // __noop always evaluates successfully and returns 0.
12944 return Success(0, E);
12945
12946 case Builtin::BI__builtin_is_constant_evaluated: {
12947 const auto *Callee = Info.CurrentCall->getCallee();
12948 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12949 (Info.CallStackDepth == 1 ||
12950 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12951 Callee->getIdentifier() &&
12952 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12953 // FIXME: Find a better way to avoid duplicated diagnostics.
12954 if (Info.EvalStatus.Diag)
12955 Info.report((Info.CallStackDepth == 1)
12956 ? E->getExprLoc()
12957 : Info.CurrentCall->getCallRange().getBegin(),
12958 diag::warn_is_constant_evaluated_always_true_constexpr)
12959 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12960 : "std::is_constant_evaluated");
12961 }
12962
12963 return Success(Info.InConstantContext, E);
12964 }
12965
12966 case Builtin::BI__builtin_is_within_lifetime:
12967 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
12968 return Success(*result, E);
12969 return false;
12970
12971 case Builtin::BI__builtin_ctz:
12972 case Builtin::BI__builtin_ctzl:
12973 case Builtin::BI__builtin_ctzll:
12974 case Builtin::BI__builtin_ctzs:
12975 case Builtin::BI__builtin_ctzg: {
12976 APSInt Val;
12977 if (!EvaluateInteger(E->getArg(0), Val, Info))
12978 return false;
12979
12980 std::optional<APSInt> Fallback;
12981 if (BuiltinOp == Builtin::BI__builtin_ctzg && E->getNumArgs() > 1) {
12982 APSInt FallbackTemp;
12983 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
12984 return false;
12985 Fallback = FallbackTemp;
12986 }
12987
12988 if (!Val) {
12989 if (Fallback)
12990 return Success(*Fallback, E);
12991
12992 return Error(E);
12993 }
12994
12995 return Success(Val.countr_zero(), E);
12996 }
12997
12998 case Builtin::BI__builtin_eh_return_data_regno: {
12999 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
13000 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
13001 return Success(Operand, E);
13002 }
13003
13004 case Builtin::BI__builtin_expect:
13005 case Builtin::BI__builtin_expect_with_probability:
13006 return Visit(E->getArg(0));
13007
13008 case Builtin::BI__builtin_ptrauth_string_discriminator: {
13009 const auto *Literal =
13010 cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts());
13011 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
13012 return Success(Result, E);
13013 }
13014
13015 case Builtin::BI__builtin_ffs:
13016 case Builtin::BI__builtin_ffsl:
13017 case Builtin::BI__builtin_ffsll: {
13018 APSInt Val;
13019 if (!EvaluateInteger(E->getArg(0), Val, Info))
13020 return false;
13021
13022 unsigned N = Val.countr_zero();
13023 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
13024 }
13025
13026 case Builtin::BI__builtin_fpclassify: {
13027 APFloat Val(0.0);
13028 if (!EvaluateFloat(E->getArg(5), Val, Info))
13029 return false;
13030 unsigned Arg;
13031 switch (Val.getCategory()) {
13032 case APFloat::fcNaN: Arg = 0; break;
13033 case APFloat::fcInfinity: Arg = 1; break;
13034 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
13035 case APFloat::fcZero: Arg = 4; break;
13036 }
13037 return Visit(E->getArg(Arg));
13038 }
13039
13040 case Builtin::BI__builtin_isinf_sign: {
13041 APFloat Val(0.0);
13042 return EvaluateFloat(E->getArg(0), Val, Info) &&
13043 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
13044 }
13045
13046 case Builtin::BI__builtin_isinf: {
13047 APFloat Val(0.0);
13048 return EvaluateFloat(E->getArg(0), Val, Info) &&
13049 Success(Val.isInfinity() ? 1 : 0, E);
13050 }
13051
13052 case Builtin::BI__builtin_isfinite: {
13053 APFloat Val(0.0);
13054 return EvaluateFloat(E->getArg(0), Val, Info) &&
13055 Success(Val.isFinite() ? 1 : 0, E);
13056 }
13057
13058 case Builtin::BI__builtin_isnan: {
13059 APFloat Val(0.0);
13060 return EvaluateFloat(E->getArg(0), Val, Info) &&
13061 Success(Val.isNaN() ? 1 : 0, E);
13062 }
13063
13064 case Builtin::BI__builtin_isnormal: {
13065 APFloat Val(0.0);
13066 return EvaluateFloat(E->getArg(0), Val, Info) &&
13067 Success(Val.isNormal() ? 1 : 0, E);
13068 }
13069
13070 case Builtin::BI__builtin_issubnormal: {
13071 APFloat Val(0.0);
13072 return EvaluateFloat(E->getArg(0), Val, Info) &&
13073 Success(Val.isDenormal() ? 1 : 0, E);
13074 }
13075
13076 case Builtin::BI__builtin_iszero: {
13077 APFloat Val(0.0);
13078 return EvaluateFloat(E->getArg(0), Val, Info) &&
13079 Success(Val.isZero() ? 1 : 0, E);
13080 }
13081
13082 case Builtin::BI__builtin_signbit:
13083 case Builtin::BI__builtin_signbitf:
13084 case Builtin::BI__builtin_signbitl: {
13085 APFloat Val(0.0);
13086 return EvaluateFloat(E->getArg(0), Val, Info) &&
13087 Success(Val.isNegative() ? 1 : 0, E);
13088 }
13089
13090 case Builtin::BI__builtin_isgreater:
13091 case Builtin::BI__builtin_isgreaterequal:
13092 case Builtin::BI__builtin_isless:
13093 case Builtin::BI__builtin_islessequal:
13094 case Builtin::BI__builtin_islessgreater:
13095 case Builtin::BI__builtin_isunordered: {
13096 APFloat LHS(0.0);
13097 APFloat RHS(0.0);
13098 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
13099 !EvaluateFloat(E->getArg(1), RHS, Info))
13100 return false;
13101
13102 return Success(
13103 [&] {
13104 switch (BuiltinOp) {
13105 case Builtin::BI__builtin_isgreater:
13106 return LHS > RHS;
13107 case Builtin::BI__builtin_isgreaterequal:
13108 return LHS >= RHS;
13109 case Builtin::BI__builtin_isless:
13110 return LHS < RHS;
13111 case Builtin::BI__builtin_islessequal:
13112 return LHS <= RHS;
13113 case Builtin::BI__builtin_islessgreater: {
13114 APFloat::cmpResult cmp = LHS.compare(RHS);
13115 return cmp == APFloat::cmpResult::cmpLessThan ||
13116 cmp == APFloat::cmpResult::cmpGreaterThan;
13117 }
13118 case Builtin::BI__builtin_isunordered:
13119 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
13120 default:
13121 llvm_unreachable("Unexpected builtin ID: Should be a floating "
13122 "point comparison function");
13123 }
13124 }()
13125 ? 1
13126 : 0,
13127 E);
13128 }
13129
13130 case Builtin::BI__builtin_issignaling: {
13131 APFloat Val(0.0);
13132 return EvaluateFloat(E->getArg(0), Val, Info) &&
13133 Success(Val.isSignaling() ? 1 : 0, E);
13134 }
13135
13136 case Builtin::BI__builtin_isfpclass: {
13137 APSInt MaskVal;
13138 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
13139 return false;
13140 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
13141 APFloat Val(0.0);
13142 return EvaluateFloat(E->getArg(0), Val, Info) &&
13143 Success((Val.classify() & Test) ? 1 : 0, E);
13144 }
13145
13146 case Builtin::BI__builtin_parity:
13147 case Builtin::BI__builtin_parityl:
13148 case Builtin::BI__builtin_parityll: {
13149 APSInt Val;
13150 if (!EvaluateInteger(E->getArg(0), Val, Info))
13151 return false;
13152
13153 return Success(Val.popcount() % 2, E);
13154 }
13155
13156 case Builtin::BI__builtin_abs:
13157 case Builtin::BI__builtin_labs:
13158 case Builtin::BI__builtin_llabs: {
13159 APSInt Val;
13160 if (!EvaluateInteger(E->getArg(0), Val, Info))
13161 return false;
13162 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
13163 /*IsUnsigned=*/false))
13164 return false;
13165 if (Val.isNegative())
13166 Val.negate();
13167 return Success(Val, E);
13168 }
13169
13170 case Builtin::BI__builtin_popcount:
13171 case Builtin::BI__builtin_popcountl:
13172 case Builtin::BI__builtin_popcountll:
13173 case Builtin::BI__builtin_popcountg:
13174 case Builtin::BI__builtin_elementwise_popcount:
13175 case Builtin::BI__popcnt16: // Microsoft variants of popcount
13176 case Builtin::BI__popcnt:
13177 case Builtin::BI__popcnt64: {
13178 APSInt Val;
13179 if (!EvaluateInteger(E->getArg(0), Val, Info))
13180 return false;
13181
13182 return Success(Val.popcount(), E);
13183 }
13184
13185 case Builtin::BI__builtin_rotateleft8:
13186 case Builtin::BI__builtin_rotateleft16:
13187 case Builtin::BI__builtin_rotateleft32:
13188 case Builtin::BI__builtin_rotateleft64:
13189 case Builtin::BI_rotl8: // Microsoft variants of rotate right
13190 case Builtin::BI_rotl16:
13191 case Builtin::BI_rotl:
13192 case Builtin::BI_lrotl:
13193 case Builtin::BI_rotl64: {
13194 APSInt Val, Amt;
13195 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13196 !EvaluateInteger(E->getArg(1), Amt, Info))
13197 return false;
13198
13199 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
13200 }
13201
13202 case Builtin::BI__builtin_rotateright8:
13203 case Builtin::BI__builtin_rotateright16:
13204 case Builtin::BI__builtin_rotateright32:
13205 case Builtin::BI__builtin_rotateright64:
13206 case Builtin::BI_rotr8: // Microsoft variants of rotate right
13207 case Builtin::BI_rotr16:
13208 case Builtin::BI_rotr:
13209 case Builtin::BI_lrotr:
13210 case Builtin::BI_rotr64: {
13211 APSInt Val, Amt;
13212 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13213 !EvaluateInteger(E->getArg(1), Amt, Info))
13214 return false;
13215
13216 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
13217 }
13218
13219 case Builtin::BI__builtin_elementwise_add_sat: {
13220 APSInt LHS, RHS;
13221 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13222 !EvaluateInteger(E->getArg(1), RHS, Info))
13223 return false;
13224
13225 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
13226 return Success(APSInt(Result, !LHS.isSigned()), E);
13227 }
13228 case Builtin::BI__builtin_elementwise_sub_sat: {
13229 APSInt LHS, RHS;
13230 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13231 !EvaluateInteger(E->getArg(1), RHS, Info))
13232 return false;
13233
13234 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
13235 return Success(APSInt(Result, !LHS.isSigned()), E);
13236 }
13237
13238 case Builtin::BIstrlen:
13239 case Builtin::BIwcslen:
13240 // A call to strlen is not a constant expression.
13241 if (Info.getLangOpts().CPlusPlus11)
13242 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
13243 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
13244 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
13245 else
13246 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
13247 [[fallthrough]];
13248 case Builtin::BI__builtin_strlen:
13249 case Builtin::BI__builtin_wcslen: {
13250 // As an extension, we support __builtin_strlen() as a constant expression,
13251 // and support folding strlen() to a constant.
13252 uint64_t StrLen;
13253 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
13254 return Success(StrLen, E);
13255 return false;
13256 }
13257
13258 case Builtin::BIstrcmp:
13259 case Builtin::BIwcscmp:
13260 case Builtin::BIstrncmp:
13261 case Builtin::BIwcsncmp:
13262 case Builtin::BImemcmp:
13263 case Builtin::BIbcmp:
13264 case Builtin::BIwmemcmp:
13265 // A call to strlen is not a constant expression.
13266 if (Info.getLangOpts().CPlusPlus11)
13267 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
13268 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
13269 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
13270 else
13271 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
13272 [[fallthrough]];
13273 case Builtin::BI__builtin_strcmp:
13274 case Builtin::BI__builtin_wcscmp:
13275 case Builtin::BI__builtin_strncmp:
13276 case Builtin::BI__builtin_wcsncmp:
13277 case Builtin::BI__builtin_memcmp:
13278 case Builtin::BI__builtin_bcmp:
13279 case Builtin::BI__builtin_wmemcmp: {
13280 LValue String1, String2;
13281 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
13282 !EvaluatePointer(E->getArg(1), String2, Info))
13283 return false;
13284
13285 uint64_t MaxLength = uint64_t(-1);
13286 if (BuiltinOp != Builtin::BIstrcmp &&
13287 BuiltinOp != Builtin::BIwcscmp &&
13288 BuiltinOp != Builtin::BI__builtin_strcmp &&
13289 BuiltinOp != Builtin::BI__builtin_wcscmp) {
13290 APSInt N;
13291 if (!EvaluateInteger(E->getArg(2), N, Info))
13292 return false;
13293 MaxLength = N.getZExtValue();
13294 }
13295
13296 // Empty substrings compare equal by definition.
13297 if (MaxLength == 0u)
13298 return Success(0, E);
13299
13300 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
13301 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
13302 String1.Designator.Invalid || String2.Designator.Invalid)
13303 return false;
13304
13305 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
13306 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
13307
13308 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
13309 BuiltinOp == Builtin::BIbcmp ||
13310 BuiltinOp == Builtin::BI__builtin_memcmp ||
13311 BuiltinOp == Builtin::BI__builtin_bcmp;
13312
13313 assert(IsRawByte ||
13314 (Info.Ctx.hasSameUnqualifiedType(
13315 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
13316 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
13317
13318 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
13319 // 'char8_t', but no other types.
13320 if (IsRawByte &&
13321 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
13322 // FIXME: Consider using our bit_cast implementation to support this.
13323 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
13324 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
13325 << CharTy1 << CharTy2;
13326 return false;
13327 }
13328
13329 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
13330 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
13331 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
13332 Char1.isInt() && Char2.isInt();
13333 };
13334 const auto &AdvanceElems = [&] {
13335 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
13336 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
13337 };
13338
13339 bool StopAtNull =
13340 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
13341 BuiltinOp != Builtin::BIwmemcmp &&
13342 BuiltinOp != Builtin::BI__builtin_memcmp &&
13343 BuiltinOp != Builtin::BI__builtin_bcmp &&
13344 BuiltinOp != Builtin::BI__builtin_wmemcmp);
13345 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
13346 BuiltinOp == Builtin::BIwcsncmp ||
13347 BuiltinOp == Builtin::BIwmemcmp ||
13348 BuiltinOp == Builtin::BI__builtin_wcscmp ||
13349 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
13350 BuiltinOp == Builtin::BI__builtin_wmemcmp;
13351
13352 for (; MaxLength; --MaxLength) {
13353 APValue Char1, Char2;
13354 if (!ReadCurElems(Char1, Char2))
13355 return false;
13356 if (Char1.getInt().ne(Char2.getInt())) {
13357 if (IsWide) // wmemcmp compares with wchar_t signedness.
13358 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
13359 // memcmp always compares unsigned chars.
13360 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
13361 }
13362 if (StopAtNull && !Char1.getInt())
13363 return Success(0, E);
13364 assert(!(StopAtNull && !Char2.getInt()));
13365 if (!AdvanceElems())
13366 return false;
13367 }
13368 // We hit the strncmp / memcmp limit.
13369 return Success(0, E);
13370 }
13371
13372 case Builtin::BI__atomic_always_lock_free:
13373 case Builtin::BI__atomic_is_lock_free:
13374 case Builtin::BI__c11_atomic_is_lock_free: {
13375 APSInt SizeVal;
13376 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
13377 return false;
13378
13379 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
13380 // of two less than or equal to the maximum inline atomic width, we know it
13381 // is lock-free. If the size isn't a power of two, or greater than the
13382 // maximum alignment where we promote atomics, we know it is not lock-free
13383 // (at least not in the sense of atomic_is_lock_free). Otherwise,
13384 // the answer can only be determined at runtime; for example, 16-byte
13385 // atomics have lock-free implementations on some, but not all,
13386 // x86-64 processors.
13387
13388 // Check power-of-two.
13389 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
13390 if (Size.isPowerOfTwo()) {
13391 // Check against inlining width.
13392 unsigned InlineWidthBits =
13393 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
13394 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
13395 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
13396 Size == CharUnits::One())
13397 return Success(1, E);
13398
13399 // If the pointer argument can be evaluated to a compile-time constant
13400 // integer (or nullptr), check if that value is appropriately aligned.
13401 const Expr *PtrArg = E->getArg(1);
13403 APSInt IntResult;
13404 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
13405 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
13406 Info.Ctx) &&
13407 IntResult.isAligned(Size.getAsAlign()))
13408 return Success(1, E);
13409
13410 // Otherwise, check if the type's alignment against Size.
13411 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
13412 // Drop the potential implicit-cast to 'const volatile void*', getting
13413 // the underlying type.
13414 if (ICE->getCastKind() == CK_BitCast)
13415 PtrArg = ICE->getSubExpr();
13416 }
13417
13418 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
13419 QualType PointeeType = PtrTy->getPointeeType();
13420 if (!PointeeType->isIncompleteType() &&
13421 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
13422 // OK, we will inline operations on this object.
13423 return Success(1, E);
13424 }
13425 }
13426 }
13427 }
13428
13429 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
13430 Success(0, E) : Error(E);
13431 }
13432 case Builtin::BI__builtin_addcb:
13433 case Builtin::BI__builtin_addcs:
13434 case Builtin::BI__builtin_addc:
13435 case Builtin::BI__builtin_addcl:
13436 case Builtin::BI__builtin_addcll:
13437 case Builtin::BI__builtin_subcb:
13438 case Builtin::BI__builtin_subcs:
13439 case Builtin::BI__builtin_subc:
13440 case Builtin::BI__builtin_subcl:
13441 case Builtin::BI__builtin_subcll: {
13442 LValue CarryOutLValue;
13443 APSInt LHS, RHS, CarryIn, CarryOut, Result;
13444 QualType ResultType = E->getArg(0)->getType();
13445 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13446 !EvaluateInteger(E->getArg(1), RHS, Info) ||
13447 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
13448 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
13449 return false;
13450 // Copy the number of bits and sign.
13451 Result = LHS;
13452 CarryOut = LHS;
13453
13454 bool FirstOverflowed = false;
13455 bool SecondOverflowed = false;
13456 switch (BuiltinOp) {
13457 default:
13458 llvm_unreachable("Invalid value for BuiltinOp");
13459 case Builtin::BI__builtin_addcb:
13460 case Builtin::BI__builtin_addcs:
13461 case Builtin::BI__builtin_addc:
13462 case Builtin::BI__builtin_addcl:
13463 case Builtin::BI__builtin_addcll:
13464 Result =
13465 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
13466 break;
13467 case Builtin::BI__builtin_subcb:
13468 case Builtin::BI__builtin_subcs:
13469 case Builtin::BI__builtin_subc:
13470 case Builtin::BI__builtin_subcl:
13471 case Builtin::BI__builtin_subcll:
13472 Result =
13473 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
13474 break;
13475 }
13476
13477 // It is possible for both overflows to happen but CGBuiltin uses an OR so
13478 // this is consistent.
13479 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
13480 APValue APV{CarryOut};
13481 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
13482 return false;
13483 return Success(Result, E);
13484 }
13485 case Builtin::BI__builtin_add_overflow:
13486 case Builtin::BI__builtin_sub_overflow:
13487 case Builtin::BI__builtin_mul_overflow:
13488 case Builtin::BI__builtin_sadd_overflow:
13489 case Builtin::BI__builtin_uadd_overflow:
13490 case Builtin::BI__builtin_uaddl_overflow:
13491 case Builtin::BI__builtin_uaddll_overflow:
13492 case Builtin::BI__builtin_usub_overflow:
13493 case Builtin::BI__builtin_usubl_overflow:
13494 case Builtin::BI__builtin_usubll_overflow:
13495 case Builtin::BI__builtin_umul_overflow:
13496 case Builtin::BI__builtin_umull_overflow:
13497 case Builtin::BI__builtin_umulll_overflow:
13498 case Builtin::BI__builtin_saddl_overflow:
13499 case Builtin::BI__builtin_saddll_overflow:
13500 case Builtin::BI__builtin_ssub_overflow:
13501 case Builtin::BI__builtin_ssubl_overflow:
13502 case Builtin::BI__builtin_ssubll_overflow:
13503 case Builtin::BI__builtin_smul_overflow:
13504 case Builtin::BI__builtin_smull_overflow:
13505 case Builtin::BI__builtin_smulll_overflow: {
13506 LValue ResultLValue;
13507 APSInt LHS, RHS;
13508
13509 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
13510 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13511 !EvaluateInteger(E->getArg(1), RHS, Info) ||
13512 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
13513 return false;
13514
13515 APSInt Result;
13516 bool DidOverflow = false;
13517
13518 // If the types don't have to match, enlarge all 3 to the largest of them.
13519 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13520 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13521 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13522 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
13524 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
13526 uint64_t LHSSize = LHS.getBitWidth();
13527 uint64_t RHSSize = RHS.getBitWidth();
13528 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
13529 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
13530
13531 // Add an additional bit if the signedness isn't uniformly agreed to. We
13532 // could do this ONLY if there is a signed and an unsigned that both have
13533 // MaxBits, but the code to check that is pretty nasty. The issue will be
13534 // caught in the shrink-to-result later anyway.
13535 if (IsSigned && !AllSigned)
13536 ++MaxBits;
13537
13538 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
13539 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
13540 Result = APSInt(MaxBits, !IsSigned);
13541 }
13542
13543 // Find largest int.
13544 switch (BuiltinOp) {
13545 default:
13546 llvm_unreachable("Invalid value for BuiltinOp");
13547 case Builtin::BI__builtin_add_overflow:
13548 case Builtin::BI__builtin_sadd_overflow:
13549 case Builtin::BI__builtin_saddl_overflow:
13550 case Builtin::BI__builtin_saddll_overflow:
13551 case Builtin::BI__builtin_uadd_overflow:
13552 case Builtin::BI__builtin_uaddl_overflow:
13553 case Builtin::BI__builtin_uaddll_overflow:
13554 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
13555 : LHS.uadd_ov(RHS, DidOverflow);
13556 break;
13557 case Builtin::BI__builtin_sub_overflow:
13558 case Builtin::BI__builtin_ssub_overflow:
13559 case Builtin::BI__builtin_ssubl_overflow:
13560 case Builtin::BI__builtin_ssubll_overflow:
13561 case Builtin::BI__builtin_usub_overflow:
13562 case Builtin::BI__builtin_usubl_overflow:
13563 case Builtin::BI__builtin_usubll_overflow:
13564 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
13565 : LHS.usub_ov(RHS, DidOverflow);
13566 break;
13567 case Builtin::BI__builtin_mul_overflow:
13568 case Builtin::BI__builtin_smul_overflow:
13569 case Builtin::BI__builtin_smull_overflow:
13570 case Builtin::BI__builtin_smulll_overflow:
13571 case Builtin::BI__builtin_umul_overflow:
13572 case Builtin::BI__builtin_umull_overflow:
13573 case Builtin::BI__builtin_umulll_overflow:
13574 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
13575 : LHS.umul_ov(RHS, DidOverflow);
13576 break;
13577 }
13578
13579 // In the case where multiple sizes are allowed, truncate and see if
13580 // the values are the same.
13581 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13582 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13583 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13584 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
13585 // since it will give us the behavior of a TruncOrSelf in the case where
13586 // its parameter <= its size. We previously set Result to be at least the
13587 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
13588 // will work exactly like TruncOrSelf.
13589 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
13590 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
13591
13592 if (!APSInt::isSameValue(Temp, Result))
13593 DidOverflow = true;
13594 Result = Temp;
13595 }
13596
13597 APValue APV{Result};
13598 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13599 return false;
13600 return Success(DidOverflow, E);
13601 }
13602
13603 case Builtin::BI__builtin_reduce_add:
13604 case Builtin::BI__builtin_reduce_mul:
13605 case Builtin::BI__builtin_reduce_and:
13606 case Builtin::BI__builtin_reduce_or:
13607 case Builtin::BI__builtin_reduce_xor:
13608 case Builtin::BI__builtin_reduce_min:
13609 case Builtin::BI__builtin_reduce_max: {
13610 APValue Source;
13611 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13612 return false;
13613
13614 unsigned SourceLen = Source.getVectorLength();
13615 APSInt Reduced = Source.getVectorElt(0).getInt();
13616 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
13617 switch (BuiltinOp) {
13618 default:
13619 return false;
13620 case Builtin::BI__builtin_reduce_add: {
13622 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
13623 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
13624 return false;
13625 break;
13626 }
13627 case Builtin::BI__builtin_reduce_mul: {
13629 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
13630 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
13631 return false;
13632 break;
13633 }
13634 case Builtin::BI__builtin_reduce_and: {
13635 Reduced &= Source.getVectorElt(EltNum).getInt();
13636 break;
13637 }
13638 case Builtin::BI__builtin_reduce_or: {
13639 Reduced |= Source.getVectorElt(EltNum).getInt();
13640 break;
13641 }
13642 case Builtin::BI__builtin_reduce_xor: {
13643 Reduced ^= Source.getVectorElt(EltNum).getInt();
13644 break;
13645 }
13646 case Builtin::BI__builtin_reduce_min: {
13647 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
13648 break;
13649 }
13650 case Builtin::BI__builtin_reduce_max: {
13651 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
13652 break;
13653 }
13654 }
13655 }
13656
13657 return Success(Reduced, E);
13658 }
13659
13660 case clang::X86::BI__builtin_ia32_addcarryx_u32:
13661 case clang::X86::BI__builtin_ia32_addcarryx_u64:
13662 case clang::X86::BI__builtin_ia32_subborrow_u32:
13663 case clang::X86::BI__builtin_ia32_subborrow_u64: {
13664 LValue ResultLValue;
13665 APSInt CarryIn, LHS, RHS;
13666 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
13667 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
13668 !EvaluateInteger(E->getArg(1), LHS, Info) ||
13669 !EvaluateInteger(E->getArg(2), RHS, Info) ||
13670 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
13671 return false;
13672
13673 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
13674 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
13675
13676 unsigned BitWidth = LHS.getBitWidth();
13677 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
13678 APInt ExResult =
13679 IsAdd
13680 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
13681 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
13682
13683 APInt Result = ExResult.extractBits(BitWidth, 0);
13684 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
13685
13686 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
13687 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13688 return false;
13689 return Success(CarryOut, E);
13690 }
13691
13692 case clang::X86::BI__builtin_ia32_bextr_u32:
13693 case clang::X86::BI__builtin_ia32_bextr_u64:
13694 case clang::X86::BI__builtin_ia32_bextri_u32:
13695 case clang::X86::BI__builtin_ia32_bextri_u64: {
13696 APSInt Val, Idx;
13697 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13698 !EvaluateInteger(E->getArg(1), Idx, Info))
13699 return false;
13700
13701 unsigned BitWidth = Val.getBitWidth();
13702 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
13703 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
13704 Length = Length > BitWidth ? BitWidth : Length;
13705
13706 // Handle out of bounds cases.
13707 if (Length == 0 || Shift >= BitWidth)
13708 return Success(0, E);
13709
13710 uint64_t Result = Val.getZExtValue() >> Shift;
13711 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
13712 return Success(Result, E);
13713 }
13714
13715 case clang::X86::BI__builtin_ia32_bzhi_si:
13716 case clang::X86::BI__builtin_ia32_bzhi_di: {
13717 APSInt Val, Idx;
13718 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13719 !EvaluateInteger(E->getArg(1), Idx, Info))
13720 return false;
13721
13722 unsigned BitWidth = Val.getBitWidth();
13723 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
13724 if (Index < BitWidth)
13725 Val.clearHighBits(BitWidth - Index);
13726 return Success(Val, E);
13727 }
13728
13729 case clang::X86::BI__builtin_ia32_lzcnt_u16:
13730 case clang::X86::BI__builtin_ia32_lzcnt_u32:
13731 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
13732 APSInt Val;
13733 if (!EvaluateInteger(E->getArg(0), Val, Info))
13734 return false;
13735 return Success(Val.countLeadingZeros(), E);
13736 }
13737
13738 case clang::X86::BI__builtin_ia32_tzcnt_u16:
13739 case clang::X86::BI__builtin_ia32_tzcnt_u32:
13740 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
13741 APSInt Val;
13742 if (!EvaluateInteger(E->getArg(0), Val, Info))
13743 return false;
13744 return Success(Val.countTrailingZeros(), E);
13745 }
13746
13747 case clang::X86::BI__builtin_ia32_pdep_si:
13748 case clang::X86::BI__builtin_ia32_pdep_di: {
13749 APSInt Val, Msk;
13750 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13751 !EvaluateInteger(E->getArg(1), Msk, Info))
13752 return false;
13753
13754 unsigned BitWidth = Val.getBitWidth();
13755 APInt Result = APInt::getZero(BitWidth);
13756 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
13757 if (Msk[I])
13758 Result.setBitVal(I, Val[P++]);
13759 return Success(Result, E);
13760 }
13761
13762 case clang::X86::BI__builtin_ia32_pext_si:
13763 case clang::X86::BI__builtin_ia32_pext_di: {
13764 APSInt Val, Msk;
13765 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13766 !EvaluateInteger(E->getArg(1), Msk, Info))
13767 return false;
13768
13769 unsigned BitWidth = Val.getBitWidth();
13770 APInt Result = APInt::getZero(BitWidth);
13771 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
13772 if (Msk[I])
13773 Result.setBitVal(P++, Val[I]);
13774 return Success(Result, E);
13775 }
13776 }
13777}
13778
13779/// Determine whether this is a pointer past the end of the complete
13780/// object referred to by the lvalue.
13782 const LValue &LV) {
13783 // A null pointer can be viewed as being "past the end" but we don't
13784 // choose to look at it that way here.
13785 if (!LV.getLValueBase())
13786 return false;
13787
13788 // If the designator is valid and refers to a subobject, we're not pointing
13789 // past the end.
13790 if (!LV.getLValueDesignator().Invalid &&
13791 !LV.getLValueDesignator().isOnePastTheEnd())
13792 return false;
13793
13794 // A pointer to an incomplete type might be past-the-end if the type's size is
13795 // zero. We cannot tell because the type is incomplete.
13796 QualType Ty = getType(LV.getLValueBase());
13797 if (Ty->isIncompleteType())
13798 return true;
13799
13800 // Can't be past the end of an invalid object.
13801 if (LV.getLValueDesignator().Invalid)
13802 return false;
13803
13804 // We're a past-the-end pointer if we point to the byte after the object,
13805 // no matter what our type or path is.
13806 auto Size = Ctx.getTypeSizeInChars(Ty);
13807 return LV.getLValueOffset() == Size;
13808}
13809
13810namespace {
13811
13812/// Data recursive integer evaluator of certain binary operators.
13813///
13814/// We use a data recursive algorithm for binary operators so that we are able
13815/// to handle extreme cases of chained binary operators without causing stack
13816/// overflow.
13817class DataRecursiveIntBinOpEvaluator {
13818 struct EvalResult {
13819 APValue Val;
13820 bool Failed = false;
13821
13822 EvalResult() = default;
13823
13824 void swap(EvalResult &RHS) {
13825 Val.swap(RHS.Val);
13826 Failed = RHS.Failed;
13827 RHS.Failed = false;
13828 }
13829 };
13830
13831 struct Job {
13832 const Expr *E;
13833 EvalResult LHSResult; // meaningful only for binary operator expression.
13834 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
13835
13836 Job() = default;
13837 Job(Job &&) = default;
13838
13839 void startSpeculativeEval(EvalInfo &Info) {
13840 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
13841 }
13842
13843 private:
13844 SpeculativeEvaluationRAII SpecEvalRAII;
13845 };
13846
13848
13849 IntExprEvaluator &IntEval;
13850 EvalInfo &Info;
13851 APValue &FinalResult;
13852
13853public:
13854 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
13855 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
13856
13857 /// True if \param E is a binary operator that we are going to handle
13858 /// data recursively.
13859 /// We handle binary operators that are comma, logical, or that have operands
13860 /// with integral or enumeration type.
13861 static bool shouldEnqueue(const BinaryOperator *E) {
13862 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
13864 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13865 E->getRHS()->getType()->isIntegralOrEnumerationType());
13866 }
13867
13868 bool Traverse(const BinaryOperator *E) {
13869 enqueue(E);
13870 EvalResult PrevResult;
13871 while (!Queue.empty())
13872 process(PrevResult);
13873
13874 if (PrevResult.Failed) return false;
13875
13876 FinalResult.swap(PrevResult.Val);
13877 return true;
13878 }
13879
13880private:
13881 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
13882 return IntEval.Success(Value, E, Result);
13883 }
13884 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
13885 return IntEval.Success(Value, E, Result);
13886 }
13887 bool Error(const Expr *E) {
13888 return IntEval.Error(E);
13889 }
13890 bool Error(const Expr *E, diag::kind D) {
13891 return IntEval.Error(E, D);
13892 }
13893
13894 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
13895 return Info.CCEDiag(E, D);
13896 }
13897
13898 // Returns true if visiting the RHS is necessary, false otherwise.
13899 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
13900 bool &SuppressRHSDiags);
13901
13902 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13903 const BinaryOperator *E, APValue &Result);
13904
13905 void EvaluateExpr(const Expr *E, EvalResult &Result) {
13906 Result.Failed = !Evaluate(Result.Val, Info, E);
13907 if (Result.Failed)
13908 Result.Val = APValue();
13909 }
13910
13911 void process(EvalResult &Result);
13912
13913 void enqueue(const Expr *E) {
13914 E = E->IgnoreParens();
13915 Queue.resize(Queue.size()+1);
13916 Queue.back().E = E;
13917 Queue.back().Kind = Job::AnyExprKind;
13918 }
13919};
13920
13921}
13922
13923bool DataRecursiveIntBinOpEvaluator::
13924 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
13925 bool &SuppressRHSDiags) {
13926 if (E->getOpcode() == BO_Comma) {
13927 // Ignore LHS but note if we could not evaluate it.
13928 if (LHSResult.Failed)
13929 return Info.noteSideEffect();
13930 return true;
13931 }
13932
13933 if (E->isLogicalOp()) {
13934 bool LHSAsBool;
13935 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
13936 // We were able to evaluate the LHS, see if we can get away with not
13937 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
13938 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
13939 Success(LHSAsBool, E, LHSResult.Val);
13940 return false; // Ignore RHS
13941 }
13942 } else {
13943 LHSResult.Failed = true;
13944
13945 // Since we weren't able to evaluate the left hand side, it
13946 // might have had side effects.
13947 if (!Info.noteSideEffect())
13948 return false;
13949
13950 // We can't evaluate the LHS; however, sometimes the result
13951 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13952 // Don't ignore RHS and suppress diagnostics from this arm.
13953 SuppressRHSDiags = true;
13954 }
13955
13956 return true;
13957 }
13958
13959 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13960 E->getRHS()->getType()->isIntegralOrEnumerationType());
13961
13962 if (LHSResult.Failed && !Info.noteFailure())
13963 return false; // Ignore RHS;
13964
13965 return true;
13966}
13967
13968static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
13969 bool IsSub) {
13970 // Compute the new offset in the appropriate width, wrapping at 64 bits.
13971 // FIXME: When compiling for a 32-bit target, we should use 32-bit
13972 // offsets.
13973 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
13974 CharUnits &Offset = LVal.getLValueOffset();
13975 uint64_t Offset64 = Offset.getQuantity();
13976 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
13977 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
13978 : Offset64 + Index64);
13979}
13980
13981bool DataRecursiveIntBinOpEvaluator::
13982 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13983 const BinaryOperator *E, APValue &Result) {
13984 if (E->getOpcode() == BO_Comma) {
13985 if (RHSResult.Failed)
13986 return false;
13987 Result = RHSResult.Val;
13988 return true;
13989 }
13990
13991 if (E->isLogicalOp()) {
13992 bool lhsResult, rhsResult;
13993 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
13994 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
13995
13996 if (LHSIsOK) {
13997 if (RHSIsOK) {
13998 if (E->getOpcode() == BO_LOr)
13999 return Success(lhsResult || rhsResult, E, Result);
14000 else
14001 return Success(lhsResult && rhsResult, E, Result);
14002 }
14003 } else {
14004 if (RHSIsOK) {
14005 // We can't evaluate the LHS; however, sometimes the result
14006 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
14007 if (rhsResult == (E->getOpcode() == BO_LOr))
14008 return Success(rhsResult, E, Result);
14009 }
14010 }
14011
14012 return false;
14013 }
14014
14015 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14016 E->getRHS()->getType()->isIntegralOrEnumerationType());
14017
14018 if (LHSResult.Failed || RHSResult.Failed)
14019 return false;
14020
14021 const APValue &LHSVal = LHSResult.Val;
14022 const APValue &RHSVal = RHSResult.Val;
14023
14024 // Handle cases like (unsigned long)&a + 4.
14025 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
14026 Result = LHSVal;
14027 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
14028 return true;
14029 }
14030
14031 // Handle cases like 4 + (unsigned long)&a
14032 if (E->getOpcode() == BO_Add &&
14033 RHSVal.isLValue() && LHSVal.isInt()) {
14034 Result = RHSVal;
14035 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
14036 return true;
14037 }
14038
14039 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
14040 // Handle (intptr_t)&&A - (intptr_t)&&B.
14041 if (!LHSVal.getLValueOffset().isZero() ||
14042 !RHSVal.getLValueOffset().isZero())
14043 return false;
14044 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
14045 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
14046 if (!LHSExpr || !RHSExpr)
14047 return false;
14048 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14049 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14050 if (!LHSAddrExpr || !RHSAddrExpr)
14051 return false;
14052 // Make sure both labels come from the same function.
14053 if (LHSAddrExpr->getLabel()->getDeclContext() !=
14054 RHSAddrExpr->getLabel()->getDeclContext())
14055 return false;
14056 Result = APValue(LHSAddrExpr, RHSAddrExpr);
14057 return true;
14058 }
14059
14060 // All the remaining cases expect both operands to be an integer
14061 if (!LHSVal.isInt() || !RHSVal.isInt())
14062 return Error(E);
14063
14064 // Set up the width and signedness manually, in case it can't be deduced
14065 // from the operation we're performing.
14066 // FIXME: Don't do this in the cases where we can deduce it.
14067 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
14069 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
14070 RHSVal.getInt(), Value))
14071 return false;
14072 return Success(Value, E, Result);
14073}
14074
14075void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
14076 Job &job = Queue.back();
14077
14078 switch (job.Kind) {
14079 case Job::AnyExprKind: {
14080 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
14081 if (shouldEnqueue(Bop)) {
14082 job.Kind = Job::BinOpKind;
14083 enqueue(Bop->getLHS());
14084 return;
14085 }
14086 }
14087
14088 EvaluateExpr(job.E, Result);
14089 Queue.pop_back();
14090 return;
14091 }
14092
14093 case Job::BinOpKind: {
14094 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14095 bool SuppressRHSDiags = false;
14096 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
14097 Queue.pop_back();
14098 return;
14099 }
14100 if (SuppressRHSDiags)
14101 job.startSpeculativeEval(Info);
14102 job.LHSResult.swap(Result);
14103 job.Kind = Job::BinOpVisitedLHSKind;
14104 enqueue(Bop->getRHS());
14105 return;
14106 }
14107
14108 case Job::BinOpVisitedLHSKind: {
14109 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14110 EvalResult RHS;
14111 RHS.swap(Result);
14112 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
14113 Queue.pop_back();
14114 return;
14115 }
14116 }
14117
14118 llvm_unreachable("Invalid Job::Kind!");
14119}
14120
14121namespace {
14122enum class CmpResult {
14123 Unequal,
14124 Less,
14125 Equal,
14126 Greater,
14127 Unordered,
14128};
14129}
14130
14131template <class SuccessCB, class AfterCB>
14132static bool
14134 SuccessCB &&Success, AfterCB &&DoAfter) {
14135 assert(!E->isValueDependent());
14136 assert(E->isComparisonOp() && "expected comparison operator");
14137 assert((E->getOpcode() == BO_Cmp ||
14139 "unsupported binary expression evaluation");
14140 auto Error = [&](const Expr *E) {
14141 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14142 return false;
14143 };
14144
14145 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
14146 bool IsEquality = E->isEqualityOp();
14147
14148 QualType LHSTy = E->getLHS()->getType();
14149 QualType RHSTy = E->getRHS()->getType();
14150
14151 if (LHSTy->isIntegralOrEnumerationType() &&
14152 RHSTy->isIntegralOrEnumerationType()) {
14153 APSInt LHS, RHS;
14154 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
14155 if (!LHSOK && !Info.noteFailure())
14156 return false;
14157 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
14158 return false;
14159 if (LHS < RHS)
14160 return Success(CmpResult::Less, E);
14161 if (LHS > RHS)
14162 return Success(CmpResult::Greater, E);
14163 return Success(CmpResult::Equal, E);
14164 }
14165
14166 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
14167 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
14168 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
14169
14170 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
14171 if (!LHSOK && !Info.noteFailure())
14172 return false;
14173 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
14174 return false;
14175 if (LHSFX < RHSFX)
14176 return Success(CmpResult::Less, E);
14177 if (LHSFX > RHSFX)
14178 return Success(CmpResult::Greater, E);
14179 return Success(CmpResult::Equal, E);
14180 }
14181
14182 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
14183 ComplexValue LHS, RHS;
14184 bool LHSOK;
14185 if (E->isAssignmentOp()) {
14186 LValue LV;
14187 EvaluateLValue(E->getLHS(), LV, Info);
14188 LHSOK = false;
14189 } else if (LHSTy->isRealFloatingType()) {
14190 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
14191 if (LHSOK) {
14192 LHS.makeComplexFloat();
14193 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
14194 }
14195 } else {
14196 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
14197 }
14198 if (!LHSOK && !Info.noteFailure())
14199 return false;
14200
14201 if (E->getRHS()->getType()->isRealFloatingType()) {
14202 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
14203 return false;
14204 RHS.makeComplexFloat();
14205 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
14206 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14207 return false;
14208
14209 if (LHS.isComplexFloat()) {
14210 APFloat::cmpResult CR_r =
14211 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
14212 APFloat::cmpResult CR_i =
14213 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
14214 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
14215 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
14216 } else {
14217 assert(IsEquality && "invalid complex comparison");
14218 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
14219 LHS.getComplexIntImag() == RHS.getComplexIntImag();
14220 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
14221 }
14222 }
14223
14224 if (LHSTy->isRealFloatingType() &&
14225 RHSTy->isRealFloatingType()) {
14226 APFloat RHS(0.0), LHS(0.0);
14227
14228 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
14229 if (!LHSOK && !Info.noteFailure())
14230 return false;
14231
14232 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
14233 return false;
14234
14235 assert(E->isComparisonOp() && "Invalid binary operator!");
14236 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
14237 if (!Info.InConstantContext &&
14238 APFloatCmpResult == APFloat::cmpUnordered &&
14239 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
14240 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
14241 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
14242 return false;
14243 }
14244 auto GetCmpRes = [&]() {
14245 switch (APFloatCmpResult) {
14246 case APFloat::cmpEqual:
14247 return CmpResult::Equal;
14248 case APFloat::cmpLessThan:
14249 return CmpResult::Less;
14250 case APFloat::cmpGreaterThan:
14251 return CmpResult::Greater;
14252 case APFloat::cmpUnordered:
14253 return CmpResult::Unordered;
14254 }
14255 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
14256 };
14257 return Success(GetCmpRes(), E);
14258 }
14259
14260 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
14261 LValue LHSValue, RHSValue;
14262
14263 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
14264 if (!LHSOK && !Info.noteFailure())
14265 return false;
14266
14267 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14268 return false;
14269
14270 // Reject differing bases from the normal codepath; we special-case
14271 // comparisons to null.
14272 if (!HasSameBase(LHSValue, RHSValue)) {
14273 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
14274 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
14275 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
14276 Info.FFDiag(E, DiagID)
14277 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
14278 return false;
14279 };
14280 // Inequalities and subtractions between unrelated pointers have
14281 // unspecified or undefined behavior.
14282 if (!IsEquality)
14283 return DiagComparison(
14284 diag::note_constexpr_pointer_comparison_unspecified);
14285 // A constant address may compare equal to the address of a symbol.
14286 // The one exception is that address of an object cannot compare equal
14287 // to a null pointer constant.
14288 // TODO: Should we restrict this to actual null pointers, and exclude the
14289 // case of zero cast to pointer type?
14290 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
14291 (!RHSValue.Base && !RHSValue.Offset.isZero()))
14292 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
14293 !RHSValue.Base);
14294 // C++2c [intro.object]/10:
14295 // Two objects [...] may have the same address if [...] they are both
14296 // potentially non-unique objects.
14297 // C++2c [intro.object]/9:
14298 // An object is potentially non-unique if it is a string literal object,
14299 // the backing array of an initializer list, or a subobject thereof.
14300 //
14301 // This makes the comparison result unspecified, so it's not a constant
14302 // expression.
14303 //
14304 // TODO: Do we need to handle the initializer list case here?
14305 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
14306 return DiagComparison(diag::note_constexpr_literal_comparison);
14307 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
14308 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
14309 !IsOpaqueConstantCall(LHSValue));
14310 // We can't tell whether weak symbols will end up pointing to the same
14311 // object.
14312 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
14313 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
14314 !IsWeakLValue(LHSValue));
14315 // We can't compare the address of the start of one object with the
14316 // past-the-end address of another object, per C++ DR1652.
14317 if (LHSValue.Base && LHSValue.Offset.isZero() &&
14318 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
14319 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
14320 true);
14321 if (RHSValue.Base && RHSValue.Offset.isZero() &&
14322 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
14323 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
14324 false);
14325 // We can't tell whether an object is at the same address as another
14326 // zero sized object.
14327 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
14328 (LHSValue.Base && isZeroSized(RHSValue)))
14329 return DiagComparison(
14330 diag::note_constexpr_pointer_comparison_zero_sized);
14331 return Success(CmpResult::Unequal, E);
14332 }
14333
14334 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
14335 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
14336
14337 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
14338 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14339
14340 // C++11 [expr.rel]p2:
14341 // - If two pointers point to non-static data members of the same object,
14342 // or to subobjects or array elements fo such members, recursively, the
14343 // pointer to the later declared member compares greater provided the
14344 // two members have the same access control and provided their class is
14345 // not a union.
14346 // [...]
14347 // - Otherwise pointer comparisons are unspecified.
14348 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
14349 bool WasArrayIndex;
14350 unsigned Mismatch = FindDesignatorMismatch(
14351 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
14352 // At the point where the designators diverge, the comparison has a
14353 // specified value if:
14354 // - we are comparing array indices
14355 // - we are comparing fields of a union, or fields with the same access
14356 // Otherwise, the result is unspecified and thus the comparison is not a
14357 // constant expression.
14358 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
14359 Mismatch < RHSDesignator.Entries.size()) {
14360 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
14361 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
14362 if (!LF && !RF)
14363 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
14364 else if (!LF)
14365 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
14366 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
14367 << RF->getParent() << RF;
14368 else if (!RF)
14369 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
14370 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
14371 << LF->getParent() << LF;
14372 else if (!LF->getParent()->isUnion() &&
14373 LF->getAccess() != RF->getAccess())
14374 Info.CCEDiag(E,
14375 diag::note_constexpr_pointer_comparison_differing_access)
14376 << LF << LF->getAccess() << RF << RF->getAccess()
14377 << LF->getParent();
14378 }
14379 }
14380
14381 // The comparison here must be unsigned, and performed with the same
14382 // width as the pointer.
14383 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
14384 uint64_t CompareLHS = LHSOffset.getQuantity();
14385 uint64_t CompareRHS = RHSOffset.getQuantity();
14386 assert(PtrSize <= 64 && "Unexpected pointer width");
14387 uint64_t Mask = ~0ULL >> (64 - PtrSize);
14388 CompareLHS &= Mask;
14389 CompareRHS &= Mask;
14390
14391 // If there is a base and this is a relational operator, we can only
14392 // compare pointers within the object in question; otherwise, the result
14393 // depends on where the object is located in memory.
14394 if (!LHSValue.Base.isNull() && IsRelational) {
14395 QualType BaseTy = getType(LHSValue.Base);
14396 if (BaseTy->isIncompleteType())
14397 return Error(E);
14398 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
14399 uint64_t OffsetLimit = Size.getQuantity();
14400 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
14401 return Error(E);
14402 }
14403
14404 if (CompareLHS < CompareRHS)
14405 return Success(CmpResult::Less, E);
14406 if (CompareLHS > CompareRHS)
14407 return Success(CmpResult::Greater, E);
14408 return Success(CmpResult::Equal, E);
14409 }
14410
14411 if (LHSTy->isMemberPointerType()) {
14412 assert(IsEquality && "unexpected member pointer operation");
14413 assert(RHSTy->isMemberPointerType() && "invalid comparison");
14414
14415 MemberPtr LHSValue, RHSValue;
14416
14417 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
14418 if (!LHSOK && !Info.noteFailure())
14419 return false;
14420
14421 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14422 return false;
14423
14424 // If either operand is a pointer to a weak function, the comparison is not
14425 // constant.
14426 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
14427 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
14428 << LHSValue.getDecl();
14429 return false;
14430 }
14431 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
14432 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
14433 << RHSValue.getDecl();
14434 return false;
14435 }
14436
14437 // C++11 [expr.eq]p2:
14438 // If both operands are null, they compare equal. Otherwise if only one is
14439 // null, they compare unequal.
14440 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
14441 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
14442 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
14443 }
14444
14445 // Otherwise if either is a pointer to a virtual member function, the
14446 // result is unspecified.
14447 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
14448 if (MD->isVirtual())
14449 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
14450 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
14451 if (MD->isVirtual())
14452 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
14453
14454 // Otherwise they compare equal if and only if they would refer to the
14455 // same member of the same most derived object or the same subobject if
14456 // they were dereferenced with a hypothetical object of the associated
14457 // class type.
14458 bool Equal = LHSValue == RHSValue;
14459 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
14460 }
14461
14462 if (LHSTy->isNullPtrType()) {
14463 assert(E->isComparisonOp() && "unexpected nullptr operation");
14464 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
14465 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
14466 // are compared, the result is true of the operator is <=, >= or ==, and
14467 // false otherwise.
14468 LValue Res;
14469 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
14470 !EvaluatePointer(E->getRHS(), Res, Info))
14471 return false;
14472 return Success(CmpResult::Equal, E);
14473 }
14474
14475 return DoAfter();
14476}
14477
14478bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
14479 if (!CheckLiteralType(Info, E))
14480 return false;
14481
14482 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
14484 switch (CR) {
14485 case CmpResult::Unequal:
14486 llvm_unreachable("should never produce Unequal for three-way comparison");
14487 case CmpResult::Less:
14488 CCR = ComparisonCategoryResult::Less;
14489 break;
14490 case CmpResult::Equal:
14491 CCR = ComparisonCategoryResult::Equal;
14492 break;
14493 case CmpResult::Greater:
14494 CCR = ComparisonCategoryResult::Greater;
14495 break;
14496 case CmpResult::Unordered:
14497 CCR = ComparisonCategoryResult::Unordered;
14498 break;
14499 }
14500 // Evaluation succeeded. Lookup the information for the comparison category
14501 // type and fetch the VarDecl for the result.
14502 const ComparisonCategoryInfo &CmpInfo =
14504 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
14505 // Check and evaluate the result as a constant expression.
14506 LValue LV;
14507 LV.set(VD);
14508 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14509 return false;
14510 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14511 ConstantExprKind::Normal);
14512 };
14513 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
14514 return ExprEvaluatorBaseTy::VisitBinCmp(E);
14515 });
14516}
14517
14518bool RecordExprEvaluator::VisitCXXParenListInitExpr(
14519 const CXXParenListInitExpr *E) {
14520 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
14521}
14522
14523bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14524 // We don't support assignment in C. C++ assignments don't get here because
14525 // assignment is an lvalue in C++.
14526 if (E->isAssignmentOp()) {
14527 Error(E);
14528 if (!Info.noteFailure())
14529 return false;
14530 }
14531
14532 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
14533 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
14534
14535 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
14536 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
14537 "DataRecursiveIntBinOpEvaluator should have handled integral types");
14538
14539 if (E->isComparisonOp()) {
14540 // Evaluate builtin binary comparisons by evaluating them as three-way
14541 // comparisons and then translating the result.
14542 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
14543 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
14544 "should only produce Unequal for equality comparisons");
14545 bool IsEqual = CR == CmpResult::Equal,
14546 IsLess = CR == CmpResult::Less,
14547 IsGreater = CR == CmpResult::Greater;
14548 auto Op = E->getOpcode();
14549 switch (Op) {
14550 default:
14551 llvm_unreachable("unsupported binary operator");
14552 case BO_EQ:
14553 case BO_NE:
14554 return Success(IsEqual == (Op == BO_EQ), E);
14555 case BO_LT:
14556 return Success(IsLess, E);
14557 case BO_GT:
14558 return Success(IsGreater, E);
14559 case BO_LE:
14560 return Success(IsEqual || IsLess, E);
14561 case BO_GE:
14562 return Success(IsEqual || IsGreater, E);
14563 }
14564 };
14565 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
14566 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14567 });
14568 }
14569
14570 QualType LHSTy = E->getLHS()->getType();
14571 QualType RHSTy = E->getRHS()->getType();
14572
14573 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
14574 E->getOpcode() == BO_Sub) {
14575 LValue LHSValue, RHSValue;
14576
14577 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
14578 if (!LHSOK && !Info.noteFailure())
14579 return false;
14580
14581 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14582 return false;
14583
14584 // Reject differing bases from the normal codepath; we special-case
14585 // comparisons to null.
14586 if (!HasSameBase(LHSValue, RHSValue)) {
14587 // Handle &&A - &&B.
14588 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
14589 return Error(E);
14590 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
14591 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
14592 if (!LHSExpr || !RHSExpr)
14593 return Error(E);
14594 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14595 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14596 if (!LHSAddrExpr || !RHSAddrExpr)
14597 return Error(E);
14598 // Make sure both labels come from the same function.
14599 if (LHSAddrExpr->getLabel()->getDeclContext() !=
14600 RHSAddrExpr->getLabel()->getDeclContext())
14601 return Error(E);
14602 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
14603 }
14604 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
14605 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
14606
14607 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
14608 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14609
14610 // C++11 [expr.add]p6:
14611 // Unless both pointers point to elements of the same array object, or
14612 // one past the last element of the array object, the behavior is
14613 // undefined.
14614 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
14615 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
14616 RHSDesignator))
14617 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
14618
14619 QualType Type = E->getLHS()->getType();
14620 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
14621
14622 CharUnits ElementSize;
14623 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
14624 return false;
14625
14626 // As an extension, a type may have zero size (empty struct or union in
14627 // C, array of zero length). Pointer subtraction in such cases has
14628 // undefined behavior, so is not constant.
14629 if (ElementSize.isZero()) {
14630 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
14631 << ElementType;
14632 return false;
14633 }
14634
14635 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
14636 // and produce incorrect results when it overflows. Such behavior
14637 // appears to be non-conforming, but is common, so perhaps we should
14638 // assume the standard intended for such cases to be undefined behavior
14639 // and check for them.
14640
14641 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
14642 // overflow in the final conversion to ptrdiff_t.
14643 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
14644 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
14645 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
14646 false);
14647 APSInt TrueResult = (LHS - RHS) / ElemSize;
14648 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
14649
14650 if (Result.extend(65) != TrueResult &&
14651 !HandleOverflow(Info, E, TrueResult, E->getType()))
14652 return false;
14653 return Success(Result, E);
14654 }
14655
14656 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14657}
14658
14659/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
14660/// a result as the expression's type.
14661bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
14662 const UnaryExprOrTypeTraitExpr *E) {
14663 switch(E->getKind()) {
14664 case UETT_PreferredAlignOf:
14665 case UETT_AlignOf: {
14666 if (E->isArgumentType())
14667 return Success(
14668 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
14669 else
14670 return Success(
14671 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
14672 }
14673
14674 case UETT_PtrAuthTypeDiscriminator: {
14675 if (E->getArgumentType()->isDependentType())
14676 return false;
14677 return Success(
14678 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
14679 }
14680 case UETT_VecStep: {
14681 QualType Ty = E->getTypeOfArgument();
14682
14683 if (Ty->isVectorType()) {
14684 unsigned n = Ty->castAs<VectorType>()->getNumElements();
14685
14686 // The vec_step built-in functions that take a 3-component
14687 // vector return 4. (OpenCL 1.1 spec 6.11.12)
14688 if (n == 3)
14689 n = 4;
14690
14691 return Success(n, E);
14692 } else
14693 return Success(1, E);
14694 }
14695
14696 case UETT_DataSizeOf:
14697 case UETT_SizeOf: {
14698 QualType SrcTy = E->getTypeOfArgument();
14699 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
14700 // the result is the size of the referenced type."
14701 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
14702 SrcTy = Ref->getPointeeType();
14703
14704 CharUnits Sizeof;
14705 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
14706 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
14707 : SizeOfType::SizeOf)) {
14708 return false;
14709 }
14710 return Success(Sizeof, E);
14711 }
14712 case UETT_OpenMPRequiredSimdAlign:
14713 assert(E->isArgumentType());
14714 return Success(
14715 Info.Ctx.toCharUnitsFromBits(
14716 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
14717 .getQuantity(),
14718 E);
14719 case UETT_VectorElements: {
14720 QualType Ty = E->getTypeOfArgument();
14721 // If the vector has a fixed size, we can determine the number of elements
14722 // at compile time.
14723 if (const auto *VT = Ty->getAs<VectorType>())
14724 return Success(VT->getNumElements(), E);
14725
14726 assert(Ty->isSizelessVectorType());
14727 if (Info.InConstantContext)
14728 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
14729 << E->getSourceRange();
14730
14731 return false;
14732 }
14733 }
14734
14735 llvm_unreachable("unknown expr/type trait");
14736}
14737
14738bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
14739 CharUnits Result;
14740 unsigned n = OOE->getNumComponents();
14741 if (n == 0)
14742 return Error(OOE);
14743 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
14744 for (unsigned i = 0; i != n; ++i) {
14745 OffsetOfNode ON = OOE->getComponent(i);
14746 switch (ON.getKind()) {
14747 case OffsetOfNode::Array: {
14748 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
14749 APSInt IdxResult;
14750 if (!EvaluateInteger(Idx, IdxResult, Info))
14751 return false;
14752 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
14753 if (!AT)
14754 return Error(OOE);
14755 CurrentType = AT->getElementType();
14756 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
14757 Result += IdxResult.getSExtValue() * ElementSize;
14758 break;
14759 }
14760
14761 case OffsetOfNode::Field: {
14762 FieldDecl *MemberDecl = ON.getField();
14763 const RecordType *RT = CurrentType->getAs<RecordType>();
14764 if (!RT)
14765 return Error(OOE);
14766 RecordDecl *RD = RT->getDecl();
14767 if (RD->isInvalidDecl()) return false;
14768 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14769 unsigned i = MemberDecl->getFieldIndex();
14770 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
14771 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
14772 CurrentType = MemberDecl->getType().getNonReferenceType();
14773 break;
14774 }
14775
14777 llvm_unreachable("dependent __builtin_offsetof");
14778
14779 case OffsetOfNode::Base: {
14780 CXXBaseSpecifier *BaseSpec = ON.getBase();
14781 if (BaseSpec->isVirtual())
14782 return Error(OOE);
14783
14784 // Find the layout of the class whose base we are looking into.
14785 const RecordType *RT = CurrentType->getAs<RecordType>();
14786 if (!RT)
14787 return Error(OOE);
14788 RecordDecl *RD = RT->getDecl();
14789 if (RD->isInvalidDecl()) return false;
14790 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14791
14792 // Find the base class itself.
14793 CurrentType = BaseSpec->getType();
14794 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
14795 if (!BaseRT)
14796 return Error(OOE);
14797
14798 // Add the offset to the base.
14799 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
14800 break;
14801 }
14802 }
14803 }
14804 return Success(Result, OOE);
14805}
14806
14807bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14808 switch (E->getOpcode()) {
14809 default:
14810 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
14811 // See C99 6.6p3.
14812 return Error(E);
14813 case UO_Extension:
14814 // FIXME: Should extension allow i-c-e extension expressions in its scope?
14815 // If so, we could clear the diagnostic ID.
14816 return Visit(E->getSubExpr());
14817 case UO_Plus:
14818 // The result is just the value.
14819 return Visit(E->getSubExpr());
14820 case UO_Minus: {
14821 if (!Visit(E->getSubExpr()))
14822 return false;
14823 if (!Result.isInt()) return Error(E);
14824 const APSInt &Value = Result.getInt();
14825 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
14826 if (Info.checkingForUndefinedBehavior())
14827 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14828 diag::warn_integer_constant_overflow)
14829 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
14830 /*UpperCase=*/true, /*InsertSeparators=*/true)
14831 << E->getType() << E->getSourceRange();
14832
14833 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
14834 E->getType()))
14835 return false;
14836 }
14837 return Success(-Value, E);
14838 }
14839 case UO_Not: {
14840 if (!Visit(E->getSubExpr()))
14841 return false;
14842 if (!Result.isInt()) return Error(E);
14843 return Success(~Result.getInt(), E);
14844 }
14845 case UO_LNot: {
14846 bool bres;
14847 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14848 return false;
14849 return Success(!bres, E);
14850 }
14851 }
14852}
14853
14854/// HandleCast - This is used to evaluate implicit or explicit casts where the
14855/// result type is integer.
14856bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
14857 const Expr *SubExpr = E->getSubExpr();
14858 QualType DestType = E->getType();
14859 QualType SrcType = SubExpr->getType();
14860
14861 switch (E->getCastKind()) {
14862 case CK_BaseToDerived:
14863 case CK_DerivedToBase:
14864 case CK_UncheckedDerivedToBase:
14865 case CK_Dynamic:
14866 case CK_ToUnion:
14867 case CK_ArrayToPointerDecay:
14868 case CK_FunctionToPointerDecay:
14869 case CK_NullToPointer:
14870 case CK_NullToMemberPointer:
14871 case CK_BaseToDerivedMemberPointer:
14872 case CK_DerivedToBaseMemberPointer:
14873 case CK_ReinterpretMemberPointer:
14874 case CK_ConstructorConversion:
14875 case CK_IntegralToPointer:
14876 case CK_ToVoid:
14877 case CK_VectorSplat:
14878 case CK_IntegralToFloating:
14879 case CK_FloatingCast:
14880 case CK_CPointerToObjCPointerCast:
14881 case CK_BlockPointerToObjCPointerCast:
14882 case CK_AnyPointerToBlockPointerCast:
14883 case CK_ObjCObjectLValueCast:
14884 case CK_FloatingRealToComplex:
14885 case CK_FloatingComplexToReal:
14886 case CK_FloatingComplexCast:
14887 case CK_FloatingComplexToIntegralComplex:
14888 case CK_IntegralRealToComplex:
14889 case CK_IntegralComplexCast:
14890 case CK_IntegralComplexToFloatingComplex:
14891 case CK_BuiltinFnToFnPtr:
14892 case CK_ZeroToOCLOpaqueType:
14893 case CK_NonAtomicToAtomic:
14894 case CK_AddressSpaceConversion:
14895 case CK_IntToOCLSampler:
14896 case CK_FloatingToFixedPoint:
14897 case CK_FixedPointToFloating:
14898 case CK_FixedPointCast:
14899 case CK_IntegralToFixedPoint:
14900 case CK_MatrixCast:
14901 llvm_unreachable("invalid cast kind for integral value");
14902
14903 case CK_BitCast:
14904 case CK_Dependent:
14905 case CK_LValueBitCast:
14906 case CK_ARCProduceObject:
14907 case CK_ARCConsumeObject:
14908 case CK_ARCReclaimReturnedObject:
14909 case CK_ARCExtendBlockObject:
14910 case CK_CopyAndAutoreleaseBlockObject:
14911 return Error(E);
14912
14913 case CK_UserDefinedConversion:
14914 case CK_LValueToRValue:
14915 case CK_AtomicToNonAtomic:
14916 case CK_NoOp:
14917 case CK_LValueToRValueBitCast:
14918 case CK_HLSLArrayRValue:
14919 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14920
14921 case CK_MemberPointerToBoolean:
14922 case CK_PointerToBoolean:
14923 case CK_IntegralToBoolean:
14924 case CK_FloatingToBoolean:
14925 case CK_BooleanToSignedIntegral:
14926 case CK_FloatingComplexToBoolean:
14927 case CK_IntegralComplexToBoolean: {
14928 bool BoolResult;
14929 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
14930 return false;
14931 uint64_t IntResult = BoolResult;
14932 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
14933 IntResult = (uint64_t)-1;
14934 return Success(IntResult, E);
14935 }
14936
14937 case CK_FixedPointToIntegral: {
14938 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
14939 if (!EvaluateFixedPoint(SubExpr, Src, Info))
14940 return false;
14941 bool Overflowed;
14942 llvm::APSInt Result = Src.convertToInt(
14943 Info.Ctx.getIntWidth(DestType),
14944 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
14945 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
14946 return false;
14947 return Success(Result, E);
14948 }
14949
14950 case CK_FixedPointToBoolean: {
14951 // Unsigned padding does not affect this.
14952 APValue Val;
14953 if (!Evaluate(Val, Info, SubExpr))
14954 return false;
14955 return Success(Val.getFixedPoint().getBoolValue(), E);
14956 }
14957
14958 case CK_IntegralCast: {
14959 if (!Visit(SubExpr))
14960 return false;
14961
14962 if (!Result.isInt()) {
14963 // Allow casts of address-of-label differences if they are no-ops
14964 // or narrowing. (The narrowing case isn't actually guaranteed to
14965 // be constant-evaluatable except in some narrow cases which are hard
14966 // to detect here. We let it through on the assumption the user knows
14967 // what they are doing.)
14968 if (Result.isAddrLabelDiff())
14969 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
14970 // Only allow casts of lvalues if they are lossless.
14971 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
14972 }
14973
14974 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
14975 Info.EvalMode == EvalInfo::EM_ConstantExpression &&
14976 DestType->isEnumeralType()) {
14977
14978 bool ConstexprVar = true;
14979
14980 // We know if we are here that we are in a context that we might require
14981 // a constant expression or a context that requires a constant
14982 // value. But if we are initializing a value we don't know if it is a
14983 // constexpr variable or not. We can check the EvaluatingDecl to determine
14984 // if it constexpr or not. If not then we don't want to emit a diagnostic.
14985 if (const auto *VD = dyn_cast_or_null<VarDecl>(
14986 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
14987 ConstexprVar = VD->isConstexpr();
14988
14989 const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
14990 const EnumDecl *ED = ET->getDecl();
14991 // Check that the value is within the range of the enumeration values.
14992 //
14993 // This corressponds to [expr.static.cast]p10 which says:
14994 // A value of integral or enumeration type can be explicitly converted
14995 // to a complete enumeration type ... If the enumeration type does not
14996 // have a fixed underlying type, the value is unchanged if the original
14997 // value is within the range of the enumeration values ([dcl.enum]), and
14998 // otherwise, the behavior is undefined.
14999 //
15000 // This was resolved as part of DR2338 which has CD5 status.
15001 if (!ED->isFixed()) {
15002 llvm::APInt Min;
15003 llvm::APInt Max;
15004
15005 ED->getValueRange(Max, Min);
15006 --Max;
15007
15008 if (ED->getNumNegativeBits() && ConstexprVar &&
15009 (Max.slt(Result.getInt().getSExtValue()) ||
15010 Min.sgt(Result.getInt().getSExtValue())))
15011 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15012 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
15013 << Max.getSExtValue() << ED;
15014 else if (!ED->getNumNegativeBits() && ConstexprVar &&
15015 Max.ult(Result.getInt().getZExtValue()))
15016 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15017 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
15018 << Max.getZExtValue() << ED;
15019 }
15020 }
15021
15022 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
15023 Result.getInt()), E);
15024 }
15025
15026 case CK_PointerToIntegral: {
15027 CCEDiag(E, diag::note_constexpr_invalid_cast)
15028 << 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
15029
15030 LValue LV;
15031 if (!EvaluatePointer(SubExpr, LV, Info))
15032 return false;
15033
15034 if (LV.getLValueBase()) {
15035 // Only allow based lvalue casts if they are lossless.
15036 // FIXME: Allow a larger integer size than the pointer size, and allow
15037 // narrowing back down to pointer width in subsequent integral casts.
15038 // FIXME: Check integer type's active bits, not its type size.
15039 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
15040 return Error(E);
15041
15042 LV.Designator.setInvalid();
15043 LV.moveInto(Result);
15044 return true;
15045 }
15046
15047 APSInt AsInt;
15048 APValue V;
15049 LV.moveInto(V);
15050 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
15051 llvm_unreachable("Can't cast this!");
15052
15053 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
15054 }
15055
15056 case CK_IntegralComplexToReal: {
15057 ComplexValue C;
15058 if (!EvaluateComplex(SubExpr, C, Info))
15059 return false;
15060 return Success(C.getComplexIntReal(), E);
15061 }
15062
15063 case CK_FloatingToIntegral: {
15064 APFloat F(0.0);
15065 if (!EvaluateFloat(SubExpr, F, Info))
15066 return false;
15067
15068 APSInt Value;
15069 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
15070 return false;
15071 return Success(Value, E);
15072 }
15073 case CK_HLSLVectorTruncation: {
15074 APValue Val;
15075 if (!EvaluateVector(SubExpr, Val, Info))
15076 return Error(E);
15077 return Success(Val.getVectorElt(0), E);
15078 }
15079 }
15080
15081 llvm_unreachable("unknown cast resulting in integral value");
15082}
15083
15084bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15085 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15086 ComplexValue LV;
15087 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15088 return false;
15089 if (!LV.isComplexInt())
15090 return Error(E);
15091 return Success(LV.getComplexIntReal(), E);
15092 }
15093
15094 return Visit(E->getSubExpr());
15095}
15096
15097bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15098 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
15099 ComplexValue LV;
15100 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15101 return false;
15102 if (!LV.isComplexInt())
15103 return Error(E);
15104 return Success(LV.getComplexIntImag(), E);
15105 }
15106
15107 VisitIgnoredValue(E->getSubExpr());
15108 return Success(0, E);
15109}
15110
15111bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
15112 return Success(E->getPackLength(), E);
15113}
15114
15115bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
15116 return Success(E->getValue(), E);
15117}
15118
15119bool IntExprEvaluator::VisitConceptSpecializationExpr(
15121 return Success(E->isSatisfied(), E);
15122}
15123
15124bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
15125 return Success(E->isSatisfied(), E);
15126}
15127
15128bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15129 switch (E->getOpcode()) {
15130 default:
15131 // Invalid unary operators
15132 return Error(E);
15133 case UO_Plus:
15134 // The result is just the value.
15135 return Visit(E->getSubExpr());
15136 case UO_Minus: {
15137 if (!Visit(E->getSubExpr())) return false;
15138 if (!Result.isFixedPoint())
15139 return Error(E);
15140 bool Overflowed;
15141 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
15142 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
15143 return false;
15144 return Success(Negated, E);
15145 }
15146 case UO_LNot: {
15147 bool bres;
15148 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
15149 return false;
15150 return Success(!bres, E);
15151 }
15152 }
15153}
15154
15155bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
15156 const Expr *SubExpr = E->getSubExpr();
15157 QualType DestType = E->getType();
15158 assert(DestType->isFixedPointType() &&
15159 "Expected destination type to be a fixed point type");
15160 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
15161
15162 switch (E->getCastKind()) {
15163 case CK_FixedPointCast: {
15164 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
15165 if (!EvaluateFixedPoint(SubExpr, Src, Info))
15166 return false;
15167 bool Overflowed;
15168 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
15169 if (Overflowed) {
15170 if (Info.checkingForUndefinedBehavior())
15171 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15172 diag::warn_fixedpoint_constant_overflow)
15173 << Result.toString() << E->getType();
15174 if (!HandleOverflow(Info, E, Result, E->getType()))
15175 return false;
15176 }
15177 return Success(Result, E);
15178 }
15179 case CK_IntegralToFixedPoint: {
15180 APSInt Src;
15181 if (!EvaluateInteger(SubExpr, Src, Info))
15182 return false;
15183
15184 bool Overflowed;
15185 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
15186 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
15187
15188 if (Overflowed) {
15189 if (Info.checkingForUndefinedBehavior())
15190 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15191 diag::warn_fixedpoint_constant_overflow)
15192 << IntResult.toString() << E->getType();
15193 if (!HandleOverflow(Info, E, IntResult, E->getType()))
15194 return false;
15195 }
15196
15197 return Success(IntResult, E);
15198 }
15199 case CK_FloatingToFixedPoint: {
15200 APFloat Src(0.0);
15201 if (!EvaluateFloat(SubExpr, Src, Info))
15202 return false;
15203
15204 bool Overflowed;
15205 APFixedPoint Result = APFixedPoint::getFromFloatValue(
15206 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
15207
15208 if (Overflowed) {
15209 if (Info.checkingForUndefinedBehavior())
15210 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15211 diag::warn_fixedpoint_constant_overflow)
15212 << Result.toString() << E->getType();
15213 if (!HandleOverflow(Info, E, Result, E->getType()))
15214 return false;
15215 }
15216
15217 return Success(Result, E);
15218 }
15219 case CK_NoOp:
15220 case CK_LValueToRValue:
15221 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15222 default:
15223 return Error(E);
15224 }
15225}
15226
15227bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15228 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15229 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15230
15231 const Expr *LHS = E->getLHS();
15232 const Expr *RHS = E->getRHS();
15233 FixedPointSemantics ResultFXSema =
15234 Info.Ctx.getFixedPointSemantics(E->getType());
15235
15236 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
15237 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
15238 return false;
15239 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
15240 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
15241 return false;
15242
15243 bool OpOverflow = false, ConversionOverflow = false;
15244 APFixedPoint Result(LHSFX.getSemantics());
15245 switch (E->getOpcode()) {
15246 case BO_Add: {
15247 Result = LHSFX.add(RHSFX, &OpOverflow)
15248 .convert(ResultFXSema, &ConversionOverflow);
15249 break;
15250 }
15251 case BO_Sub: {
15252 Result = LHSFX.sub(RHSFX, &OpOverflow)
15253 .convert(ResultFXSema, &ConversionOverflow);
15254 break;
15255 }
15256 case BO_Mul: {
15257 Result = LHSFX.mul(RHSFX, &OpOverflow)
15258 .convert(ResultFXSema, &ConversionOverflow);
15259 break;
15260 }
15261 case BO_Div: {
15262 if (RHSFX.getValue() == 0) {
15263 Info.FFDiag(E, diag::note_expr_divide_by_zero);
15264 return false;
15265 }
15266 Result = LHSFX.div(RHSFX, &OpOverflow)
15267 .convert(ResultFXSema, &ConversionOverflow);
15268 break;
15269 }
15270 case BO_Shl:
15271 case BO_Shr: {
15272 FixedPointSemantics LHSSema = LHSFX.getSemantics();
15273 llvm::APSInt RHSVal = RHSFX.getValue();
15274
15275 unsigned ShiftBW =
15276 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
15277 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
15278 // Embedded-C 4.1.6.2.2:
15279 // The right operand must be nonnegative and less than the total number
15280 // of (nonpadding) bits of the fixed-point operand ...
15281 if (RHSVal.isNegative())
15282 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
15283 else if (Amt != RHSVal)
15284 Info.CCEDiag(E, diag::note_constexpr_large_shift)
15285 << RHSVal << E->getType() << ShiftBW;
15286
15287 if (E->getOpcode() == BO_Shl)
15288 Result = LHSFX.shl(Amt, &OpOverflow);
15289 else
15290 Result = LHSFX.shr(Amt, &OpOverflow);
15291 break;
15292 }
15293 default:
15294 return false;
15295 }
15296 if (OpOverflow || ConversionOverflow) {
15297 if (Info.checkingForUndefinedBehavior())
15298 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15299 diag::warn_fixedpoint_constant_overflow)
15300 << Result.toString() << E->getType();
15301 if (!HandleOverflow(Info, E, Result, E->getType()))
15302 return false;
15303 }
15304 return Success(Result, E);
15305}
15306
15307//===----------------------------------------------------------------------===//
15308// Float Evaluation
15309//===----------------------------------------------------------------------===//
15310
15311namespace {
15312class FloatExprEvaluator
15313 : public ExprEvaluatorBase<FloatExprEvaluator> {
15314 APFloat &Result;
15315public:
15316 FloatExprEvaluator(EvalInfo &info, APFloat &result)
15317 : ExprEvaluatorBaseTy(info), Result(result) {}
15318
15319 bool Success(const APValue &V, const Expr *e) {
15320 Result = V.getFloat();
15321 return true;
15322 }
15323
15324 bool ZeroInitialization(const Expr *E) {
15325 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
15326 return true;
15327 }
15328
15329 bool VisitCallExpr(const CallExpr *E);
15330
15331 bool VisitUnaryOperator(const UnaryOperator *E);
15332 bool VisitBinaryOperator(const BinaryOperator *E);
15333 bool VisitFloatingLiteral(const FloatingLiteral *E);
15334 bool VisitCastExpr(const CastExpr *E);
15335
15336 bool VisitUnaryReal(const UnaryOperator *E);
15337 bool VisitUnaryImag(const UnaryOperator *E);
15338
15339 // FIXME: Missing: array subscript of vector, member of vector
15340};
15341} // end anonymous namespace
15342
15343static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
15344 assert(!E->isValueDependent());
15345 assert(E->isPRValue() && E->getType()->isRealFloatingType());
15346 return FloatExprEvaluator(Info, Result).Visit(E);
15347}
15348
15349static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
15350 QualType ResultTy,
15351 const Expr *Arg,
15352 bool SNaN,
15353 llvm::APFloat &Result) {
15354 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
15355 if (!S) return false;
15356
15357 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
15358
15359 llvm::APInt fill;
15360
15361 // Treat empty strings as if they were zero.
15362 if (S->getString().empty())
15363 fill = llvm::APInt(32, 0);
15364 else if (S->getString().getAsInteger(0, fill))
15365 return false;
15366
15367 if (Context.getTargetInfo().isNan2008()) {
15368 if (SNaN)
15369 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
15370 else
15371 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
15372 } else {
15373 // Prior to IEEE 754-2008, architectures were allowed to choose whether
15374 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
15375 // a different encoding to what became a standard in 2008, and for pre-
15376 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
15377 // sNaN. This is now known as "legacy NaN" encoding.
15378 if (SNaN)
15379 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
15380 else
15381 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
15382 }
15383
15384 return true;
15385}
15386
15387bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
15388 if (!IsConstantEvaluatedBuiltinCall(E))
15389 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15390
15391 switch (E->getBuiltinCallee()) {
15392 default:
15393 return false;
15394
15395 case Builtin::BI__builtin_huge_val:
15396 case Builtin::BI__builtin_huge_valf:
15397 case Builtin::BI__builtin_huge_vall:
15398 case Builtin::BI__builtin_huge_valf16:
15399 case Builtin::BI__builtin_huge_valf128:
15400 case Builtin::BI__builtin_inf:
15401 case Builtin::BI__builtin_inff:
15402 case Builtin::BI__builtin_infl:
15403 case Builtin::BI__builtin_inff16:
15404 case Builtin::BI__builtin_inff128: {
15405 const llvm::fltSemantics &Sem =
15406 Info.Ctx.getFloatTypeSemantics(E->getType());
15407 Result = llvm::APFloat::getInf(Sem);
15408 return true;
15409 }
15410
15411 case Builtin::BI__builtin_nans:
15412 case Builtin::BI__builtin_nansf:
15413 case Builtin::BI__builtin_nansl:
15414 case Builtin::BI__builtin_nansf16:
15415 case Builtin::BI__builtin_nansf128:
15416 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
15417 true, Result))
15418 return Error(E);
15419 return true;
15420
15421 case Builtin::BI__builtin_nan:
15422 case Builtin::BI__builtin_nanf:
15423 case Builtin::BI__builtin_nanl:
15424 case Builtin::BI__builtin_nanf16:
15425 case Builtin::BI__builtin_nanf128:
15426 // If this is __builtin_nan() turn this into a nan, otherwise we
15427 // can't constant fold it.
15428 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
15429 false, Result))
15430 return Error(E);
15431 return true;
15432
15433 case Builtin::BI__builtin_fabs:
15434 case Builtin::BI__builtin_fabsf:
15435 case Builtin::BI__builtin_fabsl:
15436 case Builtin::BI__builtin_fabsf128:
15437 // The C standard says "fabs raises no floating-point exceptions,
15438 // even if x is a signaling NaN. The returned value is independent of
15439 // the current rounding direction mode." Therefore constant folding can
15440 // proceed without regard to the floating point settings.
15441 // Reference, WG14 N2478 F.10.4.3
15442 if (!EvaluateFloat(E->getArg(0), Result, Info))
15443 return false;
15444
15445 if (Result.isNegative())
15446 Result.changeSign();
15447 return true;
15448
15449 case Builtin::BI__arithmetic_fence:
15450 return EvaluateFloat(E->getArg(0), Result, Info);
15451
15452 // FIXME: Builtin::BI__builtin_powi
15453 // FIXME: Builtin::BI__builtin_powif
15454 // FIXME: Builtin::BI__builtin_powil
15455
15456 case Builtin::BI__builtin_copysign:
15457 case Builtin::BI__builtin_copysignf:
15458 case Builtin::BI__builtin_copysignl:
15459 case Builtin::BI__builtin_copysignf128: {
15460 APFloat RHS(0.);
15461 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15462 !EvaluateFloat(E->getArg(1), RHS, Info))
15463 return false;
15464 Result.copySign(RHS);
15465 return true;
15466 }
15467
15468 case Builtin::BI__builtin_fmax:
15469 case Builtin::BI__builtin_fmaxf:
15470 case Builtin::BI__builtin_fmaxl:
15471 case Builtin::BI__builtin_fmaxf16:
15472 case Builtin::BI__builtin_fmaxf128: {
15473 // TODO: Handle sNaN.
15474 APFloat RHS(0.);
15475 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15476 !EvaluateFloat(E->getArg(1), RHS, Info))
15477 return false;
15478 // When comparing zeroes, return +0.0 if one of the zeroes is positive.
15479 if (Result.isZero() && RHS.isZero() && Result.isNegative())
15480 Result = RHS;
15481 else if (Result.isNaN() || RHS > Result)
15482 Result = RHS;
15483 return true;
15484 }
15485
15486 case Builtin::BI__builtin_fmin:
15487 case Builtin::BI__builtin_fminf:
15488 case Builtin::BI__builtin_fminl:
15489 case Builtin::BI__builtin_fminf16:
15490 case Builtin::BI__builtin_fminf128: {
15491 // TODO: Handle sNaN.
15492 APFloat RHS(0.);
15493 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15494 !EvaluateFloat(E->getArg(1), RHS, Info))
15495 return false;
15496 // When comparing zeroes, return -0.0 if one of the zeroes is negative.
15497 if (Result.isZero() && RHS.isZero() && RHS.isNegative())
15498 Result = RHS;
15499 else if (Result.isNaN() || RHS < Result)
15500 Result = RHS;
15501 return true;
15502 }
15503
15504 case Builtin::BI__builtin_fmaximum_num:
15505 case Builtin::BI__builtin_fmaximum_numf:
15506 case Builtin::BI__builtin_fmaximum_numl:
15507 case Builtin::BI__builtin_fmaximum_numf16:
15508 case Builtin::BI__builtin_fmaximum_numf128: {
15509 APFloat RHS(0.);
15510 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15511 !EvaluateFloat(E->getArg(1), RHS, Info))
15512 return false;
15513 Result = maximumnum(Result, RHS);
15514 return true;
15515 }
15516
15517 case Builtin::BI__builtin_fminimum_num:
15518 case Builtin::BI__builtin_fminimum_numf:
15519 case Builtin::BI__builtin_fminimum_numl:
15520 case Builtin::BI__builtin_fminimum_numf16:
15521 case Builtin::BI__builtin_fminimum_numf128: {
15522 APFloat RHS(0.);
15523 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15524 !EvaluateFloat(E->getArg(1), RHS, Info))
15525 return false;
15526 Result = minimumnum(Result, RHS);
15527 return true;
15528 }
15529 }
15530}
15531
15532bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15533 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15534 ComplexValue CV;
15535 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
15536 return false;
15537 Result = CV.FloatReal;
15538 return true;
15539 }
15540
15541 return Visit(E->getSubExpr());
15542}
15543
15544bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15545 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15546 ComplexValue CV;
15547 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
15548 return false;
15549 Result = CV.FloatImag;
15550 return true;
15551 }
15552
15553 VisitIgnoredValue(E->getSubExpr());
15554 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
15555 Result = llvm::APFloat::getZero(Sem);
15556 return true;
15557}
15558
15559bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15560 switch (E->getOpcode()) {
15561 default: return Error(E);
15562 case UO_Plus:
15563 return EvaluateFloat(E->getSubExpr(), Result, Info);
15564 case UO_Minus:
15565 // In C standard, WG14 N2478 F.3 p4
15566 // "the unary - raises no floating point exceptions,
15567 // even if the operand is signalling."
15568 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
15569 return false;
15570 Result.changeSign();
15571 return true;
15572 }
15573}
15574
15575bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15576 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15577 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15578
15579 APFloat RHS(0.0);
15580 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
15581 if (!LHSOK && !Info.noteFailure())
15582 return false;
15583 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
15584 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
15585}
15586
15587bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
15588 Result = E->getValue();
15589 return true;
15590}
15591
15592bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
15593 const Expr* SubExpr = E->getSubExpr();
15594
15595 switch (E->getCastKind()) {
15596 default:
15597 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15598
15599 case CK_IntegralToFloating: {
15600 APSInt IntResult;
15601 const FPOptions FPO = E->getFPFeaturesInEffect(
15602 Info.Ctx.getLangOpts());
15603 return EvaluateInteger(SubExpr, IntResult, Info) &&
15604 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
15605 IntResult, E->getType(), Result);
15606 }
15607
15608 case CK_FixedPointToFloating: {
15609 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
15610 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
15611 return false;
15612 Result =
15613 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
15614 return true;
15615 }
15616
15617 case CK_FloatingCast: {
15618 if (!Visit(SubExpr))
15619 return false;
15620 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
15621 Result);
15622 }
15623
15624 case CK_FloatingComplexToReal: {
15625 ComplexValue V;
15626 if (!EvaluateComplex(SubExpr, V, Info))
15627 return false;
15628 Result = V.getComplexFloatReal();
15629 return true;
15630 }
15631 case CK_HLSLVectorTruncation: {
15632 APValue Val;
15633 if (!EvaluateVector(SubExpr, Val, Info))
15634 return Error(E);
15635 return Success(Val.getVectorElt(0), E);
15636 }
15637 }
15638}
15639
15640//===----------------------------------------------------------------------===//
15641// Complex Evaluation (for float and integer)
15642//===----------------------------------------------------------------------===//
15643
15644namespace {
15645class ComplexExprEvaluator
15646 : public ExprEvaluatorBase<ComplexExprEvaluator> {
15647 ComplexValue &Result;
15648
15649public:
15650 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
15651 : ExprEvaluatorBaseTy(info), Result(Result) {}
15652
15653 bool Success(const APValue &V, const Expr *e) {
15654 Result.setFrom(V);
15655 return true;
15656 }
15657
15658 bool ZeroInitialization(const Expr *E);
15659
15660 //===--------------------------------------------------------------------===//
15661 // Visitor Methods
15662 //===--------------------------------------------------------------------===//
15663
15664 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
15665 bool VisitCastExpr(const CastExpr *E);
15666 bool VisitBinaryOperator(const BinaryOperator *E);
15667 bool VisitUnaryOperator(const UnaryOperator *E);
15668 bool VisitInitListExpr(const InitListExpr *E);
15669 bool VisitCallExpr(const CallExpr *E);
15670};
15671} // end anonymous namespace
15672
15673static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
15674 EvalInfo &Info) {
15675 assert(!E->isValueDependent());
15676 assert(E->isPRValue() && E->getType()->isAnyComplexType());
15677 return ComplexExprEvaluator(Info, Result).Visit(E);
15678}
15679
15680bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
15681 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
15682 if (ElemTy->isRealFloatingType()) {
15683 Result.makeComplexFloat();
15684 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
15685 Result.FloatReal = Zero;
15686 Result.FloatImag = Zero;
15687 } else {
15688 Result.makeComplexInt();
15689 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
15690 Result.IntReal = Zero;
15691 Result.IntImag = Zero;
15692 }
15693 return true;
15694}
15695
15696bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
15697 const Expr* SubExpr = E->getSubExpr();
15698
15699 if (SubExpr->getType()->isRealFloatingType()) {
15700 Result.makeComplexFloat();
15701 APFloat &Imag = Result.FloatImag;
15702 if (!EvaluateFloat(SubExpr, Imag, Info))
15703 return false;
15704
15705 Result.FloatReal = APFloat(Imag.getSemantics());
15706 return true;
15707 } else {
15708 assert(SubExpr->getType()->isIntegerType() &&
15709 "Unexpected imaginary literal.");
15710
15711 Result.makeComplexInt();
15712 APSInt &Imag = Result.IntImag;
15713 if (!EvaluateInteger(SubExpr, Imag, Info))
15714 return false;
15715
15716 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
15717 return true;
15718 }
15719}
15720
15721bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
15722
15723 switch (E->getCastKind()) {
15724 case CK_BitCast:
15725 case CK_BaseToDerived:
15726 case CK_DerivedToBase:
15727 case CK_UncheckedDerivedToBase:
15728 case CK_Dynamic:
15729 case CK_ToUnion:
15730 case CK_ArrayToPointerDecay:
15731 case CK_FunctionToPointerDecay:
15732 case CK_NullToPointer:
15733 case CK_NullToMemberPointer:
15734 case CK_BaseToDerivedMemberPointer:
15735 case CK_DerivedToBaseMemberPointer:
15736 case CK_MemberPointerToBoolean:
15737 case CK_ReinterpretMemberPointer:
15738 case CK_ConstructorConversion:
15739 case CK_IntegralToPointer:
15740 case CK_PointerToIntegral:
15741 case CK_PointerToBoolean:
15742 case CK_ToVoid:
15743 case CK_VectorSplat:
15744 case CK_IntegralCast:
15745 case CK_BooleanToSignedIntegral:
15746 case CK_IntegralToBoolean:
15747 case CK_IntegralToFloating:
15748 case CK_FloatingToIntegral:
15749 case CK_FloatingToBoolean:
15750 case CK_FloatingCast:
15751 case CK_CPointerToObjCPointerCast:
15752 case CK_BlockPointerToObjCPointerCast:
15753 case CK_AnyPointerToBlockPointerCast:
15754 case CK_ObjCObjectLValueCast:
15755 case CK_FloatingComplexToReal:
15756 case CK_FloatingComplexToBoolean:
15757 case CK_IntegralComplexToReal:
15758 case CK_IntegralComplexToBoolean:
15759 case CK_ARCProduceObject:
15760 case CK_ARCConsumeObject:
15761 case CK_ARCReclaimReturnedObject:
15762 case CK_ARCExtendBlockObject:
15763 case CK_CopyAndAutoreleaseBlockObject:
15764 case CK_BuiltinFnToFnPtr:
15765 case CK_ZeroToOCLOpaqueType:
15766 case CK_NonAtomicToAtomic:
15767 case CK_AddressSpaceConversion:
15768 case CK_IntToOCLSampler:
15769 case CK_FloatingToFixedPoint:
15770 case CK_FixedPointToFloating:
15771 case CK_FixedPointCast:
15772 case CK_FixedPointToBoolean:
15773 case CK_FixedPointToIntegral:
15774 case CK_IntegralToFixedPoint:
15775 case CK_MatrixCast:
15776 case CK_HLSLVectorTruncation:
15777 llvm_unreachable("invalid cast kind for complex value");
15778
15779 case CK_LValueToRValue:
15780 case CK_AtomicToNonAtomic:
15781 case CK_NoOp:
15782 case CK_LValueToRValueBitCast:
15783 case CK_HLSLArrayRValue:
15784 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15785
15786 case CK_Dependent:
15787 case CK_LValueBitCast:
15788 case CK_UserDefinedConversion:
15789 return Error(E);
15790
15791 case CK_FloatingRealToComplex: {
15792 APFloat &Real = Result.FloatReal;
15793 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
15794 return false;
15795
15796 Result.makeComplexFloat();
15797 Result.FloatImag = APFloat(Real.getSemantics());
15798 return true;
15799 }
15800
15801 case CK_FloatingComplexCast: {
15802 if (!Visit(E->getSubExpr()))
15803 return false;
15804
15805 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15806 QualType From
15807 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15808
15809 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
15810 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
15811 }
15812
15813 case CK_FloatingComplexToIntegralComplex: {
15814 if (!Visit(E->getSubExpr()))
15815 return false;
15816
15817 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15818 QualType From
15819 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15820 Result.makeComplexInt();
15821 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
15822 To, Result.IntReal) &&
15823 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
15824 To, Result.IntImag);
15825 }
15826
15827 case CK_IntegralRealToComplex: {
15828 APSInt &Real = Result.IntReal;
15829 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
15830 return false;
15831
15832 Result.makeComplexInt();
15833 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
15834 return true;
15835 }
15836
15837 case CK_IntegralComplexCast: {
15838 if (!Visit(E->getSubExpr()))
15839 return false;
15840
15841 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15842 QualType From
15843 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15844
15845 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
15846 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
15847 return true;
15848 }
15849
15850 case CK_IntegralComplexToFloatingComplex: {
15851 if (!Visit(E->getSubExpr()))
15852 return false;
15853
15854 const FPOptions FPO = E->getFPFeaturesInEffect(
15855 Info.Ctx.getLangOpts());
15856 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15857 QualType From
15858 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15859 Result.makeComplexFloat();
15860 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
15861 To, Result.FloatReal) &&
15862 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
15863 To, Result.FloatImag);
15864 }
15865 }
15866
15867 llvm_unreachable("unknown cast resulting in complex value");
15868}
15869
15870void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
15871 APFloat &ResR, APFloat &ResI) {
15872 // This is an implementation of complex multiplication according to the
15873 // constraints laid out in C11 Annex G. The implementation uses the
15874 // following naming scheme:
15875 // (a + ib) * (c + id)
15876
15877 APFloat AC = A * C;
15878 APFloat BD = B * D;
15879 APFloat AD = A * D;
15880 APFloat BC = B * C;
15881 ResR = AC - BD;
15882 ResI = AD + BC;
15883 if (ResR.isNaN() && ResI.isNaN()) {
15884 bool Recalc = false;
15885 if (A.isInfinity() || B.isInfinity()) {
15886 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
15887 A);
15888 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
15889 B);
15890 if (C.isNaN())
15891 C = APFloat::copySign(APFloat(C.getSemantics()), C);
15892 if (D.isNaN())
15893 D = APFloat::copySign(APFloat(D.getSemantics()), D);
15894 Recalc = true;
15895 }
15896 if (C.isInfinity() || D.isInfinity()) {
15897 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
15898 C);
15899 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
15900 D);
15901 if (A.isNaN())
15902 A = APFloat::copySign(APFloat(A.getSemantics()), A);
15903 if (B.isNaN())
15904 B = APFloat::copySign(APFloat(B.getSemantics()), B);
15905 Recalc = true;
15906 }
15907 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
15908 BC.isInfinity())) {
15909 if (A.isNaN())
15910 A = APFloat::copySign(APFloat(A.getSemantics()), A);
15911 if (B.isNaN())
15912 B = APFloat::copySign(APFloat(B.getSemantics()), B);
15913 if (C.isNaN())
15914 C = APFloat::copySign(APFloat(C.getSemantics()), C);
15915 if (D.isNaN())
15916 D = APFloat::copySign(APFloat(D.getSemantics()), D);
15917 Recalc = true;
15918 }
15919 if (Recalc) {
15920 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
15921 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
15922 }
15923 }
15924}
15925
15926void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
15927 APFloat &ResR, APFloat &ResI) {
15928 // This is an implementation of complex division according to the
15929 // constraints laid out in C11 Annex G. The implementation uses the
15930 // following naming scheme:
15931 // (a + ib) / (c + id)
15932
15933 int DenomLogB = 0;
15934 APFloat MaxCD = maxnum(abs(C), abs(D));
15935 if (MaxCD.isFinite()) {
15936 DenomLogB = ilogb(MaxCD);
15937 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
15938 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
15939 }
15940 APFloat Denom = C * C + D * D;
15941 ResR =
15942 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
15943 ResI =
15944 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
15945 if (ResR.isNaN() && ResI.isNaN()) {
15946 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
15947 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
15948 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
15949 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
15950 D.isFinite()) {
15951 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
15952 A);
15953 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
15954 B);
15955 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
15956 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
15957 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
15958 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
15959 C);
15960 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
15961 D);
15962 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
15963 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
15964 }
15965 }
15966}
15967
15968bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15969 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15970 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15971
15972 // Track whether the LHS or RHS is real at the type system level. When this is
15973 // the case we can simplify our evaluation strategy.
15974 bool LHSReal = false, RHSReal = false;
15975
15976 bool LHSOK;
15977 if (E->getLHS()->getType()->isRealFloatingType()) {
15978 LHSReal = true;
15979 APFloat &Real = Result.FloatReal;
15980 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
15981 if (LHSOK) {
15982 Result.makeComplexFloat();
15983 Result.FloatImag = APFloat(Real.getSemantics());
15984 }
15985 } else {
15986 LHSOK = Visit(E->getLHS());
15987 }
15988 if (!LHSOK && !Info.noteFailure())
15989 return false;
15990
15991 ComplexValue RHS;
15992 if (E->getRHS()->getType()->isRealFloatingType()) {
15993 RHSReal = true;
15994 APFloat &Real = RHS.FloatReal;
15995 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
15996 return false;
15997 RHS.makeComplexFloat();
15998 RHS.FloatImag = APFloat(Real.getSemantics());
15999 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
16000 return false;
16001
16002 assert(!(LHSReal && RHSReal) &&
16003 "Cannot have both operands of a complex operation be real.");
16004 switch (E->getOpcode()) {
16005 default: return Error(E);
16006 case BO_Add:
16007 if (Result.isComplexFloat()) {
16008 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
16009 APFloat::rmNearestTiesToEven);
16010 if (LHSReal)
16011 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16012 else if (!RHSReal)
16013 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
16014 APFloat::rmNearestTiesToEven);
16015 } else {
16016 Result.getComplexIntReal() += RHS.getComplexIntReal();
16017 Result.getComplexIntImag() += RHS.getComplexIntImag();
16018 }
16019 break;
16020 case BO_Sub:
16021 if (Result.isComplexFloat()) {
16022 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
16023 APFloat::rmNearestTiesToEven);
16024 if (LHSReal) {
16025 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16026 Result.getComplexFloatImag().changeSign();
16027 } else if (!RHSReal) {
16028 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
16029 APFloat::rmNearestTiesToEven);
16030 }
16031 } else {
16032 Result.getComplexIntReal() -= RHS.getComplexIntReal();
16033 Result.getComplexIntImag() -= RHS.getComplexIntImag();
16034 }
16035 break;
16036 case BO_Mul:
16037 if (Result.isComplexFloat()) {
16038 // This is an implementation of complex multiplication according to the
16039 // constraints laid out in C11 Annex G. The implementation uses the
16040 // following naming scheme:
16041 // (a + ib) * (c + id)
16042 ComplexValue LHS = Result;
16043 APFloat &A = LHS.getComplexFloatReal();
16044 APFloat &B = LHS.getComplexFloatImag();
16045 APFloat &C = RHS.getComplexFloatReal();
16046 APFloat &D = RHS.getComplexFloatImag();
16047 APFloat &ResR = Result.getComplexFloatReal();
16048 APFloat &ResI = Result.getComplexFloatImag();
16049 if (LHSReal) {
16050 assert(!RHSReal && "Cannot have two real operands for a complex op!");
16051 ResR = A;
16052 ResI = A;
16053 // ResR = A * C;
16054 // ResI = A * D;
16055 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
16056 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
16057 return false;
16058 } else if (RHSReal) {
16059 // ResR = C * A;
16060 // ResI = C * B;
16061 ResR = C;
16062 ResI = C;
16063 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
16064 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
16065 return false;
16066 } else {
16067 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
16068 }
16069 } else {
16070 ComplexValue LHS = Result;
16071 Result.getComplexIntReal() =
16072 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
16073 LHS.getComplexIntImag() * RHS.getComplexIntImag());
16074 Result.getComplexIntImag() =
16075 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
16076 LHS.getComplexIntImag() * RHS.getComplexIntReal());
16077 }
16078 break;
16079 case BO_Div:
16080 if (Result.isComplexFloat()) {
16081 // This is an implementation of complex division according to the
16082 // constraints laid out in C11 Annex G. The implementation uses the
16083 // following naming scheme:
16084 // (a + ib) / (c + id)
16085 ComplexValue LHS = Result;
16086 APFloat &A = LHS.getComplexFloatReal();
16087 APFloat &B = LHS.getComplexFloatImag();
16088 APFloat &C = RHS.getComplexFloatReal();
16089 APFloat &D = RHS.getComplexFloatImag();
16090 APFloat &ResR = Result.getComplexFloatReal();
16091 APFloat &ResI = Result.getComplexFloatImag();
16092 if (RHSReal) {
16093 ResR = A;
16094 ResI = B;
16095 // ResR = A / C;
16096 // ResI = B / C;
16097 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
16098 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
16099 return false;
16100 } else {
16101 if (LHSReal) {
16102 // No real optimizations we can do here, stub out with zero.
16103 B = APFloat::getZero(A.getSemantics());
16104 }
16105 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
16106 }
16107 } else {
16108 ComplexValue LHS = Result;
16109 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
16110 RHS.getComplexIntImag() * RHS.getComplexIntImag();
16111 if (Den.isZero())
16112 return Error(E, diag::note_expr_divide_by_zero);
16113
16114 Result.getComplexIntReal() =
16115 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
16116 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
16117 Result.getComplexIntImag() =
16118 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
16119 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
16120 }
16121 break;
16122 }
16123
16124 return true;
16125}
16126
16127bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16128 // Get the operand value into 'Result'.
16129 if (!Visit(E->getSubExpr()))
16130 return false;
16131
16132 switch (E->getOpcode()) {
16133 default:
16134 return Error(E);
16135 case UO_Extension:
16136 return true;
16137 case UO_Plus:
16138 // The result is always just the subexpr.
16139 return true;
16140 case UO_Minus:
16141 if (Result.isComplexFloat()) {
16142 Result.getComplexFloatReal().changeSign();
16143 Result.getComplexFloatImag().changeSign();
16144 }
16145 else {
16146 Result.getComplexIntReal() = -Result.getComplexIntReal();
16147 Result.getComplexIntImag() = -Result.getComplexIntImag();
16148 }
16149 return true;
16150 case UO_Not:
16151 if (Result.isComplexFloat())
16152 Result.getComplexFloatImag().changeSign();
16153 else
16154 Result.getComplexIntImag() = -Result.getComplexIntImag();
16155 return true;
16156 }
16157}
16158
16159bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
16160 if (E->getNumInits() == 2) {
16161 if (E->getType()->isComplexType()) {
16162 Result.makeComplexFloat();
16163 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
16164 return false;
16165 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
16166 return false;
16167 } else {
16168 Result.makeComplexInt();
16169 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
16170 return false;
16171 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
16172 return false;
16173 }
16174 return true;
16175 }
16176 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
16177}
16178
16179bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
16180 if (!IsConstantEvaluatedBuiltinCall(E))
16181 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16182
16183 switch (E->getBuiltinCallee()) {
16184 case Builtin::BI__builtin_complex:
16185 Result.makeComplexFloat();
16186 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
16187 return false;
16188 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
16189 return false;
16190 return true;
16191
16192 default:
16193 return false;
16194 }
16195}
16196
16197//===----------------------------------------------------------------------===//
16198// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
16199// implicit conversion.
16200//===----------------------------------------------------------------------===//
16201
16202namespace {
16203class AtomicExprEvaluator :
16204 public ExprEvaluatorBase<AtomicExprEvaluator> {
16205 const LValue *This;
16206 APValue &Result;
16207public:
16208 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
16209 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
16210
16211 bool Success(const APValue &V, const Expr *E) {
16212 Result = V;
16213 return true;
16214 }
16215
16216 bool ZeroInitialization(const Expr *E) {
16219 // For atomic-qualified class (and array) types in C++, initialize the
16220 // _Atomic-wrapped subobject directly, in-place.
16221 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
16222 : Evaluate(Result, Info, &VIE);
16223 }
16224
16225 bool VisitCastExpr(const CastExpr *E) {
16226 switch (E->getCastKind()) {
16227 default:
16228 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16229 case CK_NullToPointer:
16230 VisitIgnoredValue(E->getSubExpr());
16231 return ZeroInitialization(E);
16232 case CK_NonAtomicToAtomic:
16233 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
16234 : Evaluate(Result, Info, E->getSubExpr());
16235 }
16236 }
16237};
16238} // end anonymous namespace
16239
16240static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
16241 EvalInfo &Info) {
16242 assert(!E->isValueDependent());
16243 assert(E->isPRValue() && E->getType()->isAtomicType());
16244 return AtomicExprEvaluator(Info, This, Result).Visit(E);
16245}
16246
16247//===----------------------------------------------------------------------===//
16248// Void expression evaluation, primarily for a cast to void on the LHS of a
16249// comma operator
16250//===----------------------------------------------------------------------===//
16251
16252namespace {
16253class VoidExprEvaluator
16254 : public ExprEvaluatorBase<VoidExprEvaluator> {
16255public:
16256 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
16257
16258 bool Success(const APValue &V, const Expr *e) { return true; }
16259
16260 bool ZeroInitialization(const Expr *E) { return true; }
16261
16262 bool VisitCastExpr(const CastExpr *E) {
16263 switch (E->getCastKind()) {
16264 default:
16265 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16266 case CK_ToVoid:
16267 VisitIgnoredValue(E->getSubExpr());
16268 return true;
16269 }
16270 }
16271
16272 bool VisitCallExpr(const CallExpr *E) {
16273 if (!IsConstantEvaluatedBuiltinCall(E))
16274 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16275
16276 switch (E->getBuiltinCallee()) {
16277 case Builtin::BI__assume:
16278 case Builtin::BI__builtin_assume:
16279 // The argument is not evaluated!
16280 return true;
16281
16282 case Builtin::BI__builtin_operator_delete:
16283 return HandleOperatorDeleteCall(Info, E);
16284
16285 default:
16286 return false;
16287 }
16288 }
16289
16290 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
16291};
16292} // end anonymous namespace
16293
16294bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
16295 // We cannot speculatively evaluate a delete expression.
16296 if (Info.SpeculativeEvaluationDepth)
16297 return false;
16298
16299 FunctionDecl *OperatorDelete = E->getOperatorDelete();
16300 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
16301 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
16302 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
16303 return false;
16304 }
16305
16306 const Expr *Arg = E->getArgument();
16307
16308 LValue Pointer;
16309 if (!EvaluatePointer(Arg, Pointer, Info))
16310 return false;
16311 if (Pointer.Designator.Invalid)
16312 return false;
16313
16314 // Deleting a null pointer has no effect.
16315 if (Pointer.isNullPointer()) {
16316 // This is the only case where we need to produce an extension warning:
16317 // the only other way we can succeed is if we find a dynamic allocation,
16318 // and we will have warned when we allocated it in that case.
16319 if (!Info.getLangOpts().CPlusPlus20)
16320 Info.CCEDiag(E, diag::note_constexpr_new);
16321 return true;
16322 }
16323
16324 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
16325 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
16326 if (!Alloc)
16327 return false;
16328 QualType AllocType = Pointer.Base.getDynamicAllocType();
16329
16330 // For the non-array case, the designator must be empty if the static type
16331 // does not have a virtual destructor.
16332 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
16334 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
16335 << Arg->getType()->getPointeeType() << AllocType;
16336 return false;
16337 }
16338
16339 // For a class type with a virtual destructor, the selected operator delete
16340 // is the one looked up when building the destructor.
16341 if (!E->isArrayForm() && !E->isGlobalDelete()) {
16342 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
16343 if (VirtualDelete &&
16344 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
16345 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
16346 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
16347 return false;
16348 }
16349 }
16350
16351 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
16352 (*Alloc)->Value, AllocType))
16353 return false;
16354
16355 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
16356 // The element was already erased. This means the destructor call also
16357 // deleted the object.
16358 // FIXME: This probably results in undefined behavior before we get this
16359 // far, and should be diagnosed elsewhere first.
16360 Info.FFDiag(E, diag::note_constexpr_double_delete);
16361 return false;
16362 }
16363
16364 return true;
16365}
16366
16367static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
16368 assert(!E->isValueDependent());
16369 assert(E->isPRValue() && E->getType()->isVoidType());
16370 return VoidExprEvaluator(Info).Visit(E);
16371}
16372
16373//===----------------------------------------------------------------------===//
16374// Top level Expr::EvaluateAsRValue method.
16375//===----------------------------------------------------------------------===//
16376
16377static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
16378 assert(!E->isValueDependent());
16379 // In C, function designators are not lvalues, but we evaluate them as if they
16380 // are.
16381 QualType T = E->getType();
16382 if (E->isGLValue() || T->isFunctionType()) {
16383 LValue LV;
16384 if (!EvaluateLValue(E, LV, Info))
16385 return false;
16386 LV.moveInto(Result);
16387 } else if (T->isVectorType()) {
16388 if (!EvaluateVector(E, Result, Info))
16389 return false;
16390 } else if (T->isIntegralOrEnumerationType()) {
16391 if (!IntExprEvaluator(Info, Result).Visit(E))
16392 return false;
16393 } else if (T->hasPointerRepresentation()) {
16394 LValue LV;
16395 if (!EvaluatePointer(E, LV, Info))
16396 return false;
16397 LV.moveInto(Result);
16398 } else if (T->isRealFloatingType()) {
16399 llvm::APFloat F(0.0);
16400 if (!EvaluateFloat(E, F, Info))
16401 return false;
16402 Result = APValue(F);
16403 } else if (T->isAnyComplexType()) {
16404 ComplexValue C;
16405 if (!EvaluateComplex(E, C, Info))
16406 return false;
16407 C.moveInto(Result);
16408 } else if (T->isFixedPointType()) {
16409 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
16410 } else if (T->isMemberPointerType()) {
16411 MemberPtr P;
16412 if (!EvaluateMemberPointer(E, P, Info))
16413 return false;
16414 P.moveInto(Result);
16415 return true;
16416 } else if (T->isArrayType()) {
16417 LValue LV;
16418 APValue &Value =
16419 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
16420 if (!EvaluateArray(E, LV, Value, Info))
16421 return false;
16422 Result = Value;
16423 } else if (T->isRecordType()) {
16424 LValue LV;
16425 APValue &Value =
16426 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
16427 if (!EvaluateRecord(E, LV, Value, Info))
16428 return false;
16429 Result = Value;
16430 } else if (T->isVoidType()) {
16431 if (!Info.getLangOpts().CPlusPlus11)
16432 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
16433 << E->getType();
16434 if (!EvaluateVoid(E, Info))
16435 return false;
16436 } else if (T->isAtomicType()) {
16437 QualType Unqual = T.getAtomicUnqualifiedType();
16438 if (Unqual->isArrayType() || Unqual->isRecordType()) {
16439 LValue LV;
16440 APValue &Value = Info.CurrentCall->createTemporary(
16441 E, Unqual, ScopeKind::FullExpression, LV);
16442 if (!EvaluateAtomic(E, &LV, Value, Info))
16443 return false;
16444 Result = Value;
16445 } else {
16446 if (!EvaluateAtomic(E, nullptr, Result, Info))
16447 return false;
16448 }
16449 } else if (Info.getLangOpts().CPlusPlus11) {
16450 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
16451 return false;
16452 } else {
16453 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16454 return false;
16455 }
16456
16457 return true;
16458}
16459
16460/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
16461/// cases, the in-place evaluation is essential, since later initializers for
16462/// an object can indirectly refer to subobjects which were initialized earlier.
16463static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
16464 const Expr *E, bool AllowNonLiteralTypes) {
16465 assert(!E->isValueDependent());
16466
16467 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
16468 return false;
16469
16470 if (E->isPRValue()) {
16471 // Evaluate arrays and record types in-place, so that later initializers can
16472 // refer to earlier-initialized members of the object.
16473 QualType T = E->getType();
16474 if (T->isArrayType())
16475 return EvaluateArray(E, This, Result, Info);
16476 else if (T->isRecordType())
16477 return EvaluateRecord(E, This, Result, Info);
16478 else if (T->isAtomicType()) {
16479 QualType Unqual = T.getAtomicUnqualifiedType();
16480 if (Unqual->isArrayType() || Unqual->isRecordType())
16481 return EvaluateAtomic(E, &This, Result, Info);
16482 }
16483 }
16484
16485 // For any other type, in-place evaluation is unimportant.
16486 return Evaluate(Result, Info, E);
16487}
16488
16489/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
16490/// lvalue-to-rvalue cast if it is an lvalue.
16491static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
16492 assert(!E->isValueDependent());
16493
16494 if (E->getType().isNull())
16495 return false;
16496
16497 if (!CheckLiteralType(Info, E))
16498 return false;
16499
16500 if (Info.EnableNewConstInterp) {
16501 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
16502 return false;
16503 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16504 ConstantExprKind::Normal);
16505 }
16506
16507 if (!::Evaluate(Result, Info, E))
16508 return false;
16509
16510 // Implicit lvalue-to-rvalue cast.
16511 if (E->isGLValue()) {
16512 LValue LV;
16513 LV.setFrom(Info.Ctx, Result);
16514 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
16515 return false;
16516 }
16517
16518 // Check this core constant expression is a constant expression.
16519 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16520 ConstantExprKind::Normal) &&
16521 CheckMemoryLeaks(Info);
16522}
16523
16524static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
16525 const ASTContext &Ctx, bool &IsConst) {
16526 // Fast-path evaluations of integer literals, since we sometimes see files
16527 // containing vast quantities of these.
16528 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
16529 Result.Val = APValue(APSInt(L->getValue(),
16530 L->getType()->isUnsignedIntegerType()));
16531 IsConst = true;
16532 return true;
16533 }
16534
16535 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
16536 Result.Val = APValue(APSInt(APInt(1, L->getValue())));
16537 IsConst = true;
16538 return true;
16539 }
16540
16541 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
16542 Result.Val = APValue(FL->getValue());
16543 IsConst = true;
16544 return true;
16545 }
16546
16547 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
16548 Result.Val = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
16549 IsConst = true;
16550 return true;
16551 }
16552
16553 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
16554 if (CE->hasAPValueResult()) {
16555 APValue APV = CE->getAPValueResult();
16556 if (!APV.isLValue()) {
16557 Result.Val = std::move(APV);
16558 IsConst = true;
16559 return true;
16560 }
16561 }
16562
16563 // The SubExpr is usually just an IntegerLiteral.
16564 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
16565 }
16566
16567 // This case should be rare, but we need to check it before we check on
16568 // the type below.
16569 if (Exp->getType().isNull()) {
16570 IsConst = false;
16571 return true;
16572 }
16573
16574 return false;
16575}
16576
16579 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
16580 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
16581}
16582
16583static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
16584 const ASTContext &Ctx, EvalInfo &Info) {
16585 assert(!E->isValueDependent());
16586 bool IsConst;
16587 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
16588 return IsConst;
16589
16590 return EvaluateAsRValue(Info, E, Result.Val);
16591}
16592
16594 const ASTContext &Ctx,
16595 Expr::SideEffectsKind AllowSideEffects,
16596 EvalInfo &Info) {
16597 assert(!E->isValueDependent());
16599 return false;
16600
16601 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
16602 !ExprResult.Val.isInt() ||
16603 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16604 return false;
16605
16606 return true;
16607}
16608
16610 const ASTContext &Ctx,
16611 Expr::SideEffectsKind AllowSideEffects,
16612 EvalInfo &Info) {
16613 assert(!E->isValueDependent());
16614 if (!E->getType()->isFixedPointType())
16615 return false;
16616
16617 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
16618 return false;
16619
16620 if (!ExprResult.Val.isFixedPoint() ||
16621 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16622 return false;
16623
16624 return true;
16625}
16626
16627/// EvaluateAsRValue - Return true if this is a constant which we can fold using
16628/// any crazy technique (that has nothing to do with language standards) that
16629/// we want to. If this function returns true, it returns the folded constant
16630/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
16631/// will be applied to the result.
16633 bool InConstantContext) const {
16634 assert(!isValueDependent() &&
16635 "Expression evaluator can't be called on a dependent expression.");
16636 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
16637 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16638 Info.InConstantContext = InConstantContext;
16639 return ::EvaluateAsRValue(this, Result, Ctx, Info);
16640}
16641
16642bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
16643 bool InConstantContext) const {
16644 assert(!isValueDependent() &&
16645 "Expression evaluator can't be called on a dependent expression.");
16646 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
16647 EvalResult Scratch;
16648 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
16649 HandleConversionToBool(Scratch.Val, Result);
16650}
16651
16653 SideEffectsKind AllowSideEffects,
16654 bool InConstantContext) const {
16655 assert(!isValueDependent() &&
16656 "Expression evaluator can't be called on a dependent expression.");
16657 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
16658 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16659 Info.InConstantContext = InConstantContext;
16660 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
16661}
16662
16664 SideEffectsKind AllowSideEffects,
16665 bool InConstantContext) const {
16666 assert(!isValueDependent() &&
16667 "Expression evaluator can't be called on a dependent expression.");
16668 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
16669 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16670 Info.InConstantContext = InConstantContext;
16671 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
16672}
16673
16674bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
16675 SideEffectsKind AllowSideEffects,
16676 bool InConstantContext) const {
16677 assert(!isValueDependent() &&
16678 "Expression evaluator can't be called on a dependent expression.");
16679
16680 if (!getType()->isRealFloatingType())
16681 return false;
16682
16683 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
16685 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
16686 !ExprResult.Val.isFloat() ||
16687 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16688 return false;
16689
16690 Result = ExprResult.Val.getFloat();
16691 return true;
16692}
16693
16695 bool InConstantContext) const {
16696 assert(!isValueDependent() &&
16697 "Expression evaluator can't be called on a dependent expression.");
16698
16699 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
16700 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
16701 Info.InConstantContext = InConstantContext;
16702 LValue LV;
16703 CheckedTemporaries CheckedTemps;
16704 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
16705 Result.HasSideEffects ||
16706 !CheckLValueConstantExpression(Info, getExprLoc(),
16707 Ctx.getLValueReferenceType(getType()), LV,
16708 ConstantExprKind::Normal, CheckedTemps))
16709 return false;
16710
16711 LV.moveInto(Result.Val);
16712 return true;
16713}
16714
16716 APValue DestroyedValue, QualType Type,
16718 bool IsConstantDestruction) {
16719 EvalInfo Info(Ctx, EStatus,
16720 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
16721 : EvalInfo::EM_ConstantFold);
16722 Info.setEvaluatingDecl(Base, DestroyedValue,
16723 EvalInfo::EvaluatingDeclKind::Dtor);
16724 Info.InConstantContext = IsConstantDestruction;
16725
16726 LValue LVal;
16727 LVal.set(Base);
16728
16729 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
16730 EStatus.HasSideEffects)
16731 return false;
16732
16733 if (!Info.discardCleanups())
16734 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16735
16736 return true;
16737}
16738
16740 ConstantExprKind Kind) const {
16741 assert(!isValueDependent() &&
16742 "Expression evaluator can't be called on a dependent expression.");
16743 bool IsConst;
16744 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
16745 return true;
16746
16747 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
16748 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
16749 EvalInfo Info(Ctx, Result, EM);
16750 Info.InConstantContext = true;
16751
16752 if (Info.EnableNewConstInterp) {
16753 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
16754 return false;
16755 return CheckConstantExpression(Info, getExprLoc(),
16756 getStorageType(Ctx, this), Result.Val, Kind);
16757 }
16758
16759 // The type of the object we're initializing is 'const T' for a class NTTP.
16760 QualType T = getType();
16761 if (Kind == ConstantExprKind::ClassTemplateArgument)
16762 T.addConst();
16763
16764 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
16765 // represent the result of the evaluation. CheckConstantExpression ensures
16766 // this doesn't escape.
16767 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
16768 APValue::LValueBase Base(&BaseMTE);
16769 Info.setEvaluatingDecl(Base, Result.Val);
16770
16771 if (Info.EnableNewConstInterp) {
16772 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, this, Result.Val))
16773 return false;
16774 } else {
16775 LValue LVal;
16776 LVal.set(Base);
16777 // C++23 [intro.execution]/p5
16778 // A full-expression is [...] a constant-expression
16779 // So we need to make sure temporary objects are destroyed after having
16780 // evaluating the expression (per C++23 [class.temporary]/p4).
16781 FullExpressionRAII Scope(Info);
16782 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
16783 Result.HasSideEffects || !Scope.destroy())
16784 return false;
16785
16786 if (!Info.discardCleanups())
16787 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16788 }
16789
16790 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
16791 Result.Val, Kind))
16792 return false;
16793 if (!CheckMemoryLeaks(Info))
16794 return false;
16795
16796 // If this is a class template argument, it's required to have constant
16797 // destruction too.
16798 if (Kind == ConstantExprKind::ClassTemplateArgument &&
16799 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
16800 true) ||
16801 Result.HasSideEffects)) {
16802 // FIXME: Prefix a note to indicate that the problem is lack of constant
16803 // destruction.
16804 return false;
16805 }
16806
16807 return true;
16808}
16809
16811 const VarDecl *VD,
16813 bool IsConstantInitialization) const {
16814 assert(!isValueDependent() &&
16815 "Expression evaluator can't be called on a dependent expression.");
16816
16817 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
16818 std::string Name;
16819 llvm::raw_string_ostream OS(Name);
16820 VD->printQualifiedName(OS);
16821 return Name;
16822 });
16823
16824 Expr::EvalStatus EStatus;
16825 EStatus.Diag = &Notes;
16826
16827 EvalInfo Info(Ctx, EStatus,
16828 (IsConstantInitialization &&
16829 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
16830 ? EvalInfo::EM_ConstantExpression
16831 : EvalInfo::EM_ConstantFold);
16832 Info.setEvaluatingDecl(VD, Value);
16833 Info.InConstantContext = IsConstantInitialization;
16834
16835 SourceLocation DeclLoc = VD->getLocation();
16836 QualType DeclTy = VD->getType();
16837
16838 if (Info.EnableNewConstInterp) {
16839 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
16840 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
16841 return false;
16842
16843 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
16844 ConstantExprKind::Normal);
16845 } else {
16846 LValue LVal;
16847 LVal.set(VD);
16848
16849 {
16850 // C++23 [intro.execution]/p5
16851 // A full-expression is ... an init-declarator ([dcl.decl]) or a
16852 // mem-initializer.
16853 // So we need to make sure temporary objects are destroyed after having
16854 // evaluated the expression (per C++23 [class.temporary]/p4).
16855 //
16856 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
16857 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
16858 // outermost FullExpr, such as ExprWithCleanups.
16859 FullExpressionRAII Scope(Info);
16860 if (!EvaluateInPlace(Value, Info, LVal, this,
16861 /*AllowNonLiteralTypes=*/true) ||
16862 EStatus.HasSideEffects)
16863 return false;
16864 }
16865
16866 // At this point, any lifetime-extended temporaries are completely
16867 // initialized.
16868 Info.performLifetimeExtension();
16869
16870 if (!Info.discardCleanups())
16871 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16872 }
16873
16874 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
16875 ConstantExprKind::Normal) &&
16876 CheckMemoryLeaks(Info);
16877}
16878
16881 Expr::EvalStatus EStatus;
16882 EStatus.Diag = &Notes;
16883
16884 // Only treat the destruction as constant destruction if we formally have
16885 // constant initialization (or are usable in a constant expression).
16886 bool IsConstantDestruction = hasConstantInitialization();
16887
16888 // Make a copy of the value for the destructor to mutate, if we know it.
16889 // Otherwise, treat the value as default-initialized; if the destructor works
16890 // anyway, then the destruction is constant (and must be essentially empty).
16891 APValue DestroyedValue;
16892 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
16893 DestroyedValue = *getEvaluatedValue();
16894 else if (!handleDefaultInitValue(getType(), DestroyedValue))
16895 return false;
16896
16897 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
16898 getType(), getLocation(), EStatus,
16899 IsConstantDestruction) ||
16900 EStatus.HasSideEffects)
16901 return false;
16902
16903 ensureEvaluatedStmt()->HasConstantDestruction = true;
16904 return true;
16905}
16906
16907/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
16908/// constant folded, but discard the result.
16910 assert(!isValueDependent() &&
16911 "Expression evaluator can't be called on a dependent expression.");
16912
16913 EvalResult Result;
16914 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
16915 !hasUnacceptableSideEffect(Result, SEK);
16916}
16917
16920 assert(!isValueDependent() &&
16921 "Expression evaluator can't be called on a dependent expression.");
16922
16923 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
16924 EvalResult EVResult;
16925 EVResult.Diag = Diag;
16926 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16927 Info.InConstantContext = true;
16928
16929 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
16930 (void)Result;
16931 assert(Result && "Could not evaluate expression");
16932 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
16933
16934 return EVResult.Val.getInt();
16935}
16936
16939 assert(!isValueDependent() &&
16940 "Expression evaluator can't be called on a dependent expression.");
16941
16942 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
16943 EvalResult EVResult;
16944 EVResult.Diag = Diag;
16945 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16946 Info.InConstantContext = true;
16947 Info.CheckingForUndefinedBehavior = true;
16948
16949 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
16950 (void)Result;
16951 assert(Result && "Could not evaluate expression");
16952 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
16953
16954 return EVResult.Val.getInt();
16955}
16956
16958 assert(!isValueDependent() &&
16959 "Expression evaluator can't be called on a dependent expression.");
16960
16961 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
16962 bool IsConst;
16963 EvalResult EVResult;
16964 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
16965 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
16966 Info.CheckingForUndefinedBehavior = true;
16967 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
16968 }
16969}
16970
16972 assert(Val.isLValue());
16973 return IsGlobalLValue(Val.getLValueBase());
16974}
16975
16976/// isIntegerConstantExpr - this recursive routine will test if an expression is
16977/// an integer constant expression.
16978
16979/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
16980/// comma, etc
16981
16982// CheckICE - This function does the fundamental ICE checking: the returned
16983// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
16984// and a (possibly null) SourceLocation indicating the location of the problem.
16985//
16986// Note that to reduce code duplication, this helper does no evaluation
16987// itself; the caller checks whether the expression is evaluatable, and
16988// in the rare cases where CheckICE actually cares about the evaluated
16989// value, it calls into Evaluate.
16990
16991namespace {
16992
16993enum ICEKind {
16994 /// This expression is an ICE.
16995 IK_ICE,
16996 /// This expression is not an ICE, but if it isn't evaluated, it's
16997 /// a legal subexpression for an ICE. This return value is used to handle
16998 /// the comma operator in C99 mode, and non-constant subexpressions.
16999 IK_ICEIfUnevaluated,
17000 /// This expression is not an ICE, and is not a legal subexpression for one.
17001 IK_NotICE
17002};
17003
17004struct ICEDiag {
17005 ICEKind Kind;
17007
17008 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
17009};
17010
17011}
17012
17013static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
17014
17015static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
17016
17017static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
17018 Expr::EvalResult EVResult;
17019 Expr::EvalStatus Status;
17020 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17021
17022 Info.InConstantContext = true;
17023 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
17024 !EVResult.Val.isInt())
17025 return ICEDiag(IK_NotICE, E->getBeginLoc());
17026
17027 return NoDiag();
17028}
17029
17030static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
17031 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
17033 return ICEDiag(IK_NotICE, E->getBeginLoc());
17034
17035 switch (E->getStmtClass()) {
17036#define ABSTRACT_STMT(Node)
17037#define STMT(Node, Base) case Expr::Node##Class:
17038#define EXPR(Node, Base)
17039#include "clang/AST/StmtNodes.inc"
17040 case Expr::PredefinedExprClass:
17041 case Expr::FloatingLiteralClass:
17042 case Expr::ImaginaryLiteralClass:
17043 case Expr::StringLiteralClass:
17044 case Expr::ArraySubscriptExprClass:
17045 case Expr::MatrixSubscriptExprClass:
17046 case Expr::ArraySectionExprClass:
17047 case Expr::OMPArrayShapingExprClass:
17048 case Expr::OMPIteratorExprClass:
17049 case Expr::MemberExprClass:
17050 case Expr::CompoundAssignOperatorClass:
17051 case Expr::CompoundLiteralExprClass:
17052 case Expr::ExtVectorElementExprClass:
17053 case Expr::DesignatedInitExprClass:
17054 case Expr::ArrayInitLoopExprClass:
17055 case Expr::ArrayInitIndexExprClass:
17056 case Expr::NoInitExprClass:
17057 case Expr::DesignatedInitUpdateExprClass:
17058 case Expr::ImplicitValueInitExprClass:
17059 case Expr::ParenListExprClass:
17060 case Expr::VAArgExprClass:
17061 case Expr::AddrLabelExprClass:
17062 case Expr::StmtExprClass:
17063 case Expr::CXXMemberCallExprClass:
17064 case Expr::CUDAKernelCallExprClass:
17065 case Expr::CXXAddrspaceCastExprClass:
17066 case Expr::CXXDynamicCastExprClass:
17067 case Expr::CXXTypeidExprClass:
17068 case Expr::CXXUuidofExprClass:
17069 case Expr::MSPropertyRefExprClass:
17070 case Expr::MSPropertySubscriptExprClass:
17071 case Expr::CXXNullPtrLiteralExprClass:
17072 case Expr::UserDefinedLiteralClass:
17073 case Expr::CXXThisExprClass:
17074 case Expr::CXXThrowExprClass:
17075 case Expr::CXXNewExprClass:
17076 case Expr::CXXDeleteExprClass:
17077 case Expr::CXXPseudoDestructorExprClass:
17078 case Expr::UnresolvedLookupExprClass:
17079 case Expr::TypoExprClass:
17080 case Expr::RecoveryExprClass:
17081 case Expr::DependentScopeDeclRefExprClass:
17082 case Expr::CXXConstructExprClass:
17083 case Expr::CXXInheritedCtorInitExprClass:
17084 case Expr::CXXStdInitializerListExprClass:
17085 case Expr::CXXBindTemporaryExprClass:
17086 case Expr::ExprWithCleanupsClass:
17087 case Expr::CXXTemporaryObjectExprClass:
17088 case Expr::CXXUnresolvedConstructExprClass:
17089 case Expr::CXXDependentScopeMemberExprClass:
17090 case Expr::UnresolvedMemberExprClass:
17091 case Expr::ObjCStringLiteralClass:
17092 case Expr::ObjCBoxedExprClass:
17093 case Expr::ObjCArrayLiteralClass:
17094 case Expr::ObjCDictionaryLiteralClass:
17095 case Expr::ObjCEncodeExprClass:
17096 case Expr::ObjCMessageExprClass:
17097 case Expr::ObjCSelectorExprClass:
17098 case Expr::ObjCProtocolExprClass:
17099 case Expr::ObjCIvarRefExprClass:
17100 case Expr::ObjCPropertyRefExprClass:
17101 case Expr::ObjCSubscriptRefExprClass:
17102 case Expr::ObjCIsaExprClass:
17103 case Expr::ObjCAvailabilityCheckExprClass:
17104 case Expr::ShuffleVectorExprClass:
17105 case Expr::ConvertVectorExprClass:
17106 case Expr::BlockExprClass:
17107 case Expr::NoStmtClass:
17108 case Expr::OpaqueValueExprClass:
17109 case Expr::PackExpansionExprClass:
17110 case Expr::SubstNonTypeTemplateParmPackExprClass:
17111 case Expr::FunctionParmPackExprClass:
17112 case Expr::AsTypeExprClass:
17113 case Expr::ObjCIndirectCopyRestoreExprClass:
17114 case Expr::MaterializeTemporaryExprClass:
17115 case Expr::PseudoObjectExprClass:
17116 case Expr::AtomicExprClass:
17117 case Expr::LambdaExprClass:
17118 case Expr::CXXFoldExprClass:
17119 case Expr::CoawaitExprClass:
17120 case Expr::DependentCoawaitExprClass:
17121 case Expr::CoyieldExprClass:
17122 case Expr::SYCLUniqueStableNameExprClass:
17123 case Expr::CXXParenListInitExprClass:
17124 case Expr::HLSLOutArgExprClass:
17125 return ICEDiag(IK_NotICE, E->getBeginLoc());
17126
17127 case Expr::InitListExprClass: {
17128 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
17129 // form "T x = { a };" is equivalent to "T x = a;".
17130 // Unless we're initializing a reference, T is a scalar as it is known to be
17131 // of integral or enumeration type.
17132 if (E->isPRValue())
17133 if (cast<InitListExpr>(E)->getNumInits() == 1)
17134 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
17135 return ICEDiag(IK_NotICE, E->getBeginLoc());
17136 }
17137
17138 case Expr::SizeOfPackExprClass:
17139 case Expr::GNUNullExprClass:
17140 case Expr::SourceLocExprClass:
17141 case Expr::EmbedExprClass:
17142 case Expr::OpenACCAsteriskSizeExprClass:
17143 return NoDiag();
17144
17145 case Expr::PackIndexingExprClass:
17146 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
17147
17148 case Expr::SubstNonTypeTemplateParmExprClass:
17149 return
17150 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
17151
17152 case Expr::ConstantExprClass:
17153 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
17154
17155 case Expr::ParenExprClass:
17156 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
17157 case Expr::GenericSelectionExprClass:
17158 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
17159 case Expr::IntegerLiteralClass:
17160 case Expr::FixedPointLiteralClass:
17161 case Expr::CharacterLiteralClass:
17162 case Expr::ObjCBoolLiteralExprClass:
17163 case Expr::CXXBoolLiteralExprClass:
17164 case Expr::CXXScalarValueInitExprClass:
17165 case Expr::TypeTraitExprClass:
17166 case Expr::ConceptSpecializationExprClass:
17167 case Expr::RequiresExprClass:
17168 case Expr::ArrayTypeTraitExprClass:
17169 case Expr::ExpressionTraitExprClass:
17170 case Expr::CXXNoexceptExprClass:
17171 return NoDiag();
17172 case Expr::CallExprClass:
17173 case Expr::CXXOperatorCallExprClass: {
17174 // C99 6.6/3 allows function calls within unevaluated subexpressions of
17175 // constant expressions, but they can never be ICEs because an ICE cannot
17176 // contain an operand of (pointer to) function type.
17177 const CallExpr *CE = cast<CallExpr>(E);
17178 if (CE->getBuiltinCallee())
17179 return CheckEvalInICE(E, Ctx);
17180 return ICEDiag(IK_NotICE, E->getBeginLoc());
17181 }
17182 case Expr::CXXRewrittenBinaryOperatorClass:
17183 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
17184 Ctx);
17185 case Expr::DeclRefExprClass: {
17186 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
17187 if (isa<EnumConstantDecl>(D))
17188 return NoDiag();
17189
17190 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
17191 // integer variables in constant expressions:
17192 //
17193 // C++ 7.1.5.1p2
17194 // A variable of non-volatile const-qualified integral or enumeration
17195 // type initialized by an ICE can be used in ICEs.
17196 //
17197 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
17198 // that mode, use of reference variables should not be allowed.
17199 const VarDecl *VD = dyn_cast<VarDecl>(D);
17200 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
17201 !VD->getType()->isReferenceType())
17202 return NoDiag();
17203
17204 return ICEDiag(IK_NotICE, E->getBeginLoc());
17205 }
17206 case Expr::UnaryOperatorClass: {
17207 const UnaryOperator *Exp = cast<UnaryOperator>(E);
17208 switch (Exp->getOpcode()) {
17209 case UO_PostInc:
17210 case UO_PostDec:
17211 case UO_PreInc:
17212 case UO_PreDec:
17213 case UO_AddrOf:
17214 case UO_Deref:
17215 case UO_Coawait:
17216 // C99 6.6/3 allows increment and decrement within unevaluated
17217 // subexpressions of constant expressions, but they can never be ICEs
17218 // because an ICE cannot contain an lvalue operand.
17219 return ICEDiag(IK_NotICE, E->getBeginLoc());
17220 case UO_Extension:
17221 case UO_LNot:
17222 case UO_Plus:
17223 case UO_Minus:
17224 case UO_Not:
17225 case UO_Real:
17226 case UO_Imag:
17227 return CheckICE(Exp->getSubExpr(), Ctx);
17228 }
17229 llvm_unreachable("invalid unary operator class");
17230 }
17231 case Expr::OffsetOfExprClass: {
17232 // Note that per C99, offsetof must be an ICE. And AFAIK, using
17233 // EvaluateAsRValue matches the proposed gcc behavior for cases like
17234 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
17235 // compliance: we should warn earlier for offsetof expressions with
17236 // array subscripts that aren't ICEs, and if the array subscripts
17237 // are ICEs, the value of the offsetof must be an integer constant.
17238 return CheckEvalInICE(E, Ctx);
17239 }
17240 case Expr::UnaryExprOrTypeTraitExprClass: {
17241 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
17242 if ((Exp->getKind() == UETT_SizeOf) &&
17244 return ICEDiag(IK_NotICE, E->getBeginLoc());
17245 return NoDiag();
17246 }
17247 case Expr::BinaryOperatorClass: {
17248 const BinaryOperator *Exp = cast<BinaryOperator>(E);
17249 switch (Exp->getOpcode()) {
17250 case BO_PtrMemD:
17251 case BO_PtrMemI:
17252 case BO_Assign:
17253 case BO_MulAssign:
17254 case BO_DivAssign:
17255 case BO_RemAssign:
17256 case BO_AddAssign:
17257 case BO_SubAssign:
17258 case BO_ShlAssign:
17259 case BO_ShrAssign:
17260 case BO_AndAssign:
17261 case BO_XorAssign:
17262 case BO_OrAssign:
17263 // C99 6.6/3 allows assignments within unevaluated subexpressions of
17264 // constant expressions, but they can never be ICEs because an ICE cannot
17265 // contain an lvalue operand.
17266 return ICEDiag(IK_NotICE, E->getBeginLoc());
17267
17268 case BO_Mul:
17269 case BO_Div:
17270 case BO_Rem:
17271 case BO_Add:
17272 case BO_Sub:
17273 case BO_Shl:
17274 case BO_Shr:
17275 case BO_LT:
17276 case BO_GT:
17277 case BO_LE:
17278 case BO_GE:
17279 case BO_EQ:
17280 case BO_NE:
17281 case BO_And:
17282 case BO_Xor:
17283 case BO_Or:
17284 case BO_Comma:
17285 case BO_Cmp: {
17286 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
17287 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
17288 if (Exp->getOpcode() == BO_Div ||
17289 Exp->getOpcode() == BO_Rem) {
17290 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
17291 // we don't evaluate one.
17292 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
17293 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
17294 if (REval == 0)
17295 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17296 if (REval.isSigned() && REval.isAllOnes()) {
17297 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
17298 if (LEval.isMinSignedValue())
17299 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17300 }
17301 }
17302 }
17303 if (Exp->getOpcode() == BO_Comma) {
17304 if (Ctx.getLangOpts().C99) {
17305 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
17306 // if it isn't evaluated.
17307 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
17308 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17309 } else {
17310 // In both C89 and C++, commas in ICEs are illegal.
17311 return ICEDiag(IK_NotICE, E->getBeginLoc());
17312 }
17313 }
17314 return Worst(LHSResult, RHSResult);
17315 }
17316 case BO_LAnd:
17317 case BO_LOr: {
17318 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
17319 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
17320 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
17321 // Rare case where the RHS has a comma "side-effect"; we need
17322 // to actually check the condition to see whether the side
17323 // with the comma is evaluated.
17324 if ((Exp->getOpcode() == BO_LAnd) !=
17325 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
17326 return RHSResult;
17327 return NoDiag();
17328 }
17329
17330 return Worst(LHSResult, RHSResult);
17331 }
17332 }
17333 llvm_unreachable("invalid binary operator kind");
17334 }
17335 case Expr::ImplicitCastExprClass:
17336 case Expr::CStyleCastExprClass:
17337 case Expr::CXXFunctionalCastExprClass:
17338 case Expr::CXXStaticCastExprClass:
17339 case Expr::CXXReinterpretCastExprClass:
17340 case Expr::CXXConstCastExprClass:
17341 case Expr::ObjCBridgedCastExprClass: {
17342 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
17343 if (isa<ExplicitCastExpr>(E)) {
17344 if (const FloatingLiteral *FL
17345 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
17346 unsigned DestWidth = Ctx.getIntWidth(E->getType());
17347 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
17348 APSInt IgnoredVal(DestWidth, !DestSigned);
17349 bool Ignored;
17350 // If the value does not fit in the destination type, the behavior is
17351 // undefined, so we are not required to treat it as a constant
17352 // expression.
17353 if (FL->getValue().convertToInteger(IgnoredVal,
17354 llvm::APFloat::rmTowardZero,
17355 &Ignored) & APFloat::opInvalidOp)
17356 return ICEDiag(IK_NotICE, E->getBeginLoc());
17357 return NoDiag();
17358 }
17359 }
17360 switch (cast<CastExpr>(E)->getCastKind()) {
17361 case CK_LValueToRValue:
17362 case CK_AtomicToNonAtomic:
17363 case CK_NonAtomicToAtomic:
17364 case CK_NoOp:
17365 case CK_IntegralToBoolean:
17366 case CK_IntegralCast:
17367 return CheckICE(SubExpr, Ctx);
17368 default:
17369 return ICEDiag(IK_NotICE, E->getBeginLoc());
17370 }
17371 }
17372 case Expr::BinaryConditionalOperatorClass: {
17373 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
17374 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
17375 if (CommonResult.Kind == IK_NotICE) return CommonResult;
17376 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
17377 if (FalseResult.Kind == IK_NotICE) return FalseResult;
17378 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
17379 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
17380 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
17381 return FalseResult;
17382 }
17383 case Expr::ConditionalOperatorClass: {
17384 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
17385 // If the condition (ignoring parens) is a __builtin_constant_p call,
17386 // then only the true side is actually considered in an integer constant
17387 // expression, and it is fully evaluated. This is an important GNU
17388 // extension. See GCC PR38377 for discussion.
17389 if (const CallExpr *CallCE
17390 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
17391 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
17392 return CheckEvalInICE(E, Ctx);
17393 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
17394 if (CondResult.Kind == IK_NotICE)
17395 return CondResult;
17396
17397 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
17398 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
17399
17400 if (TrueResult.Kind == IK_NotICE)
17401 return TrueResult;
17402 if (FalseResult.Kind == IK_NotICE)
17403 return FalseResult;
17404 if (CondResult.Kind == IK_ICEIfUnevaluated)
17405 return CondResult;
17406 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
17407 return NoDiag();
17408 // Rare case where the diagnostics depend on which side is evaluated
17409 // Note that if we get here, CondResult is 0, and at least one of
17410 // TrueResult and FalseResult is non-zero.
17411 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
17412 return FalseResult;
17413 return TrueResult;
17414 }
17415 case Expr::CXXDefaultArgExprClass:
17416 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
17417 case Expr::CXXDefaultInitExprClass:
17418 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
17419 case Expr::ChooseExprClass: {
17420 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
17421 }
17422 case Expr::BuiltinBitCastExprClass: {
17423 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
17424 return ICEDiag(IK_NotICE, E->getBeginLoc());
17425 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
17426 }
17427 }
17428
17429 llvm_unreachable("Invalid StmtClass!");
17430}
17431
17432/// Evaluate an expression as a C++11 integral constant expression.
17434 const Expr *E,
17435 llvm::APSInt *Value,
17438 if (Loc) *Loc = E->getExprLoc();
17439 return false;
17440 }
17441
17442 APValue Result;
17443 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
17444 return false;
17445
17446 if (!Result.isInt()) {
17447 if (Loc) *Loc = E->getExprLoc();
17448 return false;
17449 }
17450
17451 if (Value) *Value = Result.getInt();
17452 return true;
17453}
17454
17456 SourceLocation *Loc) const {
17457 assert(!isValueDependent() &&
17458 "Expression evaluator can't be called on a dependent expression.");
17459
17460 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
17461
17462 if (Ctx.getLangOpts().CPlusPlus11)
17463 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
17464
17465 ICEDiag D = CheckICE(this, Ctx);
17466 if (D.Kind != IK_ICE) {
17467 if (Loc) *Loc = D.Loc;
17468 return false;
17469 }
17470 return true;
17471}
17472
17473std::optional<llvm::APSInt>
17475 if (isValueDependent()) {
17476 // Expression evaluator can't succeed on a dependent expression.
17477 return std::nullopt;
17478 }
17479
17480 APSInt Value;
17481
17482 if (Ctx.getLangOpts().CPlusPlus11) {
17484 return Value;
17485 return std::nullopt;
17486 }
17487
17488 if (!isIntegerConstantExpr(Ctx, Loc))
17489 return std::nullopt;
17490
17491 // The only possible side-effects here are due to UB discovered in the
17492 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
17493 // required to treat the expression as an ICE, so we produce the folded
17494 // value.
17496 Expr::EvalStatus Status;
17497 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
17498 Info.InConstantContext = true;
17499
17500 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
17501 llvm_unreachable("ICE cannot be evaluated!");
17502
17503 return ExprResult.Val.getInt();
17504}
17505
17507 assert(!isValueDependent() &&
17508 "Expression evaluator can't be called on a dependent expression.");
17509
17510 return CheckICE(this, Ctx).Kind == IK_ICE;
17511}
17512
17514 SourceLocation *Loc) const {
17515 assert(!isValueDependent() &&
17516 "Expression evaluator can't be called on a dependent expression.");
17517
17518 // We support this checking in C++98 mode in order to diagnose compatibility
17519 // issues.
17520 assert(Ctx.getLangOpts().CPlusPlus);
17521
17522 // Build evaluation settings.
17523 Expr::EvalStatus Status;
17525 Status.Diag = &Diags;
17526 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17527
17528 APValue Scratch;
17529 bool IsConstExpr =
17530 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
17531 // FIXME: We don't produce a diagnostic for this, but the callers that
17532 // call us on arbitrary full-expressions should generally not care.
17533 Info.discardCleanups() && !Status.HasSideEffects;
17534
17535 if (!Diags.empty()) {
17536 IsConstExpr = false;
17537 if (Loc) *Loc = Diags[0].first;
17538 } else if (!IsConstExpr) {
17539 // FIXME: This shouldn't happen.
17540 if (Loc) *Loc = getExprLoc();
17541 }
17542
17543 return IsConstExpr;
17544}
17545
17547 const FunctionDecl *Callee,
17549 const Expr *This) const {
17550 assert(!isValueDependent() &&
17551 "Expression evaluator can't be called on a dependent expression.");
17552
17553 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
17554 std::string Name;
17555 llvm::raw_string_ostream OS(Name);
17556 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
17557 /*Qualified=*/true);
17558 return Name;
17559 });
17560
17561 Expr::EvalStatus Status;
17562 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
17563 Info.InConstantContext = true;
17564
17565 LValue ThisVal;
17566 const LValue *ThisPtr = nullptr;
17567 if (This) {
17568#ifndef NDEBUG
17569 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
17570 assert(MD && "Don't provide `this` for non-methods.");
17571 assert(MD->isImplicitObjectMemberFunction() &&
17572 "Don't provide `this` for methods without an implicit object.");
17573#endif
17574 if (!This->isValueDependent() &&
17575 EvaluateObjectArgument(Info, This, ThisVal) &&
17576 !Info.EvalStatus.HasSideEffects)
17577 ThisPtr = &ThisVal;
17578
17579 // Ignore any side-effects from a failed evaluation. This is safe because
17580 // they can't interfere with any other argument evaluation.
17581 Info.EvalStatus.HasSideEffects = false;
17582 }
17583
17584 CallRef Call = Info.CurrentCall->createCall(Callee);
17585 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
17586 I != E; ++I) {
17587 unsigned Idx = I - Args.begin();
17588 if (Idx >= Callee->getNumParams())
17589 break;
17590 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
17591 if ((*I)->isValueDependent() ||
17592 !EvaluateCallArg(PVD, *I, Call, Info) ||
17593 Info.EvalStatus.HasSideEffects) {
17594 // If evaluation fails, throw away the argument entirely.
17595 if (APValue *Slot = Info.getParamSlot(Call, PVD))
17596 *Slot = APValue();
17597 }
17598
17599 // Ignore any side-effects from a failed evaluation. This is safe because
17600 // they can't interfere with any other argument evaluation.
17601 Info.EvalStatus.HasSideEffects = false;
17602 }
17603
17604 // Parameter cleanups happen in the caller and are not part of this
17605 // evaluation.
17606 Info.discardCleanups();
17607 Info.EvalStatus.HasSideEffects = false;
17608
17609 // Build fake call to Callee.
17610 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
17611 Call);
17612 // FIXME: Missing ExprWithCleanups in enable_if conditions?
17613 FullExpressionRAII Scope(Info);
17614 return Evaluate(Value, Info, this) && Scope.destroy() &&
17615 !Info.EvalStatus.HasSideEffects;
17616}
17617
17620 PartialDiagnosticAt> &Diags) {
17621 // FIXME: It would be useful to check constexpr function templates, but at the
17622 // moment the constant expression evaluator cannot cope with the non-rigorous
17623 // ASTs which we build for dependent expressions.
17624 if (FD->isDependentContext())
17625 return true;
17626
17627 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
17628 std::string Name;
17629 llvm::raw_string_ostream OS(Name);
17631 /*Qualified=*/true);
17632 return Name;
17633 });
17634
17635 Expr::EvalStatus Status;
17636 Status.Diag = &Diags;
17637
17638 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
17639 Info.InConstantContext = true;
17640 Info.CheckingPotentialConstantExpression = true;
17641
17642 // The constexpr VM attempts to compile all methods to bytecode here.
17643 if (Info.EnableNewConstInterp) {
17644 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
17645 return Diags.empty();
17646 }
17647
17648 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
17649 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
17650
17651 // Fabricate an arbitrary expression on the stack and pretend that it
17652 // is a temporary being used as the 'this' pointer.
17653 LValue This;
17654 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
17655 This.set({&VIE, Info.CurrentCall->Index});
17656
17658
17659 APValue Scratch;
17660 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
17661 // Evaluate the call as a constant initializer, to allow the construction
17662 // of objects of non-literal types.
17663 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
17664 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
17665 } else {
17668 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
17669 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
17670 /*ResultSlot=*/nullptr);
17671 }
17672
17673 return Diags.empty();
17674}
17675
17677 const FunctionDecl *FD,
17679 PartialDiagnosticAt> &Diags) {
17680 assert(!E->isValueDependent() &&
17681 "Expression evaluator can't be called on a dependent expression.");
17682
17683 Expr::EvalStatus Status;
17684 Status.Diag = &Diags;
17685
17686 EvalInfo Info(FD->getASTContext(), Status,
17687 EvalInfo::EM_ConstantExpressionUnevaluated);
17688 Info.InConstantContext = true;
17689 Info.CheckingPotentialConstantExpression = true;
17690
17691 // Fabricate a call stack frame to give the arguments a plausible cover story.
17692 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
17693 /*CallExpr=*/nullptr, CallRef());
17694
17695 APValue ResultScratch;
17696 Evaluate(ResultScratch, Info, E);
17697 return Diags.empty();
17698}
17699
17700bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
17701 unsigned Type) const {
17702 if (!getType()->isPointerType())
17703 return false;
17704
17705 Expr::EvalStatus Status;
17706 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17707 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
17708}
17709
17710static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
17711 EvalInfo &Info, std::string *StringResult) {
17712 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
17713 return false;
17714
17715 LValue String;
17716
17717 if (!EvaluatePointer(E, String, Info))
17718 return false;
17719
17720 QualType CharTy = E->getType()->getPointeeType();
17721
17722 // Fast path: if it's a string literal, search the string value.
17723 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
17724 String.getLValueBase().dyn_cast<const Expr *>())) {
17725 StringRef Str = S->getBytes();
17726 int64_t Off = String.Offset.getQuantity();
17727 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
17728 S->getCharByteWidth() == 1 &&
17729 // FIXME: Add fast-path for wchar_t too.
17730 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
17731 Str = Str.substr(Off);
17732
17733 StringRef::size_type Pos = Str.find(0);
17734 if (Pos != StringRef::npos)
17735 Str = Str.substr(0, Pos);
17736
17737 Result = Str.size();
17738 if (StringResult)
17739 *StringResult = Str;
17740 return true;
17741 }
17742
17743 // Fall through to slow path.
17744 }
17745
17746 // Slow path: scan the bytes of the string looking for the terminating 0.
17747 for (uint64_t Strlen = 0; /**/; ++Strlen) {
17748 APValue Char;
17749 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
17750 !Char.isInt())
17751 return false;
17752 if (!Char.getInt()) {
17753 Result = Strlen;
17754 return true;
17755 } else if (StringResult)
17756 StringResult->push_back(Char.getInt().getExtValue());
17757 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
17758 return false;
17759 }
17760}
17761
17762std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
17763 Expr::EvalStatus Status;
17764 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17765 uint64_t Result;
17766 std::string StringResult;
17767
17768 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
17769 return StringResult;
17770 return {};
17771}
17772
17773bool Expr::EvaluateCharRangeAsString(std::string &Result,
17774 const Expr *SizeExpression,
17775 const Expr *PtrExpression, ASTContext &Ctx,
17776 EvalResult &Status) const {
17777 LValue String;
17778 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17779 Info.InConstantContext = true;
17780
17781 FullExpressionRAII Scope(Info);
17782 APSInt SizeValue;
17783 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
17784 return false;
17785
17786 uint64_t Size = SizeValue.getZExtValue();
17787
17788 if (!::EvaluatePointer(PtrExpression, String, Info))
17789 return false;
17790
17791 QualType CharTy = PtrExpression->getType()->getPointeeType();
17792 for (uint64_t I = 0; I < Size; ++I) {
17793 APValue Char;
17794 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
17795 Char))
17796 return false;
17797
17798 APSInt C = Char.getInt();
17799 Result.push_back(static_cast<char>(C.getExtValue()));
17800 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
17801 return false;
17802 }
17803 if (!Scope.destroy())
17804 return false;
17805
17806 if (!CheckMemoryLeaks(Info))
17807 return false;
17808
17809 return true;
17810}
17811
17812bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
17813 Expr::EvalStatus Status;
17814 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17815 return EvaluateBuiltinStrLen(this, Result, Info);
17816}
17817
17818namespace {
17819struct IsWithinLifetimeHandler {
17820 EvalInfo &Info;
17821 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
17822 using result_type = std::optional<bool>;
17823 std::optional<bool> failed() { return std::nullopt; }
17824 template <typename T>
17825 std::optional<bool> found(T &Subobj, QualType SubobjType) {
17826 return true;
17827 }
17828};
17829
17830std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
17831 const CallExpr *E) {
17832 EvalInfo &Info = IEE.Info;
17833 // Sometimes this is called during some sorts of constant folding / early
17834 // evaluation. These are meant for non-constant expressions and are not
17835 // necessary since this consteval builtin will never be evaluated at runtime.
17836 // Just fail to evaluate when not in a constant context.
17837 if (!Info.InConstantContext)
17838 return std::nullopt;
17839 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
17840 const Expr *Arg = E->getArg(0);
17841 if (Arg->isValueDependent())
17842 return std::nullopt;
17843 LValue Val;
17844 if (!EvaluatePointer(Arg, Val, Info))
17845 return std::nullopt;
17846
17847 auto Error = [&](int Diag) {
17848 bool CalledFromStd = false;
17849 const auto *Callee = Info.CurrentCall->getCallee();
17850 if (Callee && Callee->isInStdNamespace()) {
17851 const IdentifierInfo *Identifier = Callee->getIdentifier();
17852 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
17853 }
17854 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
17855 : E->getExprLoc(),
17856 diag::err_invalid_is_within_lifetime)
17857 << (CalledFromStd ? "std::is_within_lifetime"
17858 : "__builtin_is_within_lifetime")
17859 << Diag;
17860 return std::nullopt;
17861 };
17862 // C++2c [meta.const.eval]p4:
17863 // During the evaluation of an expression E as a core constant expression, a
17864 // call to this function is ill-formed unless p points to an object that is
17865 // usable in constant expressions or whose complete object's lifetime began
17866 // within E.
17867
17868 // Make sure it points to an object
17869 // nullptr does not point to an object
17870 if (Val.isNullPointer() || Val.getLValueBase().isNull())
17871 return Error(0);
17872 QualType T = Val.getLValueBase().getType();
17873 assert(!T->isFunctionType() &&
17874 "Pointers to functions should have been typed as function pointers "
17875 "which would have been rejected earlier");
17876 assert(T->isObjectType());
17877 // Hypothetical array element is not an object
17878 if (Val.getLValueDesignator().isOnePastTheEnd())
17879 return Error(1);
17880 assert(Val.getLValueDesignator().isValidSubobject() &&
17881 "Unchecked case for valid subobject");
17882 // All other ill-formed values should have failed EvaluatePointer, so the
17883 // object should be a pointer to an object that is usable in a constant
17884 // expression or whose complete lifetime began within the expression
17885 CompleteObject CO =
17886 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
17887 // The lifetime hasn't begun yet if we are still evaluating the
17888 // initializer ([basic.life]p(1.2))
17889 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
17890 return Error(2);
17891
17892 if (!CO)
17893 return false;
17894 IsWithinLifetimeHandler handler{Info};
17895 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
17896}
17897} // namespace
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3443
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.
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
const Decl * D
IndirectLocalPath & Path
Expr * E
enum clang::sema::@1718::IndirectLocalPathEntry::EntryKind Kind
llvm::APSInt APSInt
Definition: Compiler.cpp:23
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1172
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC's builtin.
static bool isRead(AccessKinds AK)
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, EvalInfo &Info, std::string *StringResult=nullptr)
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 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 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.
static ICEDiag Worst(ICEDiag A, ICEDiag B)
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, const VarDecl *VD, CallStackFrame *Frame, unsigned Version, APValue *&Result)
Try to evaluate the initializer for a variable declaration.
static bool handleDefaultInitValue(QualType T, APValue &Result)
Get the value to use for a default-initialized object of type T.
static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, uint64_t Size, uint64_t Idx)
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base)
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const LValue &LVal, ConstantExprKind Kind, CheckedTemporaries &CheckedTemps)
Check that this reference or pointer core constant expression is a valid value for an address or refe...
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, const APSInt &LHS, const APSInt &RHS, unsigned BitWidth, Operation Op, APSInt &Result)
Perform the given integer operation, which is known to need at most BitWidth bits,...
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info)
Evaluate an expression of record type as a temporary.
static bool EvaluateArray(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, APValue &Value, const FieldDecl *FD)
static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E, QualType ElemType, APValue const &VecVal1, APValue const &VecVal2, unsigned EltNum, APValue &Result)
static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static const ValueDecl * HandleMemberPointerAccess(EvalInfo &Info, QualType LVType, LValue &LV, const Expr *RHS, bool IncludeMember=true)
HandleMemberPointerAccess - Evaluate a member access operation and build an lvalue referring to the r...
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, LValue &Result)
HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on the provided lvalue,...
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info)
static bool IsOpaqueConstantCall(const CallExpr *E)
Should this call expression be treated as forming an opaque constant?
static bool CheckMemberPointerConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Member pointers are constant expressions unless they point to a non-virtual dllimport member function...
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal, APValue &RVal, bool WantObjectRepresentation=false)
Perform an lvalue-to-rvalue conversion on the given glvalue.
static bool refersToCompleteObject(const LValue &LVal)
Tests to see if the LValue has a user-specified designator (that isn't necessarily valid).
static bool AreElementsOfSameArray(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B)
Determine whether the given subobject designators refer to elements of the same array object.
static bool 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)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool isModification(AccessKinds AK)
static bool handleCompareOpForVector(const APValue &LHSValue, BinaryOperatorKind Opcode, const APValue &RHSValue, APInt &Result)
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
static bool 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 CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T, UnaryExprOrTypeTrait ExprKind)
static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, APValue &Val, APSInt &Alignment)
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, APSInt Adjustment)
Update a pointer value to model pointer arithmetic.
static bool extractSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &Result, AccessKinds AK=AK_Read)
Extract the designated sub-object of an rvalue.
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, const FieldDecl *FD, const ASTRecordLayout *RL=nullptr)
Update LVal to refer to the given field, which must be a member of the type currently described by LV...
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, bool IsSub)
static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD)
void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, const Expr *E, APValue &Result, bool CopyObjectRepresentation)
Perform a trivial copy from Param, which is the parameter of a copy or move constructor or assignment...
static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, APFloat::opStatus St)
Check if the given evaluation result is allowed for constant evaluation.
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV)
EvaluateBuiltinConstantPForLValue - Determine the result of __builtin_constant_p when applied to the ...
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg)
EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to GCC as we can manage.
static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, const LValue &This, const CXXMethodDecl *NamedMember)
Check that the pointee of the 'this' pointer in a member function call is either within its lifetime ...
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Check that this core constant expression value is a valid value for a constant expression.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
static std::optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
static 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.
void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, uint64_t &Size)
Tries to evaluate the __builtin_object_size for E.
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 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 SubobjectHandler::result_type findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, SubobjectHandler &handler)
Find the designated sub-object of an rvalue.
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, unsigned Type, const LValue &LVal, CharUnits &EndOffset)
Helper for tryEvaluateBuiltinObjectSize – Given an LValue, this will determine how many bytes exist f...
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, CharUnits &Result)
Converts the given APInt to CharUnits, assuming the APInt is unsigned.
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 GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal, LValueBaseString &AsString)
static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E)
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info)
EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and produce either the intege...
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, LValue &Ptr)
Apply the given dynamic cast operation on the provided lvalue.
static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, LValue &Result)
Perform a call to 'operator new' or to ‘__builtin_operator_new’.
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result)
static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, const LValue &LHS)
Handle a builtin simple-assignment or a call to a trivial assignment operator whose left-hand side mi...
static bool isFormalAccess(AccessKinds AK)
Is this an access per the C++ definition?
static bool handleCompoundAssignment(EvalInfo &Info, const CompoundAssignOperator *E, const LValue &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, const APValue &RVal)
Perform a compound assignment of LVal <op>= RVal.
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, bool IsIncrement, APValue *Old)
Perform an increment or decrement on LVal.
static ICEDiag NoDiag()
static bool EvaluateVoid(const Expr *E, EvalInfo &Info)
static bool HandleDestruction(EvalInfo &Info, const Expr *E, const LValue &This, QualType ThisType)
Perform a destructor or pseudo-destructor call on the given object, which might in general not be a c...
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T)
static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info, const LValue &LHS, const LValue &RHS)
StringRef Identifier
Definition: Format.cpp:3040
const CFGBlock * Block
Definition: HTMLLogger.cpp:152
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic which may not be emitted.
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition: ParentMap.cpp:21
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
SourceLocation Loc
Definition: SemaObjC.cpp:759
bool Indirect
Definition: SemaObjC.cpp:760
static QualType getPointeeType(const MemRegion *R)
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the clang::TypeLoc interface and its subclasses.
__DEVICE__ long long abs(long long __n)
__device__ int
#define bool
Definition: amdgpuintrin.h:20
do v
Definition: arm_acle.h:91
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:206
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition: APValue.h:214
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool hasArrayFiller() const
Definition: APValue.h:560
const LValueBase getLValueBase() const
Definition: APValue.cpp:973
APValue & getArrayInitializedElt(unsigned I)
Definition: APValue.h:552
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition: APValue.cpp:468
APSInt & getInt()
Definition: APValue.h:465
APValue & getStructField(unsigned i)
Definition: APValue.h:593
const FieldDecl * getUnionField() const
Definition: APValue.h:605
bool isVector() const
Definition: APValue.h:449
APSInt & getComplexIntImag()
Definition: APValue.h:503
bool isAbsent() const
Definition: APValue.h:439
bool isComplexInt() const
Definition: APValue.h:446
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:203
ValueKind getKind() const
Definition: APValue.h:437
unsigned getArrayInitializedElts() const
Definition: APValue.h:571
static APValue IndeterminateValue()
Definition: APValue.h:408
bool isFloat() const
Definition: APValue.h:444
APFixedPoint & getFixedPoint()
Definition: APValue.h:487
bool hasValue() const
Definition: APValue.h:441
bool hasLValuePath() const
Definition: APValue.cpp:988
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1056
APValue & getUnionValue()
Definition: APValue.h:609
CharUnits & getLValueOffset()
Definition: APValue.cpp:983
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:693
bool isComplexFloat() const
Definition: APValue.h:447
APValue & getVectorElt(unsigned I)
Definition: APValue.h:539
APValue & getArrayFiller()
Definition: APValue.h:563
unsigned getVectorLength() const
Definition: APValue.h:547
bool isLValue() const
Definition: APValue.h:448
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition: APValue.cpp:1049
bool isIndeterminate() const
Definition: APValue.h:440
bool isInt() const
Definition: APValue.h:443
unsigned getArraySize() const
Definition: APValue.h:575
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
bool isFixedPoint() const
Definition: APValue.h:445
@ 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:451
APSInt & getComplexIntReal()
Definition: APValue.h:495
APFloat & getComplexFloatImag()
Definition: APValue.h:519
APFloat & getComplexFloatReal()
Definition: APValue.h:511
APFloat & getFloat()
Definition: APValue.h:479
APValue & getStructBase(unsigned i)
Definition: APValue.h:588
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
SourceManager & getSourceManager()
Definition: ASTContext.h:741
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
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,...
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
Definition: ASTContext.h:2573
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:834
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:2413
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
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:2482
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
Definition: ASTContext.h:3175
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2486
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:4421
LabelDecl * getLabel() const
Definition: Expr.h:4444
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition: Expr.h:5805
Represents a loop initializing the elements of an array.
Definition: Expr.h:5752
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2718
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition: ExprCXX.h:2853
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
QualType getElementType() const
Definition: Type.h:3589
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7761
Attr - This represents one attribute.
Definition: Attr.h:43
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4324
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition: Expr.h:4378
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition: Expr.h:4359
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
Expr * getLHS() const
Definition: Expr.h:3959
bool isComparisonOp() const
Definition: Expr.h:4010
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition: Expr.h:4056
bool isLogicalOp() const
Definition: Expr.h:4043
Expr * getRHS() const
Definition: Expr.h:3961
Opcode getOpcode() const
Definition: Expr.h:3954
A binding in a decomposition declaration.
Definition: DeclCXX.h:4125
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition: ExprCXX.h:5298
This class is used for builtin types like 'int'.
Definition: Type.h:3034
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:1491
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2845
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition: DeclCXX.h:2638
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1268
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1375
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2498
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
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:1737
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
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:2549
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:2556
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2657
bool isInstance() const
Definition: DeclCXX.h:2105
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2582
bool isStatic() const
Definition: DeclCXX.cpp:2280
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2560
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition: DeclCXX.cpp:2693
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2241
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:4126
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:4960
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:1245
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1629
base_class_iterator bases_end()
Definition: DeclCXX.h:629
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1378
base_class_range bases()
Definition: DeclCXX.h:620
capture_const_iterator captures_end() const
Definition: DeclCXX.h:1119
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:1735
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
base_class_iterator bases_begin()
Definition: DeclCXX.h:627
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1198
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2069
capture_const_iterator captures_begin() const
Definition: DeclCXX.h:1113
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1688
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:635
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
An expression "T()" which creates an rvalue of a non-class type T.
Definition: ExprCXX.h:2182
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:1152
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:845
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1066
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1577
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3047
Decl * getCalleeDecl()
Definition: Expr.h:3041
CaseStmt - Represent a case statement.
Definition: Stmt.h:1828
Expr * getLHS()
Definition: Stmt.h:1915
Expr * getRHS()
Definition: Stmt.h:1927
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3547
const CXXBaseSpecifier *const * path_const_iterator
Definition: Expr.h:3614
Expr * getSubExpr()
Definition: Expr.h:3597
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
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4641
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:3145
QualType getElementType() const
Definition: Type.h:3155
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4171
QualType getComputationLHSType() const
Definition: Expr.h:4205
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3477
bool isFileScope() const
Definition: Expr.h:3504
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1628
bool body_empty() const
Definition: Stmt.h:1672
Stmt *const * const_body_iterator
Definition: Stmt.h:1700
body_iterator body_end()
Definition: Stmt.h:1693
body_range body()
Definition: Stmt.h:1691
body_iterator body_begin()
Definition: Stmt.h:1692
Represents the specialization of a concept - evaluates to a prvalue of type bool.
Definition: ExprConcepts.h:42
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4262
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4294
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4285
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4289
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:3615
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition: Type.h:3678
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:205
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:245
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:3704
bool isZeroSize() const
Return true if the size is zero.
Definition: Type.h:3685
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: Type.h:3711
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3671
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3691
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1077
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4582
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:2369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1519
decl_range decls()
Definition: Stmt.h:1567
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:422
static void add(Kind k)
Definition: DeclBase.cpp:221
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:520
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
DeclContext * getDeclContext()
Definition: DeclBase.h:451
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
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:4184
Designator - A designator in a C99 designated initializer.
Definition: Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition: Stmt.h:2752
Stmt * getBody()
Definition: Stmt.h:2777
Expr * getCond()
Definition: Stmt.h:2770
Symbolic representation of a dynamic allocation.
Definition: APValue.h:65
static unsigned getMaxIndex()
Definition: APValue.h:85
Represents a reference to #emded data.
Definition: Expr.h:4916
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3277
Represents an enum.
Definition: Decl.h:3847
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4044
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4061
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4007
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:4996
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6098
EnumDecl * getDecl() const
Definition: Type.h:6105
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3799
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3474
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:3095
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:3886
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3090
bool containsErrors() const
Whether this expression contains subexpressions which had errors, 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:3086
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
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
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:3587
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
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:3224
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:2924
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:6354
bool isFPConstrained() const
Definition: LangOptions.h:906
LangOptions::FPExceptionModeKind getExceptionMode() const
Definition: LangOptions.h:924
RoundingMode getRoundingMode() const
Definition: LangOptions.h:912
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3124
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4654
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4602
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3250
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3261
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:101
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2808
Represents a function declaration or definition.
Definition: Decl.h:1935
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3243
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4064
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4052
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2305
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4188
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition: Decl.h:2658
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
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:3372
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2313
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:3088
Declaration of a template function.
Definition: DeclTemplate.h:959
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:4716
Represents a C11 generic selection.
Definition: Expr.h:5966
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:2165
Stmt * getThen()
Definition: Stmt.h:2254
Stmt * getInit()
Definition: Stmt.h:2315
bool isNonNegatedConsteval() const
Definition: Stmt.h:2350
Expr * getCond()
Definition: Stmt.h:2242
Stmt * getElse()
Definition: Stmt.h:2263
bool isConsteval() const
Definition: Stmt.h:2345
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition: Stmt.cpp:989
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1717
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5841
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3321
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3343
Describes an C or C++ initializer list.
Definition: Expr.h:5088
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
A global _GUID constant.
Definition: DeclCXX.h:4307
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4734
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
This represents a decl that may have a name.
Definition: Decl.h:253
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
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:1675
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:87
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:127
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:2519
Expr * getIndexExpr(unsigned Idx)
Definition: Expr.h:2580
const OffsetOfNode & getComponent(unsigned Idx) const
Definition: Expr.h:2566
TypeSourceInfo * getTypeSourceInfo() const
Definition: Expr.h:2559
unsigned getNumComponents() const
Definition: Expr.h:2576
Helper class for OffsetOfExpr.
Definition: Expr.h:2413
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition: Expr.h:2471
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition: Expr.h:2477
@ Array
An index into an array.
Definition: Expr.h:2418
@ Identifier
A field in a dependent type, known only by its name.
Definition: Expr.h:2422
@ Field
A field.
Definition: Expr.h:2420
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition: Expr.h:2425
Kind getKind() const
Determine what kind of offsetof node this is.
Definition: Expr.h:2467
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition: Expr.h:2487
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
This expression type represents an asterisk in an OpenACC Size-Expr, used in the 'tile' and 'gang' cl...
Definition: Expr.h:2078
A partial diagnostic which we might know in advance that we are not going to emit.
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2170
Represents a parameter to a function.
Definition: Decl.h:1725
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1785
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1991
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6546
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8015
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:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7931
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:1089
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:8134
QualType getCanonicalType() const
Definition: Type.h:7983
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8025
void removeLocalVolatile()
Definition: Type.h:8047
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:8039
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8004
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7977
Represents a struct/union/class.
Definition: Decl.h:4148
bool hasFlexibleArrayMember() const
Definition: Decl.h:4181
field_iterator field_end() const
Definition: Decl.h:4357
field_range fields() const
Definition: Decl.h:4354
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4200
bool field_empty() const
Definition: Decl.h:4362
field_iterator field_begin() const
Definition: Decl.cpp:5092
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
RecordDecl * getDecl() const
Definition: Type.h:6082
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:502
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:4514
Represents an expression that computes the length of a parameter pack.
Definition: ExprCXX.h:4258
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4810
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:4466
Stmt - This represents one statement.
Definition: Stmt.h:84
StmtClass getStmtClass() const
Definition: Stmt.h:1380
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:333
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1870
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:1187
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4490
const SwitchCase * getNextSwitchCase() const
Definition: Stmt.h:1801
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:2415
Expr * getCond()
Definition: Stmt.h:2478
Stmt * getBody()
Definition: Stmt.h:2490
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition: Stmt.cpp:1107
Stmt * getInit()
Definition: Stmt.h:2499
SwitchCase * getSwitchCaseList()
Definition: Stmt.h:2552
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4749
bool isUnion() const
Definition: Decl.h:3770
virtual bool isNan2008() const
Returns true if NaN encoding is IEEE 754-2008.
Definition: TargetInfo.h:1257
A template argument list.
Definition: DeclTemplate.h:250
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:286
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
@ 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:7913
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition: ExprCXX.h:2768
The base class of the type hierarchy.
Definition: Type.h:1828
bool isStructureType() const
Definition: Type.cpp:662
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isVoidType() const
Definition: Type.h:8510
bool isBooleanType() const
Definition: Type.h:8638
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2201
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2937
bool isIncompleteArrayType() const
Definition: Type.h:8266
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2180
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:710
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8809
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2251
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2105
bool isConstantArrayType() const
Definition: Type.h:8262
bool isNothrowT() const
Definition: Type.cpp:3106
bool isVoidPointerType() const
Definition: Type.cpp:698
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2386
bool isArrayType() const
Definition: Type.h:8258
bool isCharType() const
Definition: Type.cpp:2123
bool isFunctionPointerType() const
Definition: Type.h:8226
bool isPointerType() const
Definition: Type.h:8186
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8550
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isReferenceType() const
Definition: Type.h:8204
bool isEnumeralType() const
Definition: Type.h:8290
bool isVariableArrayType() const
Definition: Type.h:8270
bool isChar8Type() const
Definition: Type.cpp:2139
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2554
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8625
bool isExtVectorBoolType() const
Definition: Type.h:8306
bool isMemberDataPointerType() const
Definition: Type.h:8251
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8479
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isAnyComplexType() const
Definition: Type.h:8294
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8563
const RecordType * getAsStructureType() const
Definition: Type.cpp:754
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8681
bool isMemberPointerType() const
Definition: Type.h:8240
bool isAtomicType() const
Definition: Type.h:8341
bool isComplexIntegerType() const
Definition: Type.cpp:716
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8786
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2446
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8182
bool isVectorType() const
Definition: Type.h:8298
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2300
bool isFloatingType() const
Definition: Type.cpp:2283
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:2230
bool isAnyPointerType() const
Definition: Type.h:8194
TypeClass getTypeClass() const
Definition: Type.h:2341
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
bool isNullPtrType() const
Definition: Type.h:8543
bool isRecordType() const
Definition: Type.h:8286
bool isUnionType() const
Definition: Type.cpp:704
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2513
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:8672
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1920
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2622
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition: Expr.h:2691
UnaryExprOrTypeTrait getKind() const
Definition: Expr.h:2654
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
Expr * getSubExpr() const
Definition: Expr.h:2277
Opcode getOpcode() const
Definition: Expr.h:2272
static bool isIncrementOp(Opcode Op)
Definition: Expr.h:2318
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4364
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
QualType getType() const
Definition: Decl.h:682
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5388
QualType getType() const
Definition: Value.cpp:234
bool hasValue() const
Definition: Value.h:135
Represents a variable declaration or definition.
Definition: Decl.h:882
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1513
bool hasInit() const
Definition: Decl.cpp:2387
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition: Decl.cpp:2608
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1522
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2547
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition: Decl.cpp:2853
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition: Decl.cpp:2620
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2355
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:2458
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:1159
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1128
const Expr * getInit() const
Definition: Decl.h:1319
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:2600
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1135
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2364
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1204
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:2500
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1309
Represents a GCC generic vector type.
Definition: Type.h:4034
unsigned getNumElements() const
Definition: Type.h:4049
QualType getElementType() const
Definition: Type.h:4048
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2611
Expr * getCond()
Definition: Stmt.h:2663
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition: Stmt.cpp:1168
Stmt * getBody()
Definition: Stmt.h:2675
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:57
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:180
uint32_t Literal
Literals are represented as positive integers.
Definition: CNFFormula.h:35
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:3869
llvm::APFloat APFloat
Definition: Floating.h:23
llvm::APInt APInt
Definition: FixedPoint.h:19
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1157
llvm::FixedPointSemantics FixedPointSemantics
Definition: Interp.h:43
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2445
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2408
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Definition: Interp.h:2938
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:204
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:38
@ TSCS_unspecified
Definition: Specifiers.h:236
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:41
@ CSK_ArrayToPointer
Definition: State.h:45
@ CSK_Derived
Definition: State.h:43
@ CSK_Base
Definition: State.h:42
@ CSK_Real
Definition: State.h:47
@ CSK_ArrayIndex
Definition: State.h:46
@ CSK_Imag
Definition: State.h:48
@ CSK_VectorElement
Definition: State.h:49
@ CSK_Field
Definition: State.h:44
@ SD_Static
Static storage duration.
Definition: Specifiers.h:331
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition: Specifiers.h:328
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_IsWithinLifetime
Definition: State.h:37
@ 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:135
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1274
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:124
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
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
std::string ObjCEncodeStorage
Represents an element in a path from a derived class to a base class.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h: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