1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // Constant expression evaluation produces four main results:
12 //
13 //  * A success/failure flag indicating whether constant folding was successful.
14 //    This is the 'bool' return value used by most of the code in this file. A
15 //    'false' return value indicates that constant folding has failed, and any
16 //    appropriate diagnostic has already been produced.
17 //
18 //  * An evaluated result, valid only if constant folding has not failed.
19 //
20 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 //    where it is possible to determine the evaluated result regardless.
23 //
24 //  * A set of notes indicating why the evaluation was not a constant expression
25 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 //    too, why the expression could not be folded.
27 //
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "ExprConstShared.h"
36 #include "Interp/Context.h"
37 #include "Interp/Frame.h"
38 #include "Interp/State.h"
39 #include "clang/AST/APValue.h"
40 #include "clang/AST/ASTContext.h"
41 #include "clang/AST/ASTDiagnostic.h"
42 #include "clang/AST/ASTLambda.h"
43 #include "clang/AST/Attr.h"
44 #include "clang/AST/CXXInheritance.h"
45 #include "clang/AST/CharUnits.h"
46 #include "clang/AST/CurrentSourceLocExprScope.h"
47 #include "clang/AST/Expr.h"
48 #include "clang/AST/OSLog.h"
49 #include "clang/AST/OptionalDiagnostic.h"
50 #include "clang/AST/RecordLayout.h"
51 #include "clang/AST/StmtVisitor.h"
52 #include "clang/AST/TypeLoc.h"
53 #include "clang/Basic/Builtins.h"
54 #include "clang/Basic/DiagnosticSema.h"
55 #include "clang/Basic/TargetInfo.h"
56 #include "llvm/ADT/APFixedPoint.h"
57 #include "llvm/ADT/SmallBitVector.h"
58 #include "llvm/ADT/StringExtras.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/SaveAndRestore.h"
61 #include "llvm/Support/TimeProfiler.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include <cstring>
64 #include <functional>
65 #include <optional>
66 
67 #define DEBUG_TYPE "exprconstant"
68 
69 using namespace clang;
70 using llvm::APFixedPoint;
71 using llvm::APInt;
72 using llvm::APSInt;
73 using llvm::APFloat;
74 using llvm::FixedPointSemantics;
75 
76 namespace {
77   struct LValue;
78   class CallStackFrame;
79   class EvalInfo;
80 
81   using SourceLocExprScopeGuard =
82       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
83 
getType(APValue::LValueBase B)84   static QualType getType(APValue::LValueBase B) {
85     return B.getType();
86   }
87 
88   /// Get an LValue path entry, which is known to not be an array index, as a
89   /// field declaration.
getAsField(APValue::LValuePathEntry E)90   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
91     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
92   }
93   /// Get an LValue path entry, which is known to not be an array index, as a
94   /// base class declaration.
getAsBaseClass(APValue::LValuePathEntry E)95   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
96     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
97   }
98   /// Determine whether this LValue path entry for a base class names a virtual
99   /// base class.
isVirtualBaseClass(APValue::LValuePathEntry E)100   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
101     return E.getAsBaseOrMember().getInt();
102   }
103 
104   /// Given an expression, determine the type used to store the result of
105   /// evaluating that expression.
getStorageType(const ASTContext & Ctx,const Expr * E)106   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
107     if (E->isPRValue())
108       return E->getType();
109     return Ctx.getLValueReferenceType(E->getType());
110   }
111 
112   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
getAllocSizeAttr(const CallExpr * CE)113   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
114     if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
115       return DirectCallee->getAttr<AllocSizeAttr>();
116     if (const Decl *IndirectCallee = CE->getCalleeDecl())
117       return IndirectCallee->getAttr<AllocSizeAttr>();
118     return nullptr;
119   }
120 
121   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
122   /// This will look through a single cast.
123   ///
124   /// Returns null if we couldn't unwrap a function with alloc_size.
tryUnwrapAllocSizeCall(const Expr * E)125   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
126     if (!E->getType()->isPointerType())
127       return nullptr;
128 
129     E = E->IgnoreParens();
130     // If we're doing a variable assignment from e.g. malloc(N), there will
131     // probably be a cast of some kind. In exotic cases, we might also see a
132     // top-level ExprWithCleanups. Ignore them either way.
133     if (const auto *FE = dyn_cast<FullExpr>(E))
134       E = FE->getSubExpr()->IgnoreParens();
135 
136     if (const auto *Cast = dyn_cast<CastExpr>(E))
137       E = Cast->getSubExpr()->IgnoreParens();
138 
139     if (const auto *CE = dyn_cast<CallExpr>(E))
140       return getAllocSizeAttr(CE) ? CE : nullptr;
141     return nullptr;
142   }
143 
144   /// Determines whether or not the given Base contains a call to a function
145   /// with the alloc_size attribute.
isBaseAnAllocSizeCall(APValue::LValueBase Base)146   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
147     const auto *E = Base.dyn_cast<const Expr *>();
148     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
149   }
150 
151   /// Determines whether the given kind of constant expression is only ever
152   /// used for name mangling. If so, it's permitted to reference things that we
153   /// can't generate code for (in particular, dllimported functions).
isForManglingOnly(ConstantExprKind Kind)154   static bool isForManglingOnly(ConstantExprKind Kind) {
155     switch (Kind) {
156     case ConstantExprKind::Normal:
157     case ConstantExprKind::ClassTemplateArgument:
158     case ConstantExprKind::ImmediateInvocation:
159       // Note that non-type template arguments of class type are emitted as
160       // template parameter objects.
161       return false;
162 
163     case ConstantExprKind::NonClassTemplateArgument:
164       return true;
165     }
166     llvm_unreachable("unknown ConstantExprKind");
167   }
168 
isTemplateArgument(ConstantExprKind Kind)169   static bool isTemplateArgument(ConstantExprKind Kind) {
170     switch (Kind) {
171     case ConstantExprKind::Normal:
172     case ConstantExprKind::ImmediateInvocation:
173       return false;
174 
175     case ConstantExprKind::ClassTemplateArgument:
176     case ConstantExprKind::NonClassTemplateArgument:
177       return true;
178     }
179     llvm_unreachable("unknown ConstantExprKind");
180   }
181 
182   /// The bound to claim that an array of unknown bound has.
183   /// The value in MostDerivedArraySize is undefined in this case. So, set it
184   /// to an arbitrary value that's likely to loudly break things if it's used.
185   static const uint64_t AssumedSizeForUnsizedArray =
186       std::numeric_limits<uint64_t>::max() / 2;
187 
188   /// Determines if an LValue with the given LValueBase will have an unsized
189   /// array in its designator.
190   /// Find the path length and type of the most-derived subobject in the given
191   /// path, and find the size of the containing array, if any.
192   static unsigned
findMostDerivedSubobject(ASTContext & Ctx,APValue::LValueBase Base,ArrayRef<APValue::LValuePathEntry> Path,uint64_t & ArraySize,QualType & Type,bool & IsArray,bool & FirstEntryIsUnsizedArray)193   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
194                            ArrayRef<APValue::LValuePathEntry> Path,
195                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
196                            bool &FirstEntryIsUnsizedArray) {
197     // This only accepts LValueBases from APValues, and APValues don't support
198     // arrays that lack size info.
199     assert(!isBaseAnAllocSizeCall(Base) &&
200            "Unsized arrays shouldn't appear here");
201     unsigned MostDerivedLength = 0;
202     Type = getType(Base);
203 
204     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
205       if (Type->isArrayType()) {
206         const ArrayType *AT = Ctx.getAsArrayType(Type);
207         Type = AT->getElementType();
208         MostDerivedLength = I + 1;
209         IsArray = true;
210 
211         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
212           ArraySize = CAT->getSize().getZExtValue();
213         } else {
214           assert(I == 0 && "unexpected unsized array designator");
215           FirstEntryIsUnsizedArray = true;
216           ArraySize = AssumedSizeForUnsizedArray;
217         }
218       } else if (Type->isAnyComplexType()) {
219         const ComplexType *CT = Type->castAs<ComplexType>();
220         Type = CT->getElementType();
221         ArraySize = 2;
222         MostDerivedLength = I + 1;
223         IsArray = true;
224       } else if (const FieldDecl *FD = getAsField(Path[I])) {
225         Type = FD->getType();
226         ArraySize = 0;
227         MostDerivedLength = I + 1;
228         IsArray = false;
229       } else {
230         // Path[I] describes a base class.
231         ArraySize = 0;
232         IsArray = false;
233       }
234     }
235     return MostDerivedLength;
236   }
237 
238   /// A path from a glvalue to a subobject of that glvalue.
239   struct SubobjectDesignator {
240     /// True if the subobject was named in a manner not supported by C++11. Such
241     /// lvalues can still be folded, but they are not core constant expressions
242     /// and we cannot perform lvalue-to-rvalue conversions on them.
243     unsigned Invalid : 1;
244 
245     /// Is this a pointer one past the end of an object?
246     unsigned IsOnePastTheEnd : 1;
247 
248     /// Indicator of whether the first entry is an unsized array.
249     unsigned FirstEntryIsAnUnsizedArray : 1;
250 
251     /// Indicator of whether the most-derived object is an array element.
252     unsigned MostDerivedIsArrayElement : 1;
253 
254     /// The length of the path to the most-derived object of which this is a
255     /// subobject.
256     unsigned MostDerivedPathLength : 28;
257 
258     /// The size of the array of which the most-derived object is an element.
259     /// This will always be 0 if the most-derived object is not an array
260     /// element. 0 is not an indicator of whether or not the most-derived object
261     /// is an array, however, because 0-length arrays are allowed.
262     ///
263     /// If the current array is an unsized array, the value of this is
264     /// undefined.
265     uint64_t MostDerivedArraySize;
266 
267     /// The type of the most derived object referred to by this address.
268     QualType MostDerivedType;
269 
270     typedef APValue::LValuePathEntry PathEntry;
271 
272     /// The entries on the path from the glvalue to the designated subobject.
273     SmallVector<PathEntry, 8> Entries;
274 
SubobjectDesignator__anonbf0ddd820111::SubobjectDesignator275     SubobjectDesignator() : Invalid(true) {}
276 
SubobjectDesignator__anonbf0ddd820111::SubobjectDesignator277     explicit SubobjectDesignator(QualType T)
278         : Invalid(false), IsOnePastTheEnd(false),
279           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
280           MostDerivedPathLength(0), MostDerivedArraySize(0),
281           MostDerivedType(T) {}
282 
SubobjectDesignator__anonbf0ddd820111::SubobjectDesignator283     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
284         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
285           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
286           MostDerivedPathLength(0), MostDerivedArraySize(0) {
287       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
288       if (!Invalid) {
289         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
290         ArrayRef<PathEntry> VEntries = V.getLValuePath();
291         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
292         if (V.getLValueBase()) {
293           bool IsArray = false;
294           bool FirstIsUnsizedArray = false;
295           MostDerivedPathLength = findMostDerivedSubobject(
296               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
297               MostDerivedType, IsArray, FirstIsUnsizedArray);
298           MostDerivedIsArrayElement = IsArray;
299           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
300         }
301       }
302     }
303 
truncate__anonbf0ddd820111::SubobjectDesignator304     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
305                   unsigned NewLength) {
306       if (Invalid)
307         return;
308 
309       assert(Base && "cannot truncate path for null pointer");
310       assert(NewLength <= Entries.size() && "not a truncation");
311 
312       if (NewLength == Entries.size())
313         return;
314       Entries.resize(NewLength);
315 
316       bool IsArray = false;
317       bool FirstIsUnsizedArray = false;
318       MostDerivedPathLength = findMostDerivedSubobject(
319           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
320           FirstIsUnsizedArray);
321       MostDerivedIsArrayElement = IsArray;
322       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
323     }
324 
setInvalid__anonbf0ddd820111::SubobjectDesignator325     void setInvalid() {
326       Invalid = true;
327       Entries.clear();
328     }
329 
330     /// Determine whether the most derived subobject is an array without a
331     /// known bound.
isMostDerivedAnUnsizedArray__anonbf0ddd820111::SubobjectDesignator332     bool isMostDerivedAnUnsizedArray() const {
333       assert(!Invalid && "Calling this makes no sense on invalid designators");
334       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
335     }
336 
337     /// Determine what the most derived array's size is. Results in an assertion
338     /// failure if the most derived array lacks a size.
getMostDerivedArraySize__anonbf0ddd820111::SubobjectDesignator339     uint64_t getMostDerivedArraySize() const {
340       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
341       return MostDerivedArraySize;
342     }
343 
344     /// Determine whether this is a one-past-the-end pointer.
isOnePastTheEnd__anonbf0ddd820111::SubobjectDesignator345     bool isOnePastTheEnd() const {
346       assert(!Invalid);
347       if (IsOnePastTheEnd)
348         return true;
349       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
350           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
351               MostDerivedArraySize)
352         return true;
353       return false;
354     }
355 
356     /// Get the range of valid index adjustments in the form
357     ///   {maximum value that can be subtracted from this pointer,
358     ///    maximum value that can be added to this pointer}
validIndexAdjustments__anonbf0ddd820111::SubobjectDesignator359     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
360       if (Invalid || isMostDerivedAnUnsizedArray())
361         return {0, 0};
362 
363       // [expr.add]p4: For the purposes of these operators, a pointer to a
364       // nonarray object behaves the same as a pointer to the first element of
365       // an array of length one with the type of the object as its element type.
366       bool IsArray = MostDerivedPathLength == Entries.size() &&
367                      MostDerivedIsArrayElement;
368       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
369                                     : (uint64_t)IsOnePastTheEnd;
370       uint64_t ArraySize =
371           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
372       return {ArrayIndex, ArraySize - ArrayIndex};
373     }
374 
375     /// Check that this refers to a valid subobject.
isValidSubobject__anonbf0ddd820111::SubobjectDesignator376     bool isValidSubobject() const {
377       if (Invalid)
378         return false;
379       return !isOnePastTheEnd();
380     }
381     /// Check that this refers to a valid subobject, and if not, produce a
382     /// relevant diagnostic and set the designator as invalid.
383     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
384 
385     /// Get the type of the designated object.
getType__anonbf0ddd820111::SubobjectDesignator386     QualType getType(ASTContext &Ctx) const {
387       assert(!Invalid && "invalid designator has no subobject type");
388       return MostDerivedPathLength == Entries.size()
389                  ? MostDerivedType
390                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
391     }
392 
393     /// Update this designator to refer to the first element within this array.
addArrayUnchecked__anonbf0ddd820111::SubobjectDesignator394     void addArrayUnchecked(const ConstantArrayType *CAT) {
395       Entries.push_back(PathEntry::ArrayIndex(0));
396 
397       // This is a most-derived object.
398       MostDerivedType = CAT->getElementType();
399       MostDerivedIsArrayElement = true;
400       MostDerivedArraySize = CAT->getSize().getZExtValue();
401       MostDerivedPathLength = Entries.size();
402     }
403     /// Update this designator to refer to the first element within the array of
404     /// elements of type T. This is an array of unknown size.
addUnsizedArrayUnchecked__anonbf0ddd820111::SubobjectDesignator405     void addUnsizedArrayUnchecked(QualType ElemTy) {
406       Entries.push_back(PathEntry::ArrayIndex(0));
407 
408       MostDerivedType = ElemTy;
409       MostDerivedIsArrayElement = true;
410       // The value in MostDerivedArraySize is undefined in this case. So, set it
411       // to an arbitrary value that's likely to loudly break things if it's
412       // used.
413       MostDerivedArraySize = AssumedSizeForUnsizedArray;
414       MostDerivedPathLength = Entries.size();
415     }
416     /// Update this designator to refer to the given base or member of this
417     /// object.
addDeclUnchecked__anonbf0ddd820111::SubobjectDesignator418     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
419       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
420 
421       // If this isn't a base class, it's a new most-derived object.
422       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
423         MostDerivedType = FD->getType();
424         MostDerivedIsArrayElement = false;
425         MostDerivedArraySize = 0;
426         MostDerivedPathLength = Entries.size();
427       }
428     }
429     /// Update this designator to refer to the given complex component.
addComplexUnchecked__anonbf0ddd820111::SubobjectDesignator430     void addComplexUnchecked(QualType EltTy, bool Imag) {
431       Entries.push_back(PathEntry::ArrayIndex(Imag));
432 
433       // This is technically a most-derived object, though in practice this
434       // is unlikely to matter.
435       MostDerivedType = EltTy;
436       MostDerivedIsArrayElement = true;
437       MostDerivedArraySize = 2;
438       MostDerivedPathLength = Entries.size();
439     }
440     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
441     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
442                                    const APSInt &N);
443     /// Add N to the address of this subobject.
adjustIndex__anonbf0ddd820111::SubobjectDesignator444     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
445       if (Invalid || !N) return;
446       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
447       if (isMostDerivedAnUnsizedArray()) {
448         diagnoseUnsizedArrayPointerArithmetic(Info, E);
449         // Can't verify -- trust that the user is doing the right thing (or if
450         // not, trust that the caller will catch the bad behavior).
451         // FIXME: Should we reject if this overflows, at least?
452         Entries.back() = PathEntry::ArrayIndex(
453             Entries.back().getAsArrayIndex() + TruncatedN);
454         return;
455       }
456 
457       // [expr.add]p4: For the purposes of these operators, a pointer to a
458       // nonarray object behaves the same as a pointer to the first element of
459       // an array of length one with the type of the object as its element type.
460       bool IsArray = MostDerivedPathLength == Entries.size() &&
461                      MostDerivedIsArrayElement;
462       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
463                                     : (uint64_t)IsOnePastTheEnd;
464       uint64_t ArraySize =
465           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
466 
467       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
468         // Calculate the actual index in a wide enough type, so we can include
469         // it in the note.
470         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
471         (llvm::APInt&)N += ArrayIndex;
472         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
473         diagnosePointerArithmetic(Info, E, N);
474         setInvalid();
475         return;
476       }
477 
478       ArrayIndex += TruncatedN;
479       assert(ArrayIndex <= ArraySize &&
480              "bounds check succeeded for out-of-bounds index");
481 
482       if (IsArray)
483         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
484       else
485         IsOnePastTheEnd = (ArrayIndex != 0);
486     }
487   };
488 
489   /// A scope at the end of which an object can need to be destroyed.
490   enum class ScopeKind {
491     Block,
492     FullExpression,
493     Call
494   };
495 
496   /// A reference to a particular call and its arguments.
497   struct CallRef {
CallRef__anonbf0ddd820111::CallRef498     CallRef() : OrigCallee(), CallIndex(0), Version() {}
CallRef__anonbf0ddd820111::CallRef499     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
500         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
501 
operator bool__anonbf0ddd820111::CallRef502     explicit operator bool() const { return OrigCallee; }
503 
504     /// Get the parameter that the caller initialized, corresponding to the
505     /// given parameter in the callee.
getOrigParam__anonbf0ddd820111::CallRef506     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
507       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
508                         : PVD;
509     }
510 
511     /// The callee at the point where the arguments were evaluated. This might
512     /// be different from the actual callee (a different redeclaration, or a
513     /// virtual override), but this function's parameters are the ones that
514     /// appear in the parameter map.
515     const FunctionDecl *OrigCallee;
516     /// The call index of the frame that holds the argument values.
517     unsigned CallIndex;
518     /// The version of the parameters corresponding to this call.
519     unsigned Version;
520   };
521 
522   /// A stack frame in the constexpr call stack.
523   class CallStackFrame : public interp::Frame {
524   public:
525     EvalInfo &Info;
526 
527     /// Parent - The caller of this stack frame.
528     CallStackFrame *Caller;
529 
530     /// Callee - The function which was called.
531     const FunctionDecl *Callee;
532 
533     /// This - The binding for the this pointer in this call, if any.
534     const LValue *This;
535 
536     /// CallExpr - The syntactical structure of member function calls
537     const Expr *CallExpr;
538 
539     /// Information on how to find the arguments to this call. Our arguments
540     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
541     /// key and this value as the version.
542     CallRef Arguments;
543 
544     /// Source location information about the default argument or default
545     /// initializer expression we're evaluating, if any.
546     CurrentSourceLocExprScope CurSourceLocExprScope;
547 
548     // Note that we intentionally use std::map here so that references to
549     // values are stable.
550     typedef std::pair<const void *, unsigned> MapKeyTy;
551     typedef std::map<MapKeyTy, APValue> MapTy;
552     /// Temporaries - Temporary lvalues materialized within this stack frame.
553     MapTy Temporaries;
554 
555     /// CallRange - The source range of the call expression for this call.
556     SourceRange CallRange;
557 
558     /// Index - The call index of this call.
559     unsigned Index;
560 
561     /// The stack of integers for tracking version numbers for temporaries.
562     SmallVector<unsigned, 2> TempVersionStack = {1};
563     unsigned CurTempVersion = TempVersionStack.back();
564 
getTempVersion() const565     unsigned getTempVersion() const { return TempVersionStack.back(); }
566 
pushTempVersion()567     void pushTempVersion() {
568       TempVersionStack.push_back(++CurTempVersion);
569     }
570 
popTempVersion()571     void popTempVersion() {
572       TempVersionStack.pop_back();
573     }
574 
createCall(const FunctionDecl * Callee)575     CallRef createCall(const FunctionDecl *Callee) {
576       return {Callee, Index, ++CurTempVersion};
577     }
578 
579     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
580     // on the overall stack usage of deeply-recursing constexpr evaluations.
581     // (We should cache this map rather than recomputing it repeatedly.)
582     // But let's try this and see how it goes; we can look into caching the map
583     // as a later change.
584 
585     /// LambdaCaptureFields - Mapping from captured variables/this to
586     /// corresponding data members in the closure class.
587     llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
588     FieldDecl *LambdaThisCaptureField = nullptr;
589 
590     CallStackFrame(EvalInfo &Info, SourceRange CallRange,
591                    const FunctionDecl *Callee, const LValue *This,
592                    const Expr *CallExpr, CallRef Arguments);
593     ~CallStackFrame();
594 
595     // Return the temporary for Key whose version number is Version.
getTemporary(const void * Key,unsigned Version)596     APValue *getTemporary(const void *Key, unsigned Version) {
597       MapKeyTy KV(Key, Version);
598       auto LB = Temporaries.lower_bound(KV);
599       if (LB != Temporaries.end() && LB->first == KV)
600         return &LB->second;
601       return nullptr;
602     }
603 
604     // Return the current temporary for Key in the map.
getCurrentTemporary(const void * Key)605     APValue *getCurrentTemporary(const void *Key) {
606       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
607       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
608         return &std::prev(UB)->second;
609       return nullptr;
610     }
611 
612     // Return the version number of the current temporary for Key.
getCurrentTemporaryVersion(const void * Key) const613     unsigned getCurrentTemporaryVersion(const void *Key) const {
614       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
615       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
616         return std::prev(UB)->first.second;
617       return 0;
618     }
619 
620     /// Allocate storage for an object of type T in this stack frame.
621     /// Populates LV with a handle to the created object. Key identifies
622     /// the temporary within the stack frame, and must not be reused without
623     /// bumping the temporary version number.
624     template<typename KeyT>
625     APValue &createTemporary(const KeyT *Key, QualType T,
626                              ScopeKind Scope, LValue &LV);
627 
628     /// Allocate storage for a parameter of a function call made in this frame.
629     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
630 
631     void describe(llvm::raw_ostream &OS) const override;
632 
getCaller() const633     Frame *getCaller() const override { return Caller; }
getCallRange() const634     SourceRange getCallRange() const override { return CallRange; }
getCallee() const635     const FunctionDecl *getCallee() const override { return Callee; }
636 
isStdFunction() const637     bool isStdFunction() const {
638       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
639         if (DC->isStdNamespace())
640           return true;
641       return false;
642     }
643 
644     /// Whether we're in a context where [[msvc::constexpr]] evaluation is
645     /// permitted. See MSConstexprDocs for description of permitted contexts.
646     bool CanEvalMSConstexpr = false;
647 
648   private:
649     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
650                          ScopeKind Scope);
651   };
652 
653   /// Temporarily override 'this'.
654   class ThisOverrideRAII {
655   public:
ThisOverrideRAII(CallStackFrame & Frame,const LValue * NewThis,bool Enable)656     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
657         : Frame(Frame), OldThis(Frame.This) {
658       if (Enable)
659         Frame.This = NewThis;
660     }
~ThisOverrideRAII()661     ~ThisOverrideRAII() {
662       Frame.This = OldThis;
663     }
664   private:
665     CallStackFrame &Frame;
666     const LValue *OldThis;
667   };
668 
669   // A shorthand time trace scope struct, prints source range, for example
670   // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
671   class ExprTimeTraceScope {
672   public:
ExprTimeTraceScope(const Expr * E,const ASTContext & Ctx,StringRef Name)673     ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
674         : TimeScope(Name, [E, &Ctx] {
675             return E->getSourceRange().printToString(Ctx.getSourceManager());
676           }) {}
677 
678   private:
679     llvm::TimeTraceScope TimeScope;
680   };
681 
682   /// RAII object used to change the current ability of
683   /// [[msvc::constexpr]] evaulation.
684   struct MSConstexprContextRAII {
685     CallStackFrame &Frame;
686     bool OldValue;
MSConstexprContextRAII__anonbf0ddd820111::MSConstexprContextRAII687     explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
688         : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
689       Frame.CanEvalMSConstexpr = Value;
690     }
691 
~MSConstexprContextRAII__anonbf0ddd820111::MSConstexprContextRAII692     ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
693   };
694 }
695 
696 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
697                               const LValue &This, QualType ThisType);
698 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
699                               APValue::LValueBase LVBase, APValue &Value,
700                               QualType T);
701 
702 namespace {
703   /// A cleanup, and a flag indicating whether it is lifetime-extended.
704   class Cleanup {
705     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
706     APValue::LValueBase Base;
707     QualType T;
708 
709   public:
Cleanup(APValue * Val,APValue::LValueBase Base,QualType T,ScopeKind Scope)710     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
711             ScopeKind Scope)
712         : Value(Val, Scope), Base(Base), T(T) {}
713 
714     /// Determine whether this cleanup should be performed at the end of the
715     /// given kind of scope.
isDestroyedAtEndOf(ScopeKind K) const716     bool isDestroyedAtEndOf(ScopeKind K) const {
717       return (int)Value.getInt() >= (int)K;
718     }
endLifetime(EvalInfo & Info,bool RunDestructors)719     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
720       if (RunDestructors) {
721         SourceLocation Loc;
722         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
723           Loc = VD->getLocation();
724         else if (const Expr *E = Base.dyn_cast<const Expr*>())
725           Loc = E->getExprLoc();
726         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
727       }
728       *Value.getPointer() = APValue();
729       return true;
730     }
731 
hasSideEffect()732     bool hasSideEffect() {
733       return T.isDestructedType();
734     }
735   };
736 
737   /// A reference to an object whose construction we are currently evaluating.
738   struct ObjectUnderConstruction {
739     APValue::LValueBase Base;
740     ArrayRef<APValue::LValuePathEntry> Path;
operator ==(const ObjectUnderConstruction & LHS,const ObjectUnderConstruction & RHS)741     friend bool operator==(const ObjectUnderConstruction &LHS,
742                            const ObjectUnderConstruction &RHS) {
743       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
744     }
hash_value(const ObjectUnderConstruction & Obj)745     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
746       return llvm::hash_combine(Obj.Base, Obj.Path);
747     }
748   };
749   enum class ConstructionPhase {
750     None,
751     Bases,
752     AfterBases,
753     AfterFields,
754     Destroying,
755     DestroyingBases
756   };
757 }
758 
759 namespace llvm {
760 template<> struct DenseMapInfo<ObjectUnderConstruction> {
761   using Base = DenseMapInfo<APValue::LValueBase>;
getEmptyKeyllvm::DenseMapInfo762   static ObjectUnderConstruction getEmptyKey() {
763     return {Base::getEmptyKey(), {}}; }
getTombstoneKeyllvm::DenseMapInfo764   static ObjectUnderConstruction getTombstoneKey() {
765     return {Base::getTombstoneKey(), {}};
766   }
getHashValuellvm::DenseMapInfo767   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
768     return hash_value(Object);
769   }
isEqualllvm::DenseMapInfo770   static bool isEqual(const ObjectUnderConstruction &LHS,
771                       const ObjectUnderConstruction &RHS) {
772     return LHS == RHS;
773   }
774 };
775 }
776 
777 namespace {
778   /// A dynamically-allocated heap object.
779   struct DynAlloc {
780     /// The value of this heap-allocated object.
781     APValue Value;
782     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
783     /// or a CallExpr (the latter is for direct calls to operator new inside
784     /// std::allocator<T>::allocate).
785     const Expr *AllocExpr = nullptr;
786 
787     enum Kind {
788       New,
789       ArrayNew,
790       StdAllocator
791     };
792 
793     /// Get the kind of the allocation. This must match between allocation
794     /// and deallocation.
getKind__anonbf0ddd820411::DynAlloc795     Kind getKind() const {
796       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
797         return NE->isArray() ? ArrayNew : New;
798       assert(isa<CallExpr>(AllocExpr));
799       return StdAllocator;
800     }
801   };
802 
803   struct DynAllocOrder {
operator ()__anonbf0ddd820411::DynAllocOrder804     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
805       return L.getIndex() < R.getIndex();
806     }
807   };
808 
809   /// EvalInfo - This is a private struct used by the evaluator to capture
810   /// information about a subexpression as it is folded.  It retains information
811   /// about the AST context, but also maintains information about the folded
812   /// expression.
813   ///
814   /// If an expression could be evaluated, it is still possible it is not a C
815   /// "integer constant expression" or constant expression.  If not, this struct
816   /// captures information about how and why not.
817   ///
818   /// One bit of information passed *into* the request for constant folding
819   /// indicates whether the subexpression is "evaluated" or not according to C
820   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
821   /// evaluate the expression regardless of what the RHS is, but C only allows
822   /// certain things in certain situations.
823   class EvalInfo : public interp::State {
824   public:
825     ASTContext &Ctx;
826 
827     /// EvalStatus - Contains information about the evaluation.
828     Expr::EvalStatus &EvalStatus;
829 
830     /// CurrentCall - The top of the constexpr call stack.
831     CallStackFrame *CurrentCall;
832 
833     /// CallStackDepth - The number of calls in the call stack right now.
834     unsigned CallStackDepth;
835 
836     /// NextCallIndex - The next call index to assign.
837     unsigned NextCallIndex;
838 
839     /// StepsLeft - The remaining number of evaluation steps we're permitted
840     /// to perform. This is essentially a limit for the number of statements
841     /// we will evaluate.
842     unsigned StepsLeft;
843 
844     /// Enable the experimental new constant interpreter. If an expression is
845     /// not supported by the interpreter, an error is triggered.
846     bool EnableNewConstInterp;
847 
848     /// BottomFrame - The frame in which evaluation started. This must be
849     /// initialized after CurrentCall and CallStackDepth.
850     CallStackFrame BottomFrame;
851 
852     /// A stack of values whose lifetimes end at the end of some surrounding
853     /// evaluation frame.
854     llvm::SmallVector<Cleanup, 16> CleanupStack;
855 
856     /// EvaluatingDecl - This is the declaration whose initializer is being
857     /// evaluated, if any.
858     APValue::LValueBase EvaluatingDecl;
859 
860     enum class EvaluatingDeclKind {
861       None,
862       /// We're evaluating the construction of EvaluatingDecl.
863       Ctor,
864       /// We're evaluating the destruction of EvaluatingDecl.
865       Dtor,
866     };
867     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
868 
869     /// EvaluatingDeclValue - This is the value being constructed for the
870     /// declaration whose initializer is being evaluated, if any.
871     APValue *EvaluatingDeclValue;
872 
873     /// Set of objects that are currently being constructed.
874     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
875         ObjectsUnderConstruction;
876 
877     /// Current heap allocations, along with the location where each was
878     /// allocated. We use std::map here because we need stable addresses
879     /// for the stored APValues.
880     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
881 
882     /// The number of heap allocations performed so far in this evaluation.
883     unsigned NumHeapAllocs = 0;
884 
885     struct EvaluatingConstructorRAII {
886       EvalInfo &EI;
887       ObjectUnderConstruction Object;
888       bool DidInsert;
EvaluatingConstructorRAII__anonbf0ddd820411::EvalInfo::EvaluatingConstructorRAII889       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
890                                 bool HasBases)
891           : EI(EI), Object(Object) {
892         DidInsert =
893             EI.ObjectsUnderConstruction
894                 .insert({Object, HasBases ? ConstructionPhase::Bases
895                                           : ConstructionPhase::AfterBases})
896                 .second;
897       }
finishedConstructingBases__anonbf0ddd820411::EvalInfo::EvaluatingConstructorRAII898       void finishedConstructingBases() {
899         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
900       }
finishedConstructingFields__anonbf0ddd820411::EvalInfo::EvaluatingConstructorRAII901       void finishedConstructingFields() {
902         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
903       }
~EvaluatingConstructorRAII__anonbf0ddd820411::EvalInfo::EvaluatingConstructorRAII904       ~EvaluatingConstructorRAII() {
905         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
906       }
907     };
908 
909     struct EvaluatingDestructorRAII {
910       EvalInfo &EI;
911       ObjectUnderConstruction Object;
912       bool DidInsert;
EvaluatingDestructorRAII__anonbf0ddd820411::EvalInfo::EvaluatingDestructorRAII913       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
914           : EI(EI), Object(Object) {
915         DidInsert = EI.ObjectsUnderConstruction
916                         .insert({Object, ConstructionPhase::Destroying})
917                         .second;
918       }
startedDestroyingBases__anonbf0ddd820411::EvalInfo::EvaluatingDestructorRAII919       void startedDestroyingBases() {
920         EI.ObjectsUnderConstruction[Object] =
921             ConstructionPhase::DestroyingBases;
922       }
~EvaluatingDestructorRAII__anonbf0ddd820411::EvalInfo::EvaluatingDestructorRAII923       ~EvaluatingDestructorRAII() {
924         if (DidInsert)
925           EI.ObjectsUnderConstruction.erase(Object);
926       }
927     };
928 
929     ConstructionPhase
isEvaluatingCtorDtor(APValue::LValueBase Base,ArrayRef<APValue::LValuePathEntry> Path)930     isEvaluatingCtorDtor(APValue::LValueBase Base,
931                          ArrayRef<APValue::LValuePathEntry> Path) {
932       return ObjectsUnderConstruction.lookup({Base, Path});
933     }
934 
935     /// If we're currently speculatively evaluating, the outermost call stack
936     /// depth at which we can mutate state, otherwise 0.
937     unsigned SpeculativeEvaluationDepth = 0;
938 
939     /// The current array initialization index, if we're performing array
940     /// initialization.
941     uint64_t ArrayInitIndex = -1;
942 
943     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
944     /// notes attached to it will also be stored, otherwise they will not be.
945     bool HasActiveDiagnostic;
946 
947     /// Have we emitted a diagnostic explaining why we couldn't constant
948     /// fold (not just why it's not strictly a constant expression)?
949     bool HasFoldFailureDiagnostic;
950 
951     /// Whether we're checking that an expression is a potential constant
952     /// expression. If so, do not fail on constructs that could become constant
953     /// later on (such as a use of an undefined global).
954     bool CheckingPotentialConstantExpression = false;
955 
956     /// Whether we're checking for an expression that has undefined behavior.
957     /// If so, we will produce warnings if we encounter an operation that is
958     /// always undefined.
959     ///
960     /// Note that we still need to evaluate the expression normally when this
961     /// is set; this is used when evaluating ICEs in C.
962     bool CheckingForUndefinedBehavior = false;
963 
964     enum EvaluationMode {
965       /// Evaluate as a constant expression. Stop if we find that the expression
966       /// is not a constant expression.
967       EM_ConstantExpression,
968 
969       /// Evaluate as a constant expression. Stop if we find that the expression
970       /// is not a constant expression. Some expressions can be retried in the
971       /// optimizer if we don't constant fold them here, but in an unevaluated
972       /// context we try to fold them immediately since the optimizer never
973       /// gets a chance to look at it.
974       EM_ConstantExpressionUnevaluated,
975 
976       /// Fold the expression to a constant. Stop if we hit a side-effect that
977       /// we can't model.
978       EM_ConstantFold,
979 
980       /// Evaluate in any way we know how. Don't worry about side-effects that
981       /// can't be modeled.
982       EM_IgnoreSideEffects,
983     } EvalMode;
984 
985     /// Are we checking whether the expression is a potential constant
986     /// expression?
checkingPotentialConstantExpression() const987     bool checkingPotentialConstantExpression() const override  {
988       return CheckingPotentialConstantExpression;
989     }
990 
991     /// Are we checking an expression for overflow?
992     // FIXME: We should check for any kind of undefined or suspicious behavior
993     // in such constructs, not just overflow.
checkingForUndefinedBehavior() const994     bool checkingForUndefinedBehavior() const override {
995       return CheckingForUndefinedBehavior;
996     }
997 
EvalInfo(const ASTContext & C,Expr::EvalStatus & S,EvaluationMode Mode)998     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
999         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
1000           CallStackDepth(0), NextCallIndex(1),
1001           StepsLeft(C.getLangOpts().ConstexprStepLimit),
1002           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
1003           BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
1004                       /*This=*/nullptr,
1005                       /*CallExpr=*/nullptr, CallRef()),
1006           EvaluatingDecl((const ValueDecl *)nullptr),
1007           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
1008           HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
1009 
~EvalInfo()1010     ~EvalInfo() {
1011       discardCleanups();
1012     }
1013 
getCtx() const1014     ASTContext &getCtx() const override { return Ctx; }
1015 
setEvaluatingDecl(APValue::LValueBase Base,APValue & Value,EvaluatingDeclKind EDK=EvaluatingDeclKind::Ctor)1016     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1017                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1018       EvaluatingDecl = Base;
1019       IsEvaluatingDecl = EDK;
1020       EvaluatingDeclValue = &Value;
1021     }
1022 
CheckCallLimit(SourceLocation Loc)1023     bool CheckCallLimit(SourceLocation Loc) {
1024       // Don't perform any constexpr calls (other than the call we're checking)
1025       // when checking a potential constant expression.
1026       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1027         return false;
1028       if (NextCallIndex == 0) {
1029         // NextCallIndex has wrapped around.
1030         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1031         return false;
1032       }
1033       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1034         return true;
1035       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1036         << getLangOpts().ConstexprCallDepth;
1037       return false;
1038     }
1039 
CheckArraySize(SourceLocation Loc,unsigned BitWidth,uint64_t ElemCount,bool Diag)1040     bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1041                         uint64_t ElemCount, bool Diag) {
1042       // FIXME: GH63562
1043       // APValue stores array extents as unsigned,
1044       // so anything that is greater that unsigned would overflow when
1045       // constructing the array, we catch this here.
1046       if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1047           ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1048         if (Diag)
1049           FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1050         return false;
1051       }
1052 
1053       // FIXME: GH63562
1054       // Arrays allocate an APValue per element.
1055       // We use the number of constexpr steps as a proxy for the maximum size
1056       // of arrays to avoid exhausting the system resources, as initialization
1057       // of each element is likely to take some number of steps anyway.
1058       uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1059       if (ElemCount > Limit) {
1060         if (Diag)
1061           FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1062               << ElemCount << Limit;
1063         return false;
1064       }
1065       return true;
1066     }
1067 
1068     std::pair<CallStackFrame *, unsigned>
getCallFrameAndDepth(unsigned CallIndex)1069     getCallFrameAndDepth(unsigned CallIndex) {
1070       assert(CallIndex && "no call index in getCallFrameAndDepth");
1071       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1072       // be null in this loop.
1073       unsigned Depth = CallStackDepth;
1074       CallStackFrame *Frame = CurrentCall;
1075       while (Frame->Index > CallIndex) {
1076         Frame = Frame->Caller;
1077         --Depth;
1078       }
1079       if (Frame->Index == CallIndex)
1080         return {Frame, Depth};
1081       return {nullptr, 0};
1082     }
1083 
nextStep(const Stmt * S)1084     bool nextStep(const Stmt *S) {
1085       if (!StepsLeft) {
1086         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1087         return false;
1088       }
1089       --StepsLeft;
1090       return true;
1091     }
1092 
1093     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1094 
lookupDynamicAlloc(DynamicAllocLValue DA)1095     std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1096       std::optional<DynAlloc *> Result;
1097       auto It = HeapAllocs.find(DA);
1098       if (It != HeapAllocs.end())
1099         Result = &It->second;
1100       return Result;
1101     }
1102 
1103     /// Get the allocated storage for the given parameter of the given call.
getParamSlot(CallRef Call,const ParmVarDecl * PVD)1104     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1105       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1106       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1107                    : nullptr;
1108     }
1109 
1110     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1111     struct StdAllocatorCaller {
1112       unsigned FrameIndex;
1113       QualType ElemType;
operator bool__anonbf0ddd820411::EvalInfo::StdAllocatorCaller1114       explicit operator bool() const { return FrameIndex != 0; };
1115     };
1116 
getStdAllocatorCaller(StringRef FnName) const1117     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1118       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1119            Call = Call->Caller) {
1120         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1121         if (!MD)
1122           continue;
1123         const IdentifierInfo *FnII = MD->getIdentifier();
1124         if (!FnII || !FnII->isStr(FnName))
1125           continue;
1126 
1127         const auto *CTSD =
1128             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1129         if (!CTSD)
1130           continue;
1131 
1132         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1133         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1134         if (CTSD->isInStdNamespace() && ClassII &&
1135             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1136             TAL[0].getKind() == TemplateArgument::Type)
1137           return {Call->Index, TAL[0].getAsType()};
1138       }
1139 
1140       return {};
1141     }
1142 
performLifetimeExtension()1143     void performLifetimeExtension() {
1144       // Disable the cleanups for lifetime-extended temporaries.
1145       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1146         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1147       });
1148     }
1149 
1150     /// Throw away any remaining cleanups at the end of evaluation. If any
1151     /// cleanups would have had a side-effect, note that as an unmodeled
1152     /// side-effect and return false. Otherwise, return true.
discardCleanups()1153     bool discardCleanups() {
1154       for (Cleanup &C : CleanupStack) {
1155         if (C.hasSideEffect() && !noteSideEffect()) {
1156           CleanupStack.clear();
1157           return false;
1158         }
1159       }
1160       CleanupStack.clear();
1161       return true;
1162     }
1163 
1164   private:
getCurrentFrame()1165     interp::Frame *getCurrentFrame() override { return CurrentCall; }
getBottomFrame() const1166     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1167 
hasActiveDiagnostic()1168     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
setActiveDiagnostic(bool Flag)1169     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1170 
setFoldFailureDiagnostic(bool Flag)1171     void setFoldFailureDiagnostic(bool Flag) override {
1172       HasFoldFailureDiagnostic = Flag;
1173     }
1174 
getEvalStatus() const1175     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1176 
1177     // If we have a prior diagnostic, it will be noting that the expression
1178     // isn't a constant expression. This diagnostic is more important,
1179     // unless we require this evaluation to produce a constant expression.
1180     //
1181     // FIXME: We might want to show both diagnostics to the user in
1182     // EM_ConstantFold mode.
hasPriorDiagnostic()1183     bool hasPriorDiagnostic() override {
1184       if (!EvalStatus.Diag->empty()) {
1185         switch (EvalMode) {
1186         case EM_ConstantFold:
1187         case EM_IgnoreSideEffects:
1188           if (!HasFoldFailureDiagnostic)
1189             break;
1190           // We've already failed to fold something. Keep that diagnostic.
1191           [[fallthrough]];
1192         case EM_ConstantExpression:
1193         case EM_ConstantExpressionUnevaluated:
1194           setActiveDiagnostic(false);
1195           return true;
1196         }
1197       }
1198       return false;
1199     }
1200 
getCallStackDepth()1201     unsigned getCallStackDepth() override { return CallStackDepth; }
1202 
1203   public:
1204     /// Should we continue evaluation after encountering a side-effect that we
1205     /// couldn't model?
keepEvaluatingAfterSideEffect()1206     bool keepEvaluatingAfterSideEffect() {
1207       switch (EvalMode) {
1208       case EM_IgnoreSideEffects:
1209         return true;
1210 
1211       case EM_ConstantExpression:
1212       case EM_ConstantExpressionUnevaluated:
1213       case EM_ConstantFold:
1214         // By default, assume any side effect might be valid in some other
1215         // evaluation of this expression from a different context.
1216         return checkingPotentialConstantExpression() ||
1217                checkingForUndefinedBehavior();
1218       }
1219       llvm_unreachable("Missed EvalMode case");
1220     }
1221 
1222     /// Note that we have had a side-effect, and determine whether we should
1223     /// keep evaluating.
noteSideEffect()1224     bool noteSideEffect() {
1225       EvalStatus.HasSideEffects = true;
1226       return keepEvaluatingAfterSideEffect();
1227     }
1228 
1229     /// Should we continue evaluation after encountering undefined behavior?
keepEvaluatingAfterUndefinedBehavior()1230     bool keepEvaluatingAfterUndefinedBehavior() {
1231       switch (EvalMode) {
1232       case EM_IgnoreSideEffects:
1233       case EM_ConstantFold:
1234         return true;
1235 
1236       case EM_ConstantExpression:
1237       case EM_ConstantExpressionUnevaluated:
1238         return checkingForUndefinedBehavior();
1239       }
1240       llvm_unreachable("Missed EvalMode case");
1241     }
1242 
1243     /// Note that we hit something that was technically undefined behavior, but
1244     /// that we can evaluate past it (such as signed overflow or floating-point
1245     /// division by zero.)
noteUndefinedBehavior()1246     bool noteUndefinedBehavior() override {
1247       EvalStatus.HasUndefinedBehavior = true;
1248       return keepEvaluatingAfterUndefinedBehavior();
1249     }
1250 
1251     /// Should we continue evaluation as much as possible after encountering a
1252     /// construct which can't be reduced to a value?
keepEvaluatingAfterFailure() const1253     bool keepEvaluatingAfterFailure() const override {
1254       if (!StepsLeft)
1255         return false;
1256 
1257       switch (EvalMode) {
1258       case EM_ConstantExpression:
1259       case EM_ConstantExpressionUnevaluated:
1260       case EM_ConstantFold:
1261       case EM_IgnoreSideEffects:
1262         return checkingPotentialConstantExpression() ||
1263                checkingForUndefinedBehavior();
1264       }
1265       llvm_unreachable("Missed EvalMode case");
1266     }
1267 
1268     /// Notes that we failed to evaluate an expression that other expressions
1269     /// directly depend on, and determine if we should keep evaluating. This
1270     /// should only be called if we actually intend to keep evaluating.
1271     ///
1272     /// Call noteSideEffect() instead if we may be able to ignore the value that
1273     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1274     ///
1275     /// (Foo(), 1)      // use noteSideEffect
1276     /// (Foo() || true) // use noteSideEffect
1277     /// Foo() + 1       // use noteFailure
noteFailure()1278     [[nodiscard]] bool noteFailure() {
1279       // Failure when evaluating some expression often means there is some
1280       // subexpression whose evaluation was skipped. Therefore, (because we
1281       // don't track whether we skipped an expression when unwinding after an
1282       // evaluation failure) every evaluation failure that bubbles up from a
1283       // subexpression implies that a side-effect has potentially happened. We
1284       // skip setting the HasSideEffects flag to true until we decide to
1285       // continue evaluating after that point, which happens here.
1286       bool KeepGoing = keepEvaluatingAfterFailure();
1287       EvalStatus.HasSideEffects |= KeepGoing;
1288       return KeepGoing;
1289     }
1290 
1291     class ArrayInitLoopIndex {
1292       EvalInfo &Info;
1293       uint64_t OuterIndex;
1294 
1295     public:
ArrayInitLoopIndex(EvalInfo & Info)1296       ArrayInitLoopIndex(EvalInfo &Info)
1297           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1298         Info.ArrayInitIndex = 0;
1299       }
~ArrayInitLoopIndex()1300       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1301 
operator uint64_t&()1302       operator uint64_t&() { return Info.ArrayInitIndex; }
1303     };
1304   };
1305 
1306   /// Object used to treat all foldable expressions as constant expressions.
1307   struct FoldConstant {
1308     EvalInfo &Info;
1309     bool Enabled;
1310     bool HadNoPriorDiags;
1311     EvalInfo::EvaluationMode OldMode;
1312 
FoldConstant__anonbf0ddd820411::FoldConstant1313     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1314       : Info(Info),
1315         Enabled(Enabled),
1316         HadNoPriorDiags(Info.EvalStatus.Diag &&
1317                         Info.EvalStatus.Diag->empty() &&
1318                         !Info.EvalStatus.HasSideEffects),
1319         OldMode(Info.EvalMode) {
1320       if (Enabled)
1321         Info.EvalMode = EvalInfo::EM_ConstantFold;
1322     }
keepDiagnostics__anonbf0ddd820411::FoldConstant1323     void keepDiagnostics() { Enabled = false; }
~FoldConstant__anonbf0ddd820411::FoldConstant1324     ~FoldConstant() {
1325       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1326           !Info.EvalStatus.HasSideEffects)
1327         Info.EvalStatus.Diag->clear();
1328       Info.EvalMode = OldMode;
1329     }
1330   };
1331 
1332   /// RAII object used to set the current evaluation mode to ignore
1333   /// side-effects.
1334   struct IgnoreSideEffectsRAII {
1335     EvalInfo &Info;
1336     EvalInfo::EvaluationMode OldMode;
IgnoreSideEffectsRAII__anonbf0ddd820411::IgnoreSideEffectsRAII1337     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1338         : Info(Info), OldMode(Info.EvalMode) {
1339       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1340     }
1341 
~IgnoreSideEffectsRAII__anonbf0ddd820411::IgnoreSideEffectsRAII1342     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1343   };
1344 
1345   /// RAII object used to optionally suppress diagnostics and side-effects from
1346   /// a speculative evaluation.
1347   class SpeculativeEvaluationRAII {
1348     EvalInfo *Info = nullptr;
1349     Expr::EvalStatus OldStatus;
1350     unsigned OldSpeculativeEvaluationDepth = 0;
1351 
moveFromAndCancel(SpeculativeEvaluationRAII && Other)1352     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1353       Info = Other.Info;
1354       OldStatus = Other.OldStatus;
1355       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1356       Other.Info = nullptr;
1357     }
1358 
maybeRestoreState()1359     void maybeRestoreState() {
1360       if (!Info)
1361         return;
1362 
1363       Info->EvalStatus = OldStatus;
1364       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1365     }
1366 
1367   public:
1368     SpeculativeEvaluationRAII() = default;
1369 
SpeculativeEvaluationRAII(EvalInfo & Info,SmallVectorImpl<PartialDiagnosticAt> * NewDiag=nullptr)1370     SpeculativeEvaluationRAII(
1371         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1372         : Info(&Info), OldStatus(Info.EvalStatus),
1373           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1374       Info.EvalStatus.Diag = NewDiag;
1375       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1376     }
1377 
1378     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
SpeculativeEvaluationRAII(SpeculativeEvaluationRAII && Other)1379     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1380       moveFromAndCancel(std::move(Other));
1381     }
1382 
operator =(SpeculativeEvaluationRAII && Other)1383     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1384       maybeRestoreState();
1385       moveFromAndCancel(std::move(Other));
1386       return *this;
1387     }
1388 
~SpeculativeEvaluationRAII()1389     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1390   };
1391 
1392   /// RAII object wrapping a full-expression or block scope, and handling
1393   /// the ending of the lifetime of temporaries created within it.
1394   template<ScopeKind Kind>
1395   class ScopeRAII {
1396     EvalInfo &Info;
1397     unsigned OldStackSize;
1398   public:
ScopeRAII(EvalInfo & Info)1399     ScopeRAII(EvalInfo &Info)
1400         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1401       // Push a new temporary version. This is needed to distinguish between
1402       // temporaries created in different iterations of a loop.
1403       Info.CurrentCall->pushTempVersion();
1404     }
destroy(bool RunDestructors=true)1405     bool destroy(bool RunDestructors = true) {
1406       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1407       OldStackSize = -1U;
1408       return OK;
1409     }
~ScopeRAII()1410     ~ScopeRAII() {
1411       if (OldStackSize != -1U)
1412         destroy(false);
1413       // Body moved to a static method to encourage the compiler to inline away
1414       // instances of this class.
1415       Info.CurrentCall->popTempVersion();
1416     }
1417   private:
cleanup(EvalInfo & Info,bool RunDestructors,unsigned OldStackSize)1418     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1419                         unsigned OldStackSize) {
1420       assert(OldStackSize <= Info.CleanupStack.size() &&
1421              "running cleanups out of order?");
1422 
1423       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1424       // for a full-expression scope.
1425       bool Success = true;
1426       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1427         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1428           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1429             Success = false;
1430             break;
1431           }
1432         }
1433       }
1434 
1435       // Compact any retained cleanups.
1436       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1437       if (Kind != ScopeKind::Block)
1438         NewEnd =
1439             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1440               return C.isDestroyedAtEndOf(Kind);
1441             });
1442       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1443       return Success;
1444     }
1445   };
1446   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1447   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1448   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1449 }
1450 
checkSubobject(EvalInfo & Info,const Expr * E,CheckSubobjectKind CSK)1451 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1452                                          CheckSubobjectKind CSK) {
1453   if (Invalid)
1454     return false;
1455   if (isOnePastTheEnd()) {
1456     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1457       << CSK;
1458     setInvalid();
1459     return false;
1460   }
1461   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1462   // must actually be at least one array element; even a VLA cannot have a
1463   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1464   return true;
1465 }
1466 
diagnoseUnsizedArrayPointerArithmetic(EvalInfo & Info,const Expr * E)1467 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1468                                                                 const Expr *E) {
1469   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1470   // Do not set the designator as invalid: we can represent this situation,
1471   // and correct handling of __builtin_object_size requires us to do so.
1472 }
1473 
diagnosePointerArithmetic(EvalInfo & Info,const Expr * E,const APSInt & N)1474 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1475                                                     const Expr *E,
1476                                                     const APSInt &N) {
1477   // If we're complaining, we must be able to statically determine the size of
1478   // the most derived array.
1479   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1480     Info.CCEDiag(E, diag::note_constexpr_array_index)
1481       << N << /*array*/ 0
1482       << static_cast<unsigned>(getMostDerivedArraySize());
1483   else
1484     Info.CCEDiag(E, diag::note_constexpr_array_index)
1485       << N << /*non-array*/ 1;
1486   setInvalid();
1487 }
1488 
CallStackFrame(EvalInfo & Info,SourceRange CallRange,const FunctionDecl * Callee,const LValue * This,const Expr * CallExpr,CallRef Call)1489 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1490                                const FunctionDecl *Callee, const LValue *This,
1491                                const Expr *CallExpr, CallRef Call)
1492     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1493       CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1494       Index(Info.NextCallIndex++) {
1495   Info.CurrentCall = this;
1496   ++Info.CallStackDepth;
1497 }
1498 
~CallStackFrame()1499 CallStackFrame::~CallStackFrame() {
1500   assert(Info.CurrentCall == this && "calls retired out of order");
1501   --Info.CallStackDepth;
1502   Info.CurrentCall = Caller;
1503 }
1504 
isRead(AccessKinds AK)1505 static bool isRead(AccessKinds AK) {
1506   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1507 }
1508 
isModification(AccessKinds AK)1509 static bool isModification(AccessKinds AK) {
1510   switch (AK) {
1511   case AK_Read:
1512   case AK_ReadObjectRepresentation:
1513   case AK_MemberCall:
1514   case AK_DynamicCast:
1515   case AK_TypeId:
1516     return false;
1517   case AK_Assign:
1518   case AK_Increment:
1519   case AK_Decrement:
1520   case AK_Construct:
1521   case AK_Destroy:
1522     return true;
1523   }
1524   llvm_unreachable("unknown access kind");
1525 }
1526 
isAnyAccess(AccessKinds AK)1527 static bool isAnyAccess(AccessKinds AK) {
1528   return isRead(AK) || isModification(AK);
1529 }
1530 
1531 /// Is this an access per the C++ definition?
isFormalAccess(AccessKinds AK)1532 static bool isFormalAccess(AccessKinds AK) {
1533   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1534 }
1535 
1536 /// Is this kind of axcess valid on an indeterminate object value?
isValidIndeterminateAccess(AccessKinds AK)1537 static bool isValidIndeterminateAccess(AccessKinds AK) {
1538   switch (AK) {
1539   case AK_Read:
1540   case AK_Increment:
1541   case AK_Decrement:
1542     // These need the object's value.
1543     return false;
1544 
1545   case AK_ReadObjectRepresentation:
1546   case AK_Assign:
1547   case AK_Construct:
1548   case AK_Destroy:
1549     // Construction and destruction don't need the value.
1550     return true;
1551 
1552   case AK_MemberCall:
1553   case AK_DynamicCast:
1554   case AK_TypeId:
1555     // These aren't really meaningful on scalars.
1556     return true;
1557   }
1558   llvm_unreachable("unknown access kind");
1559 }
1560 
1561 namespace {
1562   struct ComplexValue {
1563   private:
1564     bool IsInt;
1565 
1566   public:
1567     APSInt IntReal, IntImag;
1568     APFloat FloatReal, FloatImag;
1569 
ComplexValue__anonbf0ddd820711::ComplexValue1570     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1571 
makeComplexFloat__anonbf0ddd820711::ComplexValue1572     void makeComplexFloat() { IsInt = false; }
isComplexFloat__anonbf0ddd820711::ComplexValue1573     bool isComplexFloat() const { return !IsInt; }
getComplexFloatReal__anonbf0ddd820711::ComplexValue1574     APFloat &getComplexFloatReal() { return FloatReal; }
getComplexFloatImag__anonbf0ddd820711::ComplexValue1575     APFloat &getComplexFloatImag() { return FloatImag; }
1576 
makeComplexInt__anonbf0ddd820711::ComplexValue1577     void makeComplexInt() { IsInt = true; }
isComplexInt__anonbf0ddd820711::ComplexValue1578     bool isComplexInt() const { return IsInt; }
getComplexIntReal__anonbf0ddd820711::ComplexValue1579     APSInt &getComplexIntReal() { return IntReal; }
getComplexIntImag__anonbf0ddd820711::ComplexValue1580     APSInt &getComplexIntImag() { return IntImag; }
1581 
moveInto__anonbf0ddd820711::ComplexValue1582     void moveInto(APValue &v) const {
1583       if (isComplexFloat())
1584         v = APValue(FloatReal, FloatImag);
1585       else
1586         v = APValue(IntReal, IntImag);
1587     }
setFrom__anonbf0ddd820711::ComplexValue1588     void setFrom(const APValue &v) {
1589       assert(v.isComplexFloat() || v.isComplexInt());
1590       if (v.isComplexFloat()) {
1591         makeComplexFloat();
1592         FloatReal = v.getComplexFloatReal();
1593         FloatImag = v.getComplexFloatImag();
1594       } else {
1595         makeComplexInt();
1596         IntReal = v.getComplexIntReal();
1597         IntImag = v.getComplexIntImag();
1598       }
1599     }
1600   };
1601 
1602   struct LValue {
1603     APValue::LValueBase Base;
1604     CharUnits Offset;
1605     SubobjectDesignator Designator;
1606     bool IsNullPtr : 1;
1607     bool InvalidBase : 1;
1608 
getLValueBase__anonbf0ddd820711::LValue1609     const APValue::LValueBase getLValueBase() const { return Base; }
getLValueOffset__anonbf0ddd820711::LValue1610     CharUnits &getLValueOffset() { return Offset; }
getLValueOffset__anonbf0ddd820711::LValue1611     const CharUnits &getLValueOffset() const { return Offset; }
getLValueDesignator__anonbf0ddd820711::LValue1612     SubobjectDesignator &getLValueDesignator() { return Designator; }
getLValueDesignator__anonbf0ddd820711::LValue1613     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
isNullPointer__anonbf0ddd820711::LValue1614     bool isNullPointer() const { return IsNullPtr;}
1615 
getLValueCallIndex__anonbf0ddd820711::LValue1616     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
getLValueVersion__anonbf0ddd820711::LValue1617     unsigned getLValueVersion() const { return Base.getVersion(); }
1618 
moveInto__anonbf0ddd820711::LValue1619     void moveInto(APValue &V) const {
1620       if (Designator.Invalid)
1621         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1622       else {
1623         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1624         V = APValue(Base, Offset, Designator.Entries,
1625                     Designator.IsOnePastTheEnd, IsNullPtr);
1626       }
1627     }
setFrom__anonbf0ddd820711::LValue1628     void setFrom(ASTContext &Ctx, const APValue &V) {
1629       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1630       Base = V.getLValueBase();
1631       Offset = V.getLValueOffset();
1632       InvalidBase = false;
1633       Designator = SubobjectDesignator(Ctx, V);
1634       IsNullPtr = V.isNullPointer();
1635     }
1636 
set__anonbf0ddd820711::LValue1637     void set(APValue::LValueBase B, bool BInvalid = false) {
1638 #ifndef NDEBUG
1639       // We only allow a few types of invalid bases. Enforce that here.
1640       if (BInvalid) {
1641         const auto *E = B.get<const Expr *>();
1642         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1643                "Unexpected type of invalid base");
1644       }
1645 #endif
1646 
1647       Base = B;
1648       Offset = CharUnits::fromQuantity(0);
1649       InvalidBase = BInvalid;
1650       Designator = SubobjectDesignator(getType(B));
1651       IsNullPtr = false;
1652     }
1653 
setNull__anonbf0ddd820711::LValue1654     void setNull(ASTContext &Ctx, QualType PointerTy) {
1655       Base = (const ValueDecl *)nullptr;
1656       Offset =
1657           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1658       InvalidBase = false;
1659       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1660       IsNullPtr = true;
1661     }
1662 
setInvalid__anonbf0ddd820711::LValue1663     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1664       set(B, true);
1665     }
1666 
toString__anonbf0ddd820711::LValue1667     std::string toString(ASTContext &Ctx, QualType T) const {
1668       APValue Printable;
1669       moveInto(Printable);
1670       return Printable.getAsString(Ctx, T);
1671     }
1672 
1673   private:
1674     // Check that this LValue is not based on a null pointer. If it is, produce
1675     // a diagnostic and mark the designator as invalid.
1676     template <typename GenDiagType>
checkNullPointerDiagnosingWith__anonbf0ddd820711::LValue1677     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1678       if (Designator.Invalid)
1679         return false;
1680       if (IsNullPtr) {
1681         GenDiag();
1682         Designator.setInvalid();
1683         return false;
1684       }
1685       return true;
1686     }
1687 
1688   public:
checkNullPointer__anonbf0ddd820711::LValue1689     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1690                           CheckSubobjectKind CSK) {
1691       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1692         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1693       });
1694     }
1695 
checkNullPointerForFoldAccess__anonbf0ddd820711::LValue1696     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1697                                        AccessKinds AK) {
1698       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1699         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1700       });
1701     }
1702 
1703     // Check this LValue refers to an object. If not, set the designator to be
1704     // invalid and emit a diagnostic.
checkSubobject__anonbf0ddd820711::LValue1705     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1706       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1707              Designator.checkSubobject(Info, E, CSK);
1708     }
1709 
addDecl__anonbf0ddd820711::LValue1710     void addDecl(EvalInfo &Info, const Expr *E,
1711                  const Decl *D, bool Virtual = false) {
1712       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1713         Designator.addDeclUnchecked(D, Virtual);
1714     }
addUnsizedArray__anonbf0ddd820711::LValue1715     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1716       if (!Designator.Entries.empty()) {
1717         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1718         Designator.setInvalid();
1719         return;
1720       }
1721       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1722         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1723         Designator.FirstEntryIsAnUnsizedArray = true;
1724         Designator.addUnsizedArrayUnchecked(ElemTy);
1725       }
1726     }
addArray__anonbf0ddd820711::LValue1727     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1728       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1729         Designator.addArrayUnchecked(CAT);
1730     }
addComplex__anonbf0ddd820711::LValue1731     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1732       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1733         Designator.addComplexUnchecked(EltTy, Imag);
1734     }
clearIsNullPointer__anonbf0ddd820711::LValue1735     void clearIsNullPointer() {
1736       IsNullPtr = false;
1737     }
adjustOffsetAndIndex__anonbf0ddd820711::LValue1738     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1739                               const APSInt &Index, CharUnits ElementSize) {
1740       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1741       // but we're not required to diagnose it and it's valid in C++.)
1742       if (!Index)
1743         return;
1744 
1745       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1746       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1747       // offsets.
1748       uint64_t Offset64 = Offset.getQuantity();
1749       uint64_t ElemSize64 = ElementSize.getQuantity();
1750       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1751       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1752 
1753       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1754         Designator.adjustIndex(Info, E, Index);
1755       clearIsNullPointer();
1756     }
adjustOffset__anonbf0ddd820711::LValue1757     void adjustOffset(CharUnits N) {
1758       Offset += N;
1759       if (N.getQuantity())
1760         clearIsNullPointer();
1761     }
1762   };
1763 
1764   struct MemberPtr {
MemberPtr__anonbf0ddd820711::MemberPtr1765     MemberPtr() {}
MemberPtr__anonbf0ddd820711::MemberPtr1766     explicit MemberPtr(const ValueDecl *Decl)
1767         : DeclAndIsDerivedMember(Decl, false) {}
1768 
1769     /// The member or (direct or indirect) field referred to by this member
1770     /// pointer, or 0 if this is a null member pointer.
getDecl__anonbf0ddd820711::MemberPtr1771     const ValueDecl *getDecl() const {
1772       return DeclAndIsDerivedMember.getPointer();
1773     }
1774     /// Is this actually a member of some type derived from the relevant class?
isDerivedMember__anonbf0ddd820711::MemberPtr1775     bool isDerivedMember() const {
1776       return DeclAndIsDerivedMember.getInt();
1777     }
1778     /// Get the class which the declaration actually lives in.
getContainingRecord__anonbf0ddd820711::MemberPtr1779     const CXXRecordDecl *getContainingRecord() const {
1780       return cast<CXXRecordDecl>(
1781           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1782     }
1783 
moveInto__anonbf0ddd820711::MemberPtr1784     void moveInto(APValue &V) const {
1785       V = APValue(getDecl(), isDerivedMember(), Path);
1786     }
setFrom__anonbf0ddd820711::MemberPtr1787     void setFrom(const APValue &V) {
1788       assert(V.isMemberPointer());
1789       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1790       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1791       Path.clear();
1792       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1793       Path.insert(Path.end(), P.begin(), P.end());
1794     }
1795 
1796     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1797     /// whether the member is a member of some class derived from the class type
1798     /// of the member pointer.
1799     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1800     /// Path - The path of base/derived classes from the member declaration's
1801     /// class (exclusive) to the class type of the member pointer (inclusive).
1802     SmallVector<const CXXRecordDecl*, 4> Path;
1803 
1804     /// Perform a cast towards the class of the Decl (either up or down the
1805     /// hierarchy).
castBack__anonbf0ddd820711::MemberPtr1806     bool castBack(const CXXRecordDecl *Class) {
1807       assert(!Path.empty());
1808       const CXXRecordDecl *Expected;
1809       if (Path.size() >= 2)
1810         Expected = Path[Path.size() - 2];
1811       else
1812         Expected = getContainingRecord();
1813       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1814         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1815         // if B does not contain the original member and is not a base or
1816         // derived class of the class containing the original member, the result
1817         // of the cast is undefined.
1818         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1819         // (D::*). We consider that to be a language defect.
1820         return false;
1821       }
1822       Path.pop_back();
1823       return true;
1824     }
1825     /// Perform a base-to-derived member pointer cast.
castToDerived__anonbf0ddd820711::MemberPtr1826     bool castToDerived(const CXXRecordDecl *Derived) {
1827       if (!getDecl())
1828         return true;
1829       if (!isDerivedMember()) {
1830         Path.push_back(Derived);
1831         return true;
1832       }
1833       if (!castBack(Derived))
1834         return false;
1835       if (Path.empty())
1836         DeclAndIsDerivedMember.setInt(false);
1837       return true;
1838     }
1839     /// Perform a derived-to-base member pointer cast.
castToBase__anonbf0ddd820711::MemberPtr1840     bool castToBase(const CXXRecordDecl *Base) {
1841       if (!getDecl())
1842         return true;
1843       if (Path.empty())
1844         DeclAndIsDerivedMember.setInt(true);
1845       if (isDerivedMember()) {
1846         Path.push_back(Base);
1847         return true;
1848       }
1849       return castBack(Base);
1850     }
1851   };
1852 
1853   /// Compare two member pointers, which are assumed to be of the same type.
operator ==(const MemberPtr & LHS,const MemberPtr & RHS)1854   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1855     if (!LHS.getDecl() || !RHS.getDecl())
1856       return !LHS.getDecl() && !RHS.getDecl();
1857     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1858       return false;
1859     return LHS.Path == RHS.Path;
1860   }
1861 }
1862 
1863 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1864 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1865                             const LValue &This, const Expr *E,
1866                             bool AllowNonLiteralTypes = false);
1867 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1868                            bool InvalidBaseOK = false);
1869 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1870                             bool InvalidBaseOK = false);
1871 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1872                                   EvalInfo &Info);
1873 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1874 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1875 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1876                                     EvalInfo &Info);
1877 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1878 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1879 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1880                            EvalInfo &Info);
1881 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1882 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1883                                   EvalInfo &Info);
1884 
1885 /// Evaluate an integer or fixed point expression into an APResult.
1886 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1887                                         EvalInfo &Info);
1888 
1889 /// Evaluate only a fixed point expression into an APResult.
1890 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1891                                EvalInfo &Info);
1892 
1893 //===----------------------------------------------------------------------===//
1894 // Misc utilities
1895 //===----------------------------------------------------------------------===//
1896 
1897 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1898 /// preserving its value (by extending by up to one bit as needed).
negateAsSigned(APSInt & Int)1899 static void negateAsSigned(APSInt &Int) {
1900   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1901     Int = Int.extend(Int.getBitWidth() + 1);
1902     Int.setIsSigned(true);
1903   }
1904   Int = -Int;
1905 }
1906 
1907 template<typename KeyT>
createTemporary(const KeyT * Key,QualType T,ScopeKind Scope,LValue & LV)1908 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1909                                          ScopeKind Scope, LValue &LV) {
1910   unsigned Version = getTempVersion();
1911   APValue::LValueBase Base(Key, Index, Version);
1912   LV.set(Base);
1913   return createLocal(Base, Key, T, Scope);
1914 }
1915 
1916 /// Allocate storage for a parameter of a function call made in this frame.
createParam(CallRef Args,const ParmVarDecl * PVD,LValue & LV)1917 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1918                                      LValue &LV) {
1919   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1920   APValue::LValueBase Base(PVD, Index, Args.Version);
1921   LV.set(Base);
1922   // We always destroy parameters at the end of the call, even if we'd allow
1923   // them to live to the end of the full-expression at runtime, in order to
1924   // give portable results and match other compilers.
1925   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1926 }
1927 
createLocal(APValue::LValueBase Base,const void * Key,QualType T,ScopeKind Scope)1928 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1929                                      QualType T, ScopeKind Scope) {
1930   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1931   unsigned Version = Base.getVersion();
1932   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1933   assert(Result.isAbsent() && "local created multiple times");
1934 
1935   // If we're creating a local immediately in the operand of a speculative
1936   // evaluation, don't register a cleanup to be run outside the speculative
1937   // evaluation context, since we won't actually be able to initialize this
1938   // object.
1939   if (Index <= Info.SpeculativeEvaluationDepth) {
1940     if (T.isDestructedType())
1941       Info.noteSideEffect();
1942   } else {
1943     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1944   }
1945   return Result;
1946 }
1947 
createHeapAlloc(const Expr * E,QualType T,LValue & LV)1948 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1949   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1950     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1951     return nullptr;
1952   }
1953 
1954   DynamicAllocLValue DA(NumHeapAllocs++);
1955   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1956   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1957                                    std::forward_as_tuple(DA), std::tuple<>());
1958   assert(Result.second && "reused a heap alloc index?");
1959   Result.first->second.AllocExpr = E;
1960   return &Result.first->second.Value;
1961 }
1962 
1963 /// Produce a string describing the given constexpr call.
describe(raw_ostream & Out) const1964 void CallStackFrame::describe(raw_ostream &Out) const {
1965   unsigned ArgIndex = 0;
1966   bool IsMemberCall =
1967       isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1968       cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1969 
1970   if (!IsMemberCall)
1971     Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1972                                  /*Qualified=*/false);
1973 
1974   if (This && IsMemberCall) {
1975     if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1976       const Expr *Object = MCE->getImplicitObjectArgument();
1977       Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1978                           /*Indentation=*/0);
1979       if (Object->getType()->isPointerType())
1980           Out << "->";
1981       else
1982           Out << ".";
1983     } else if (const auto *OCE =
1984                    dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1985       OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1986                                   Info.Ctx.getPrintingPolicy(),
1987                                   /*Indentation=*/0);
1988       Out << ".";
1989     } else {
1990       APValue Val;
1991       This->moveInto(Val);
1992       Val.printPretty(
1993           Out, Info.Ctx,
1994           Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1995       Out << ".";
1996     }
1997     Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1998                                  /*Qualified=*/false);
1999     IsMemberCall = false;
2000   }
2001 
2002   Out << '(';
2003 
2004   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2005        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2006     if (ArgIndex > (unsigned)IsMemberCall)
2007       Out << ", ";
2008 
2009     const ParmVarDecl *Param = *I;
2010     APValue *V = Info.getParamSlot(Arguments, Param);
2011     if (V)
2012       V->printPretty(Out, Info.Ctx, Param->getType());
2013     else
2014       Out << "<...>";
2015 
2016     if (ArgIndex == 0 && IsMemberCall)
2017       Out << "->" << *Callee << '(';
2018   }
2019 
2020   Out << ')';
2021 }
2022 
2023 /// Evaluate an expression to see if it had side-effects, and discard its
2024 /// result.
2025 /// \return \c true if the caller should keep evaluating.
EvaluateIgnoredValue(EvalInfo & Info,const Expr * E)2026 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2027   assert(!E->isValueDependent());
2028   APValue Scratch;
2029   if (!Evaluate(Scratch, Info, E))
2030     // We don't need the value, but we might have skipped a side effect here.
2031     return Info.noteSideEffect();
2032   return true;
2033 }
2034 
2035 /// Should this call expression be treated as a no-op?
IsNoOpCall(const CallExpr * E)2036 static bool IsNoOpCall(const CallExpr *E) {
2037   unsigned Builtin = E->getBuiltinCallee();
2038   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2039           Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2040           Builtin == Builtin::BI__builtin_function_start);
2041 }
2042 
IsGlobalLValue(APValue::LValueBase B)2043 static bool IsGlobalLValue(APValue::LValueBase B) {
2044   // C++11 [expr.const]p3 An address constant expression is a prvalue core
2045   // constant expression of pointer type that evaluates to...
2046 
2047   // ... a null pointer value, or a prvalue core constant expression of type
2048   // std::nullptr_t.
2049   if (!B)
2050     return true;
2051 
2052   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2053     // ... the address of an object with static storage duration,
2054     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2055       return VD->hasGlobalStorage();
2056     if (isa<TemplateParamObjectDecl>(D))
2057       return true;
2058     // ... the address of a function,
2059     // ... the address of a GUID [MS extension],
2060     // ... the address of an unnamed global constant
2061     return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2062   }
2063 
2064   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2065     return true;
2066 
2067   const Expr *E = B.get<const Expr*>();
2068   switch (E->getStmtClass()) {
2069   default:
2070     return false;
2071   case Expr::CompoundLiteralExprClass: {
2072     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2073     return CLE->isFileScope() && CLE->isLValue();
2074   }
2075   case Expr::MaterializeTemporaryExprClass:
2076     // A materialized temporary might have been lifetime-extended to static
2077     // storage duration.
2078     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2079   // A string literal has static storage duration.
2080   case Expr::StringLiteralClass:
2081   case Expr::PredefinedExprClass:
2082   case Expr::ObjCStringLiteralClass:
2083   case Expr::ObjCEncodeExprClass:
2084     return true;
2085   case Expr::ObjCBoxedExprClass:
2086     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2087   case Expr::CallExprClass:
2088     return IsNoOpCall(cast<CallExpr>(E));
2089   // For GCC compatibility, &&label has static storage duration.
2090   case Expr::AddrLabelExprClass:
2091     return true;
2092   // A Block literal expression may be used as the initialization value for
2093   // Block variables at global or local static scope.
2094   case Expr::BlockExprClass:
2095     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2096   // The APValue generated from a __builtin_source_location will be emitted as a
2097   // literal.
2098   case Expr::SourceLocExprClass:
2099     return true;
2100   case Expr::ImplicitValueInitExprClass:
2101     // FIXME:
2102     // We can never form an lvalue with an implicit value initialization as its
2103     // base through expression evaluation, so these only appear in one case: the
2104     // implicit variable declaration we invent when checking whether a constexpr
2105     // constructor can produce a constant expression. We must assume that such
2106     // an expression might be a global lvalue.
2107     return true;
2108   }
2109 }
2110 
GetLValueBaseDecl(const LValue & LVal)2111 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2112   return LVal.Base.dyn_cast<const ValueDecl*>();
2113 }
2114 
IsLiteralLValue(const LValue & Value)2115 static bool IsLiteralLValue(const LValue &Value) {
2116   if (Value.getLValueCallIndex())
2117     return false;
2118   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2119   return E && !isa<MaterializeTemporaryExpr>(E);
2120 }
2121 
IsWeakLValue(const LValue & Value)2122 static bool IsWeakLValue(const LValue &Value) {
2123   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2124   return Decl && Decl->isWeak();
2125 }
2126 
isZeroSized(const LValue & Value)2127 static bool isZeroSized(const LValue &Value) {
2128   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2129   if (Decl && isa<VarDecl>(Decl)) {
2130     QualType Ty = Decl->getType();
2131     if (Ty->isArrayType())
2132       return Ty->isIncompleteType() ||
2133              Decl->getASTContext().getTypeSize(Ty) == 0;
2134   }
2135   return false;
2136 }
2137 
HasSameBase(const LValue & A,const LValue & B)2138 static bool HasSameBase(const LValue &A, const LValue &B) {
2139   if (!A.getLValueBase())
2140     return !B.getLValueBase();
2141   if (!B.getLValueBase())
2142     return false;
2143 
2144   if (A.getLValueBase().getOpaqueValue() !=
2145       B.getLValueBase().getOpaqueValue())
2146     return false;
2147 
2148   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2149          A.getLValueVersion() == B.getLValueVersion();
2150 }
2151 
NoteLValueLocation(EvalInfo & Info,APValue::LValueBase Base)2152 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2153   assert(Base && "no location for a null lvalue");
2154   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2155 
2156   // For a parameter, find the corresponding call stack frame (if it still
2157   // exists), and point at the parameter of the function definition we actually
2158   // invoked.
2159   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2160     unsigned Idx = PVD->getFunctionScopeIndex();
2161     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2162       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2163           F->Arguments.Version == Base.getVersion() && F->Callee &&
2164           Idx < F->Callee->getNumParams()) {
2165         VD = F->Callee->getParamDecl(Idx);
2166         break;
2167       }
2168     }
2169   }
2170 
2171   if (VD)
2172     Info.Note(VD->getLocation(), diag::note_declared_at);
2173   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2174     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2175   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2176     // FIXME: Produce a note for dangling pointers too.
2177     if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2178       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2179                 diag::note_constexpr_dynamic_alloc_here);
2180   }
2181 
2182   // We have no information to show for a typeid(T) object.
2183 }
2184 
2185 enum class CheckEvaluationResultKind {
2186   ConstantExpression,
2187   FullyInitialized,
2188 };
2189 
2190 /// Materialized temporaries that we've already checked to determine if they're
2191 /// initializsed by a constant expression.
2192 using CheckedTemporaries =
2193     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2194 
2195 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2196                                   EvalInfo &Info, SourceLocation DiagLoc,
2197                                   QualType Type, const APValue &Value,
2198                                   ConstantExprKind Kind,
2199                                   const FieldDecl *SubobjectDecl,
2200                                   CheckedTemporaries &CheckedTemps);
2201 
2202 /// Check that this reference or pointer core constant expression is a valid
2203 /// value for an address or reference constant expression. Return true if we
2204 /// can fold this expression, whether or not it's a constant expression.
CheckLValueConstantExpression(EvalInfo & Info,SourceLocation Loc,QualType Type,const LValue & LVal,ConstantExprKind Kind,CheckedTemporaries & CheckedTemps)2205 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2206                                           QualType Type, const LValue &LVal,
2207                                           ConstantExprKind Kind,
2208                                           CheckedTemporaries &CheckedTemps) {
2209   bool IsReferenceType = Type->isReferenceType();
2210 
2211   APValue::LValueBase Base = LVal.getLValueBase();
2212   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2213 
2214   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2215   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2216 
2217   // Additional restrictions apply in a template argument. We only enforce the
2218   // C++20 restrictions here; additional syntactic and semantic restrictions
2219   // are applied elsewhere.
2220   if (isTemplateArgument(Kind)) {
2221     int InvalidBaseKind = -1;
2222     StringRef Ident;
2223     if (Base.is<TypeInfoLValue>())
2224       InvalidBaseKind = 0;
2225     else if (isa_and_nonnull<StringLiteral>(BaseE))
2226       InvalidBaseKind = 1;
2227     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2228              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2229       InvalidBaseKind = 2;
2230     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2231       InvalidBaseKind = 3;
2232       Ident = PE->getIdentKindName();
2233     }
2234 
2235     if (InvalidBaseKind != -1) {
2236       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2237           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2238           << Ident;
2239       return false;
2240     }
2241   }
2242 
2243   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2244       FD && FD->isImmediateFunction()) {
2245     Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2246         << !Type->isAnyPointerType();
2247     Info.Note(FD->getLocation(), diag::note_declared_at);
2248     return false;
2249   }
2250 
2251   // Check that the object is a global. Note that the fake 'this' object we
2252   // manufacture when checking potential constant expressions is conservatively
2253   // assumed to be global here.
2254   if (!IsGlobalLValue(Base)) {
2255     if (Info.getLangOpts().CPlusPlus11) {
2256       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2257           << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2258           << BaseVD;
2259       auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2260       if (VarD && VarD->isConstexpr()) {
2261         // Non-static local constexpr variables have unintuitive semantics:
2262         //   constexpr int a = 1;
2263         //   constexpr const int *p = &a;
2264         // ... is invalid because the address of 'a' is not constant. Suggest
2265         // adding a 'static' in this case.
2266         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2267             << VarD
2268             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2269       } else {
2270         NoteLValueLocation(Info, Base);
2271       }
2272     } else {
2273       Info.FFDiag(Loc);
2274     }
2275     // Don't allow references to temporaries to escape.
2276     return false;
2277   }
2278   assert((Info.checkingPotentialConstantExpression() ||
2279           LVal.getLValueCallIndex() == 0) &&
2280          "have call index for global lvalue");
2281 
2282   if (Base.is<DynamicAllocLValue>()) {
2283     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2284         << IsReferenceType << !Designator.Entries.empty();
2285     NoteLValueLocation(Info, Base);
2286     return false;
2287   }
2288 
2289   if (BaseVD) {
2290     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2291       // Check if this is a thread-local variable.
2292       if (Var->getTLSKind())
2293         // FIXME: Diagnostic!
2294         return false;
2295 
2296       // A dllimport variable never acts like a constant, unless we're
2297       // evaluating a value for use only in name mangling.
2298       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2299         // FIXME: Diagnostic!
2300         return false;
2301 
2302       // In CUDA/HIP device compilation, only device side variables have
2303       // constant addresses.
2304       if (Info.getCtx().getLangOpts().CUDA &&
2305           Info.getCtx().getLangOpts().CUDAIsDevice &&
2306           Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2307         if ((!Var->hasAttr<CUDADeviceAttr>() &&
2308              !Var->hasAttr<CUDAConstantAttr>() &&
2309              !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2310              !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2311             Var->hasAttr<HIPManagedAttr>())
2312           return false;
2313       }
2314     }
2315     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2316       // __declspec(dllimport) must be handled very carefully:
2317       // We must never initialize an expression with the thunk in C++.
2318       // Doing otherwise would allow the same id-expression to yield
2319       // different addresses for the same function in different translation
2320       // units.  However, this means that we must dynamically initialize the
2321       // expression with the contents of the import address table at runtime.
2322       //
2323       // The C language has no notion of ODR; furthermore, it has no notion of
2324       // dynamic initialization.  This means that we are permitted to
2325       // perform initialization with the address of the thunk.
2326       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2327           FD->hasAttr<DLLImportAttr>())
2328         // FIXME: Diagnostic!
2329         return false;
2330     }
2331   } else if (const auto *MTE =
2332                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2333     if (CheckedTemps.insert(MTE).second) {
2334       QualType TempType = getType(Base);
2335       if (TempType.isDestructedType()) {
2336         Info.FFDiag(MTE->getExprLoc(),
2337                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2338             << TempType;
2339         return false;
2340       }
2341 
2342       APValue *V = MTE->getOrCreateValue(false);
2343       assert(V && "evasluation result refers to uninitialised temporary");
2344       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2345                                  Info, MTE->getExprLoc(), TempType, *V, Kind,
2346                                  /*SubobjectDecl=*/nullptr, CheckedTemps))
2347         return false;
2348     }
2349   }
2350 
2351   // Allow address constant expressions to be past-the-end pointers. This is
2352   // an extension: the standard requires them to point to an object.
2353   if (!IsReferenceType)
2354     return true;
2355 
2356   // A reference constant expression must refer to an object.
2357   if (!Base) {
2358     // FIXME: diagnostic
2359     Info.CCEDiag(Loc);
2360     return true;
2361   }
2362 
2363   // Does this refer one past the end of some object?
2364   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2365     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2366       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2367     NoteLValueLocation(Info, Base);
2368   }
2369 
2370   return true;
2371 }
2372 
2373 /// Member pointers are constant expressions unless they point to a
2374 /// non-virtual dllimport member function.
CheckMemberPointerConstantExpression(EvalInfo & Info,SourceLocation Loc,QualType Type,const APValue & Value,ConstantExprKind Kind)2375 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2376                                                  SourceLocation Loc,
2377                                                  QualType Type,
2378                                                  const APValue &Value,
2379                                                  ConstantExprKind Kind) {
2380   const ValueDecl *Member = Value.getMemberPointerDecl();
2381   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2382   if (!FD)
2383     return true;
2384   if (FD->isImmediateFunction()) {
2385     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2386     Info.Note(FD->getLocation(), diag::note_declared_at);
2387     return false;
2388   }
2389   return isForManglingOnly(Kind) || FD->isVirtual() ||
2390          !FD->hasAttr<DLLImportAttr>();
2391 }
2392 
2393 /// Check that this core constant expression is of literal type, and if not,
2394 /// produce an appropriate diagnostic.
CheckLiteralType(EvalInfo & Info,const Expr * E,const LValue * This=nullptr)2395 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2396                              const LValue *This = nullptr) {
2397   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2398     return true;
2399 
2400   // C++1y: A constant initializer for an object o [...] may also invoke
2401   // constexpr constructors for o and its subobjects even if those objects
2402   // are of non-literal class types.
2403   //
2404   // C++11 missed this detail for aggregates, so classes like this:
2405   //   struct foo_t { union { int i; volatile int j; } u; };
2406   // are not (obviously) initializable like so:
2407   //   __attribute__((__require_constant_initialization__))
2408   //   static const foo_t x = {{0}};
2409   // because "i" is a subobject with non-literal initialization (due to the
2410   // volatile member of the union). See:
2411   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2412   // Therefore, we use the C++1y behavior.
2413   if (This && Info.EvaluatingDecl == This->getLValueBase())
2414     return true;
2415 
2416   // Prvalue constant expressions must be of literal types.
2417   if (Info.getLangOpts().CPlusPlus11)
2418     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2419       << E->getType();
2420   else
2421     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2422   return false;
2423 }
2424 
CheckEvaluationResult(CheckEvaluationResultKind CERK,EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value,ConstantExprKind Kind,const FieldDecl * SubobjectDecl,CheckedTemporaries & CheckedTemps)2425 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2426                                   EvalInfo &Info, SourceLocation DiagLoc,
2427                                   QualType Type, const APValue &Value,
2428                                   ConstantExprKind Kind,
2429                                   const FieldDecl *SubobjectDecl,
2430                                   CheckedTemporaries &CheckedTemps) {
2431   if (!Value.hasValue()) {
2432     if (SubobjectDecl) {
2433       Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2434           << /*(name)*/ 1 << SubobjectDecl;
2435       Info.Note(SubobjectDecl->getLocation(),
2436                 diag::note_constexpr_subobject_declared_here);
2437     } else {
2438       Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2439           << /*of type*/ 0 << Type;
2440     }
2441     return false;
2442   }
2443 
2444   // We allow _Atomic(T) to be initialized from anything that T can be
2445   // initialized from.
2446   if (const AtomicType *AT = Type->getAs<AtomicType>())
2447     Type = AT->getValueType();
2448 
2449   // Core issue 1454: For a literal constant expression of array or class type,
2450   // each subobject of its value shall have been initialized by a constant
2451   // expression.
2452   if (Value.isArray()) {
2453     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2454     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2455       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2456                                  Value.getArrayInitializedElt(I), Kind,
2457                                  SubobjectDecl, CheckedTemps))
2458         return false;
2459     }
2460     if (!Value.hasArrayFiller())
2461       return true;
2462     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2463                                  Value.getArrayFiller(), Kind, SubobjectDecl,
2464                                  CheckedTemps);
2465   }
2466   if (Value.isUnion() && Value.getUnionField()) {
2467     return CheckEvaluationResult(
2468         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2469         Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2470   }
2471   if (Value.isStruct()) {
2472     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2473     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2474       unsigned BaseIndex = 0;
2475       for (const CXXBaseSpecifier &BS : CD->bases()) {
2476         const APValue &BaseValue = Value.getStructBase(BaseIndex);
2477         if (!BaseValue.hasValue()) {
2478           SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2479           Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2480               << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2481           return false;
2482         }
2483         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2484                                    Kind, /*SubobjectDecl=*/nullptr,
2485                                    CheckedTemps))
2486           return false;
2487         ++BaseIndex;
2488       }
2489     }
2490     for (const auto *I : RD->fields()) {
2491       if (I->isUnnamedBitfield())
2492         continue;
2493 
2494       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2495                                  Value.getStructField(I->getFieldIndex()), Kind,
2496                                  I, CheckedTemps))
2497         return false;
2498     }
2499   }
2500 
2501   if (Value.isLValue() &&
2502       CERK == CheckEvaluationResultKind::ConstantExpression) {
2503     LValue LVal;
2504     LVal.setFrom(Info.Ctx, Value);
2505     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2506                                          CheckedTemps);
2507   }
2508 
2509   if (Value.isMemberPointer() &&
2510       CERK == CheckEvaluationResultKind::ConstantExpression)
2511     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2512 
2513   // Everything else is fine.
2514   return true;
2515 }
2516 
2517 /// Check that this core constant expression value is a valid value for a
2518 /// constant expression. If not, report an appropriate diagnostic. Does not
2519 /// check that the expression is of literal type.
CheckConstantExpression(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value,ConstantExprKind Kind)2520 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2521                                     QualType Type, const APValue &Value,
2522                                     ConstantExprKind Kind) {
2523   // Nothing to check for a constant expression of type 'cv void'.
2524   if (Type->isVoidType())
2525     return true;
2526 
2527   CheckedTemporaries CheckedTemps;
2528   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2529                                Info, DiagLoc, Type, Value, Kind,
2530                                /*SubobjectDecl=*/nullptr, CheckedTemps);
2531 }
2532 
2533 /// Check that this evaluated value is fully-initialized and can be loaded by
2534 /// an lvalue-to-rvalue conversion.
CheckFullyInitialized(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value)2535 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2536                                   QualType Type, const APValue &Value) {
2537   CheckedTemporaries CheckedTemps;
2538   return CheckEvaluationResult(
2539       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2540       ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2541 }
2542 
2543 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2544 /// "the allocated storage is deallocated within the evaluation".
CheckMemoryLeaks(EvalInfo & Info)2545 static bool CheckMemoryLeaks(EvalInfo &Info) {
2546   if (!Info.HeapAllocs.empty()) {
2547     // We can still fold to a constant despite a compile-time memory leak,
2548     // so long as the heap allocation isn't referenced in the result (we check
2549     // that in CheckConstantExpression).
2550     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2551                  diag::note_constexpr_memory_leak)
2552         << unsigned(Info.HeapAllocs.size() - 1);
2553   }
2554   return true;
2555 }
2556 
EvalPointerValueAsBool(const APValue & Value,bool & Result)2557 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2558   // A null base expression indicates a null pointer.  These are always
2559   // evaluatable, and they are false unless the offset is zero.
2560   if (!Value.getLValueBase()) {
2561     // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2562     Result = !Value.getLValueOffset().isZero();
2563     return true;
2564   }
2565 
2566   // We have a non-null base.  These are generally known to be true, but if it's
2567   // a weak declaration it can be null at runtime.
2568   Result = true;
2569   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2570   return !Decl || !Decl->isWeak();
2571 }
2572 
HandleConversionToBool(const APValue & Val,bool & Result)2573 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2574   // TODO: This function should produce notes if it fails.
2575   switch (Val.getKind()) {
2576   case APValue::None:
2577   case APValue::Indeterminate:
2578     return false;
2579   case APValue::Int:
2580     Result = Val.getInt().getBoolValue();
2581     return true;
2582   case APValue::FixedPoint:
2583     Result = Val.getFixedPoint().getBoolValue();
2584     return true;
2585   case APValue::Float:
2586     Result = !Val.getFloat().isZero();
2587     return true;
2588   case APValue::ComplexInt:
2589     Result = Val.getComplexIntReal().getBoolValue() ||
2590              Val.getComplexIntImag().getBoolValue();
2591     return true;
2592   case APValue::ComplexFloat:
2593     Result = !Val.getComplexFloatReal().isZero() ||
2594              !Val.getComplexFloatImag().isZero();
2595     return true;
2596   case APValue::LValue:
2597     return EvalPointerValueAsBool(Val, Result);
2598   case APValue::MemberPointer:
2599     if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2600       return false;
2601     }
2602     Result = Val.getMemberPointerDecl();
2603     return true;
2604   case APValue::Vector:
2605   case APValue::Array:
2606   case APValue::Struct:
2607   case APValue::Union:
2608   case APValue::AddrLabelDiff:
2609     return false;
2610   }
2611 
2612   llvm_unreachable("unknown APValue kind");
2613 }
2614 
EvaluateAsBooleanCondition(const Expr * E,bool & Result,EvalInfo & Info)2615 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2616                                        EvalInfo &Info) {
2617   assert(!E->isValueDependent());
2618   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2619   APValue Val;
2620   if (!Evaluate(Val, Info, E))
2621     return false;
2622   return HandleConversionToBool(Val, Result);
2623 }
2624 
2625 template<typename T>
HandleOverflow(EvalInfo & Info,const Expr * E,const T & SrcValue,QualType DestType)2626 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2627                            const T &SrcValue, QualType DestType) {
2628   Info.CCEDiag(E, diag::note_constexpr_overflow)
2629     << SrcValue << DestType;
2630   return Info.noteUndefinedBehavior();
2631 }
2632 
HandleFloatToIntCast(EvalInfo & Info,const Expr * E,QualType SrcType,const APFloat & Value,QualType DestType,APSInt & Result)2633 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2634                                  QualType SrcType, const APFloat &Value,
2635                                  QualType DestType, APSInt &Result) {
2636   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2637   // Determine whether we are converting to unsigned or signed.
2638   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2639 
2640   Result = APSInt(DestWidth, !DestSigned);
2641   bool ignored;
2642   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2643       & APFloat::opInvalidOp)
2644     return HandleOverflow(Info, E, Value, DestType);
2645   return true;
2646 }
2647 
2648 /// Get rounding mode to use in evaluation of the specified expression.
2649 ///
2650 /// If rounding mode is unknown at compile time, still try to evaluate the
2651 /// expression. If the result is exact, it does not depend on rounding mode.
2652 /// So return "tonearest" mode instead of "dynamic".
getActiveRoundingMode(EvalInfo & Info,const Expr * E)2653 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2654   llvm::RoundingMode RM =
2655       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2656   if (RM == llvm::RoundingMode::Dynamic)
2657     RM = llvm::RoundingMode::NearestTiesToEven;
2658   return RM;
2659 }
2660 
2661 /// Check if the given evaluation result is allowed for constant evaluation.
checkFloatingPointResult(EvalInfo & Info,const Expr * E,APFloat::opStatus St)2662 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2663                                      APFloat::opStatus St) {
2664   // In a constant context, assume that any dynamic rounding mode or FP
2665   // exception state matches the default floating-point environment.
2666   if (Info.InConstantContext)
2667     return true;
2668 
2669   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2670   if ((St & APFloat::opInexact) &&
2671       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2672     // Inexact result means that it depends on rounding mode. If the requested
2673     // mode is dynamic, the evaluation cannot be made in compile time.
2674     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2675     return false;
2676   }
2677 
2678   if ((St != APFloat::opOK) &&
2679       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2680        FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2681        FPO.getAllowFEnvAccess())) {
2682     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2683     return false;
2684   }
2685 
2686   if ((St & APFloat::opStatus::opInvalidOp) &&
2687       FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2688     // There is no usefully definable result.
2689     Info.FFDiag(E);
2690     return false;
2691   }
2692 
2693   // FIXME: if:
2694   // - evaluation triggered other FP exception, and
2695   // - exception mode is not "ignore", and
2696   // - the expression being evaluated is not a part of global variable
2697   //   initializer,
2698   // the evaluation probably need to be rejected.
2699   return true;
2700 }
2701 
HandleFloatToFloatCast(EvalInfo & Info,const Expr * E,QualType SrcType,QualType DestType,APFloat & Result)2702 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2703                                    QualType SrcType, QualType DestType,
2704                                    APFloat &Result) {
2705   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2706   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2707   APFloat::opStatus St;
2708   APFloat Value = Result;
2709   bool ignored;
2710   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2711   return checkFloatingPointResult(Info, E, St);
2712 }
2713 
HandleIntToIntCast(EvalInfo & Info,const Expr * E,QualType DestType,QualType SrcType,const APSInt & Value)2714 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2715                                  QualType DestType, QualType SrcType,
2716                                  const APSInt &Value) {
2717   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2718   // Figure out if this is a truncate, extend or noop cast.
2719   // If the input is signed, do a sign extend, noop, or truncate.
2720   APSInt Result = Value.extOrTrunc(DestWidth);
2721   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2722   if (DestType->isBooleanType())
2723     Result = Value.getBoolValue();
2724   return Result;
2725 }
2726 
HandleIntToFloatCast(EvalInfo & Info,const Expr * E,const FPOptions FPO,QualType SrcType,const APSInt & Value,QualType DestType,APFloat & Result)2727 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2728                                  const FPOptions FPO,
2729                                  QualType SrcType, const APSInt &Value,
2730                                  QualType DestType, APFloat &Result) {
2731   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2732   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2733   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2734   return checkFloatingPointResult(Info, E, St);
2735 }
2736 
truncateBitfieldValue(EvalInfo & Info,const Expr * E,APValue & Value,const FieldDecl * FD)2737 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2738                                   APValue &Value, const FieldDecl *FD) {
2739   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2740 
2741   if (!Value.isInt()) {
2742     // Trying to store a pointer-cast-to-integer into a bitfield.
2743     // FIXME: In this case, we should provide the diagnostic for casting
2744     // a pointer to an integer.
2745     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2746     Info.FFDiag(E);
2747     return false;
2748   }
2749 
2750   APSInt &Int = Value.getInt();
2751   unsigned OldBitWidth = Int.getBitWidth();
2752   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2753   if (NewBitWidth < OldBitWidth)
2754     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2755   return true;
2756 }
2757 
2758 /// Perform the given integer operation, which is known to need at most BitWidth
2759 /// bits, and check for overflow in the original type (if that type was not an
2760 /// unsigned type).
2761 template<typename Operation>
CheckedIntArithmetic(EvalInfo & Info,const Expr * E,const APSInt & LHS,const APSInt & RHS,unsigned BitWidth,Operation Op,APSInt & Result)2762 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2763                                  const APSInt &LHS, const APSInt &RHS,
2764                                  unsigned BitWidth, Operation Op,
2765                                  APSInt &Result) {
2766   if (LHS.isUnsigned()) {
2767     Result = Op(LHS, RHS);
2768     return true;
2769   }
2770 
2771   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2772   Result = Value.trunc(LHS.getBitWidth());
2773   if (Result.extend(BitWidth) != Value) {
2774     if (Info.checkingForUndefinedBehavior())
2775       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2776                                        diag::warn_integer_constant_overflow)
2777           << toString(Result, 10) << E->getType() << E->getSourceRange();
2778     return HandleOverflow(Info, E, Value, E->getType());
2779   }
2780   return true;
2781 }
2782 
2783 /// Perform the given binary integer operation.
handleIntIntBinOp(EvalInfo & Info,const BinaryOperator * E,const APSInt & LHS,BinaryOperatorKind Opcode,APSInt RHS,APSInt & Result)2784 static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2785                               const APSInt &LHS, BinaryOperatorKind Opcode,
2786                               APSInt RHS, APSInt &Result) {
2787   bool HandleOverflowResult = true;
2788   switch (Opcode) {
2789   default:
2790     Info.FFDiag(E);
2791     return false;
2792   case BO_Mul:
2793     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2794                                 std::multiplies<APSInt>(), Result);
2795   case BO_Add:
2796     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2797                                 std::plus<APSInt>(), Result);
2798   case BO_Sub:
2799     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2800                                 std::minus<APSInt>(), Result);
2801   case BO_And: Result = LHS & RHS; return true;
2802   case BO_Xor: Result = LHS ^ RHS; return true;
2803   case BO_Or:  Result = LHS | RHS; return true;
2804   case BO_Div:
2805   case BO_Rem:
2806     if (RHS == 0) {
2807       Info.FFDiag(E, diag::note_expr_divide_by_zero)
2808           << E->getRHS()->getSourceRange();
2809       return false;
2810     }
2811     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2812     // this operation and gives the two's complement result.
2813     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2814         LHS.isMinSignedValue())
2815       HandleOverflowResult = HandleOverflow(
2816           Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2817     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2818     return HandleOverflowResult;
2819   case BO_Shl: {
2820     if (Info.getLangOpts().OpenCL)
2821       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2822       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2823                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2824                     RHS.isUnsigned());
2825     else if (RHS.isSigned() && RHS.isNegative()) {
2826       // During constant-folding, a negative shift is an opposite shift. Such
2827       // a shift is not a constant expression.
2828       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2829       RHS = -RHS;
2830       goto shift_right;
2831     }
2832   shift_left:
2833     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2834     // the shifted type.
2835     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2836     if (SA != RHS) {
2837       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2838         << RHS << E->getType() << LHS.getBitWidth();
2839     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2840       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2841       // operand, and must not overflow the corresponding unsigned type.
2842       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2843       // E1 x 2^E2 module 2^N.
2844       if (LHS.isNegative())
2845         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2846       else if (LHS.countl_zero() < SA)
2847         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2848     }
2849     Result = LHS << SA;
2850     return true;
2851   }
2852   case BO_Shr: {
2853     if (Info.getLangOpts().OpenCL)
2854       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2855       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2856                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2857                     RHS.isUnsigned());
2858     else if (RHS.isSigned() && RHS.isNegative()) {
2859       // During constant-folding, a negative shift is an opposite shift. Such a
2860       // shift is not a constant expression.
2861       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2862       RHS = -RHS;
2863       goto shift_left;
2864     }
2865   shift_right:
2866     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2867     // shifted type.
2868     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2869     if (SA != RHS)
2870       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2871         << RHS << E->getType() << LHS.getBitWidth();
2872     Result = LHS >> SA;
2873     return true;
2874   }
2875 
2876   case BO_LT: Result = LHS < RHS; return true;
2877   case BO_GT: Result = LHS > RHS; return true;
2878   case BO_LE: Result = LHS <= RHS; return true;
2879   case BO_GE: Result = LHS >= RHS; return true;
2880   case BO_EQ: Result = LHS == RHS; return true;
2881   case BO_NE: Result = LHS != RHS; return true;
2882   case BO_Cmp:
2883     llvm_unreachable("BO_Cmp should be handled elsewhere");
2884   }
2885 }
2886 
2887 /// Perform the given binary floating-point operation, in-place, on LHS.
handleFloatFloatBinOp(EvalInfo & Info,const BinaryOperator * E,APFloat & LHS,BinaryOperatorKind Opcode,const APFloat & RHS)2888 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2889                                   APFloat &LHS, BinaryOperatorKind Opcode,
2890                                   const APFloat &RHS) {
2891   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2892   APFloat::opStatus St;
2893   switch (Opcode) {
2894   default:
2895     Info.FFDiag(E);
2896     return false;
2897   case BO_Mul:
2898     St = LHS.multiply(RHS, RM);
2899     break;
2900   case BO_Add:
2901     St = LHS.add(RHS, RM);
2902     break;
2903   case BO_Sub:
2904     St = LHS.subtract(RHS, RM);
2905     break;
2906   case BO_Div:
2907     // [expr.mul]p4:
2908     //   If the second operand of / or % is zero the behavior is undefined.
2909     if (RHS.isZero())
2910       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2911     St = LHS.divide(RHS, RM);
2912     break;
2913   }
2914 
2915   // [expr.pre]p4:
2916   //   If during the evaluation of an expression, the result is not
2917   //   mathematically defined [...], the behavior is undefined.
2918   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2919   if (LHS.isNaN()) {
2920     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2921     return Info.noteUndefinedBehavior();
2922   }
2923 
2924   return checkFloatingPointResult(Info, E, St);
2925 }
2926 
handleLogicalOpForVector(const APInt & LHSValue,BinaryOperatorKind Opcode,const APInt & RHSValue,APInt & Result)2927 static bool handleLogicalOpForVector(const APInt &LHSValue,
2928                                      BinaryOperatorKind Opcode,
2929                                      const APInt &RHSValue, APInt &Result) {
2930   bool LHS = (LHSValue != 0);
2931   bool RHS = (RHSValue != 0);
2932 
2933   if (Opcode == BO_LAnd)
2934     Result = LHS && RHS;
2935   else
2936     Result = LHS || RHS;
2937   return true;
2938 }
handleLogicalOpForVector(const APFloat & LHSValue,BinaryOperatorKind Opcode,const APFloat & RHSValue,APInt & Result)2939 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2940                                      BinaryOperatorKind Opcode,
2941                                      const APFloat &RHSValue, APInt &Result) {
2942   bool LHS = !LHSValue.isZero();
2943   bool RHS = !RHSValue.isZero();
2944 
2945   if (Opcode == BO_LAnd)
2946     Result = LHS && RHS;
2947   else
2948     Result = LHS || RHS;
2949   return true;
2950 }
2951 
handleLogicalOpForVector(const APValue & LHSValue,BinaryOperatorKind Opcode,const APValue & RHSValue,APInt & Result)2952 static bool handleLogicalOpForVector(const APValue &LHSValue,
2953                                      BinaryOperatorKind Opcode,
2954                                      const APValue &RHSValue, APInt &Result) {
2955   // The result is always an int type, however operands match the first.
2956   if (LHSValue.getKind() == APValue::Int)
2957     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2958                                     RHSValue.getInt(), Result);
2959   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2960   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2961                                   RHSValue.getFloat(), Result);
2962 }
2963 
2964 template <typename APTy>
2965 static bool
handleCompareOpForVectorHelper(const APTy & LHSValue,BinaryOperatorKind Opcode,const APTy & RHSValue,APInt & Result)2966 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2967                                const APTy &RHSValue, APInt &Result) {
2968   switch (Opcode) {
2969   default:
2970     llvm_unreachable("unsupported binary operator");
2971   case BO_EQ:
2972     Result = (LHSValue == RHSValue);
2973     break;
2974   case BO_NE:
2975     Result = (LHSValue != RHSValue);
2976     break;
2977   case BO_LT:
2978     Result = (LHSValue < RHSValue);
2979     break;
2980   case BO_GT:
2981     Result = (LHSValue > RHSValue);
2982     break;
2983   case BO_LE:
2984     Result = (LHSValue <= RHSValue);
2985     break;
2986   case BO_GE:
2987     Result = (LHSValue >= RHSValue);
2988     break;
2989   }
2990 
2991   // The boolean operations on these vector types use an instruction that
2992   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2993   // to -1 to make sure that we produce the correct value.
2994   Result.negate();
2995 
2996   return true;
2997 }
2998 
handleCompareOpForVector(const APValue & LHSValue,BinaryOperatorKind Opcode,const APValue & RHSValue,APInt & Result)2999 static bool handleCompareOpForVector(const APValue &LHSValue,
3000                                      BinaryOperatorKind Opcode,
3001                                      const APValue &RHSValue, APInt &Result) {
3002   // The result is always an int type, however operands match the first.
3003   if (LHSValue.getKind() == APValue::Int)
3004     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3005                                           RHSValue.getInt(), Result);
3006   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3007   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3008                                         RHSValue.getFloat(), Result);
3009 }
3010 
3011 // Perform binary operations for vector types, in place on the LHS.
handleVectorVectorBinOp(EvalInfo & Info,const BinaryOperator * E,BinaryOperatorKind Opcode,APValue & LHSValue,const APValue & RHSValue)3012 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3013                                     BinaryOperatorKind Opcode,
3014                                     APValue &LHSValue,
3015                                     const APValue &RHSValue) {
3016   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3017          "Operation not supported on vector types");
3018 
3019   const auto *VT = E->getType()->castAs<VectorType>();
3020   unsigned NumElements = VT->getNumElements();
3021   QualType EltTy = VT->getElementType();
3022 
3023   // In the cases (typically C as I've observed) where we aren't evaluating
3024   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3025   // just give up.
3026   if (!LHSValue.isVector()) {
3027     assert(LHSValue.isLValue() &&
3028            "A vector result that isn't a vector OR uncalculated LValue");
3029     Info.FFDiag(E);
3030     return false;
3031   }
3032 
3033   assert(LHSValue.getVectorLength() == NumElements &&
3034          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3035 
3036   SmallVector<APValue, 4> ResultElements;
3037 
3038   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3039     APValue LHSElt = LHSValue.getVectorElt(EltNum);
3040     APValue RHSElt = RHSValue.getVectorElt(EltNum);
3041 
3042     if (EltTy->isIntegerType()) {
3043       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3044                        EltTy->isUnsignedIntegerType()};
3045       bool Success = true;
3046 
3047       if (BinaryOperator::isLogicalOp(Opcode))
3048         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3049       else if (BinaryOperator::isComparisonOp(Opcode))
3050         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3051       else
3052         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3053                                     RHSElt.getInt(), EltResult);
3054 
3055       if (!Success) {
3056         Info.FFDiag(E);
3057         return false;
3058       }
3059       ResultElements.emplace_back(EltResult);
3060 
3061     } else if (EltTy->isFloatingType()) {
3062       assert(LHSElt.getKind() == APValue::Float &&
3063              RHSElt.getKind() == APValue::Float &&
3064              "Mismatched LHS/RHS/Result Type");
3065       APFloat LHSFloat = LHSElt.getFloat();
3066 
3067       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3068                                  RHSElt.getFloat())) {
3069         Info.FFDiag(E);
3070         return false;
3071       }
3072 
3073       ResultElements.emplace_back(LHSFloat);
3074     }
3075   }
3076 
3077   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3078   return true;
3079 }
3080 
3081 /// Cast an lvalue referring to a base subobject to a derived class, by
3082 /// truncating the lvalue's path to the given length.
CastToDerivedClass(EvalInfo & Info,const Expr * E,LValue & Result,const RecordDecl * TruncatedType,unsigned TruncatedElements)3083 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3084                                const RecordDecl *TruncatedType,
3085                                unsigned TruncatedElements) {
3086   SubobjectDesignator &D = Result.Designator;
3087 
3088   // Check we actually point to a derived class object.
3089   if (TruncatedElements == D.Entries.size())
3090     return true;
3091   assert(TruncatedElements >= D.MostDerivedPathLength &&
3092          "not casting to a derived class");
3093   if (!Result.checkSubobject(Info, E, CSK_Derived))
3094     return false;
3095 
3096   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3097   const RecordDecl *RD = TruncatedType;
3098   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3099     if (RD->isInvalidDecl()) return false;
3100     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3101     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3102     if (isVirtualBaseClass(D.Entries[I]))
3103       Result.Offset -= Layout.getVBaseClassOffset(Base);
3104     else
3105       Result.Offset -= Layout.getBaseClassOffset(Base);
3106     RD = Base;
3107   }
3108   D.Entries.resize(TruncatedElements);
3109   return true;
3110 }
3111 
HandleLValueDirectBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * Derived,const CXXRecordDecl * Base,const ASTRecordLayout * RL=nullptr)3112 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3113                                    const CXXRecordDecl *Derived,
3114                                    const CXXRecordDecl *Base,
3115                                    const ASTRecordLayout *RL = nullptr) {
3116   if (!RL) {
3117     if (Derived->isInvalidDecl()) return false;
3118     RL = &Info.Ctx.getASTRecordLayout(Derived);
3119   }
3120 
3121   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3122   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3123   return true;
3124 }
3125 
HandleLValueBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * DerivedDecl,const CXXBaseSpecifier * Base)3126 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3127                              const CXXRecordDecl *DerivedDecl,
3128                              const CXXBaseSpecifier *Base) {
3129   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3130 
3131   if (!Base->isVirtual())
3132     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3133 
3134   SubobjectDesignator &D = Obj.Designator;
3135   if (D.Invalid)
3136     return false;
3137 
3138   // Extract most-derived object and corresponding type.
3139   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3140   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3141     return false;
3142 
3143   // Find the virtual base class.
3144   if (DerivedDecl->isInvalidDecl()) return false;
3145   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3146   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3147   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3148   return true;
3149 }
3150 
HandleLValueBasePath(EvalInfo & Info,const CastExpr * E,QualType Type,LValue & Result)3151 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3152                                  QualType Type, LValue &Result) {
3153   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3154                                      PathE = E->path_end();
3155        PathI != PathE; ++PathI) {
3156     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3157                           *PathI))
3158       return false;
3159     Type = (*PathI)->getType();
3160   }
3161   return true;
3162 }
3163 
3164 /// Cast an lvalue referring to a derived class to a known base subobject.
CastToBaseClass(EvalInfo & Info,const Expr * E,LValue & Result,const CXXRecordDecl * DerivedRD,const CXXRecordDecl * BaseRD)3165 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3166                             const CXXRecordDecl *DerivedRD,
3167                             const CXXRecordDecl *BaseRD) {
3168   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3169                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3170   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3171     llvm_unreachable("Class must be derived from the passed in base class!");
3172 
3173   for (CXXBasePathElement &Elem : Paths.front())
3174     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3175       return false;
3176   return true;
3177 }
3178 
3179 /// Update LVal to refer to the given field, which must be a member of the type
3180 /// currently described by LVal.
HandleLValueMember(EvalInfo & Info,const Expr * E,LValue & LVal,const FieldDecl * FD,const ASTRecordLayout * RL=nullptr)3181 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3182                                const FieldDecl *FD,
3183                                const ASTRecordLayout *RL = nullptr) {
3184   if (!RL) {
3185     if (FD->getParent()->isInvalidDecl()) return false;
3186     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3187   }
3188 
3189   unsigned I = FD->getFieldIndex();
3190   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3191   LVal.addDecl(Info, E, FD);
3192   return true;
3193 }
3194 
3195 /// Update LVal to refer to the given indirect field.
HandleLValueIndirectMember(EvalInfo & Info,const Expr * E,LValue & LVal,const IndirectFieldDecl * IFD)3196 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3197                                        LValue &LVal,
3198                                        const IndirectFieldDecl *IFD) {
3199   for (const auto *C : IFD->chain())
3200     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3201       return false;
3202   return true;
3203 }
3204 
3205 enum class SizeOfType {
3206   SizeOf,
3207   DataSizeOf,
3208 };
3209 
3210 /// Get the size of the given type in char units.
HandleSizeof(EvalInfo & Info,SourceLocation Loc,QualType Type,CharUnits & Size,SizeOfType SOT=SizeOfType::SizeOf)3211 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3212                          CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3213   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3214   // extension.
3215   if (Type->isVoidType() || Type->isFunctionType()) {
3216     Size = CharUnits::One();
3217     return true;
3218   }
3219 
3220   if (Type->isDependentType()) {
3221     Info.FFDiag(Loc);
3222     return false;
3223   }
3224 
3225   if (!Type->isConstantSizeType()) {
3226     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3227     // FIXME: Better diagnostic.
3228     Info.FFDiag(Loc);
3229     return false;
3230   }
3231 
3232   if (SOT == SizeOfType::SizeOf)
3233     Size = Info.Ctx.getTypeSizeInChars(Type);
3234   else
3235     Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3236   return true;
3237 }
3238 
3239 /// Update a pointer value to model pointer arithmetic.
3240 /// \param Info - Information about the ongoing evaluation.
3241 /// \param E - The expression being evaluated, for diagnostic purposes.
3242 /// \param LVal - The pointer value to be updated.
3243 /// \param EltTy - The pointee type represented by LVal.
3244 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,APSInt Adjustment)3245 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3246                                         LValue &LVal, QualType EltTy,
3247                                         APSInt Adjustment) {
3248   CharUnits SizeOfPointee;
3249   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3250     return false;
3251 
3252   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3253   return true;
3254 }
3255 
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,int64_t Adjustment)3256 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3257                                         LValue &LVal, QualType EltTy,
3258                                         int64_t Adjustment) {
3259   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3260                                      APSInt::get(Adjustment));
3261 }
3262 
3263 /// Update an lvalue to refer to a component of a complex number.
3264 /// \param Info - Information about the ongoing evaluation.
3265 /// \param LVal - The lvalue to be updated.
3266 /// \param EltTy - The complex number's component type.
3267 /// \param Imag - False for the real component, true for the imaginary.
HandleLValueComplexElement(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,bool Imag)3268 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3269                                        LValue &LVal, QualType EltTy,
3270                                        bool Imag) {
3271   if (Imag) {
3272     CharUnits SizeOfComponent;
3273     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3274       return false;
3275     LVal.Offset += SizeOfComponent;
3276   }
3277   LVal.addComplex(Info, E, EltTy, Imag);
3278   return true;
3279 }
3280 
3281 /// Try to evaluate the initializer for a variable declaration.
3282 ///
3283 /// \param Info   Information about the ongoing evaluation.
3284 /// \param E      An expression to be used when printing diagnostics.
3285 /// \param VD     The variable whose initializer should be obtained.
3286 /// \param Version The version of the variable within the frame.
3287 /// \param Frame  The frame in which the variable was created. Must be null
3288 ///               if this variable is not local to the evaluation.
3289 /// \param Result Filled in with a pointer to the value of the variable.
evaluateVarDeclInit(EvalInfo & Info,const Expr * E,const VarDecl * VD,CallStackFrame * Frame,unsigned Version,APValue * & Result)3290 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3291                                 const VarDecl *VD, CallStackFrame *Frame,
3292                                 unsigned Version, APValue *&Result) {
3293   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3294 
3295   // If this is a local variable, dig out its value.
3296   if (Frame) {
3297     Result = Frame->getTemporary(VD, Version);
3298     if (Result)
3299       return true;
3300 
3301     if (!isa<ParmVarDecl>(VD)) {
3302       // Assume variables referenced within a lambda's call operator that were
3303       // not declared within the call operator are captures and during checking
3304       // of a potential constant expression, assume they are unknown constant
3305       // expressions.
3306       assert(isLambdaCallOperator(Frame->Callee) &&
3307              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3308              "missing value for local variable");
3309       if (Info.checkingPotentialConstantExpression())
3310         return false;
3311       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3312       // still reachable at all?
3313       Info.FFDiag(E->getBeginLoc(),
3314                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3315           << "captures not currently allowed";
3316       return false;
3317     }
3318   }
3319 
3320   // If we're currently evaluating the initializer of this declaration, use that
3321   // in-flight value.
3322   if (Info.EvaluatingDecl == Base) {
3323     Result = Info.EvaluatingDeclValue;
3324     return true;
3325   }
3326 
3327   if (isa<ParmVarDecl>(VD)) {
3328     // Assume parameters of a potential constant expression are usable in
3329     // constant expressions.
3330     if (!Info.checkingPotentialConstantExpression() ||
3331         !Info.CurrentCall->Callee ||
3332         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3333       if (Info.getLangOpts().CPlusPlus11) {
3334         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3335             << VD;
3336         NoteLValueLocation(Info, Base);
3337       } else {
3338         Info.FFDiag(E);
3339       }
3340     }
3341     return false;
3342   }
3343 
3344   if (E->isValueDependent())
3345     return false;
3346 
3347   // Dig out the initializer, and use the declaration which it's attached to.
3348   // FIXME: We should eventually check whether the variable has a reachable
3349   // initializing declaration.
3350   const Expr *Init = VD->getAnyInitializer(VD);
3351   if (!Init) {
3352     // Don't diagnose during potential constant expression checking; an
3353     // initializer might be added later.
3354     if (!Info.checkingPotentialConstantExpression()) {
3355       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3356         << VD;
3357       NoteLValueLocation(Info, Base);
3358     }
3359     return false;
3360   }
3361 
3362   if (Init->isValueDependent()) {
3363     // The DeclRefExpr is not value-dependent, but the variable it refers to
3364     // has a value-dependent initializer. This should only happen in
3365     // constant-folding cases, where the variable is not actually of a suitable
3366     // type for use in a constant expression (otherwise the DeclRefExpr would
3367     // have been value-dependent too), so diagnose that.
3368     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3369     if (!Info.checkingPotentialConstantExpression()) {
3370       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3371                          ? diag::note_constexpr_ltor_non_constexpr
3372                          : diag::note_constexpr_ltor_non_integral, 1)
3373           << VD << VD->getType();
3374       NoteLValueLocation(Info, Base);
3375     }
3376     return false;
3377   }
3378 
3379   // Check that we can fold the initializer. In C++, we will have already done
3380   // this in the cases where it matters for conformance.
3381   if (!VD->evaluateValue()) {
3382     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3383     NoteLValueLocation(Info, Base);
3384     return false;
3385   }
3386 
3387   // Check that the variable is actually usable in constant expressions. For a
3388   // const integral variable or a reference, we might have a non-constant
3389   // initializer that we can nonetheless evaluate the initializer for. Such
3390   // variables are not usable in constant expressions. In C++98, the
3391   // initializer also syntactically needs to be an ICE.
3392   //
3393   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3394   // expressions here; doing so would regress diagnostics for things like
3395   // reading from a volatile constexpr variable.
3396   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3397        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3398       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3399        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3400     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3401     NoteLValueLocation(Info, Base);
3402   }
3403 
3404   // Never use the initializer of a weak variable, not even for constant
3405   // folding. We can't be sure that this is the definition that will be used.
3406   if (VD->isWeak()) {
3407     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3408     NoteLValueLocation(Info, Base);
3409     return false;
3410   }
3411 
3412   Result = VD->getEvaluatedValue();
3413   return true;
3414 }
3415 
3416 /// Get the base index of the given base class within an APValue representing
3417 /// the given derived class.
getBaseIndex(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)3418 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3419                              const CXXRecordDecl *Base) {
3420   Base = Base->getCanonicalDecl();
3421   unsigned Index = 0;
3422   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3423          E = Derived->bases_end(); I != E; ++I, ++Index) {
3424     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3425       return Index;
3426   }
3427 
3428   llvm_unreachable("base class missing from derived class's bases list");
3429 }
3430 
3431 /// Extract the value of a character from a string literal.
extractStringLiteralCharacter(EvalInfo & Info,const Expr * Lit,uint64_t Index)3432 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3433                                             uint64_t Index) {
3434   assert(!isa<SourceLocExpr>(Lit) &&
3435          "SourceLocExpr should have already been converted to a StringLiteral");
3436 
3437   // FIXME: Support MakeStringConstant
3438   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3439     std::string Str;
3440     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3441     assert(Index <= Str.size() && "Index too large");
3442     return APSInt::getUnsigned(Str.c_str()[Index]);
3443   }
3444 
3445   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3446     Lit = PE->getFunctionName();
3447   const StringLiteral *S = cast<StringLiteral>(Lit);
3448   const ConstantArrayType *CAT =
3449       Info.Ctx.getAsConstantArrayType(S->getType());
3450   assert(CAT && "string literal isn't an array");
3451   QualType CharType = CAT->getElementType();
3452   assert(CharType->isIntegerType() && "unexpected character type");
3453   APSInt Value(Info.Ctx.getTypeSize(CharType),
3454                CharType->isUnsignedIntegerType());
3455   if (Index < S->getLength())
3456     Value = S->getCodeUnit(Index);
3457   return Value;
3458 }
3459 
3460 // Expand a string literal into an array of characters.
3461 //
3462 // FIXME: This is inefficient; we should probably introduce something similar
3463 // to the LLVM ConstantDataArray to make this cheaper.
expandStringLiteral(EvalInfo & Info,const StringLiteral * S,APValue & Result,QualType AllocType=QualType ())3464 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3465                                 APValue &Result,
3466                                 QualType AllocType = QualType()) {
3467   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3468       AllocType.isNull() ? S->getType() : AllocType);
3469   assert(CAT && "string literal isn't an array");
3470   QualType CharType = CAT->getElementType();
3471   assert(CharType->isIntegerType() && "unexpected character type");
3472 
3473   unsigned Elts = CAT->getSize().getZExtValue();
3474   Result = APValue(APValue::UninitArray(),
3475                    std::min(S->getLength(), Elts), Elts);
3476   APSInt Value(Info.Ctx.getTypeSize(CharType),
3477                CharType->isUnsignedIntegerType());
3478   if (Result.hasArrayFiller())
3479     Result.getArrayFiller() = APValue(Value);
3480   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3481     Value = S->getCodeUnit(I);
3482     Result.getArrayInitializedElt(I) = APValue(Value);
3483   }
3484 }
3485 
3486 // Expand an array so that it has more than Index filled elements.
expandArray(APValue & Array,unsigned Index)3487 static void expandArray(APValue &Array, unsigned Index) {
3488   unsigned Size = Array.getArraySize();
3489   assert(Index < Size);
3490 
3491   // Always at least double the number of elements for which we store a value.
3492   unsigned OldElts = Array.getArrayInitializedElts();
3493   unsigned NewElts = std::max(Index+1, OldElts * 2);
3494   NewElts = std::min(Size, std::max(NewElts, 8u));
3495 
3496   // Copy the data across.
3497   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3498   for (unsigned I = 0; I != OldElts; ++I)
3499     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3500   for (unsigned I = OldElts; I != NewElts; ++I)
3501     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3502   if (NewValue.hasArrayFiller())
3503     NewValue.getArrayFiller() = Array.getArrayFiller();
3504   Array.swap(NewValue);
3505 }
3506 
3507 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3508 /// conversion. If it's of class type, we may assume that the copy operation
3509 /// is trivial. Note that this is never true for a union type with fields
3510 /// (because the copy always "reads" the active member) and always true for
3511 /// a non-class type.
3512 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
isReadByLvalueToRvalueConversion(QualType T)3513 static bool isReadByLvalueToRvalueConversion(QualType T) {
3514   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3515   return !RD || isReadByLvalueToRvalueConversion(RD);
3516 }
isReadByLvalueToRvalueConversion(const CXXRecordDecl * RD)3517 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3518   // FIXME: A trivial copy of a union copies the object representation, even if
3519   // the union is empty.
3520   if (RD->isUnion())
3521     return !RD->field_empty();
3522   if (RD->isEmpty())
3523     return false;
3524 
3525   for (auto *Field : RD->fields())
3526     if (!Field->isUnnamedBitfield() &&
3527         isReadByLvalueToRvalueConversion(Field->getType()))
3528       return true;
3529 
3530   for (auto &BaseSpec : RD->bases())
3531     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3532       return true;
3533 
3534   return false;
3535 }
3536 
3537 /// Diagnose an attempt to read from any unreadable field within the specified
3538 /// type, which might be a class type.
diagnoseMutableFields(EvalInfo & Info,const Expr * E,AccessKinds AK,QualType T)3539 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3540                                   QualType T) {
3541   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3542   if (!RD)
3543     return false;
3544 
3545   if (!RD->hasMutableFields())
3546     return false;
3547 
3548   for (auto *Field : RD->fields()) {
3549     // If we're actually going to read this field in some way, then it can't
3550     // be mutable. If we're in a union, then assigning to a mutable field
3551     // (even an empty one) can change the active member, so that's not OK.
3552     // FIXME: Add core issue number for the union case.
3553     if (Field->isMutable() &&
3554         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3555       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3556       Info.Note(Field->getLocation(), diag::note_declared_at);
3557       return true;
3558     }
3559 
3560     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3561       return true;
3562   }
3563 
3564   for (auto &BaseSpec : RD->bases())
3565     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3566       return true;
3567 
3568   // All mutable fields were empty, and thus not actually read.
3569   return false;
3570 }
3571 
lifetimeStartedInEvaluation(EvalInfo & Info,APValue::LValueBase Base,bool MutableSubobject=false)3572 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3573                                         APValue::LValueBase Base,
3574                                         bool MutableSubobject = false) {
3575   // A temporary or transient heap allocation we created.
3576   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3577     return true;
3578 
3579   switch (Info.IsEvaluatingDecl) {
3580   case EvalInfo::EvaluatingDeclKind::None:
3581     return false;
3582 
3583   case EvalInfo::EvaluatingDeclKind::Ctor:
3584     // The variable whose initializer we're evaluating.
3585     if (Info.EvaluatingDecl == Base)
3586       return true;
3587 
3588     // A temporary lifetime-extended by the variable whose initializer we're
3589     // evaluating.
3590     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3591       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3592         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3593     return false;
3594 
3595   case EvalInfo::EvaluatingDeclKind::Dtor:
3596     // C++2a [expr.const]p6:
3597     //   [during constant destruction] the lifetime of a and its non-mutable
3598     //   subobjects (but not its mutable subobjects) [are] considered to start
3599     //   within e.
3600     if (MutableSubobject || Base != Info.EvaluatingDecl)
3601       return false;
3602     // FIXME: We can meaningfully extend this to cover non-const objects, but
3603     // we will need special handling: we should be able to access only
3604     // subobjects of such objects that are themselves declared const.
3605     QualType T = getType(Base);
3606     return T.isConstQualified() || T->isReferenceType();
3607   }
3608 
3609   llvm_unreachable("unknown evaluating decl kind");
3610 }
3611 
CheckArraySize(EvalInfo & Info,const ConstantArrayType * CAT,SourceLocation CallLoc={})3612 static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3613                            SourceLocation CallLoc = {}) {
3614   return Info.CheckArraySize(
3615       CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3616       CAT->getNumAddressingBits(Info.Ctx), CAT->getSize().getZExtValue(),
3617       /*Diag=*/true);
3618 }
3619 
3620 namespace {
3621 /// A handle to a complete object (an object that is not a subobject of
3622 /// another object).
3623 struct CompleteObject {
3624   /// The identity of the object.
3625   APValue::LValueBase Base;
3626   /// The value of the complete object.
3627   APValue *Value;
3628   /// The type of the complete object.
3629   QualType Type;
3630 
CompleteObject__anonbf0ddd820a11::CompleteObject3631   CompleteObject() : Value(nullptr) {}
CompleteObject__anonbf0ddd820a11::CompleteObject3632   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3633       : Base(Base), Value(Value), Type(Type) {}
3634 
mayAccessMutableMembers__anonbf0ddd820a11::CompleteObject3635   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3636     // If this isn't a "real" access (eg, if it's just accessing the type
3637     // info), allow it. We assume the type doesn't change dynamically for
3638     // subobjects of constexpr objects (even though we'd hit UB here if it
3639     // did). FIXME: Is this right?
3640     if (!isAnyAccess(AK))
3641       return true;
3642 
3643     // In C++14 onwards, it is permitted to read a mutable member whose
3644     // lifetime began within the evaluation.
3645     // FIXME: Should we also allow this in C++11?
3646     if (!Info.getLangOpts().CPlusPlus14)
3647       return false;
3648     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3649   }
3650 
operator bool__anonbf0ddd820a11::CompleteObject3651   explicit operator bool() const { return !Type.isNull(); }
3652 };
3653 } // end anonymous namespace
3654 
getSubobjectType(QualType ObjType,QualType SubobjType,bool IsMutable=false)3655 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3656                                  bool IsMutable = false) {
3657   // C++ [basic.type.qualifier]p1:
3658   // - A const object is an object of type const T or a non-mutable subobject
3659   //   of a const object.
3660   if (ObjType.isConstQualified() && !IsMutable)
3661     SubobjType.addConst();
3662   // - A volatile object is an object of type const T or a subobject of a
3663   //   volatile object.
3664   if (ObjType.isVolatileQualified())
3665     SubobjType.addVolatile();
3666   return SubobjType;
3667 }
3668 
3669 /// Find the designated sub-object of an rvalue.
3670 template<typename SubobjectHandler>
3671 typename SubobjectHandler::result_type
findSubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,SubobjectHandler & handler)3672 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3673               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3674   if (Sub.Invalid)
3675     // A diagnostic will have already been produced.
3676     return handler.failed();
3677   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3678     if (Info.getLangOpts().CPlusPlus11)
3679       Info.FFDiag(E, Sub.isOnePastTheEnd()
3680                          ? diag::note_constexpr_access_past_end
3681                          : diag::note_constexpr_access_unsized_array)
3682           << handler.AccessKind;
3683     else
3684       Info.FFDiag(E);
3685     return handler.failed();
3686   }
3687 
3688   APValue *O = Obj.Value;
3689   QualType ObjType = Obj.Type;
3690   const FieldDecl *LastField = nullptr;
3691   const FieldDecl *VolatileField = nullptr;
3692 
3693   // Walk the designator's path to find the subobject.
3694   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3695     // Reading an indeterminate value is undefined, but assigning over one is OK.
3696     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3697         (O->isIndeterminate() &&
3698          !isValidIndeterminateAccess(handler.AccessKind))) {
3699       if (!Info.checkingPotentialConstantExpression())
3700         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3701             << handler.AccessKind << O->isIndeterminate()
3702             << E->getSourceRange();
3703       return handler.failed();
3704     }
3705 
3706     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3707     //    const and volatile semantics are not applied on an object under
3708     //    {con,de}struction.
3709     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3710         ObjType->isRecordType() &&
3711         Info.isEvaluatingCtorDtor(
3712             Obj.Base,
3713             llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3714             ConstructionPhase::None) {
3715       ObjType = Info.Ctx.getCanonicalType(ObjType);
3716       ObjType.removeLocalConst();
3717       ObjType.removeLocalVolatile();
3718     }
3719 
3720     // If this is our last pass, check that the final object type is OK.
3721     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3722       // Accesses to volatile objects are prohibited.
3723       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3724         if (Info.getLangOpts().CPlusPlus) {
3725           int DiagKind;
3726           SourceLocation Loc;
3727           const NamedDecl *Decl = nullptr;
3728           if (VolatileField) {
3729             DiagKind = 2;
3730             Loc = VolatileField->getLocation();
3731             Decl = VolatileField;
3732           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3733             DiagKind = 1;
3734             Loc = VD->getLocation();
3735             Decl = VD;
3736           } else {
3737             DiagKind = 0;
3738             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3739               Loc = E->getExprLoc();
3740           }
3741           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3742               << handler.AccessKind << DiagKind << Decl;
3743           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3744         } else {
3745           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3746         }
3747         return handler.failed();
3748       }
3749 
3750       // If we are reading an object of class type, there may still be more
3751       // things we need to check: if there are any mutable subobjects, we
3752       // cannot perform this read. (This only happens when performing a trivial
3753       // copy or assignment.)
3754       if (ObjType->isRecordType() &&
3755           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3756           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3757         return handler.failed();
3758     }
3759 
3760     if (I == N) {
3761       if (!handler.found(*O, ObjType))
3762         return false;
3763 
3764       // If we modified a bit-field, truncate it to the right width.
3765       if (isModification(handler.AccessKind) &&
3766           LastField && LastField->isBitField() &&
3767           !truncateBitfieldValue(Info, E, *O, LastField))
3768         return false;
3769 
3770       return true;
3771     }
3772 
3773     LastField = nullptr;
3774     if (ObjType->isArrayType()) {
3775       // Next subobject is an array element.
3776       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3777       assert(CAT && "vla in literal type?");
3778       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3779       if (CAT->getSize().ule(Index)) {
3780         // Note, it should not be possible to form a pointer with a valid
3781         // designator which points more than one past the end of the array.
3782         if (Info.getLangOpts().CPlusPlus11)
3783           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3784             << handler.AccessKind;
3785         else
3786           Info.FFDiag(E);
3787         return handler.failed();
3788       }
3789 
3790       ObjType = CAT->getElementType();
3791 
3792       if (O->getArrayInitializedElts() > Index)
3793         O = &O->getArrayInitializedElt(Index);
3794       else if (!isRead(handler.AccessKind)) {
3795         if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3796           return handler.failed();
3797 
3798         expandArray(*O, Index);
3799         O = &O->getArrayInitializedElt(Index);
3800       } else
3801         O = &O->getArrayFiller();
3802     } else if (ObjType->isAnyComplexType()) {
3803       // Next subobject is a complex number.
3804       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3805       if (Index > 1) {
3806         if (Info.getLangOpts().CPlusPlus11)
3807           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3808             << handler.AccessKind;
3809         else
3810           Info.FFDiag(E);
3811         return handler.failed();
3812       }
3813 
3814       ObjType = getSubobjectType(
3815           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3816 
3817       assert(I == N - 1 && "extracting subobject of scalar?");
3818       if (O->isComplexInt()) {
3819         return handler.found(Index ? O->getComplexIntImag()
3820                                    : O->getComplexIntReal(), ObjType);
3821       } else {
3822         assert(O->isComplexFloat());
3823         return handler.found(Index ? O->getComplexFloatImag()
3824                                    : O->getComplexFloatReal(), ObjType);
3825       }
3826     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3827       if (Field->isMutable() &&
3828           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3829         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3830           << handler.AccessKind << Field;
3831         Info.Note(Field->getLocation(), diag::note_declared_at);
3832         return handler.failed();
3833       }
3834 
3835       // Next subobject is a class, struct or union field.
3836       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3837       if (RD->isUnion()) {
3838         const FieldDecl *UnionField = O->getUnionField();
3839         if (!UnionField ||
3840             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3841           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3842             // Placement new onto an inactive union member makes it active.
3843             O->setUnion(Field, APValue());
3844           } else {
3845             // FIXME: If O->getUnionValue() is absent, report that there's no
3846             // active union member rather than reporting the prior active union
3847             // member. We'll need to fix nullptr_t to not use APValue() as its
3848             // representation first.
3849             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3850                 << handler.AccessKind << Field << !UnionField << UnionField;
3851             return handler.failed();
3852           }
3853         }
3854         O = &O->getUnionValue();
3855       } else
3856         O = &O->getStructField(Field->getFieldIndex());
3857 
3858       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3859       LastField = Field;
3860       if (Field->getType().isVolatileQualified())
3861         VolatileField = Field;
3862     } else {
3863       // Next subobject is a base class.
3864       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3865       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3866       O = &O->getStructBase(getBaseIndex(Derived, Base));
3867 
3868       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3869     }
3870   }
3871 }
3872 
3873 namespace {
3874 struct ExtractSubobjectHandler {
3875   EvalInfo &Info;
3876   const Expr *E;
3877   APValue &Result;
3878   const AccessKinds AccessKind;
3879 
3880   typedef bool result_type;
failed__anonbf0ddd820b11::ExtractSubobjectHandler3881   bool failed() { return false; }
found__anonbf0ddd820b11::ExtractSubobjectHandler3882   bool found(APValue &Subobj, QualType SubobjType) {
3883     Result = Subobj;
3884     if (AccessKind == AK_ReadObjectRepresentation)
3885       return true;
3886     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3887   }
found__anonbf0ddd820b11::ExtractSubobjectHandler3888   bool found(APSInt &Value, QualType SubobjType) {
3889     Result = APValue(Value);
3890     return true;
3891   }
found__anonbf0ddd820b11::ExtractSubobjectHandler3892   bool found(APFloat &Value, QualType SubobjType) {
3893     Result = APValue(Value);
3894     return true;
3895   }
3896 };
3897 } // end anonymous namespace
3898 
3899 /// Extract the designated sub-object of an rvalue.
extractSubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,APValue & Result,AccessKinds AK=AK_Read)3900 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3901                              const CompleteObject &Obj,
3902                              const SubobjectDesignator &Sub, APValue &Result,
3903                              AccessKinds AK = AK_Read) {
3904   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3905   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3906   return findSubobject(Info, E, Obj, Sub, Handler);
3907 }
3908 
3909 namespace {
3910 struct ModifySubobjectHandler {
3911   EvalInfo &Info;
3912   APValue &NewVal;
3913   const Expr *E;
3914 
3915   typedef bool result_type;
3916   static const AccessKinds AccessKind = AK_Assign;
3917 
checkConst__anonbf0ddd820c11::ModifySubobjectHandler3918   bool checkConst(QualType QT) {
3919     // Assigning to a const object has undefined behavior.
3920     if (QT.isConstQualified()) {
3921       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3922       return false;
3923     }
3924     return true;
3925   }
3926 
failed__anonbf0ddd820c11::ModifySubobjectHandler3927   bool failed() { return false; }
found__anonbf0ddd820c11::ModifySubobjectHandler3928   bool found(APValue &Subobj, QualType SubobjType) {
3929     if (!checkConst(SubobjType))
3930       return false;
3931     // We've been given ownership of NewVal, so just swap it in.
3932     Subobj.swap(NewVal);
3933     return true;
3934   }
found__anonbf0ddd820c11::ModifySubobjectHandler3935   bool found(APSInt &Value, QualType SubobjType) {
3936     if (!checkConst(SubobjType))
3937       return false;
3938     if (!NewVal.isInt()) {
3939       // Maybe trying to write a cast pointer value into a complex?
3940       Info.FFDiag(E);
3941       return false;
3942     }
3943     Value = NewVal.getInt();
3944     return true;
3945   }
found__anonbf0ddd820c11::ModifySubobjectHandler3946   bool found(APFloat &Value, QualType SubobjType) {
3947     if (!checkConst(SubobjType))
3948       return false;
3949     Value = NewVal.getFloat();
3950     return true;
3951   }
3952 };
3953 } // end anonymous namespace
3954 
3955 const AccessKinds ModifySubobjectHandler::AccessKind;
3956 
3957 /// Update the designated sub-object of an rvalue to the given value.
modifySubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,APValue & NewVal)3958 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3959                             const CompleteObject &Obj,
3960                             const SubobjectDesignator &Sub,
3961                             APValue &NewVal) {
3962   ModifySubobjectHandler Handler = { Info, NewVal, E };
3963   return findSubobject(Info, E, Obj, Sub, Handler);
3964 }
3965 
3966 /// Find the position where two subobject designators diverge, or equivalently
3967 /// the length of the common initial subsequence.
FindDesignatorMismatch(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B,bool & WasArrayIndex)3968 static unsigned FindDesignatorMismatch(QualType ObjType,
3969                                        const SubobjectDesignator &A,
3970                                        const SubobjectDesignator &B,
3971                                        bool &WasArrayIndex) {
3972   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3973   for (/**/; I != N; ++I) {
3974     if (!ObjType.isNull() &&
3975         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3976       // Next subobject is an array element.
3977       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3978         WasArrayIndex = true;
3979         return I;
3980       }
3981       if (ObjType->isAnyComplexType())
3982         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3983       else
3984         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3985     } else {
3986       if (A.Entries[I].getAsBaseOrMember() !=
3987           B.Entries[I].getAsBaseOrMember()) {
3988         WasArrayIndex = false;
3989         return I;
3990       }
3991       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3992         // Next subobject is a field.
3993         ObjType = FD->getType();
3994       else
3995         // Next subobject is a base class.
3996         ObjType = QualType();
3997     }
3998   }
3999   WasArrayIndex = false;
4000   return I;
4001 }
4002 
4003 /// Determine whether the given subobject designators refer to elements of the
4004 /// same array object.
AreElementsOfSameArray(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B)4005 static bool AreElementsOfSameArray(QualType ObjType,
4006                                    const SubobjectDesignator &A,
4007                                    const SubobjectDesignator &B) {
4008   if (A.Entries.size() != B.Entries.size())
4009     return false;
4010 
4011   bool IsArray = A.MostDerivedIsArrayElement;
4012   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4013     // A is a subobject of the array element.
4014     return false;
4015 
4016   // If A (and B) designates an array element, the last entry will be the array
4017   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4018   // of length 1' case, and the entire path must match.
4019   bool WasArrayIndex;
4020   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4021   return CommonLength >= A.Entries.size() - IsArray;
4022 }
4023 
4024 /// Find the complete object to which an LValue refers.
findCompleteObject(EvalInfo & Info,const Expr * E,AccessKinds AK,const LValue & LVal,QualType LValType)4025 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4026                                          AccessKinds AK, const LValue &LVal,
4027                                          QualType LValType) {
4028   if (LVal.InvalidBase) {
4029     Info.FFDiag(E);
4030     return CompleteObject();
4031   }
4032 
4033   if (!LVal.Base) {
4034     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4035     return CompleteObject();
4036   }
4037 
4038   CallStackFrame *Frame = nullptr;
4039   unsigned Depth = 0;
4040   if (LVal.getLValueCallIndex()) {
4041     std::tie(Frame, Depth) =
4042         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4043     if (!Frame) {
4044       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4045         << AK << LVal.Base.is<const ValueDecl*>();
4046       NoteLValueLocation(Info, LVal.Base);
4047       return CompleteObject();
4048     }
4049   }
4050 
4051   bool IsAccess = isAnyAccess(AK);
4052 
4053   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4054   // is not a constant expression (even if the object is non-volatile). We also
4055   // apply this rule to C++98, in order to conform to the expected 'volatile'
4056   // semantics.
4057   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4058     if (Info.getLangOpts().CPlusPlus)
4059       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4060         << AK << LValType;
4061     else
4062       Info.FFDiag(E);
4063     return CompleteObject();
4064   }
4065 
4066   // Compute value storage location and type of base object.
4067   APValue *BaseVal = nullptr;
4068   QualType BaseType = getType(LVal.Base);
4069 
4070   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4071       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4072     // This is the object whose initializer we're evaluating, so its lifetime
4073     // started in the current evaluation.
4074     BaseVal = Info.EvaluatingDeclValue;
4075   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4076     // Allow reading from a GUID declaration.
4077     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4078       if (isModification(AK)) {
4079         // All the remaining cases do not permit modification of the object.
4080         Info.FFDiag(E, diag::note_constexpr_modify_global);
4081         return CompleteObject();
4082       }
4083       APValue &V = GD->getAsAPValue();
4084       if (V.isAbsent()) {
4085         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4086             << GD->getType();
4087         return CompleteObject();
4088       }
4089       return CompleteObject(LVal.Base, &V, GD->getType());
4090     }
4091 
4092     // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4093     if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4094       if (isModification(AK)) {
4095         Info.FFDiag(E, diag::note_constexpr_modify_global);
4096         return CompleteObject();
4097       }
4098       return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4099                             GCD->getType());
4100     }
4101 
4102     // Allow reading from template parameter objects.
4103     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4104       if (isModification(AK)) {
4105         Info.FFDiag(E, diag::note_constexpr_modify_global);
4106         return CompleteObject();
4107       }
4108       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4109                             TPO->getType());
4110     }
4111 
4112     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4113     // In C++11, constexpr, non-volatile variables initialized with constant
4114     // expressions are constant expressions too. Inside constexpr functions,
4115     // parameters are constant expressions even if they're non-const.
4116     // In C++1y, objects local to a constant expression (those with a Frame) are
4117     // both readable and writable inside constant expressions.
4118     // In C, such things can also be folded, although they are not ICEs.
4119     const VarDecl *VD = dyn_cast<VarDecl>(D);
4120     if (VD) {
4121       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4122         VD = VDef;
4123     }
4124     if (!VD || VD->isInvalidDecl()) {
4125       Info.FFDiag(E);
4126       return CompleteObject();
4127     }
4128 
4129     bool IsConstant = BaseType.isConstant(Info.Ctx);
4130 
4131     // Unless we're looking at a local variable or argument in a constexpr call,
4132     // the variable we're reading must be const.
4133     if (!Frame) {
4134       if (IsAccess && isa<ParmVarDecl>(VD)) {
4135         // Access of a parameter that's not associated with a frame isn't going
4136         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4137         // suitable diagnostic.
4138       } else if (Info.getLangOpts().CPlusPlus14 &&
4139                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4140         // OK, we can read and modify an object if we're in the process of
4141         // evaluating its initializer, because its lifetime began in this
4142         // evaluation.
4143       } else if (isModification(AK)) {
4144         // All the remaining cases do not permit modification of the object.
4145         Info.FFDiag(E, diag::note_constexpr_modify_global);
4146         return CompleteObject();
4147       } else if (VD->isConstexpr()) {
4148         // OK, we can read this variable.
4149       } else if (BaseType->isIntegralOrEnumerationType()) {
4150         if (!IsConstant) {
4151           if (!IsAccess)
4152             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4153           if (Info.getLangOpts().CPlusPlus) {
4154             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4155             Info.Note(VD->getLocation(), diag::note_declared_at);
4156           } else {
4157             Info.FFDiag(E);
4158           }
4159           return CompleteObject();
4160         }
4161       } else if (!IsAccess) {
4162         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4163       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4164                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4165         // This variable might end up being constexpr. Don't diagnose it yet.
4166       } else if (IsConstant) {
4167         // Keep evaluating to see what we can do. In particular, we support
4168         // folding of const floating-point types, in order to make static const
4169         // data members of such types (supported as an extension) more useful.
4170         if (Info.getLangOpts().CPlusPlus) {
4171           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4172                               ? diag::note_constexpr_ltor_non_constexpr
4173                               : diag::note_constexpr_ltor_non_integral, 1)
4174               << VD << BaseType;
4175           Info.Note(VD->getLocation(), diag::note_declared_at);
4176         } else {
4177           Info.CCEDiag(E);
4178         }
4179       } else {
4180         // Never allow reading a non-const value.
4181         if (Info.getLangOpts().CPlusPlus) {
4182           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4183                              ? diag::note_constexpr_ltor_non_constexpr
4184                              : diag::note_constexpr_ltor_non_integral, 1)
4185               << VD << BaseType;
4186           Info.Note(VD->getLocation(), diag::note_declared_at);
4187         } else {
4188           Info.FFDiag(E);
4189         }
4190         return CompleteObject();
4191       }
4192     }
4193 
4194     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4195       return CompleteObject();
4196   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4197     std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4198     if (!Alloc) {
4199       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4200       return CompleteObject();
4201     }
4202     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4203                           LVal.Base.getDynamicAllocType());
4204   } else {
4205     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4206 
4207     if (!Frame) {
4208       if (const MaterializeTemporaryExpr *MTE =
4209               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4210         assert(MTE->getStorageDuration() == SD_Static &&
4211                "should have a frame for a non-global materialized temporary");
4212 
4213         // C++20 [expr.const]p4: [DR2126]
4214         //   An object or reference is usable in constant expressions if it is
4215         //   - a temporary object of non-volatile const-qualified literal type
4216         //     whose lifetime is extended to that of a variable that is usable
4217         //     in constant expressions
4218         //
4219         // C++20 [expr.const]p5:
4220         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4221         //   - a non-volatile glvalue that refers to an object that is usable
4222         //     in constant expressions, or
4223         //   - a non-volatile glvalue of literal type that refers to a
4224         //     non-volatile object whose lifetime began within the evaluation
4225         //     of E;
4226         //
4227         // C++11 misses the 'began within the evaluation of e' check and
4228         // instead allows all temporaries, including things like:
4229         //   int &&r = 1;
4230         //   int x = ++r;
4231         //   constexpr int k = r;
4232         // Therefore we use the C++14-onwards rules in C++11 too.
4233         //
4234         // Note that temporaries whose lifetimes began while evaluating a
4235         // variable's constructor are not usable while evaluating the
4236         // corresponding destructor, not even if they're of const-qualified
4237         // types.
4238         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4239             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4240           if (!IsAccess)
4241             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4242           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4243           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4244           return CompleteObject();
4245         }
4246 
4247         BaseVal = MTE->getOrCreateValue(false);
4248         assert(BaseVal && "got reference to unevaluated temporary");
4249       } else {
4250         if (!IsAccess)
4251           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4252         APValue Val;
4253         LVal.moveInto(Val);
4254         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4255             << AK
4256             << Val.getAsString(Info.Ctx,
4257                                Info.Ctx.getLValueReferenceType(LValType));
4258         NoteLValueLocation(Info, LVal.Base);
4259         return CompleteObject();
4260       }
4261     } else {
4262       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4263       assert(BaseVal && "missing value for temporary");
4264     }
4265   }
4266 
4267   // In C++14, we can't safely access any mutable state when we might be
4268   // evaluating after an unmodeled side effect. Parameters are modeled as state
4269   // in the caller, but aren't visible once the call returns, so they can be
4270   // modified in a speculatively-evaluated call.
4271   //
4272   // FIXME: Not all local state is mutable. Allow local constant subobjects
4273   // to be read here (but take care with 'mutable' fields).
4274   unsigned VisibleDepth = Depth;
4275   if (llvm::isa_and_nonnull<ParmVarDecl>(
4276           LVal.Base.dyn_cast<const ValueDecl *>()))
4277     ++VisibleDepth;
4278   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4279        Info.EvalStatus.HasSideEffects) ||
4280       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4281     return CompleteObject();
4282 
4283   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4284 }
4285 
4286 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4287 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4288 /// glvalue referred to by an entity of reference type.
4289 ///
4290 /// \param Info - Information about the ongoing evaluation.
4291 /// \param Conv - The expression for which we are performing the conversion.
4292 ///               Used for diagnostics.
4293 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4294 ///               case of a non-class type).
4295 /// \param LVal - The glvalue on which we are attempting to perform this action.
4296 /// \param RVal - The produced value will be placed here.
4297 /// \param WantObjectRepresentation - If true, we're looking for the object
4298 ///               representation rather than the value, and in particular,
4299 ///               there is no requirement that the result be fully initialized.
4300 static bool
handleLValueToRValueConversion(EvalInfo & Info,const Expr * Conv,QualType Type,const LValue & LVal,APValue & RVal,bool WantObjectRepresentation=false)4301 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4302                                const LValue &LVal, APValue &RVal,
4303                                bool WantObjectRepresentation = false) {
4304   if (LVal.Designator.Invalid)
4305     return false;
4306 
4307   // Check for special cases where there is no existing APValue to look at.
4308   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4309 
4310   AccessKinds AK =
4311       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4312 
4313   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4314     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4315       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4316       // initializer until now for such expressions. Such an expression can't be
4317       // an ICE in C, so this only matters for fold.
4318       if (Type.isVolatileQualified()) {
4319         Info.FFDiag(Conv);
4320         return false;
4321       }
4322 
4323       APValue Lit;
4324       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4325         return false;
4326 
4327       // According to GCC info page:
4328       //
4329       // 6.28 Compound Literals
4330       //
4331       // As an optimization, G++ sometimes gives array compound literals longer
4332       // lifetimes: when the array either appears outside a function or has a
4333       // const-qualified type. If foo and its initializer had elements of type
4334       // char *const rather than char *, or if foo were a global variable, the
4335       // array would have static storage duration. But it is probably safest
4336       // just to avoid the use of array compound literals in C++ code.
4337       //
4338       // Obey that rule by checking constness for converted array types.
4339 
4340       QualType CLETy = CLE->getType();
4341       if (CLETy->isArrayType() && !Type->isArrayType()) {
4342         if (!CLETy.isConstant(Info.Ctx)) {
4343           Info.FFDiag(Conv);
4344           Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4345           return false;
4346         }
4347       }
4348 
4349       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4350       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4351     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4352       // Special-case character extraction so we don't have to construct an
4353       // APValue for the whole string.
4354       assert(LVal.Designator.Entries.size() <= 1 &&
4355              "Can only read characters from string literals");
4356       if (LVal.Designator.Entries.empty()) {
4357         // Fail for now for LValue to RValue conversion of an array.
4358         // (This shouldn't show up in C/C++, but it could be triggered by a
4359         // weird EvaluateAsRValue call from a tool.)
4360         Info.FFDiag(Conv);
4361         return false;
4362       }
4363       if (LVal.Designator.isOnePastTheEnd()) {
4364         if (Info.getLangOpts().CPlusPlus11)
4365           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4366         else
4367           Info.FFDiag(Conv);
4368         return false;
4369       }
4370       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4371       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4372       return true;
4373     }
4374   }
4375 
4376   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4377   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4378 }
4379 
4380 /// Perform an assignment of Val to LVal. Takes ownership of Val.
handleAssignment(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,APValue & Val)4381 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4382                              QualType LValType, APValue &Val) {
4383   if (LVal.Designator.Invalid)
4384     return false;
4385 
4386   if (!Info.getLangOpts().CPlusPlus14) {
4387     Info.FFDiag(E);
4388     return false;
4389   }
4390 
4391   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4392   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4393 }
4394 
4395 namespace {
4396 struct CompoundAssignSubobjectHandler {
4397   EvalInfo &Info;
4398   const CompoundAssignOperator *E;
4399   QualType PromotedLHSType;
4400   BinaryOperatorKind Opcode;
4401   const APValue &RHS;
4402 
4403   static const AccessKinds AccessKind = AK_Assign;
4404 
4405   typedef bool result_type;
4406 
checkConst__anonbf0ddd820d11::CompoundAssignSubobjectHandler4407   bool checkConst(QualType QT) {
4408     // Assigning to a const object has undefined behavior.
4409     if (QT.isConstQualified()) {
4410       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4411       return false;
4412     }
4413     return true;
4414   }
4415 
failed__anonbf0ddd820d11::CompoundAssignSubobjectHandler4416   bool failed() { return false; }
found__anonbf0ddd820d11::CompoundAssignSubobjectHandler4417   bool found(APValue &Subobj, QualType SubobjType) {
4418     switch (Subobj.getKind()) {
4419     case APValue::Int:
4420       return found(Subobj.getInt(), SubobjType);
4421     case APValue::Float:
4422       return found(Subobj.getFloat(), SubobjType);
4423     case APValue::ComplexInt:
4424     case APValue::ComplexFloat:
4425       // FIXME: Implement complex compound assignment.
4426       Info.FFDiag(E);
4427       return false;
4428     case APValue::LValue:
4429       return foundPointer(Subobj, SubobjType);
4430     case APValue::Vector:
4431       return foundVector(Subobj, SubobjType);
4432     case APValue::Indeterminate:
4433       Info.FFDiag(E, diag::note_constexpr_access_uninit)
4434           << /*read of=*/0 << /*uninitialized object=*/1
4435           << E->getLHS()->getSourceRange();
4436       return false;
4437     default:
4438       // FIXME: can this happen?
4439       Info.FFDiag(E);
4440       return false;
4441     }
4442   }
4443 
foundVector__anonbf0ddd820d11::CompoundAssignSubobjectHandler4444   bool foundVector(APValue &Value, QualType SubobjType) {
4445     if (!checkConst(SubobjType))
4446       return false;
4447 
4448     if (!SubobjType->isVectorType()) {
4449       Info.FFDiag(E);
4450       return false;
4451     }
4452     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4453   }
4454 
found__anonbf0ddd820d11::CompoundAssignSubobjectHandler4455   bool found(APSInt &Value, QualType SubobjType) {
4456     if (!checkConst(SubobjType))
4457       return false;
4458 
4459     if (!SubobjType->isIntegerType()) {
4460       // We don't support compound assignment on integer-cast-to-pointer
4461       // values.
4462       Info.FFDiag(E);
4463       return false;
4464     }
4465 
4466     if (RHS.isInt()) {
4467       APSInt LHS =
4468           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4469       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4470         return false;
4471       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4472       return true;
4473     } else if (RHS.isFloat()) {
4474       const FPOptions FPO = E->getFPFeaturesInEffect(
4475                                     Info.Ctx.getLangOpts());
4476       APFloat FValue(0.0);
4477       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4478                                   PromotedLHSType, FValue) &&
4479              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4480              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4481                                   Value);
4482     }
4483 
4484     Info.FFDiag(E);
4485     return false;
4486   }
found__anonbf0ddd820d11::CompoundAssignSubobjectHandler4487   bool found(APFloat &Value, QualType SubobjType) {
4488     return checkConst(SubobjType) &&
4489            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4490                                   Value) &&
4491            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4492            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4493   }
foundPointer__anonbf0ddd820d11::CompoundAssignSubobjectHandler4494   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4495     if (!checkConst(SubobjType))
4496       return false;
4497 
4498     QualType PointeeType;
4499     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4500       PointeeType = PT->getPointeeType();
4501 
4502     if (PointeeType.isNull() || !RHS.isInt() ||
4503         (Opcode != BO_Add && Opcode != BO_Sub)) {
4504       Info.FFDiag(E);
4505       return false;
4506     }
4507 
4508     APSInt Offset = RHS.getInt();
4509     if (Opcode == BO_Sub)
4510       negateAsSigned(Offset);
4511 
4512     LValue LVal;
4513     LVal.setFrom(Info.Ctx, Subobj);
4514     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4515       return false;
4516     LVal.moveInto(Subobj);
4517     return true;
4518   }
4519 };
4520 } // end anonymous namespace
4521 
4522 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4523 
4524 /// Perform a compound assignment of LVal <op>= RVal.
handleCompoundAssignment(EvalInfo & Info,const CompoundAssignOperator * E,const LValue & LVal,QualType LValType,QualType PromotedLValType,BinaryOperatorKind Opcode,const APValue & RVal)4525 static bool handleCompoundAssignment(EvalInfo &Info,
4526                                      const CompoundAssignOperator *E,
4527                                      const LValue &LVal, QualType LValType,
4528                                      QualType PromotedLValType,
4529                                      BinaryOperatorKind Opcode,
4530                                      const APValue &RVal) {
4531   if (LVal.Designator.Invalid)
4532     return false;
4533 
4534   if (!Info.getLangOpts().CPlusPlus14) {
4535     Info.FFDiag(E);
4536     return false;
4537   }
4538 
4539   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4540   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4541                                              RVal };
4542   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4543 }
4544 
4545 namespace {
4546 struct IncDecSubobjectHandler {
4547   EvalInfo &Info;
4548   const UnaryOperator *E;
4549   AccessKinds AccessKind;
4550   APValue *Old;
4551 
4552   typedef bool result_type;
4553 
checkConst__anonbf0ddd820e11::IncDecSubobjectHandler4554   bool checkConst(QualType QT) {
4555     // Assigning to a const object has undefined behavior.
4556     if (QT.isConstQualified()) {
4557       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4558       return false;
4559     }
4560     return true;
4561   }
4562 
failed__anonbf0ddd820e11::IncDecSubobjectHandler4563   bool failed() { return false; }
found__anonbf0ddd820e11::IncDecSubobjectHandler4564   bool found(APValue &Subobj, QualType SubobjType) {
4565     // Stash the old value. Also clear Old, so we don't clobber it later
4566     // if we're post-incrementing a complex.
4567     if (Old) {
4568       *Old = Subobj;
4569       Old = nullptr;
4570     }
4571 
4572     switch (Subobj.getKind()) {
4573     case APValue::Int:
4574       return found(Subobj.getInt(), SubobjType);
4575     case APValue::Float:
4576       return found(Subobj.getFloat(), SubobjType);
4577     case APValue::ComplexInt:
4578       return found(Subobj.getComplexIntReal(),
4579                    SubobjType->castAs<ComplexType>()->getElementType()
4580                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4581     case APValue::ComplexFloat:
4582       return found(Subobj.getComplexFloatReal(),
4583                    SubobjType->castAs<ComplexType>()->getElementType()
4584                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4585     case APValue::LValue:
4586       return foundPointer(Subobj, SubobjType);
4587     default:
4588       // FIXME: can this happen?
4589       Info.FFDiag(E);
4590       return false;
4591     }
4592   }
found__anonbf0ddd820e11::IncDecSubobjectHandler4593   bool found(APSInt &Value, QualType SubobjType) {
4594     if (!checkConst(SubobjType))
4595       return false;
4596 
4597     if (!SubobjType->isIntegerType()) {
4598       // We don't support increment / decrement on integer-cast-to-pointer
4599       // values.
4600       Info.FFDiag(E);
4601       return false;
4602     }
4603 
4604     if (Old) *Old = APValue(Value);
4605 
4606     // bool arithmetic promotes to int, and the conversion back to bool
4607     // doesn't reduce mod 2^n, so special-case it.
4608     if (SubobjType->isBooleanType()) {
4609       if (AccessKind == AK_Increment)
4610         Value = 1;
4611       else
4612         Value = !Value;
4613       return true;
4614     }
4615 
4616     bool WasNegative = Value.isNegative();
4617     if (AccessKind == AK_Increment) {
4618       ++Value;
4619 
4620       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4621         APSInt ActualValue(Value, /*IsUnsigned*/true);
4622         return HandleOverflow(Info, E, ActualValue, SubobjType);
4623       }
4624     } else {
4625       --Value;
4626 
4627       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4628         unsigned BitWidth = Value.getBitWidth();
4629         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4630         ActualValue.setBit(BitWidth);
4631         return HandleOverflow(Info, E, ActualValue, SubobjType);
4632       }
4633     }
4634     return true;
4635   }
found__anonbf0ddd820e11::IncDecSubobjectHandler4636   bool found(APFloat &Value, QualType SubobjType) {
4637     if (!checkConst(SubobjType))
4638       return false;
4639 
4640     if (Old) *Old = APValue(Value);
4641 
4642     APFloat One(Value.getSemantics(), 1);
4643     llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4644     APFloat::opStatus St;
4645     if (AccessKind == AK_Increment)
4646       St = Value.add(One, RM);
4647     else
4648       St = Value.subtract(One, RM);
4649     return checkFloatingPointResult(Info, E, St);
4650   }
foundPointer__anonbf0ddd820e11::IncDecSubobjectHandler4651   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4652     if (!checkConst(SubobjType))
4653       return false;
4654 
4655     QualType PointeeType;
4656     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4657       PointeeType = PT->getPointeeType();
4658     else {
4659       Info.FFDiag(E);
4660       return false;
4661     }
4662 
4663     LValue LVal;
4664     LVal.setFrom(Info.Ctx, Subobj);
4665     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4666                                      AccessKind == AK_Increment ? 1 : -1))
4667       return false;
4668     LVal.moveInto(Subobj);
4669     return true;
4670   }
4671 };
4672 } // end anonymous namespace
4673 
4674 /// Perform an increment or decrement on LVal.
handleIncDec(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,bool IsIncrement,APValue * Old)4675 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4676                          QualType LValType, bool IsIncrement, APValue *Old) {
4677   if (LVal.Designator.Invalid)
4678     return false;
4679 
4680   if (!Info.getLangOpts().CPlusPlus14) {
4681     Info.FFDiag(E);
4682     return false;
4683   }
4684 
4685   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4686   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4687   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4688   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4689 }
4690 
4691 /// Build an lvalue for the object argument of a member function call.
EvaluateObjectArgument(EvalInfo & Info,const Expr * Object,LValue & This)4692 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4693                                    LValue &This) {
4694   if (Object->getType()->isPointerType() && Object->isPRValue())
4695     return EvaluatePointer(Object, This, Info);
4696 
4697   if (Object->isGLValue())
4698     return EvaluateLValue(Object, This, Info);
4699 
4700   if (Object->getType()->isLiteralType(Info.Ctx))
4701     return EvaluateTemporary(Object, This, Info);
4702 
4703   if (Object->getType()->isRecordType() && Object->isPRValue())
4704     return EvaluateTemporary(Object, This, Info);
4705 
4706   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4707   return false;
4708 }
4709 
4710 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4711 /// lvalue referring to the result.
4712 ///
4713 /// \param Info - Information about the ongoing evaluation.
4714 /// \param LV - An lvalue referring to the base of the member pointer.
4715 /// \param RHS - The member pointer expression.
4716 /// \param IncludeMember - Specifies whether the member itself is included in
4717 ///        the resulting LValue subobject designator. This is not possible when
4718 ///        creating a bound member function.
4719 /// \return The field or method declaration to which the member pointer refers,
4720 ///         or 0 if evaluation fails.
HandleMemberPointerAccess(EvalInfo & Info,QualType LVType,LValue & LV,const Expr * RHS,bool IncludeMember=true)4721 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4722                                                   QualType LVType,
4723                                                   LValue &LV,
4724                                                   const Expr *RHS,
4725                                                   bool IncludeMember = true) {
4726   MemberPtr MemPtr;
4727   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4728     return nullptr;
4729 
4730   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4731   // member value, the behavior is undefined.
4732   if (!MemPtr.getDecl()) {
4733     // FIXME: Specific diagnostic.
4734     Info.FFDiag(RHS);
4735     return nullptr;
4736   }
4737 
4738   if (MemPtr.isDerivedMember()) {
4739     // This is a member of some derived class. Truncate LV appropriately.
4740     // The end of the derived-to-base path for the base object must match the
4741     // derived-to-base path for the member pointer.
4742     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4743         LV.Designator.Entries.size()) {
4744       Info.FFDiag(RHS);
4745       return nullptr;
4746     }
4747     unsigned PathLengthToMember =
4748         LV.Designator.Entries.size() - MemPtr.Path.size();
4749     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4750       const CXXRecordDecl *LVDecl = getAsBaseClass(
4751           LV.Designator.Entries[PathLengthToMember + I]);
4752       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4753       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4754         Info.FFDiag(RHS);
4755         return nullptr;
4756       }
4757     }
4758 
4759     // Truncate the lvalue to the appropriate derived class.
4760     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4761                             PathLengthToMember))
4762       return nullptr;
4763   } else if (!MemPtr.Path.empty()) {
4764     // Extend the LValue path with the member pointer's path.
4765     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4766                                   MemPtr.Path.size() + IncludeMember);
4767 
4768     // Walk down to the appropriate base class.
4769     if (const PointerType *PT = LVType->getAs<PointerType>())
4770       LVType = PT->getPointeeType();
4771     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4772     assert(RD && "member pointer access on non-class-type expression");
4773     // The first class in the path is that of the lvalue.
4774     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4775       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4776       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4777         return nullptr;
4778       RD = Base;
4779     }
4780     // Finally cast to the class containing the member.
4781     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4782                                 MemPtr.getContainingRecord()))
4783       return nullptr;
4784   }
4785 
4786   // Add the member. Note that we cannot build bound member functions here.
4787   if (IncludeMember) {
4788     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4789       if (!HandleLValueMember(Info, RHS, LV, FD))
4790         return nullptr;
4791     } else if (const IndirectFieldDecl *IFD =
4792                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4793       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4794         return nullptr;
4795     } else {
4796       llvm_unreachable("can't construct reference to bound member function");
4797     }
4798   }
4799 
4800   return MemPtr.getDecl();
4801 }
4802 
HandleMemberPointerAccess(EvalInfo & Info,const BinaryOperator * BO,LValue & LV,bool IncludeMember=true)4803 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4804                                                   const BinaryOperator *BO,
4805                                                   LValue &LV,
4806                                                   bool IncludeMember = true) {
4807   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4808 
4809   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4810     if (Info.noteFailure()) {
4811       MemberPtr MemPtr;
4812       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4813     }
4814     return nullptr;
4815   }
4816 
4817   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4818                                    BO->getRHS(), IncludeMember);
4819 }
4820 
4821 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4822 /// the provided lvalue, which currently refers to the base object.
HandleBaseToDerivedCast(EvalInfo & Info,const CastExpr * E,LValue & Result)4823 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4824                                     LValue &Result) {
4825   SubobjectDesignator &D = Result.Designator;
4826   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4827     return false;
4828 
4829   QualType TargetQT = E->getType();
4830   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4831     TargetQT = PT->getPointeeType();
4832 
4833   // Check this cast lands within the final derived-to-base subobject path.
4834   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4835     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4836       << D.MostDerivedType << TargetQT;
4837     return false;
4838   }
4839 
4840   // Check the type of the final cast. We don't need to check the path,
4841   // since a cast can only be formed if the path is unique.
4842   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4843   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4844   const CXXRecordDecl *FinalType;
4845   if (NewEntriesSize == D.MostDerivedPathLength)
4846     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4847   else
4848     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4849   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4850     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4851       << D.MostDerivedType << TargetQT;
4852     return false;
4853   }
4854 
4855   // Truncate the lvalue to the appropriate derived class.
4856   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4857 }
4858 
4859 /// Get the value to use for a default-initialized object of type T.
4860 /// Return false if it encounters something invalid.
handleDefaultInitValue(QualType T,APValue & Result)4861 static bool handleDefaultInitValue(QualType T, APValue &Result) {
4862   bool Success = true;
4863 
4864   // If there is already a value present don't overwrite it.
4865   if (!Result.isAbsent())
4866     return true;
4867 
4868   if (auto *RD = T->getAsCXXRecordDecl()) {
4869     if (RD->isInvalidDecl()) {
4870       Result = APValue();
4871       return false;
4872     }
4873     if (RD->isUnion()) {
4874       Result = APValue((const FieldDecl *)nullptr);
4875       return true;
4876     }
4877     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4878                      std::distance(RD->field_begin(), RD->field_end()));
4879 
4880     unsigned Index = 0;
4881     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4882                                                   End = RD->bases_end();
4883          I != End; ++I, ++Index)
4884       Success &=
4885           handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
4886 
4887     for (const auto *I : RD->fields()) {
4888       if (I->isUnnamedBitfield())
4889         continue;
4890       Success &= handleDefaultInitValue(
4891           I->getType(), Result.getStructField(I->getFieldIndex()));
4892     }
4893     return Success;
4894   }
4895 
4896   if (auto *AT =
4897           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4898     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4899     if (Result.hasArrayFiller())
4900       Success &=
4901           handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4902 
4903     return Success;
4904   }
4905 
4906   Result = APValue::IndeterminateValue();
4907   return true;
4908 }
4909 
4910 namespace {
4911 enum EvalStmtResult {
4912   /// Evaluation failed.
4913   ESR_Failed,
4914   /// Hit a 'return' statement.
4915   ESR_Returned,
4916   /// Evaluation succeeded.
4917   ESR_Succeeded,
4918   /// Hit a 'continue' statement.
4919   ESR_Continue,
4920   /// Hit a 'break' statement.
4921   ESR_Break,
4922   /// Still scanning for 'case' or 'default' statement.
4923   ESR_CaseNotFound
4924 };
4925 }
4926 
EvaluateVarDecl(EvalInfo & Info,const VarDecl * VD)4927 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4928   if (VD->isInvalidDecl())
4929     return false;
4930   // We don't need to evaluate the initializer for a static local.
4931   if (!VD->hasLocalStorage())
4932     return true;
4933 
4934   LValue Result;
4935   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4936                                                    ScopeKind::Block, Result);
4937 
4938   const Expr *InitE = VD->getInit();
4939   if (!InitE) {
4940     if (VD->getType()->isDependentType())
4941       return Info.noteSideEffect();
4942     return handleDefaultInitValue(VD->getType(), Val);
4943   }
4944   if (InitE->isValueDependent())
4945     return false;
4946 
4947   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4948     // Wipe out any partially-computed value, to allow tracking that this
4949     // evaluation failed.
4950     Val = APValue();
4951     return false;
4952   }
4953 
4954   return true;
4955 }
4956 
EvaluateDecl(EvalInfo & Info,const Decl * D)4957 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4958   bool OK = true;
4959 
4960   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4961     OK &= EvaluateVarDecl(Info, VD);
4962 
4963   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4964     for (auto *BD : DD->bindings())
4965       if (auto *VD = BD->getHoldingVar())
4966         OK &= EvaluateDecl(Info, VD);
4967 
4968   return OK;
4969 }
4970 
EvaluateDependentExpr(const Expr * E,EvalInfo & Info)4971 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4972   assert(E->isValueDependent());
4973   if (Info.noteSideEffect())
4974     return true;
4975   assert(E->containsErrors() && "valid value-dependent expression should never "
4976                                 "reach invalid code path.");
4977   return false;
4978 }
4979 
4980 /// Evaluate a condition (either a variable declaration or an expression).
EvaluateCond(EvalInfo & Info,const VarDecl * CondDecl,const Expr * Cond,bool & Result)4981 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4982                          const Expr *Cond, bool &Result) {
4983   if (Cond->isValueDependent())
4984     return false;
4985   FullExpressionRAII Scope(Info);
4986   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4987     return false;
4988   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4989     return false;
4990   return Scope.destroy();
4991 }
4992 
4993 namespace {
4994 /// A location where the result (returned value) of evaluating a
4995 /// statement should be stored.
4996 struct StmtResult {
4997   /// The APValue that should be filled in with the returned value.
4998   APValue &Value;
4999   /// The location containing the result, if any (used to support RVO).
5000   const LValue *Slot;
5001 };
5002 
5003 struct TempVersionRAII {
5004   CallStackFrame &Frame;
5005 
TempVersionRAII__anonbf0ddd821011::TempVersionRAII5006   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5007     Frame.pushTempVersion();
5008   }
5009 
~TempVersionRAII__anonbf0ddd821011::TempVersionRAII5010   ~TempVersionRAII() {
5011     Frame.popTempVersion();
5012   }
5013 };
5014 
5015 }
5016 
5017 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5018                                    const Stmt *S,
5019                                    const SwitchCase *SC = nullptr);
5020 
5021 /// Evaluate the body of a loop, and translate the result as appropriate.
EvaluateLoopBody(StmtResult & Result,EvalInfo & Info,const Stmt * Body,const SwitchCase * Case=nullptr)5022 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5023                                        const Stmt *Body,
5024                                        const SwitchCase *Case = nullptr) {
5025   BlockScopeRAII Scope(Info);
5026 
5027   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5028   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5029     ESR = ESR_Failed;
5030 
5031   switch (ESR) {
5032   case ESR_Break:
5033     return ESR_Succeeded;
5034   case ESR_Succeeded:
5035   case ESR_Continue:
5036     return ESR_Continue;
5037   case ESR_Failed:
5038   case ESR_Returned:
5039   case ESR_CaseNotFound:
5040     return ESR;
5041   }
5042   llvm_unreachable("Invalid EvalStmtResult!");
5043 }
5044 
5045 /// Evaluate a switch statement.
EvaluateSwitch(StmtResult & Result,EvalInfo & Info,const SwitchStmt * SS)5046 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5047                                      const SwitchStmt *SS) {
5048   BlockScopeRAII Scope(Info);
5049 
5050   // Evaluate the switch condition.
5051   APSInt Value;
5052   {
5053     if (const Stmt *Init = SS->getInit()) {
5054       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5055       if (ESR != ESR_Succeeded) {
5056         if (ESR != ESR_Failed && !Scope.destroy())
5057           ESR = ESR_Failed;
5058         return ESR;
5059       }
5060     }
5061 
5062     FullExpressionRAII CondScope(Info);
5063     if (SS->getConditionVariable() &&
5064         !EvaluateDecl(Info, SS->getConditionVariable()))
5065       return ESR_Failed;
5066     if (SS->getCond()->isValueDependent()) {
5067       // We don't know what the value is, and which branch should jump to.
5068       EvaluateDependentExpr(SS->getCond(), Info);
5069       return ESR_Failed;
5070     }
5071     if (!EvaluateInteger(SS->getCond(), Value, Info))
5072       return ESR_Failed;
5073 
5074     if (!CondScope.destroy())
5075       return ESR_Failed;
5076   }
5077 
5078   // Find the switch case corresponding to the value of the condition.
5079   // FIXME: Cache this lookup.
5080   const SwitchCase *Found = nullptr;
5081   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5082        SC = SC->getNextSwitchCase()) {
5083     if (isa<DefaultStmt>(SC)) {
5084       Found = SC;
5085       continue;
5086     }
5087 
5088     const CaseStmt *CS = cast<CaseStmt>(SC);
5089     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5090     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5091                               : LHS;
5092     if (LHS <= Value && Value <= RHS) {
5093       Found = SC;
5094       break;
5095     }
5096   }
5097 
5098   if (!Found)
5099     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5100 
5101   // Search the switch body for the switch case and evaluate it from there.
5102   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5103   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5104     return ESR_Failed;
5105 
5106   switch (ESR) {
5107   case ESR_Break:
5108     return ESR_Succeeded;
5109   case ESR_Succeeded:
5110   case ESR_Continue:
5111   case ESR_Failed:
5112   case ESR_Returned:
5113     return ESR;
5114   case ESR_CaseNotFound:
5115     // This can only happen if the switch case is nested within a statement
5116     // expression. We have no intention of supporting that.
5117     Info.FFDiag(Found->getBeginLoc(),
5118                 diag::note_constexpr_stmt_expr_unsupported);
5119     return ESR_Failed;
5120   }
5121   llvm_unreachable("Invalid EvalStmtResult!");
5122 }
5123 
CheckLocalVariableDeclaration(EvalInfo & Info,const VarDecl * VD)5124 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5125   // An expression E is a core constant expression unless the evaluation of E
5126   // would evaluate one of the following: [C++23] - a control flow that passes
5127   // through a declaration of a variable with static or thread storage duration
5128   // unless that variable is usable in constant expressions.
5129   if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5130       !VD->isUsableInConstantExpressions(Info.Ctx)) {
5131     Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5132         << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5133     return false;
5134   }
5135   return true;
5136 }
5137 
5138 // Evaluate a statement.
EvaluateStmt(StmtResult & Result,EvalInfo & Info,const Stmt * S,const SwitchCase * Case)5139 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5140                                    const Stmt *S, const SwitchCase *Case) {
5141   if (!Info.nextStep(S))
5142     return ESR_Failed;
5143 
5144   // If we're hunting down a 'case' or 'default' label, recurse through
5145   // substatements until we hit the label.
5146   if (Case) {
5147     switch (S->getStmtClass()) {
5148     case Stmt::CompoundStmtClass:
5149       // FIXME: Precompute which substatement of a compound statement we
5150       // would jump to, and go straight there rather than performing a
5151       // linear scan each time.
5152     case Stmt::LabelStmtClass:
5153     case Stmt::AttributedStmtClass:
5154     case Stmt::DoStmtClass:
5155       break;
5156 
5157     case Stmt::CaseStmtClass:
5158     case Stmt::DefaultStmtClass:
5159       if (Case == S)
5160         Case = nullptr;
5161       break;
5162 
5163     case Stmt::IfStmtClass: {
5164       // FIXME: Precompute which side of an 'if' we would jump to, and go
5165       // straight there rather than scanning both sides.
5166       const IfStmt *IS = cast<IfStmt>(S);
5167 
5168       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5169       // preceded by our switch label.
5170       BlockScopeRAII Scope(Info);
5171 
5172       // Step into the init statement in case it brings an (uninitialized)
5173       // variable into scope.
5174       if (const Stmt *Init = IS->getInit()) {
5175         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5176         if (ESR != ESR_CaseNotFound) {
5177           assert(ESR != ESR_Succeeded);
5178           return ESR;
5179         }
5180       }
5181 
5182       // Condition variable must be initialized if it exists.
5183       // FIXME: We can skip evaluating the body if there's a condition
5184       // variable, as there can't be any case labels within it.
5185       // (The same is true for 'for' statements.)
5186 
5187       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5188       if (ESR == ESR_Failed)
5189         return ESR;
5190       if (ESR != ESR_CaseNotFound)
5191         return Scope.destroy() ? ESR : ESR_Failed;
5192       if (!IS->getElse())
5193         return ESR_CaseNotFound;
5194 
5195       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5196       if (ESR == ESR_Failed)
5197         return ESR;
5198       if (ESR != ESR_CaseNotFound)
5199         return Scope.destroy() ? ESR : ESR_Failed;
5200       return ESR_CaseNotFound;
5201     }
5202 
5203     case Stmt::WhileStmtClass: {
5204       EvalStmtResult ESR =
5205           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5206       if (ESR != ESR_Continue)
5207         return ESR;
5208       break;
5209     }
5210 
5211     case Stmt::ForStmtClass: {
5212       const ForStmt *FS = cast<ForStmt>(S);
5213       BlockScopeRAII Scope(Info);
5214 
5215       // Step into the init statement in case it brings an (uninitialized)
5216       // variable into scope.
5217       if (const Stmt *Init = FS->getInit()) {
5218         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5219         if (ESR != ESR_CaseNotFound) {
5220           assert(ESR != ESR_Succeeded);
5221           return ESR;
5222         }
5223       }
5224 
5225       EvalStmtResult ESR =
5226           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5227       if (ESR != ESR_Continue)
5228         return ESR;
5229       if (const auto *Inc = FS->getInc()) {
5230         if (Inc->isValueDependent()) {
5231           if (!EvaluateDependentExpr(Inc, Info))
5232             return ESR_Failed;
5233         } else {
5234           FullExpressionRAII IncScope(Info);
5235           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5236             return ESR_Failed;
5237         }
5238       }
5239       break;
5240     }
5241 
5242     case Stmt::DeclStmtClass: {
5243       // Start the lifetime of any uninitialized variables we encounter. They
5244       // might be used by the selected branch of the switch.
5245       const DeclStmt *DS = cast<DeclStmt>(S);
5246       for (const auto *D : DS->decls()) {
5247         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5248           if (!CheckLocalVariableDeclaration(Info, VD))
5249             return ESR_Failed;
5250           if (VD->hasLocalStorage() && !VD->getInit())
5251             if (!EvaluateVarDecl(Info, VD))
5252               return ESR_Failed;
5253           // FIXME: If the variable has initialization that can't be jumped
5254           // over, bail out of any immediately-surrounding compound-statement
5255           // too. There can't be any case labels here.
5256         }
5257       }
5258       return ESR_CaseNotFound;
5259     }
5260 
5261     default:
5262       return ESR_CaseNotFound;
5263     }
5264   }
5265 
5266   switch (S->getStmtClass()) {
5267   default:
5268     if (const Expr *E = dyn_cast<Expr>(S)) {
5269       if (E->isValueDependent()) {
5270         if (!EvaluateDependentExpr(E, Info))
5271           return ESR_Failed;
5272       } else {
5273         // Don't bother evaluating beyond an expression-statement which couldn't
5274         // be evaluated.
5275         // FIXME: Do we need the FullExpressionRAII object here?
5276         // VisitExprWithCleanups should create one when necessary.
5277         FullExpressionRAII Scope(Info);
5278         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5279           return ESR_Failed;
5280       }
5281       return ESR_Succeeded;
5282     }
5283 
5284     Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5285     return ESR_Failed;
5286 
5287   case Stmt::NullStmtClass:
5288     return ESR_Succeeded;
5289 
5290   case Stmt::DeclStmtClass: {
5291     const DeclStmt *DS = cast<DeclStmt>(S);
5292     for (const auto *D : DS->decls()) {
5293       const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5294       if (VD && !CheckLocalVariableDeclaration(Info, VD))
5295         return ESR_Failed;
5296       // Each declaration initialization is its own full-expression.
5297       FullExpressionRAII Scope(Info);
5298       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5299         return ESR_Failed;
5300       if (!Scope.destroy())
5301         return ESR_Failed;
5302     }
5303     return ESR_Succeeded;
5304   }
5305 
5306   case Stmt::ReturnStmtClass: {
5307     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5308     FullExpressionRAII Scope(Info);
5309     if (RetExpr && RetExpr->isValueDependent()) {
5310       EvaluateDependentExpr(RetExpr, Info);
5311       // We know we returned, but we don't know what the value is.
5312       return ESR_Failed;
5313     }
5314     if (RetExpr &&
5315         !(Result.Slot
5316               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5317               : Evaluate(Result.Value, Info, RetExpr)))
5318       return ESR_Failed;
5319     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5320   }
5321 
5322   case Stmt::CompoundStmtClass: {
5323     BlockScopeRAII Scope(Info);
5324 
5325     const CompoundStmt *CS = cast<CompoundStmt>(S);
5326     for (const auto *BI : CS->body()) {
5327       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5328       if (ESR == ESR_Succeeded)
5329         Case = nullptr;
5330       else if (ESR != ESR_CaseNotFound) {
5331         if (ESR != ESR_Failed && !Scope.destroy())
5332           return ESR_Failed;
5333         return ESR;
5334       }
5335     }
5336     if (Case)
5337       return ESR_CaseNotFound;
5338     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5339   }
5340 
5341   case Stmt::IfStmtClass: {
5342     const IfStmt *IS = cast<IfStmt>(S);
5343 
5344     // Evaluate the condition, as either a var decl or as an expression.
5345     BlockScopeRAII Scope(Info);
5346     if (const Stmt *Init = IS->getInit()) {
5347       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5348       if (ESR != ESR_Succeeded) {
5349         if (ESR != ESR_Failed && !Scope.destroy())
5350           return ESR_Failed;
5351         return ESR;
5352       }
5353     }
5354     bool Cond;
5355     if (IS->isConsteval()) {
5356       Cond = IS->isNonNegatedConsteval();
5357       // If we are not in a constant context, if consteval should not evaluate
5358       // to true.
5359       if (!Info.InConstantContext)
5360         Cond = !Cond;
5361     } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5362                              Cond))
5363       return ESR_Failed;
5364 
5365     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5366       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5367       if (ESR != ESR_Succeeded) {
5368         if (ESR != ESR_Failed && !Scope.destroy())
5369           return ESR_Failed;
5370         return ESR;
5371       }
5372     }
5373     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5374   }
5375 
5376   case Stmt::WhileStmtClass: {
5377     const WhileStmt *WS = cast<WhileStmt>(S);
5378     while (true) {
5379       BlockScopeRAII Scope(Info);
5380       bool Continue;
5381       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5382                         Continue))
5383         return ESR_Failed;
5384       if (!Continue)
5385         break;
5386 
5387       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5388       if (ESR != ESR_Continue) {
5389         if (ESR != ESR_Failed && !Scope.destroy())
5390           return ESR_Failed;
5391         return ESR;
5392       }
5393       if (!Scope.destroy())
5394         return ESR_Failed;
5395     }
5396     return ESR_Succeeded;
5397   }
5398 
5399   case Stmt::DoStmtClass: {
5400     const DoStmt *DS = cast<DoStmt>(S);
5401     bool Continue;
5402     do {
5403       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5404       if (ESR != ESR_Continue)
5405         return ESR;
5406       Case = nullptr;
5407 
5408       if (DS->getCond()->isValueDependent()) {
5409         EvaluateDependentExpr(DS->getCond(), Info);
5410         // Bailout as we don't know whether to keep going or terminate the loop.
5411         return ESR_Failed;
5412       }
5413       FullExpressionRAII CondScope(Info);
5414       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5415           !CondScope.destroy())
5416         return ESR_Failed;
5417     } while (Continue);
5418     return ESR_Succeeded;
5419   }
5420 
5421   case Stmt::ForStmtClass: {
5422     const ForStmt *FS = cast<ForStmt>(S);
5423     BlockScopeRAII ForScope(Info);
5424     if (FS->getInit()) {
5425       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5426       if (ESR != ESR_Succeeded) {
5427         if (ESR != ESR_Failed && !ForScope.destroy())
5428           return ESR_Failed;
5429         return ESR;
5430       }
5431     }
5432     while (true) {
5433       BlockScopeRAII IterScope(Info);
5434       bool Continue = true;
5435       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5436                                          FS->getCond(), Continue))
5437         return ESR_Failed;
5438       if (!Continue)
5439         break;
5440 
5441       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5442       if (ESR != ESR_Continue) {
5443         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5444           return ESR_Failed;
5445         return ESR;
5446       }
5447 
5448       if (const auto *Inc = FS->getInc()) {
5449         if (Inc->isValueDependent()) {
5450           if (!EvaluateDependentExpr(Inc, Info))
5451             return ESR_Failed;
5452         } else {
5453           FullExpressionRAII IncScope(Info);
5454           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5455             return ESR_Failed;
5456         }
5457       }
5458 
5459       if (!IterScope.destroy())
5460         return ESR_Failed;
5461     }
5462     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5463   }
5464 
5465   case Stmt::CXXForRangeStmtClass: {
5466     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5467     BlockScopeRAII Scope(Info);
5468 
5469     // Evaluate the init-statement if present.
5470     if (FS->getInit()) {
5471       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5472       if (ESR != ESR_Succeeded) {
5473         if (ESR != ESR_Failed && !Scope.destroy())
5474           return ESR_Failed;
5475         return ESR;
5476       }
5477     }
5478 
5479     // Initialize the __range variable.
5480     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5481     if (ESR != ESR_Succeeded) {
5482       if (ESR != ESR_Failed && !Scope.destroy())
5483         return ESR_Failed;
5484       return ESR;
5485     }
5486 
5487     // In error-recovery cases it's possible to get here even if we failed to
5488     // synthesize the __begin and __end variables.
5489     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5490       return ESR_Failed;
5491 
5492     // Create the __begin and __end iterators.
5493     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5494     if (ESR != ESR_Succeeded) {
5495       if (ESR != ESR_Failed && !Scope.destroy())
5496         return ESR_Failed;
5497       return ESR;
5498     }
5499     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5500     if (ESR != ESR_Succeeded) {
5501       if (ESR != ESR_Failed && !Scope.destroy())
5502         return ESR_Failed;
5503       return ESR;
5504     }
5505 
5506     while (true) {
5507       // Condition: __begin != __end.
5508       {
5509         if (FS->getCond()->isValueDependent()) {
5510           EvaluateDependentExpr(FS->getCond(), Info);
5511           // We don't know whether to keep going or terminate the loop.
5512           return ESR_Failed;
5513         }
5514         bool Continue = true;
5515         FullExpressionRAII CondExpr(Info);
5516         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5517           return ESR_Failed;
5518         if (!Continue)
5519           break;
5520       }
5521 
5522       // User's variable declaration, initialized by *__begin.
5523       BlockScopeRAII InnerScope(Info);
5524       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5525       if (ESR != ESR_Succeeded) {
5526         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5527           return ESR_Failed;
5528         return ESR;
5529       }
5530 
5531       // Loop body.
5532       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5533       if (ESR != ESR_Continue) {
5534         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5535           return ESR_Failed;
5536         return ESR;
5537       }
5538       if (FS->getInc()->isValueDependent()) {
5539         if (!EvaluateDependentExpr(FS->getInc(), Info))
5540           return ESR_Failed;
5541       } else {
5542         // Increment: ++__begin
5543         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5544           return ESR_Failed;
5545       }
5546 
5547       if (!InnerScope.destroy())
5548         return ESR_Failed;
5549     }
5550 
5551     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5552   }
5553 
5554   case Stmt::SwitchStmtClass:
5555     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5556 
5557   case Stmt::ContinueStmtClass:
5558     return ESR_Continue;
5559 
5560   case Stmt::BreakStmtClass:
5561     return ESR_Break;
5562 
5563   case Stmt::LabelStmtClass:
5564     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5565 
5566   case Stmt::AttributedStmtClass: {
5567     const auto *AS = cast<AttributedStmt>(S);
5568     const auto *SS = AS->getSubStmt();
5569     MSConstexprContextRAII ConstexprContext(
5570         *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5571                                isa<ReturnStmt>(SS));
5572     return EvaluateStmt(Result, Info, SS, Case);
5573   }
5574 
5575   case Stmt::CaseStmtClass:
5576   case Stmt::DefaultStmtClass:
5577     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5578   case Stmt::CXXTryStmtClass:
5579     // Evaluate try blocks by evaluating all sub statements.
5580     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5581   }
5582 }
5583 
5584 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5585 /// default constructor. If so, we'll fold it whether or not it's marked as
5586 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5587 /// so we need special handling.
CheckTrivialDefaultConstructor(EvalInfo & Info,SourceLocation Loc,const CXXConstructorDecl * CD,bool IsValueInitialization)5588 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5589                                            const CXXConstructorDecl *CD,
5590                                            bool IsValueInitialization) {
5591   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5592     return false;
5593 
5594   // Value-initialization does not call a trivial default constructor, so such a
5595   // call is a core constant expression whether or not the constructor is
5596   // constexpr.
5597   if (!CD->isConstexpr() && !IsValueInitialization) {
5598     if (Info.getLangOpts().CPlusPlus11) {
5599       // FIXME: If DiagDecl is an implicitly-declared special member function,
5600       // we should be much more explicit about why it's not constexpr.
5601       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5602         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5603       Info.Note(CD->getLocation(), diag::note_declared_at);
5604     } else {
5605       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5606     }
5607   }
5608   return true;
5609 }
5610 
5611 /// CheckConstexprFunction - Check that a function can be called in a constant
5612 /// expression.
CheckConstexprFunction(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Declaration,const FunctionDecl * Definition,const Stmt * Body)5613 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5614                                    const FunctionDecl *Declaration,
5615                                    const FunctionDecl *Definition,
5616                                    const Stmt *Body) {
5617   // Potential constant expressions can contain calls to declared, but not yet
5618   // defined, constexpr functions.
5619   if (Info.checkingPotentialConstantExpression() && !Definition &&
5620       Declaration->isConstexpr())
5621     return false;
5622 
5623   // Bail out if the function declaration itself is invalid.  We will
5624   // have produced a relevant diagnostic while parsing it, so just
5625   // note the problematic sub-expression.
5626   if (Declaration->isInvalidDecl()) {
5627     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5628     return false;
5629   }
5630 
5631   // DR1872: An instantiated virtual constexpr function can't be called in a
5632   // constant expression (prior to C++20). We can still constant-fold such a
5633   // call.
5634   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5635       cast<CXXMethodDecl>(Declaration)->isVirtual())
5636     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5637 
5638   if (Definition && Definition->isInvalidDecl()) {
5639     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5640     return false;
5641   }
5642 
5643   // Can we evaluate this function call?
5644   if (Definition && Body &&
5645       (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
5646                                         Definition->hasAttr<MSConstexprAttr>())))
5647     return true;
5648 
5649   if (Info.getLangOpts().CPlusPlus11) {
5650     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5651 
5652     // If this function is not constexpr because it is an inherited
5653     // non-constexpr constructor, diagnose that directly.
5654     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5655     if (CD && CD->isInheritingConstructor()) {
5656       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5657       if (!Inherited->isConstexpr())
5658         DiagDecl = CD = Inherited;
5659     }
5660 
5661     // FIXME: If DiagDecl is an implicitly-declared special member function
5662     // or an inheriting constructor, we should be much more explicit about why
5663     // it's not constexpr.
5664     if (CD && CD->isInheritingConstructor())
5665       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5666         << CD->getInheritedConstructor().getConstructor()->getParent();
5667     else
5668       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5669         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5670     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5671   } else {
5672     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5673   }
5674   return false;
5675 }
5676 
5677 namespace {
5678 struct CheckDynamicTypeHandler {
5679   AccessKinds AccessKind;
5680   typedef bool result_type;
failed__anonbf0ddd821111::CheckDynamicTypeHandler5681   bool failed() { return false; }
found__anonbf0ddd821111::CheckDynamicTypeHandler5682   bool found(APValue &Subobj, QualType SubobjType) { return true; }
found__anonbf0ddd821111::CheckDynamicTypeHandler5683   bool found(APSInt &Value, QualType SubobjType) { return true; }
found__anonbf0ddd821111::CheckDynamicTypeHandler5684   bool found(APFloat &Value, QualType SubobjType) { return true; }
5685 };
5686 } // end anonymous namespace
5687 
5688 /// Check that we can access the notional vptr of an object / determine its
5689 /// dynamic type.
checkDynamicType(EvalInfo & Info,const Expr * E,const LValue & This,AccessKinds AK,bool Polymorphic)5690 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5691                              AccessKinds AK, bool Polymorphic) {
5692   if (This.Designator.Invalid)
5693     return false;
5694 
5695   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5696 
5697   if (!Obj)
5698     return false;
5699 
5700   if (!Obj.Value) {
5701     // The object is not usable in constant expressions, so we can't inspect
5702     // its value to see if it's in-lifetime or what the active union members
5703     // are. We can still check for a one-past-the-end lvalue.
5704     if (This.Designator.isOnePastTheEnd() ||
5705         This.Designator.isMostDerivedAnUnsizedArray()) {
5706       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5707                          ? diag::note_constexpr_access_past_end
5708                          : diag::note_constexpr_access_unsized_array)
5709           << AK;
5710       return false;
5711     } else if (Polymorphic) {
5712       // Conservatively refuse to perform a polymorphic operation if we would
5713       // not be able to read a notional 'vptr' value.
5714       APValue Val;
5715       This.moveInto(Val);
5716       QualType StarThisType =
5717           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5718       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5719           << AK << Val.getAsString(Info.Ctx, StarThisType);
5720       return false;
5721     }
5722     return true;
5723   }
5724 
5725   CheckDynamicTypeHandler Handler{AK};
5726   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5727 }
5728 
5729 /// Check that the pointee of the 'this' pointer in a member function call is
5730 /// either within its lifetime or in its period of construction or destruction.
5731 static bool
checkNonVirtualMemberCallThisPointer(EvalInfo & Info,const Expr * E,const LValue & This,const CXXMethodDecl * NamedMember)5732 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5733                                      const LValue &This,
5734                                      const CXXMethodDecl *NamedMember) {
5735   return checkDynamicType(
5736       Info, E, This,
5737       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5738 }
5739 
5740 struct DynamicType {
5741   /// The dynamic class type of the object.
5742   const CXXRecordDecl *Type;
5743   /// The corresponding path length in the lvalue.
5744   unsigned PathLength;
5745 };
5746 
getBaseClassType(SubobjectDesignator & Designator,unsigned PathLength)5747 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5748                                              unsigned PathLength) {
5749   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5750       Designator.Entries.size() && "invalid path length");
5751   return (PathLength == Designator.MostDerivedPathLength)
5752              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5753              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5754 }
5755 
5756 /// Determine the dynamic type of an object.
ComputeDynamicType(EvalInfo & Info,const Expr * E,LValue & This,AccessKinds AK)5757 static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5758                                                      const Expr *E,
5759                                                      LValue &This,
5760                                                      AccessKinds AK) {
5761   // If we don't have an lvalue denoting an object of class type, there is no
5762   // meaningful dynamic type. (We consider objects of non-class type to have no
5763   // dynamic type.)
5764   if (!checkDynamicType(Info, E, This, AK, true))
5765     return std::nullopt;
5766 
5767   // Refuse to compute a dynamic type in the presence of virtual bases. This
5768   // shouldn't happen other than in constant-folding situations, since literal
5769   // types can't have virtual bases.
5770   //
5771   // Note that consumers of DynamicType assume that the type has no virtual
5772   // bases, and will need modifications if this restriction is relaxed.
5773   const CXXRecordDecl *Class =
5774       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5775   if (!Class || Class->getNumVBases()) {
5776     Info.FFDiag(E);
5777     return std::nullopt;
5778   }
5779 
5780   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5781   // binary search here instead. But the overwhelmingly common case is that
5782   // we're not in the middle of a constructor, so it probably doesn't matter
5783   // in practice.
5784   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5785   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5786        PathLength <= Path.size(); ++PathLength) {
5787     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5788                                       Path.slice(0, PathLength))) {
5789     case ConstructionPhase::Bases:
5790     case ConstructionPhase::DestroyingBases:
5791       // We're constructing or destroying a base class. This is not the dynamic
5792       // type.
5793       break;
5794 
5795     case ConstructionPhase::None:
5796     case ConstructionPhase::AfterBases:
5797     case ConstructionPhase::AfterFields:
5798     case ConstructionPhase::Destroying:
5799       // We've finished constructing the base classes and not yet started
5800       // destroying them again, so this is the dynamic type.
5801       return DynamicType{getBaseClassType(This.Designator, PathLength),
5802                          PathLength};
5803     }
5804   }
5805 
5806   // CWG issue 1517: we're constructing a base class of the object described by
5807   // 'This', so that object has not yet begun its period of construction and
5808   // any polymorphic operation on it results in undefined behavior.
5809   Info.FFDiag(E);
5810   return std::nullopt;
5811 }
5812 
5813 /// Perform virtual dispatch.
HandleVirtualDispatch(EvalInfo & Info,const Expr * E,LValue & This,const CXXMethodDecl * Found,llvm::SmallVectorImpl<QualType> & CovariantAdjustmentPath)5814 static const CXXMethodDecl *HandleVirtualDispatch(
5815     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5816     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5817   std::optional<DynamicType> DynType = ComputeDynamicType(
5818       Info, E, This,
5819       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5820   if (!DynType)
5821     return nullptr;
5822 
5823   // Find the final overrider. It must be declared in one of the classes on the
5824   // path from the dynamic type to the static type.
5825   // FIXME: If we ever allow literal types to have virtual base classes, that
5826   // won't be true.
5827   const CXXMethodDecl *Callee = Found;
5828   unsigned PathLength = DynType->PathLength;
5829   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5830     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5831     const CXXMethodDecl *Overrider =
5832         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5833     if (Overrider) {
5834       Callee = Overrider;
5835       break;
5836     }
5837   }
5838 
5839   // C++2a [class.abstract]p6:
5840   //   the effect of making a virtual call to a pure virtual function [...] is
5841   //   undefined
5842   if (Callee->isPureVirtual()) {
5843     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5844     Info.Note(Callee->getLocation(), diag::note_declared_at);
5845     return nullptr;
5846   }
5847 
5848   // If necessary, walk the rest of the path to determine the sequence of
5849   // covariant adjustment steps to apply.
5850   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5851                                        Found->getReturnType())) {
5852     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5853     for (unsigned CovariantPathLength = PathLength + 1;
5854          CovariantPathLength != This.Designator.Entries.size();
5855          ++CovariantPathLength) {
5856       const CXXRecordDecl *NextClass =
5857           getBaseClassType(This.Designator, CovariantPathLength);
5858       const CXXMethodDecl *Next =
5859           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5860       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5861                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5862         CovariantAdjustmentPath.push_back(Next->getReturnType());
5863     }
5864     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5865                                          CovariantAdjustmentPath.back()))
5866       CovariantAdjustmentPath.push_back(Found->getReturnType());
5867   }
5868 
5869   // Perform 'this' adjustment.
5870   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5871     return nullptr;
5872 
5873   return Callee;
5874 }
5875 
5876 /// Perform the adjustment from a value returned by a virtual function to
5877 /// a value of the statically expected type, which may be a pointer or
5878 /// reference to a base class of the returned type.
HandleCovariantReturnAdjustment(EvalInfo & Info,const Expr * E,APValue & Result,ArrayRef<QualType> Path)5879 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5880                                             APValue &Result,
5881                                             ArrayRef<QualType> Path) {
5882   assert(Result.isLValue() &&
5883          "unexpected kind of APValue for covariant return");
5884   if (Result.isNullPointer())
5885     return true;
5886 
5887   LValue LVal;
5888   LVal.setFrom(Info.Ctx, Result);
5889 
5890   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5891   for (unsigned I = 1; I != Path.size(); ++I) {
5892     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5893     assert(OldClass && NewClass && "unexpected kind of covariant return");
5894     if (OldClass != NewClass &&
5895         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5896       return false;
5897     OldClass = NewClass;
5898   }
5899 
5900   LVal.moveInto(Result);
5901   return true;
5902 }
5903 
5904 /// Determine whether \p Base, which is known to be a direct base class of
5905 /// \p Derived, is a public base class.
isBaseClassPublic(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)5906 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5907                               const CXXRecordDecl *Base) {
5908   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5909     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5910     if (BaseClass && declaresSameEntity(BaseClass, Base))
5911       return BaseSpec.getAccessSpecifier() == AS_public;
5912   }
5913   llvm_unreachable("Base is not a direct base of Derived");
5914 }
5915 
5916 /// Apply the given dynamic cast operation on the provided lvalue.
5917 ///
5918 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5919 /// to find a suitable target subobject.
HandleDynamicCast(EvalInfo & Info,const ExplicitCastExpr * E,LValue & Ptr)5920 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5921                               LValue &Ptr) {
5922   // We can't do anything with a non-symbolic pointer value.
5923   SubobjectDesignator &D = Ptr.Designator;
5924   if (D.Invalid)
5925     return false;
5926 
5927   // C++ [expr.dynamic.cast]p6:
5928   //   If v is a null pointer value, the result is a null pointer value.
5929   if (Ptr.isNullPointer() && !E->isGLValue())
5930     return true;
5931 
5932   // For all the other cases, we need the pointer to point to an object within
5933   // its lifetime / period of construction / destruction, and we need to know
5934   // its dynamic type.
5935   std::optional<DynamicType> DynType =
5936       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5937   if (!DynType)
5938     return false;
5939 
5940   // C++ [expr.dynamic.cast]p7:
5941   //   If T is "pointer to cv void", then the result is a pointer to the most
5942   //   derived object
5943   if (E->getType()->isVoidPointerType())
5944     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5945 
5946   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5947   assert(C && "dynamic_cast target is not void pointer nor class");
5948   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5949 
5950   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5951     // C++ [expr.dynamic.cast]p9:
5952     if (!E->isGLValue()) {
5953       //   The value of a failed cast to pointer type is the null pointer value
5954       //   of the required result type.
5955       Ptr.setNull(Info.Ctx, E->getType());
5956       return true;
5957     }
5958 
5959     //   A failed cast to reference type throws [...] std::bad_cast.
5960     unsigned DiagKind;
5961     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5962                    DynType->Type->isDerivedFrom(C)))
5963       DiagKind = 0;
5964     else if (!Paths || Paths->begin() == Paths->end())
5965       DiagKind = 1;
5966     else if (Paths->isAmbiguous(CQT))
5967       DiagKind = 2;
5968     else {
5969       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5970       DiagKind = 3;
5971     }
5972     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5973         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5974         << Info.Ctx.getRecordType(DynType->Type)
5975         << E->getType().getUnqualifiedType();
5976     return false;
5977   };
5978 
5979   // Runtime check, phase 1:
5980   //   Walk from the base subobject towards the derived object looking for the
5981   //   target type.
5982   for (int PathLength = Ptr.Designator.Entries.size();
5983        PathLength >= (int)DynType->PathLength; --PathLength) {
5984     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5985     if (declaresSameEntity(Class, C))
5986       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5987     // We can only walk across public inheritance edges.
5988     if (PathLength > (int)DynType->PathLength &&
5989         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5990                            Class))
5991       return RuntimeCheckFailed(nullptr);
5992   }
5993 
5994   // Runtime check, phase 2:
5995   //   Search the dynamic type for an unambiguous public base of type C.
5996   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5997                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5998   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5999       Paths.front().Access == AS_public) {
6000     // Downcast to the dynamic type...
6001     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6002       return false;
6003     // ... then upcast to the chosen base class subobject.
6004     for (CXXBasePathElement &Elem : Paths.front())
6005       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6006         return false;
6007     return true;
6008   }
6009 
6010   // Otherwise, the runtime check fails.
6011   return RuntimeCheckFailed(&Paths);
6012 }
6013 
6014 namespace {
6015 struct StartLifetimeOfUnionMemberHandler {
6016   EvalInfo &Info;
6017   const Expr *LHSExpr;
6018   const FieldDecl *Field;
6019   bool DuringInit;
6020   bool Failed = false;
6021   static const AccessKinds AccessKind = AK_Assign;
6022 
6023   typedef bool result_type;
failed__anonbf0ddd821311::StartLifetimeOfUnionMemberHandler6024   bool failed() { return Failed; }
found__anonbf0ddd821311::StartLifetimeOfUnionMemberHandler6025   bool found(APValue &Subobj, QualType SubobjType) {
6026     // We are supposed to perform no initialization but begin the lifetime of
6027     // the object. We interpret that as meaning to do what default
6028     // initialization of the object would do if all constructors involved were
6029     // trivial:
6030     //  * All base, non-variant member, and array element subobjects' lifetimes
6031     //    begin
6032     //  * No variant members' lifetimes begin
6033     //  * All scalar subobjects whose lifetimes begin have indeterminate values
6034     assert(SubobjType->isUnionType());
6035     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6036       // This union member is already active. If it's also in-lifetime, there's
6037       // nothing to do.
6038       if (Subobj.getUnionValue().hasValue())
6039         return true;
6040     } else if (DuringInit) {
6041       // We're currently in the process of initializing a different union
6042       // member.  If we carried on, that initialization would attempt to
6043       // store to an inactive union member, resulting in undefined behavior.
6044       Info.FFDiag(LHSExpr,
6045                   diag::note_constexpr_union_member_change_during_init);
6046       return false;
6047     }
6048     APValue Result;
6049     Failed = !handleDefaultInitValue(Field->getType(), Result);
6050     Subobj.setUnion(Field, Result);
6051     return true;
6052   }
found__anonbf0ddd821311::StartLifetimeOfUnionMemberHandler6053   bool found(APSInt &Value, QualType SubobjType) {
6054     llvm_unreachable("wrong value kind for union object");
6055   }
found__anonbf0ddd821311::StartLifetimeOfUnionMemberHandler6056   bool found(APFloat &Value, QualType SubobjType) {
6057     llvm_unreachable("wrong value kind for union object");
6058   }
6059 };
6060 } // end anonymous namespace
6061 
6062 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6063 
6064 /// Handle a builtin simple-assignment or a call to a trivial assignment
6065 /// operator whose left-hand side might involve a union member access. If it
6066 /// does, implicitly start the lifetime of any accessed union elements per
6067 /// C++20 [class.union]5.
MaybeHandleUnionActiveMemberChange(EvalInfo & Info,const Expr * LHSExpr,const LValue & LHS)6068 static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6069                                                const Expr *LHSExpr,
6070                                                const LValue &LHS) {
6071   if (LHS.InvalidBase || LHS.Designator.Invalid)
6072     return false;
6073 
6074   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
6075   // C++ [class.union]p5:
6076   //   define the set S(E) of subexpressions of E as follows:
6077   unsigned PathLength = LHS.Designator.Entries.size();
6078   for (const Expr *E = LHSExpr; E != nullptr;) {
6079     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
6080     if (auto *ME = dyn_cast<MemberExpr>(E)) {
6081       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6082       // Note that we can't implicitly start the lifetime of a reference,
6083       // so we don't need to proceed any further if we reach one.
6084       if (!FD || FD->getType()->isReferenceType())
6085         break;
6086 
6087       //    ... and also contains A.B if B names a union member ...
6088       if (FD->getParent()->isUnion()) {
6089         //    ... of a non-class, non-array type, or of a class type with a
6090         //    trivial default constructor that is not deleted, or an array of
6091         //    such types.
6092         auto *RD =
6093             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6094         if (!RD || RD->hasTrivialDefaultConstructor())
6095           UnionPathLengths.push_back({PathLength - 1, FD});
6096       }
6097 
6098       E = ME->getBase();
6099       --PathLength;
6100       assert(declaresSameEntity(FD,
6101                                 LHS.Designator.Entries[PathLength]
6102                                     .getAsBaseOrMember().getPointer()));
6103 
6104       //   -- If E is of the form A[B] and is interpreted as a built-in array
6105       //      subscripting operator, S(E) is [S(the array operand, if any)].
6106     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6107       // Step over an ArrayToPointerDecay implicit cast.
6108       auto *Base = ASE->getBase()->IgnoreImplicit();
6109       if (!Base->getType()->isArrayType())
6110         break;
6111 
6112       E = Base;
6113       --PathLength;
6114 
6115     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6116       // Step over a derived-to-base conversion.
6117       E = ICE->getSubExpr();
6118       if (ICE->getCastKind() == CK_NoOp)
6119         continue;
6120       if (ICE->getCastKind() != CK_DerivedToBase &&
6121           ICE->getCastKind() != CK_UncheckedDerivedToBase)
6122         break;
6123       // Walk path backwards as we walk up from the base to the derived class.
6124       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6125         if (Elt->isVirtual()) {
6126           // A class with virtual base classes never has a trivial default
6127           // constructor, so S(E) is empty in this case.
6128           E = nullptr;
6129           break;
6130         }
6131 
6132         --PathLength;
6133         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6134                                   LHS.Designator.Entries[PathLength]
6135                                       .getAsBaseOrMember().getPointer()));
6136       }
6137 
6138     //   -- Otherwise, S(E) is empty.
6139     } else {
6140       break;
6141     }
6142   }
6143 
6144   // Common case: no unions' lifetimes are started.
6145   if (UnionPathLengths.empty())
6146     return true;
6147 
6148   //   if modification of X [would access an inactive union member], an object
6149   //   of the type of X is implicitly created
6150   CompleteObject Obj =
6151       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6152   if (!Obj)
6153     return false;
6154   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6155            llvm::reverse(UnionPathLengths)) {
6156     // Form a designator for the union object.
6157     SubobjectDesignator D = LHS.Designator;
6158     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6159 
6160     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6161                       ConstructionPhase::AfterBases;
6162     StartLifetimeOfUnionMemberHandler StartLifetime{
6163         Info, LHSExpr, LengthAndField.second, DuringInit};
6164     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6165       return false;
6166   }
6167 
6168   return true;
6169 }
6170 
EvaluateCallArg(const ParmVarDecl * PVD,const Expr * Arg,CallRef Call,EvalInfo & Info,bool NonNull=false)6171 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6172                             CallRef Call, EvalInfo &Info,
6173                             bool NonNull = false) {
6174   LValue LV;
6175   // Create the parameter slot and register its destruction. For a vararg
6176   // argument, create a temporary.
6177   // FIXME: For calling conventions that destroy parameters in the callee,
6178   // should we consider performing destruction when the function returns
6179   // instead?
6180   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6181                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6182                                                        ScopeKind::Call, LV);
6183   if (!EvaluateInPlace(V, Info, LV, Arg))
6184     return false;
6185 
6186   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6187   // undefined behavior, so is non-constant.
6188   if (NonNull && V.isLValue() && V.isNullPointer()) {
6189     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6190     return false;
6191   }
6192 
6193   return true;
6194 }
6195 
6196 /// Evaluate the arguments to a function call.
EvaluateArgs(ArrayRef<const Expr * > Args,CallRef Call,EvalInfo & Info,const FunctionDecl * Callee,bool RightToLeft=false)6197 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6198                          EvalInfo &Info, const FunctionDecl *Callee,
6199                          bool RightToLeft = false) {
6200   bool Success = true;
6201   llvm::SmallBitVector ForbiddenNullArgs;
6202   if (Callee->hasAttr<NonNullAttr>()) {
6203     ForbiddenNullArgs.resize(Args.size());
6204     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6205       if (!Attr->args_size()) {
6206         ForbiddenNullArgs.set();
6207         break;
6208       } else
6209         for (auto Idx : Attr->args()) {
6210           unsigned ASTIdx = Idx.getASTIndex();
6211           if (ASTIdx >= Args.size())
6212             continue;
6213           ForbiddenNullArgs[ASTIdx] = true;
6214         }
6215     }
6216   }
6217   for (unsigned I = 0; I < Args.size(); I++) {
6218     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6219     const ParmVarDecl *PVD =
6220         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6221     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6222     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6223       // If we're checking for a potential constant expression, evaluate all
6224       // initializers even if some of them fail.
6225       if (!Info.noteFailure())
6226         return false;
6227       Success = false;
6228     }
6229   }
6230   return Success;
6231 }
6232 
6233 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6234 /// constructor or assignment operator.
handleTrivialCopy(EvalInfo & Info,const ParmVarDecl * Param,const Expr * E,APValue & Result,bool CopyObjectRepresentation)6235 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6236                               const Expr *E, APValue &Result,
6237                               bool CopyObjectRepresentation) {
6238   // Find the reference argument.
6239   CallStackFrame *Frame = Info.CurrentCall;
6240   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6241   if (!RefValue) {
6242     Info.FFDiag(E);
6243     return false;
6244   }
6245 
6246   // Copy out the contents of the RHS object.
6247   LValue RefLValue;
6248   RefLValue.setFrom(Info.Ctx, *RefValue);
6249   return handleLValueToRValueConversion(
6250       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6251       CopyObjectRepresentation);
6252 }
6253 
6254 /// Evaluate a function call.
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)6255 static bool HandleFunctionCall(SourceLocation CallLoc,
6256                                const FunctionDecl *Callee, const LValue *This,
6257                                const Expr *E, ArrayRef<const Expr *> Args,
6258                                CallRef Call, const Stmt *Body, EvalInfo &Info,
6259                                APValue &Result, const LValue *ResultSlot) {
6260   if (!Info.CheckCallLimit(CallLoc))
6261     return false;
6262 
6263   CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);
6264 
6265   // For a trivial copy or move assignment, perform an APValue copy. This is
6266   // essential for unions, where the operations performed by the assignment
6267   // operator cannot be represented as statements.
6268   //
6269   // Skip this for non-union classes with no fields; in that case, the defaulted
6270   // copy/move does not actually read the object.
6271   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6272   if (MD && MD->isDefaulted() &&
6273       (MD->getParent()->isUnion() ||
6274        (MD->isTrivial() &&
6275         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6276     assert(This &&
6277            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6278     APValue RHSValue;
6279     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6280                            MD->getParent()->isUnion()))
6281       return false;
6282     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6283                           RHSValue))
6284       return false;
6285     This->moveInto(Result);
6286     return true;
6287   } else if (MD && isLambdaCallOperator(MD)) {
6288     // We're in a lambda; determine the lambda capture field maps unless we're
6289     // just constexpr checking a lambda's call operator. constexpr checking is
6290     // done before the captures have been added to the closure object (unless
6291     // we're inferring constexpr-ness), so we don't have access to them in this
6292     // case. But since we don't need the captures to constexpr check, we can
6293     // just ignore them.
6294     if (!Info.checkingPotentialConstantExpression())
6295       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6296                                         Frame.LambdaThisCaptureField);
6297   }
6298 
6299   StmtResult Ret = {Result, ResultSlot};
6300   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6301   if (ESR == ESR_Succeeded) {
6302     if (Callee->getReturnType()->isVoidType())
6303       return true;
6304     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6305   }
6306   return ESR == ESR_Returned;
6307 }
6308 
6309 /// Evaluate a constructor call.
HandleConstructorCall(const Expr * E,const LValue & This,CallRef Call,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6310 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6311                                   CallRef Call,
6312                                   const CXXConstructorDecl *Definition,
6313                                   EvalInfo &Info, APValue &Result) {
6314   SourceLocation CallLoc = E->getExprLoc();
6315   if (!Info.CheckCallLimit(CallLoc))
6316     return false;
6317 
6318   const CXXRecordDecl *RD = Definition->getParent();
6319   if (RD->getNumVBases()) {
6320     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6321     return false;
6322   }
6323 
6324   EvalInfo::EvaluatingConstructorRAII EvalObj(
6325       Info,
6326       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6327       RD->getNumBases());
6328   CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6329 
6330   // FIXME: Creating an APValue just to hold a nonexistent return value is
6331   // wasteful.
6332   APValue RetVal;
6333   StmtResult Ret = {RetVal, nullptr};
6334 
6335   // If it's a delegating constructor, delegate.
6336   if (Definition->isDelegatingConstructor()) {
6337     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6338     if ((*I)->getInit()->isValueDependent()) {
6339       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6340         return false;
6341     } else {
6342       FullExpressionRAII InitScope(Info);
6343       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6344           !InitScope.destroy())
6345         return false;
6346     }
6347     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6348   }
6349 
6350   // For a trivial copy or move constructor, perform an APValue copy. This is
6351   // essential for unions (or classes with anonymous union members), where the
6352   // operations performed by the constructor cannot be represented by
6353   // ctor-initializers.
6354   //
6355   // Skip this for empty non-union classes; we should not perform an
6356   // lvalue-to-rvalue conversion on them because their copy constructor does not
6357   // actually read them.
6358   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6359       (Definition->getParent()->isUnion() ||
6360        (Definition->isTrivial() &&
6361         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6362     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6363                              Definition->getParent()->isUnion());
6364   }
6365 
6366   // Reserve space for the struct members.
6367   if (!Result.hasValue()) {
6368     if (!RD->isUnion())
6369       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6370                        std::distance(RD->field_begin(), RD->field_end()));
6371     else
6372       // A union starts with no active member.
6373       Result = APValue((const FieldDecl*)nullptr);
6374   }
6375 
6376   if (RD->isInvalidDecl()) return false;
6377   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6378 
6379   // A scope for temporaries lifetime-extended by reference members.
6380   BlockScopeRAII LifetimeExtendedScope(Info);
6381 
6382   bool Success = true;
6383   unsigned BasesSeen = 0;
6384 #ifndef NDEBUG
6385   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6386 #endif
6387   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6388   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6389     // We might be initializing the same field again if this is an indirect
6390     // field initialization.
6391     if (FieldIt == RD->field_end() ||
6392         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6393       assert(Indirect && "fields out of order?");
6394       return;
6395     }
6396 
6397     // Default-initialize any fields with no explicit initializer.
6398     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6399       assert(FieldIt != RD->field_end() && "missing field?");
6400       if (!FieldIt->isUnnamedBitfield())
6401         Success &= handleDefaultInitValue(
6402             FieldIt->getType(),
6403             Result.getStructField(FieldIt->getFieldIndex()));
6404     }
6405     ++FieldIt;
6406   };
6407   for (const auto *I : Definition->inits()) {
6408     LValue Subobject = This;
6409     LValue SubobjectParent = This;
6410     APValue *Value = &Result;
6411 
6412     // Determine the subobject to initialize.
6413     FieldDecl *FD = nullptr;
6414     if (I->isBaseInitializer()) {
6415       QualType BaseType(I->getBaseClass(), 0);
6416 #ifndef NDEBUG
6417       // Non-virtual base classes are initialized in the order in the class
6418       // definition. We have already checked for virtual base classes.
6419       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6420       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6421              "base class initializers not in expected order");
6422       ++BaseIt;
6423 #endif
6424       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6425                                   BaseType->getAsCXXRecordDecl(), &Layout))
6426         return false;
6427       Value = &Result.getStructBase(BasesSeen++);
6428     } else if ((FD = I->getMember())) {
6429       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6430         return false;
6431       if (RD->isUnion()) {
6432         Result = APValue(FD);
6433         Value = &Result.getUnionValue();
6434       } else {
6435         SkipToField(FD, false);
6436         Value = &Result.getStructField(FD->getFieldIndex());
6437       }
6438     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6439       // Walk the indirect field decl's chain to find the object to initialize,
6440       // and make sure we've initialized every step along it.
6441       auto IndirectFieldChain = IFD->chain();
6442       for (auto *C : IndirectFieldChain) {
6443         FD = cast<FieldDecl>(C);
6444         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6445         // Switch the union field if it differs. This happens if we had
6446         // preceding zero-initialization, and we're now initializing a union
6447         // subobject other than the first.
6448         // FIXME: In this case, the values of the other subobjects are
6449         // specified, since zero-initialization sets all padding bits to zero.
6450         if (!Value->hasValue() ||
6451             (Value->isUnion() && Value->getUnionField() != FD)) {
6452           if (CD->isUnion())
6453             *Value = APValue(FD);
6454           else
6455             // FIXME: This immediately starts the lifetime of all members of
6456             // an anonymous struct. It would be preferable to strictly start
6457             // member lifetime in initialization order.
6458             Success &=
6459                 handleDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6460         }
6461         // Store Subobject as its parent before updating it for the last element
6462         // in the chain.
6463         if (C == IndirectFieldChain.back())
6464           SubobjectParent = Subobject;
6465         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6466           return false;
6467         if (CD->isUnion())
6468           Value = &Value->getUnionValue();
6469         else {
6470           if (C == IndirectFieldChain.front() && !RD->isUnion())
6471             SkipToField(FD, true);
6472           Value = &Value->getStructField(FD->getFieldIndex());
6473         }
6474       }
6475     } else {
6476       llvm_unreachable("unknown base initializer kind");
6477     }
6478 
6479     // Need to override This for implicit field initializers as in this case
6480     // This refers to innermost anonymous struct/union containing initializer,
6481     // not to currently constructed class.
6482     const Expr *Init = I->getInit();
6483     if (Init->isValueDependent()) {
6484       if (!EvaluateDependentExpr(Init, Info))
6485         return false;
6486     } else {
6487       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6488                                     isa<CXXDefaultInitExpr>(Init));
6489       FullExpressionRAII InitScope(Info);
6490       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6491           (FD && FD->isBitField() &&
6492            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6493         // If we're checking for a potential constant expression, evaluate all
6494         // initializers even if some of them fail.
6495         if (!Info.noteFailure())
6496           return false;
6497         Success = false;
6498       }
6499     }
6500 
6501     // This is the point at which the dynamic type of the object becomes this
6502     // class type.
6503     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6504       EvalObj.finishedConstructingBases();
6505   }
6506 
6507   // Default-initialize any remaining fields.
6508   if (!RD->isUnion()) {
6509     for (; FieldIt != RD->field_end(); ++FieldIt) {
6510       if (!FieldIt->isUnnamedBitfield())
6511         Success &= handleDefaultInitValue(
6512             FieldIt->getType(),
6513             Result.getStructField(FieldIt->getFieldIndex()));
6514     }
6515   }
6516 
6517   EvalObj.finishedConstructingFields();
6518 
6519   return Success &&
6520          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6521          LifetimeExtendedScope.destroy();
6522 }
6523 
HandleConstructorCall(const Expr * E,const LValue & This,ArrayRef<const Expr * > Args,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6524 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6525                                   ArrayRef<const Expr*> Args,
6526                                   const CXXConstructorDecl *Definition,
6527                                   EvalInfo &Info, APValue &Result) {
6528   CallScopeRAII CallScope(Info);
6529   CallRef Call = Info.CurrentCall->createCall(Definition);
6530   if (!EvaluateArgs(Args, Call, Info, Definition))
6531     return false;
6532 
6533   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6534          CallScope.destroy();
6535 }
6536 
HandleDestructionImpl(EvalInfo & Info,SourceRange CallRange,const LValue & This,APValue & Value,QualType T)6537 static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6538                                   const LValue &This, APValue &Value,
6539                                   QualType T) {
6540   // Objects can only be destroyed while they're within their lifetimes.
6541   // FIXME: We have no representation for whether an object of type nullptr_t
6542   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6543   // as indeterminate instead?
6544   if (Value.isAbsent() && !T->isNullPtrType()) {
6545     APValue Printable;
6546     This.moveInto(Printable);
6547     Info.FFDiag(CallRange.getBegin(),
6548                 diag::note_constexpr_destroy_out_of_lifetime)
6549         << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6550     return false;
6551   }
6552 
6553   // Invent an expression for location purposes.
6554   // FIXME: We shouldn't need to do this.
6555   OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
6556 
6557   // For arrays, destroy elements right-to-left.
6558   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6559     uint64_t Size = CAT->getSize().getZExtValue();
6560     QualType ElemT = CAT->getElementType();
6561 
6562     if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
6563       return false;
6564 
6565     LValue ElemLV = This;
6566     ElemLV.addArray(Info, &LocE, CAT);
6567     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6568       return false;
6569 
6570     // Ensure that we have actual array elements available to destroy; the
6571     // destructors might mutate the value, so we can't run them on the array
6572     // filler.
6573     if (Size && Size > Value.getArrayInitializedElts())
6574       expandArray(Value, Value.getArraySize() - 1);
6575 
6576     for (; Size != 0; --Size) {
6577       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6578       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6579           !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
6580         return false;
6581     }
6582 
6583     // End the lifetime of this array now.
6584     Value = APValue();
6585     return true;
6586   }
6587 
6588   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6589   if (!RD) {
6590     if (T.isDestructedType()) {
6591       Info.FFDiag(CallRange.getBegin(),
6592                   diag::note_constexpr_unsupported_destruction)
6593           << T;
6594       return false;
6595     }
6596 
6597     Value = APValue();
6598     return true;
6599   }
6600 
6601   if (RD->getNumVBases()) {
6602     Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
6603     return false;
6604   }
6605 
6606   const CXXDestructorDecl *DD = RD->getDestructor();
6607   if (!DD && !RD->hasTrivialDestructor()) {
6608     Info.FFDiag(CallRange.getBegin());
6609     return false;
6610   }
6611 
6612   if (!DD || DD->isTrivial() ||
6613       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6614     // A trivial destructor just ends the lifetime of the object. Check for
6615     // this case before checking for a body, because we might not bother
6616     // building a body for a trivial destructor. Note that it doesn't matter
6617     // whether the destructor is constexpr in this case; all trivial
6618     // destructors are constexpr.
6619     //
6620     // If an anonymous union would be destroyed, some enclosing destructor must
6621     // have been explicitly defined, and the anonymous union destruction should
6622     // have no effect.
6623     Value = APValue();
6624     return true;
6625   }
6626 
6627   if (!Info.CheckCallLimit(CallRange.getBegin()))
6628     return false;
6629 
6630   const FunctionDecl *Definition = nullptr;
6631   const Stmt *Body = DD->getBody(Definition);
6632 
6633   if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
6634     return false;
6635 
6636   CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
6637                        CallRef());
6638 
6639   // We're now in the period of destruction of this object.
6640   unsigned BasesLeft = RD->getNumBases();
6641   EvalInfo::EvaluatingDestructorRAII EvalObj(
6642       Info,
6643       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6644   if (!EvalObj.DidInsert) {
6645     // C++2a [class.dtor]p19:
6646     //   the behavior is undefined if the destructor is invoked for an object
6647     //   whose lifetime has ended
6648     // (Note that formally the lifetime ends when the period of destruction
6649     // begins, even though certain uses of the object remain valid until the
6650     // period of destruction ends.)
6651     Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
6652     return false;
6653   }
6654 
6655   // FIXME: Creating an APValue just to hold a nonexistent return value is
6656   // wasteful.
6657   APValue RetVal;
6658   StmtResult Ret = {RetVal, nullptr};
6659   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6660     return false;
6661 
6662   // A union destructor does not implicitly destroy its members.
6663   if (RD->isUnion())
6664     return true;
6665 
6666   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6667 
6668   // We don't have a good way to iterate fields in reverse, so collect all the
6669   // fields first and then walk them backwards.
6670   SmallVector<FieldDecl*, 16> Fields(RD->fields());
6671   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6672     if (FD->isUnnamedBitfield())
6673       continue;
6674 
6675     LValue Subobject = This;
6676     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6677       return false;
6678 
6679     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6680     if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6681                                FD->getType()))
6682       return false;
6683   }
6684 
6685   if (BasesLeft != 0)
6686     EvalObj.startedDestroyingBases();
6687 
6688   // Destroy base classes in reverse order.
6689   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6690     --BasesLeft;
6691 
6692     QualType BaseType = Base.getType();
6693     LValue Subobject = This;
6694     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6695                                 BaseType->getAsCXXRecordDecl(), &Layout))
6696       return false;
6697 
6698     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6699     if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6700                                BaseType))
6701       return false;
6702   }
6703   assert(BasesLeft == 0 && "NumBases was wrong?");
6704 
6705   // The period of destruction ends now. The object is gone.
6706   Value = APValue();
6707   return true;
6708 }
6709 
6710 namespace {
6711 struct DestroyObjectHandler {
6712   EvalInfo &Info;
6713   const Expr *E;
6714   const LValue &This;
6715   const AccessKinds AccessKind;
6716 
6717   typedef bool result_type;
failed__anonbf0ddd821511::DestroyObjectHandler6718   bool failed() { return false; }
found__anonbf0ddd821511::DestroyObjectHandler6719   bool found(APValue &Subobj, QualType SubobjType) {
6720     return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
6721                                  SubobjType);
6722   }
found__anonbf0ddd821511::DestroyObjectHandler6723   bool found(APSInt &Value, QualType SubobjType) {
6724     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6725     return false;
6726   }
found__anonbf0ddd821511::DestroyObjectHandler6727   bool found(APFloat &Value, QualType SubobjType) {
6728     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6729     return false;
6730   }
6731 };
6732 }
6733 
6734 /// Perform a destructor or pseudo-destructor call on the given object, which
6735 /// might in general not be a complete object.
HandleDestruction(EvalInfo & Info,const Expr * E,const LValue & This,QualType ThisType)6736 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6737                               const LValue &This, QualType ThisType) {
6738   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6739   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6740   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6741 }
6742 
6743 /// Destroy and end the lifetime of the given complete object.
HandleDestruction(EvalInfo & Info,SourceLocation Loc,APValue::LValueBase LVBase,APValue & Value,QualType T)6744 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6745                               APValue::LValueBase LVBase, APValue &Value,
6746                               QualType T) {
6747   // If we've had an unmodeled side-effect, we can't rely on mutable state
6748   // (such as the object we're about to destroy) being correct.
6749   if (Info.EvalStatus.HasSideEffects)
6750     return false;
6751 
6752   LValue LV;
6753   LV.set({LVBase});
6754   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6755 }
6756 
6757 /// Perform a call to 'operator new' or to `__builtin_operator_new'.
HandleOperatorNewCall(EvalInfo & Info,const CallExpr * E,LValue & Result)6758 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6759                                   LValue &Result) {
6760   if (Info.checkingPotentialConstantExpression() ||
6761       Info.SpeculativeEvaluationDepth)
6762     return false;
6763 
6764   // This is permitted only within a call to std::allocator<T>::allocate.
6765   auto Caller = Info.getStdAllocatorCaller("allocate");
6766   if (!Caller) {
6767     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6768                                      ? diag::note_constexpr_new_untyped
6769                                      : diag::note_constexpr_new);
6770     return false;
6771   }
6772 
6773   QualType ElemType = Caller.ElemType;
6774   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6775     Info.FFDiag(E->getExprLoc(),
6776                 diag::note_constexpr_new_not_complete_object_type)
6777         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6778     return false;
6779   }
6780 
6781   APSInt ByteSize;
6782   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6783     return false;
6784   bool IsNothrow = false;
6785   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6786     EvaluateIgnoredValue(Info, E->getArg(I));
6787     IsNothrow |= E->getType()->isNothrowT();
6788   }
6789 
6790   CharUnits ElemSize;
6791   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6792     return false;
6793   APInt Size, Remainder;
6794   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6795   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6796   if (Remainder != 0) {
6797     // This likely indicates a bug in the implementation of 'std::allocator'.
6798     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6799         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6800     return false;
6801   }
6802 
6803   if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
6804                            Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
6805     if (IsNothrow) {
6806       Result.setNull(Info.Ctx, E->getType());
6807       return true;
6808     }
6809     return false;
6810   }
6811 
6812   QualType AllocType = Info.Ctx.getConstantArrayType(
6813       ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
6814   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6815   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6816   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6817   return true;
6818 }
6819 
hasVirtualDestructor(QualType T)6820 static bool hasVirtualDestructor(QualType T) {
6821   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6822     if (CXXDestructorDecl *DD = RD->getDestructor())
6823       return DD->isVirtual();
6824   return false;
6825 }
6826 
getVirtualOperatorDelete(QualType T)6827 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6828   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6829     if (CXXDestructorDecl *DD = RD->getDestructor())
6830       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6831   return nullptr;
6832 }
6833 
6834 /// Check that the given object is a suitable pointer to a heap allocation that
6835 /// still exists and is of the right kind for the purpose of a deletion.
6836 ///
6837 /// On success, returns the heap allocation to deallocate. On failure, produces
6838 /// a diagnostic and returns std::nullopt.
CheckDeleteKind(EvalInfo & Info,const Expr * E,const LValue & Pointer,DynAlloc::Kind DeallocKind)6839 static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6840                                                  const LValue &Pointer,
6841                                                  DynAlloc::Kind DeallocKind) {
6842   auto PointerAsString = [&] {
6843     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6844   };
6845 
6846   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6847   if (!DA) {
6848     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6849         << PointerAsString();
6850     if (Pointer.Base)
6851       NoteLValueLocation(Info, Pointer.Base);
6852     return std::nullopt;
6853   }
6854 
6855   std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6856   if (!Alloc) {
6857     Info.FFDiag(E, diag::note_constexpr_double_delete);
6858     return std::nullopt;
6859   }
6860 
6861   if (DeallocKind != (*Alloc)->getKind()) {
6862     QualType AllocType = Pointer.Base.getDynamicAllocType();
6863     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6864         << DeallocKind << (*Alloc)->getKind() << AllocType;
6865     NoteLValueLocation(Info, Pointer.Base);
6866     return std::nullopt;
6867   }
6868 
6869   bool Subobject = false;
6870   if (DeallocKind == DynAlloc::New) {
6871     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6872                 Pointer.Designator.isOnePastTheEnd();
6873   } else {
6874     Subobject = Pointer.Designator.Entries.size() != 1 ||
6875                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6876   }
6877   if (Subobject) {
6878     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6879         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6880     return std::nullopt;
6881   }
6882 
6883   return Alloc;
6884 }
6885 
6886 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
HandleOperatorDeleteCall(EvalInfo & Info,const CallExpr * E)6887 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6888   if (Info.checkingPotentialConstantExpression() ||
6889       Info.SpeculativeEvaluationDepth)
6890     return false;
6891 
6892   // This is permitted only within a call to std::allocator<T>::deallocate.
6893   if (!Info.getStdAllocatorCaller("deallocate")) {
6894     Info.FFDiag(E->getExprLoc());
6895     return true;
6896   }
6897 
6898   LValue Pointer;
6899   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6900     return false;
6901   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6902     EvaluateIgnoredValue(Info, E->getArg(I));
6903 
6904   if (Pointer.Designator.Invalid)
6905     return false;
6906 
6907   // Deleting a null pointer would have no effect, but it's not permitted by
6908   // std::allocator<T>::deallocate's contract.
6909   if (Pointer.isNullPointer()) {
6910     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6911     return true;
6912   }
6913 
6914   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6915     return false;
6916 
6917   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6918   return true;
6919 }
6920 
6921 //===----------------------------------------------------------------------===//
6922 // Generic Evaluation
6923 //===----------------------------------------------------------------------===//
6924 namespace {
6925 
6926 class BitCastBuffer {
6927   // FIXME: We're going to need bit-level granularity when we support
6928   // bit-fields.
6929   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6930   // we don't support a host or target where that is the case. Still, we should
6931   // use a more generic type in case we ever do.
6932   SmallVector<std::optional<unsigned char>, 32> Bytes;
6933 
6934   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6935                 "Need at least 8 bit unsigned char");
6936 
6937   bool TargetIsLittleEndian;
6938 
6939 public:
BitCastBuffer(CharUnits Width,bool TargetIsLittleEndian)6940   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6941       : Bytes(Width.getQuantity()),
6942         TargetIsLittleEndian(TargetIsLittleEndian) {}
6943 
readObject(CharUnits Offset,CharUnits Width,SmallVectorImpl<unsigned char> & Output) const6944   [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
6945                                 SmallVectorImpl<unsigned char> &Output) const {
6946     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6947       // If a byte of an integer is uninitialized, then the whole integer is
6948       // uninitialized.
6949       if (!Bytes[I.getQuantity()])
6950         return false;
6951       Output.push_back(*Bytes[I.getQuantity()]);
6952     }
6953     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6954       std::reverse(Output.begin(), Output.end());
6955     return true;
6956   }
6957 
writeObject(CharUnits Offset,SmallVectorImpl<unsigned char> & Input)6958   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6959     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6960       std::reverse(Input.begin(), Input.end());
6961 
6962     size_t Index = 0;
6963     for (unsigned char Byte : Input) {
6964       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6965       Bytes[Offset.getQuantity() + Index] = Byte;
6966       ++Index;
6967     }
6968   }
6969 
size()6970   size_t size() { return Bytes.size(); }
6971 };
6972 
6973 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6974 /// target would represent the value at runtime.
6975 class APValueToBufferConverter {
6976   EvalInfo &Info;
6977   BitCastBuffer Buffer;
6978   const CastExpr *BCE;
6979 
APValueToBufferConverter(EvalInfo & Info,CharUnits ObjectWidth,const CastExpr * BCE)6980   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6981                            const CastExpr *BCE)
6982       : Info(Info),
6983         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6984         BCE(BCE) {}
6985 
visit(const APValue & Val,QualType Ty)6986   bool visit(const APValue &Val, QualType Ty) {
6987     return visit(Val, Ty, CharUnits::fromQuantity(0));
6988   }
6989 
6990   // Write out Val with type Ty into Buffer starting at Offset.
visit(const APValue & Val,QualType Ty,CharUnits Offset)6991   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6992     assert((size_t)Offset.getQuantity() <= Buffer.size());
6993 
6994     // As a special case, nullptr_t has an indeterminate value.
6995     if (Ty->isNullPtrType())
6996       return true;
6997 
6998     // Dig through Src to find the byte at SrcOffset.
6999     switch (Val.getKind()) {
7000     case APValue::Indeterminate:
7001     case APValue::None:
7002       return true;
7003 
7004     case APValue::Int:
7005       return visitInt(Val.getInt(), Ty, Offset);
7006     case APValue::Float:
7007       return visitFloat(Val.getFloat(), Ty, Offset);
7008     case APValue::Array:
7009       return visitArray(Val, Ty, Offset);
7010     case APValue::Struct:
7011       return visitRecord(Val, Ty, Offset);
7012     case APValue::Vector:
7013       return visitVector(Val, Ty, Offset);
7014 
7015     case APValue::ComplexInt:
7016     case APValue::ComplexFloat:
7017     case APValue::FixedPoint:
7018       // FIXME: We should support these.
7019 
7020     case APValue::Union:
7021     case APValue::MemberPointer:
7022     case APValue::AddrLabelDiff: {
7023       Info.FFDiag(BCE->getBeginLoc(),
7024                   diag::note_constexpr_bit_cast_unsupported_type)
7025           << Ty;
7026       return false;
7027     }
7028 
7029     case APValue::LValue:
7030       llvm_unreachable("LValue subobject in bit_cast?");
7031     }
7032     llvm_unreachable("Unhandled APValue::ValueKind");
7033   }
7034 
visitRecord(const APValue & Val,QualType Ty,CharUnits Offset)7035   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7036     const RecordDecl *RD = Ty->getAsRecordDecl();
7037     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7038 
7039     // Visit the base classes.
7040     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7041       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7042         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7043         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7044 
7045         if (!visitRecord(Val.getStructBase(I), BS.getType(),
7046                          Layout.getBaseClassOffset(BaseDecl) + Offset))
7047           return false;
7048       }
7049     }
7050 
7051     // Visit the fields.
7052     unsigned FieldIdx = 0;
7053     for (FieldDecl *FD : RD->fields()) {
7054       if (FD->isBitField()) {
7055         Info.FFDiag(BCE->getBeginLoc(),
7056                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7057         return false;
7058       }
7059 
7060       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7061 
7062       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7063              "only bit-fields can have sub-char alignment");
7064       CharUnits FieldOffset =
7065           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7066       QualType FieldTy = FD->getType();
7067       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7068         return false;
7069       ++FieldIdx;
7070     }
7071 
7072     return true;
7073   }
7074 
visitArray(const APValue & Val,QualType Ty,CharUnits Offset)7075   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7076     const auto *CAT =
7077         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7078     if (!CAT)
7079       return false;
7080 
7081     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7082     unsigned NumInitializedElts = Val.getArrayInitializedElts();
7083     unsigned ArraySize = Val.getArraySize();
7084     // First, initialize the initialized elements.
7085     for (unsigned I = 0; I != NumInitializedElts; ++I) {
7086       const APValue &SubObj = Val.getArrayInitializedElt(I);
7087       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7088         return false;
7089     }
7090 
7091     // Next, initialize the rest of the array using the filler.
7092     if (Val.hasArrayFiller()) {
7093       const APValue &Filler = Val.getArrayFiller();
7094       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7095         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7096           return false;
7097       }
7098     }
7099 
7100     return true;
7101   }
7102 
visitVector(const APValue & Val,QualType Ty,CharUnits Offset)7103   bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7104     const VectorType *VTy = Ty->castAs<VectorType>();
7105     QualType EltTy = VTy->getElementType();
7106     unsigned NElts = VTy->getNumElements();
7107     unsigned EltSize =
7108         VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7109 
7110     if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7111       // The vector's size in bits is not a multiple of the target's byte size,
7112       // so its layout is unspecified. For now, we'll simply treat these cases
7113       // as unsupported (this should only be possible with OpenCL bool vectors
7114       // whose element count isn't a multiple of the byte size).
7115       Info.FFDiag(BCE->getBeginLoc(),
7116                   diag::note_constexpr_bit_cast_invalid_vector)
7117           << Ty.getCanonicalType() << EltSize << NElts
7118           << Info.Ctx.getCharWidth();
7119       return false;
7120     }
7121 
7122     if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7123                                            &APFloat::x87DoubleExtended()) {
7124       // The layout for x86_fp80 vectors seems to be handled very inconsistently
7125       // by both clang and LLVM, so for now we won't allow bit_casts involving
7126       // it in a constexpr context.
7127       Info.FFDiag(BCE->getBeginLoc(),
7128                   diag::note_constexpr_bit_cast_unsupported_type)
7129           << EltTy;
7130       return false;
7131     }
7132 
7133     if (VTy->isExtVectorBoolType()) {
7134       // Special handling for OpenCL bool vectors:
7135       // Since these vectors are stored as packed bits, but we can't write
7136       // individual bits to the BitCastBuffer, we'll buffer all of the elements
7137       // together into an appropriately sized APInt and write them all out at
7138       // once. Because we don't accept vectors where NElts * EltSize isn't a
7139       // multiple of the char size, there will be no padding space, so we don't
7140       // have to worry about writing data which should have been left
7141       // uninitialized.
7142       bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7143 
7144       llvm::APInt Res = llvm::APInt::getZero(NElts);
7145       for (unsigned I = 0; I < NElts; ++I) {
7146         const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7147         assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7148                "bool vector element must be 1-bit unsigned integer!");
7149 
7150         Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7151       }
7152 
7153       SmallVector<uint8_t, 8> Bytes(NElts / 8);
7154       llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7155       Buffer.writeObject(Offset, Bytes);
7156     } else {
7157       // Iterate over each of the elements and write them out to the buffer at
7158       // the appropriate offset.
7159       CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7160       for (unsigned I = 0; I < NElts; ++I) {
7161         if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7162           return false;
7163       }
7164     }
7165 
7166     return true;
7167   }
7168 
visitInt(const APSInt & Val,QualType Ty,CharUnits Offset)7169   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7170     APSInt AdjustedVal = Val;
7171     unsigned Width = AdjustedVal.getBitWidth();
7172     if (Ty->isBooleanType()) {
7173       Width = Info.Ctx.getTypeSize(Ty);
7174       AdjustedVal = AdjustedVal.extend(Width);
7175     }
7176 
7177     SmallVector<uint8_t, 8> Bytes(Width / 8);
7178     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7179     Buffer.writeObject(Offset, Bytes);
7180     return true;
7181   }
7182 
visitFloat(const APFloat & Val,QualType Ty,CharUnits Offset)7183   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7184     APSInt AsInt(Val.bitcastToAPInt());
7185     return visitInt(AsInt, Ty, Offset);
7186   }
7187 
7188 public:
7189   static std::optional<BitCastBuffer>
convert(EvalInfo & Info,const APValue & Src,const CastExpr * BCE)7190   convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7191     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7192     APValueToBufferConverter Converter(Info, DstSize, BCE);
7193     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7194       return std::nullopt;
7195     return Converter.Buffer;
7196   }
7197 };
7198 
7199 /// Write an BitCastBuffer into an APValue.
7200 class BufferToAPValueConverter {
7201   EvalInfo &Info;
7202   const BitCastBuffer &Buffer;
7203   const CastExpr *BCE;
7204 
BufferToAPValueConverter(EvalInfo & Info,const BitCastBuffer & Buffer,const CastExpr * BCE)7205   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7206                            const CastExpr *BCE)
7207       : Info(Info), Buffer(Buffer), BCE(BCE) {}
7208 
7209   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7210   // with an invalid type, so anything left is a deficiency on our part (FIXME).
7211   // Ideally this will be unreachable.
unsupportedType(QualType Ty)7212   std::nullopt_t unsupportedType(QualType Ty) {
7213     Info.FFDiag(BCE->getBeginLoc(),
7214                 diag::note_constexpr_bit_cast_unsupported_type)
7215         << Ty;
7216     return std::nullopt;
7217   }
7218 
unrepresentableValue(QualType Ty,const APSInt & Val)7219   std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7220     Info.FFDiag(BCE->getBeginLoc(),
7221                 diag::note_constexpr_bit_cast_unrepresentable_value)
7222         << Ty << toString(Val, /*Radix=*/10);
7223     return std::nullopt;
7224   }
7225 
visit(const BuiltinType * T,CharUnits Offset,const EnumType * EnumSugar=nullptr)7226   std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7227                                const EnumType *EnumSugar = nullptr) {
7228     if (T->isNullPtrType()) {
7229       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7230       return APValue((Expr *)nullptr,
7231                      /*Offset=*/CharUnits::fromQuantity(NullValue),
7232                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7233     }
7234 
7235     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7236 
7237     // Work around floating point types that contain unused padding bytes. This
7238     // is really just `long double` on x86, which is the only fundamental type
7239     // with padding bytes.
7240     if (T->isRealFloatingType()) {
7241       const llvm::fltSemantics &Semantics =
7242           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7243       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7244       assert(NumBits % 8 == 0);
7245       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7246       if (NumBytes != SizeOf)
7247         SizeOf = NumBytes;
7248     }
7249 
7250     SmallVector<uint8_t, 8> Bytes;
7251     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7252       // If this is std::byte or unsigned char, then its okay to store an
7253       // indeterminate value.
7254       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7255       bool IsUChar =
7256           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7257                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7258       if (!IsStdByte && !IsUChar) {
7259         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7260         Info.FFDiag(BCE->getExprLoc(),
7261                     diag::note_constexpr_bit_cast_indet_dest)
7262             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7263         return std::nullopt;
7264       }
7265 
7266       return APValue::IndeterminateValue();
7267     }
7268 
7269     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7270     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7271 
7272     if (T->isIntegralOrEnumerationType()) {
7273       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7274 
7275       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7276       if (IntWidth != Val.getBitWidth()) {
7277         APSInt Truncated = Val.trunc(IntWidth);
7278         if (Truncated.extend(Val.getBitWidth()) != Val)
7279           return unrepresentableValue(QualType(T, 0), Val);
7280         Val = Truncated;
7281       }
7282 
7283       return APValue(Val);
7284     }
7285 
7286     if (T->isRealFloatingType()) {
7287       const llvm::fltSemantics &Semantics =
7288           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7289       return APValue(APFloat(Semantics, Val));
7290     }
7291 
7292     return unsupportedType(QualType(T, 0));
7293   }
7294 
visit(const RecordType * RTy,CharUnits Offset)7295   std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7296     const RecordDecl *RD = RTy->getAsRecordDecl();
7297     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7298 
7299     unsigned NumBases = 0;
7300     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7301       NumBases = CXXRD->getNumBases();
7302 
7303     APValue ResultVal(APValue::UninitStruct(), NumBases,
7304                       std::distance(RD->field_begin(), RD->field_end()));
7305 
7306     // Visit the base classes.
7307     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7308       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7309         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7310         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7311         if (BaseDecl->isEmpty() ||
7312             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7313           continue;
7314 
7315         std::optional<APValue> SubObj = visitType(
7316             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7317         if (!SubObj)
7318           return std::nullopt;
7319         ResultVal.getStructBase(I) = *SubObj;
7320       }
7321     }
7322 
7323     // Visit the fields.
7324     unsigned FieldIdx = 0;
7325     for (FieldDecl *FD : RD->fields()) {
7326       // FIXME: We don't currently support bit-fields. A lot of the logic for
7327       // this is in CodeGen, so we need to factor it around.
7328       if (FD->isBitField()) {
7329         Info.FFDiag(BCE->getBeginLoc(),
7330                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7331         return std::nullopt;
7332       }
7333 
7334       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7335       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7336 
7337       CharUnits FieldOffset =
7338           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7339           Offset;
7340       QualType FieldTy = FD->getType();
7341       std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7342       if (!SubObj)
7343         return std::nullopt;
7344       ResultVal.getStructField(FieldIdx) = *SubObj;
7345       ++FieldIdx;
7346     }
7347 
7348     return ResultVal;
7349   }
7350 
visit(const EnumType * Ty,CharUnits Offset)7351   std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7352     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7353     assert(!RepresentationType.isNull() &&
7354            "enum forward decl should be caught by Sema");
7355     const auto *AsBuiltin =
7356         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7357     // Recurse into the underlying type. Treat std::byte transparently as
7358     // unsigned char.
7359     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7360   }
7361 
visit(const ConstantArrayType * Ty,CharUnits Offset)7362   std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7363     size_t Size = Ty->getSize().getLimitedValue();
7364     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7365 
7366     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7367     for (size_t I = 0; I != Size; ++I) {
7368       std::optional<APValue> ElementValue =
7369           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7370       if (!ElementValue)
7371         return std::nullopt;
7372       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7373     }
7374 
7375     return ArrayValue;
7376   }
7377 
visit(const VectorType * VTy,CharUnits Offset)7378   std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7379     QualType EltTy = VTy->getElementType();
7380     unsigned NElts = VTy->getNumElements();
7381     unsigned EltSize =
7382         VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7383 
7384     if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7385       // The vector's size in bits is not a multiple of the target's byte size,
7386       // so its layout is unspecified. For now, we'll simply treat these cases
7387       // as unsupported (this should only be possible with OpenCL bool vectors
7388       // whose element count isn't a multiple of the byte size).
7389       Info.FFDiag(BCE->getBeginLoc(),
7390                   diag::note_constexpr_bit_cast_invalid_vector)
7391           << QualType(VTy, 0) << EltSize << NElts << Info.Ctx.getCharWidth();
7392       return std::nullopt;
7393     }
7394 
7395     if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7396                                            &APFloat::x87DoubleExtended()) {
7397       // The layout for x86_fp80 vectors seems to be handled very inconsistently
7398       // by both clang and LLVM, so for now we won't allow bit_casts involving
7399       // it in a constexpr context.
7400       Info.FFDiag(BCE->getBeginLoc(),
7401                   diag::note_constexpr_bit_cast_unsupported_type)
7402           << EltTy;
7403       return std::nullopt;
7404     }
7405 
7406     SmallVector<APValue, 4> Elts;
7407     Elts.reserve(NElts);
7408     if (VTy->isExtVectorBoolType()) {
7409       // Special handling for OpenCL bool vectors:
7410       // Since these vectors are stored as packed bits, but we can't read
7411       // individual bits from the BitCastBuffer, we'll buffer all of the
7412       // elements together into an appropriately sized APInt and write them all
7413       // out at once. Because we don't accept vectors where NElts * EltSize
7414       // isn't a multiple of the char size, there will be no padding space, so
7415       // we don't have to worry about reading any padding data which didn't
7416       // actually need to be accessed.
7417       bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7418 
7419       SmallVector<uint8_t, 8> Bytes;
7420       Bytes.reserve(NElts / 8);
7421       if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7422         return std::nullopt;
7423 
7424       APSInt SValInt(NElts, true);
7425       llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7426 
7427       for (unsigned I = 0; I < NElts; ++I) {
7428         llvm::APInt Elt =
7429             SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7430         Elts.emplace_back(
7431             APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7432       }
7433     } else {
7434       // Iterate over each of the elements and read them from the buffer at
7435       // the appropriate offset.
7436       CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7437       for (unsigned I = 0; I < NElts; ++I) {
7438         std::optional<APValue> EltValue =
7439             visitType(EltTy, Offset + I * EltSizeChars);
7440         if (!EltValue)
7441           return std::nullopt;
7442         Elts.push_back(std::move(*EltValue));
7443       }
7444     }
7445 
7446     return APValue(Elts.data(), Elts.size());
7447   }
7448 
visit(const Type * Ty,CharUnits Offset)7449   std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7450     return unsupportedType(QualType(Ty, 0));
7451   }
7452 
visitType(QualType Ty,CharUnits Offset)7453   std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7454     QualType Can = Ty.getCanonicalType();
7455 
7456     switch (Can->getTypeClass()) {
7457 #define TYPE(Class, Base)                                                      \
7458   case Type::Class:                                                            \
7459     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7460 #define ABSTRACT_TYPE(Class, Base)
7461 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7462   case Type::Class:                                                            \
7463     llvm_unreachable("non-canonical type should be impossible!");
7464 #define DEPENDENT_TYPE(Class, Base)                                            \
7465   case Type::Class:                                                            \
7466     llvm_unreachable(                                                          \
7467         "dependent types aren't supported in the constant evaluator!");
7468 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7469   case Type::Class:                                                            \
7470     llvm_unreachable("either dependent or not canonical!");
7471 #include "clang/AST/TypeNodes.inc"
7472     }
7473     llvm_unreachable("Unhandled Type::TypeClass");
7474   }
7475 
7476 public:
7477   // Pull out a full value of type DstType.
convert(EvalInfo & Info,BitCastBuffer & Buffer,const CastExpr * BCE)7478   static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7479                                         const CastExpr *BCE) {
7480     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7481     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7482   }
7483 };
7484 
checkBitCastConstexprEligibilityType(SourceLocation Loc,QualType Ty,EvalInfo * Info,const ASTContext & Ctx,bool CheckingDest)7485 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7486                                                  QualType Ty, EvalInfo *Info,
7487                                                  const ASTContext &Ctx,
7488                                                  bool CheckingDest) {
7489   Ty = Ty.getCanonicalType();
7490 
7491   auto diag = [&](int Reason) {
7492     if (Info)
7493       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7494           << CheckingDest << (Reason == 4) << Reason;
7495     return false;
7496   };
7497   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7498     if (Info)
7499       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7500           << NoteTy << Construct << Ty;
7501     return false;
7502   };
7503 
7504   if (Ty->isUnionType())
7505     return diag(0);
7506   if (Ty->isPointerType())
7507     return diag(1);
7508   if (Ty->isMemberPointerType())
7509     return diag(2);
7510   if (Ty.isVolatileQualified())
7511     return diag(3);
7512 
7513   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7514     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7515       for (CXXBaseSpecifier &BS : CXXRD->bases())
7516         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7517                                                   CheckingDest))
7518           return note(1, BS.getType(), BS.getBeginLoc());
7519     }
7520     for (FieldDecl *FD : Record->fields()) {
7521       if (FD->getType()->isReferenceType())
7522         return diag(4);
7523       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7524                                                 CheckingDest))
7525         return note(0, FD->getType(), FD->getBeginLoc());
7526     }
7527   }
7528 
7529   if (Ty->isArrayType() &&
7530       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7531                                             Info, Ctx, CheckingDest))
7532     return false;
7533 
7534   return true;
7535 }
7536 
checkBitCastConstexprEligibility(EvalInfo * Info,const ASTContext & Ctx,const CastExpr * BCE)7537 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7538                                              const ASTContext &Ctx,
7539                                              const CastExpr *BCE) {
7540   bool DestOK = checkBitCastConstexprEligibilityType(
7541       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7542   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7543                                 BCE->getBeginLoc(),
7544                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7545   return SourceOK;
7546 }
7547 
handleRValueToRValueBitCast(EvalInfo & Info,APValue & DestValue,const APValue & SourceRValue,const CastExpr * BCE)7548 static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7549                                         const APValue &SourceRValue,
7550                                         const CastExpr *BCE) {
7551   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7552          "no host or target supports non 8-bit chars");
7553 
7554   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7555     return false;
7556 
7557   // Read out SourceValue into a char buffer.
7558   std::optional<BitCastBuffer> Buffer =
7559       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7560   if (!Buffer)
7561     return false;
7562 
7563   // Write out the buffer into a new APValue.
7564   std::optional<APValue> MaybeDestValue =
7565       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7566   if (!MaybeDestValue)
7567     return false;
7568 
7569   DestValue = std::move(*MaybeDestValue);
7570   return true;
7571 }
7572 
handleLValueToRValueBitCast(EvalInfo & Info,APValue & DestValue,APValue & SourceValue,const CastExpr * BCE)7573 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7574                                         APValue &SourceValue,
7575                                         const CastExpr *BCE) {
7576   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7577          "no host or target supports non 8-bit chars");
7578   assert(SourceValue.isLValue() &&
7579          "LValueToRValueBitcast requires an lvalue operand!");
7580 
7581   LValue SourceLValue;
7582   APValue SourceRValue;
7583   SourceLValue.setFrom(Info.Ctx, SourceValue);
7584   if (!handleLValueToRValueConversion(
7585           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7586           SourceRValue, /*WantObjectRepresentation=*/true))
7587     return false;
7588 
7589   return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
7590 }
7591 
7592 template <class Derived>
7593 class ExprEvaluatorBase
7594   : public ConstStmtVisitor<Derived, bool> {
7595 private:
getDerived()7596   Derived &getDerived() { return static_cast<Derived&>(*this); }
DerivedSuccess(const APValue & V,const Expr * E)7597   bool DerivedSuccess(const APValue &V, const Expr *E) {
7598     return getDerived().Success(V, E);
7599   }
DerivedZeroInitialization(const Expr * E)7600   bool DerivedZeroInitialization(const Expr *E) {
7601     return getDerived().ZeroInitialization(E);
7602   }
7603 
7604   // Check whether a conditional operator with a non-constant condition is a
7605   // potential constant expression. If neither arm is a potential constant
7606   // expression, then the conditional operator is not either.
7607   template<typename ConditionalOperator>
CheckPotentialConstantConditional(const ConditionalOperator * E)7608   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7609     assert(Info.checkingPotentialConstantExpression());
7610 
7611     // Speculatively evaluate both arms.
7612     SmallVector<PartialDiagnosticAt, 8> Diag;
7613     {
7614       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7615       StmtVisitorTy::Visit(E->getFalseExpr());
7616       if (Diag.empty())
7617         return;
7618     }
7619 
7620     {
7621       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7622       Diag.clear();
7623       StmtVisitorTy::Visit(E->getTrueExpr());
7624       if (Diag.empty())
7625         return;
7626     }
7627 
7628     Error(E, diag::note_constexpr_conditional_never_const);
7629   }
7630 
7631 
7632   template<typename ConditionalOperator>
HandleConditionalOperator(const ConditionalOperator * E)7633   bool HandleConditionalOperator(const ConditionalOperator *E) {
7634     bool BoolResult;
7635     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7636       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7637         CheckPotentialConstantConditional(E);
7638         return false;
7639       }
7640       if (Info.noteFailure()) {
7641         StmtVisitorTy::Visit(E->getTrueExpr());
7642         StmtVisitorTy::Visit(E->getFalseExpr());
7643       }
7644       return false;
7645     }
7646 
7647     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7648     return StmtVisitorTy::Visit(EvalExpr);
7649   }
7650 
7651 protected:
7652   EvalInfo &Info;
7653   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7654   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7655 
CCEDiag(const Expr * E,diag::kind D)7656   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7657     return Info.CCEDiag(E, D);
7658   }
7659 
ZeroInitialization(const Expr * E)7660   bool ZeroInitialization(const Expr *E) { return Error(E); }
7661 
IsConstantEvaluatedBuiltinCall(const CallExpr * E)7662   bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7663     unsigned BuiltinOp = E->getBuiltinCallee();
7664     return BuiltinOp != 0 &&
7665            Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7666   }
7667 
7668 public:
ExprEvaluatorBase(EvalInfo & Info)7669   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7670 
getEvalInfo()7671   EvalInfo &getEvalInfo() { return Info; }
7672 
7673   /// Report an evaluation error. This should only be called when an error is
7674   /// first discovered. When propagating an error, just return false.
Error(const Expr * E,diag::kind D)7675   bool Error(const Expr *E, diag::kind D) {
7676     Info.FFDiag(E, D) << E->getSourceRange();
7677     return false;
7678   }
Error(const Expr * E)7679   bool Error(const Expr *E) {
7680     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7681   }
7682 
VisitStmt(const Stmt *)7683   bool VisitStmt(const Stmt *) {
7684     llvm_unreachable("Expression evaluator should not be called on stmts");
7685   }
VisitExpr(const Expr * E)7686   bool VisitExpr(const Expr *E) {
7687     return Error(E);
7688   }
7689 
VisitPredefinedExpr(const PredefinedExpr * E)7690   bool VisitPredefinedExpr(const PredefinedExpr *E) {
7691     return StmtVisitorTy::Visit(E->getFunctionName());
7692   }
VisitConstantExpr(const ConstantExpr * E)7693   bool VisitConstantExpr(const ConstantExpr *E) {
7694     if (E->hasAPValueResult())
7695       return DerivedSuccess(E->getAPValueResult(), E);
7696 
7697     return StmtVisitorTy::Visit(E->getSubExpr());
7698   }
7699 
VisitParenExpr(const ParenExpr * E)7700   bool VisitParenExpr(const ParenExpr *E)
7701     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryExtension(const UnaryOperator * E)7702   bool VisitUnaryExtension(const UnaryOperator *E)
7703     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryPlus(const UnaryOperator * E)7704   bool VisitUnaryPlus(const UnaryOperator *E)
7705     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitChooseExpr(const ChooseExpr * E)7706   bool VisitChooseExpr(const ChooseExpr *E)
7707     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
VisitGenericSelectionExpr(const GenericSelectionExpr * E)7708   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7709     { return StmtVisitorTy::Visit(E->getResultExpr()); }
VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr * E)7710   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7711     { return StmtVisitorTy::Visit(E->getReplacement()); }
VisitCXXDefaultArgExpr(const CXXDefaultArgExpr * E)7712   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7713     TempVersionRAII RAII(*Info.CurrentCall);
7714     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7715     return StmtVisitorTy::Visit(E->getExpr());
7716   }
VisitCXXDefaultInitExpr(const CXXDefaultInitExpr * E)7717   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7718     TempVersionRAII RAII(*Info.CurrentCall);
7719     // The initializer may not have been parsed yet, or might be erroneous.
7720     if (!E->getExpr())
7721       return Error(E);
7722     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7723     return StmtVisitorTy::Visit(E->getExpr());
7724   }
7725 
VisitExprWithCleanups(const ExprWithCleanups * E)7726   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7727     FullExpressionRAII Scope(Info);
7728     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7729   }
7730 
7731   // Temporaries are registered when created, so we don't care about
7732   // CXXBindTemporaryExpr.
VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr * E)7733   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7734     return StmtVisitorTy::Visit(E->getSubExpr());
7735   }
7736 
VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr * E)7737   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7738     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7739     return static_cast<Derived*>(this)->VisitCastExpr(E);
7740   }
VisitCXXDynamicCastExpr(const CXXDynamicCastExpr * E)7741   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7742     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7743       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7744     return static_cast<Derived*>(this)->VisitCastExpr(E);
7745   }
VisitBuiltinBitCastExpr(const BuiltinBitCastExpr * E)7746   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7747     return static_cast<Derived*>(this)->VisitCastExpr(E);
7748   }
7749 
VisitBinaryOperator(const BinaryOperator * E)7750   bool VisitBinaryOperator(const BinaryOperator *E) {
7751     switch (E->getOpcode()) {
7752     default:
7753       return Error(E);
7754 
7755     case BO_Comma:
7756       VisitIgnoredValue(E->getLHS());
7757       return StmtVisitorTy::Visit(E->getRHS());
7758 
7759     case BO_PtrMemD:
7760     case BO_PtrMemI: {
7761       LValue Obj;
7762       if (!HandleMemberPointerAccess(Info, E, Obj))
7763         return false;
7764       APValue Result;
7765       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7766         return false;
7767       return DerivedSuccess(Result, E);
7768     }
7769     }
7770   }
7771 
VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator * E)7772   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7773     return StmtVisitorTy::Visit(E->getSemanticForm());
7774   }
7775 
VisitBinaryConditionalOperator(const BinaryConditionalOperator * E)7776   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7777     // Evaluate and cache the common expression. We treat it as a temporary,
7778     // even though it's not quite the same thing.
7779     LValue CommonLV;
7780     if (!Evaluate(Info.CurrentCall->createTemporary(
7781                       E->getOpaqueValue(),
7782                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7783                       ScopeKind::FullExpression, CommonLV),
7784                   Info, E->getCommon()))
7785       return false;
7786 
7787     return HandleConditionalOperator(E);
7788   }
7789 
VisitConditionalOperator(const ConditionalOperator * E)7790   bool VisitConditionalOperator(const ConditionalOperator *E) {
7791     bool IsBcpCall = false;
7792     // If the condition (ignoring parens) is a __builtin_constant_p call,
7793     // the result is a constant expression if it can be folded without
7794     // side-effects. This is an important GNU extension. See GCC PR38377
7795     // for discussion.
7796     if (const CallExpr *CallCE =
7797           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7798       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7799         IsBcpCall = true;
7800 
7801     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7802     // constant expression; we can't check whether it's potentially foldable.
7803     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7804     // it would return 'false' in this mode.
7805     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7806       return false;
7807 
7808     FoldConstant Fold(Info, IsBcpCall);
7809     if (!HandleConditionalOperator(E)) {
7810       Fold.keepDiagnostics();
7811       return false;
7812     }
7813 
7814     return true;
7815   }
7816 
VisitOpaqueValueExpr(const OpaqueValueExpr * E)7817   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7818     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
7819         Value && !Value->isAbsent())
7820       return DerivedSuccess(*Value, E);
7821 
7822     const Expr *Source = E->getSourceExpr();
7823     if (!Source)
7824       return Error(E);
7825     if (Source == E) {
7826       assert(0 && "OpaqueValueExpr recursively refers to itself");
7827       return Error(E);
7828     }
7829     return StmtVisitorTy::Visit(Source);
7830   }
7831 
VisitPseudoObjectExpr(const PseudoObjectExpr * E)7832   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7833     for (const Expr *SemE : E->semantics()) {
7834       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7835         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7836         // result expression: there could be two different LValues that would
7837         // refer to the same object in that case, and we can't model that.
7838         if (SemE == E->getResultExpr())
7839           return Error(E);
7840 
7841         // Unique OVEs get evaluated if and when we encounter them when
7842         // emitting the rest of the semantic form, rather than eagerly.
7843         if (OVE->isUnique())
7844           continue;
7845 
7846         LValue LV;
7847         if (!Evaluate(Info.CurrentCall->createTemporary(
7848                           OVE, getStorageType(Info.Ctx, OVE),
7849                           ScopeKind::FullExpression, LV),
7850                       Info, OVE->getSourceExpr()))
7851           return false;
7852       } else if (SemE == E->getResultExpr()) {
7853         if (!StmtVisitorTy::Visit(SemE))
7854           return false;
7855       } else {
7856         if (!EvaluateIgnoredValue(Info, SemE))
7857           return false;
7858       }
7859     }
7860     return true;
7861   }
7862 
VisitCallExpr(const CallExpr * E)7863   bool VisitCallExpr(const CallExpr *E) {
7864     APValue Result;
7865     if (!handleCallExpr(E, Result, nullptr))
7866       return false;
7867     return DerivedSuccess(Result, E);
7868   }
7869 
handleCallExpr(const CallExpr * E,APValue & Result,const LValue * ResultSlot)7870   bool handleCallExpr(const CallExpr *E, APValue &Result,
7871                      const LValue *ResultSlot) {
7872     CallScopeRAII CallScope(Info);
7873 
7874     const Expr *Callee = E->getCallee()->IgnoreParens();
7875     QualType CalleeType = Callee->getType();
7876 
7877     const FunctionDecl *FD = nullptr;
7878     LValue *This = nullptr, ThisVal;
7879     auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7880     bool HasQualifier = false;
7881 
7882     CallRef Call;
7883 
7884     // Extract function decl and 'this' pointer from the callee.
7885     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7886       const CXXMethodDecl *Member = nullptr;
7887       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7888         // Explicit bound member calls, such as x.f() or p->g();
7889         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7890           return false;
7891         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7892         if (!Member)
7893           return Error(Callee);
7894         This = &ThisVal;
7895         HasQualifier = ME->hasQualifier();
7896       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7897         // Indirect bound member calls ('.*' or '->*').
7898         const ValueDecl *D =
7899             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7900         if (!D)
7901           return false;
7902         Member = dyn_cast<CXXMethodDecl>(D);
7903         if (!Member)
7904           return Error(Callee);
7905         This = &ThisVal;
7906       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7907         if (!Info.getLangOpts().CPlusPlus20)
7908           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7909         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7910                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7911       } else
7912         return Error(Callee);
7913       FD = Member;
7914     } else if (CalleeType->isFunctionPointerType()) {
7915       LValue CalleeLV;
7916       if (!EvaluatePointer(Callee, CalleeLV, Info))
7917         return false;
7918 
7919       if (!CalleeLV.getLValueOffset().isZero())
7920         return Error(Callee);
7921       if (CalleeLV.isNullPointer()) {
7922         Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7923             << const_cast<Expr *>(Callee);
7924         return false;
7925       }
7926       FD = dyn_cast_or_null<FunctionDecl>(
7927           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7928       if (!FD)
7929         return Error(Callee);
7930       // Don't call function pointers which have been cast to some other type.
7931       // Per DR (no number yet), the caller and callee can differ in noexcept.
7932       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7933         CalleeType->getPointeeType(), FD->getType())) {
7934         return Error(E);
7935       }
7936 
7937       // For an (overloaded) assignment expression, evaluate the RHS before the
7938       // LHS.
7939       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7940       if (OCE && OCE->isAssignmentOp()) {
7941         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7942         Call = Info.CurrentCall->createCall(FD);
7943         bool HasThis = false;
7944         if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7945           HasThis = MD->isImplicitObjectMemberFunction();
7946         if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
7947                           /*RightToLeft=*/true))
7948           return false;
7949       }
7950 
7951       // Overloaded operator calls to member functions are represented as normal
7952       // calls with '*this' as the first argument.
7953       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7954       if (MD &&
7955           (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
7956         // FIXME: When selecting an implicit conversion for an overloaded
7957         // operator delete, we sometimes try to evaluate calls to conversion
7958         // operators without a 'this' parameter!
7959         if (Args.empty())
7960           return Error(E);
7961 
7962         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7963           return false;
7964 
7965         // If we are calling a static operator, the 'this' argument needs to be
7966         // ignored after being evaluated.
7967         if (MD->isInstance())
7968           This = &ThisVal;
7969 
7970         // If this is syntactically a simple assignment using a trivial
7971         // assignment operator, start the lifetimes of union members as needed,
7972         // per C++20 [class.union]5.
7973         if (Info.getLangOpts().CPlusPlus20 && OCE &&
7974             OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7975             !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7976           return false;
7977 
7978         Args = Args.slice(1);
7979       } else if (MD && MD->isLambdaStaticInvoker()) {
7980         // Map the static invoker for the lambda back to the call operator.
7981         // Conveniently, we don't have to slice out the 'this' argument (as is
7982         // being done for the non-static case), since a static member function
7983         // doesn't have an implicit argument passed in.
7984         const CXXRecordDecl *ClosureClass = MD->getParent();
7985         assert(
7986             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7987             "Number of captures must be zero for conversion to function-ptr");
7988 
7989         const CXXMethodDecl *LambdaCallOp =
7990             ClosureClass->getLambdaCallOperator();
7991 
7992         // Set 'FD', the function that will be called below, to the call
7993         // operator.  If the closure object represents a generic lambda, find
7994         // the corresponding specialization of the call operator.
7995 
7996         if (ClosureClass->isGenericLambda()) {
7997           assert(MD->isFunctionTemplateSpecialization() &&
7998                  "A generic lambda's static-invoker function must be a "
7999                  "template specialization");
8000           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8001           FunctionTemplateDecl *CallOpTemplate =
8002               LambdaCallOp->getDescribedFunctionTemplate();
8003           void *InsertPos = nullptr;
8004           FunctionDecl *CorrespondingCallOpSpecialization =
8005               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8006           assert(CorrespondingCallOpSpecialization &&
8007                  "We must always have a function call operator specialization "
8008                  "that corresponds to our static invoker specialization");
8009           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
8010         } else
8011           FD = LambdaCallOp;
8012       } else if (FD->isReplaceableGlobalAllocationFunction()) {
8013         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
8014             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
8015           LValue Ptr;
8016           if (!HandleOperatorNewCall(Info, E, Ptr))
8017             return false;
8018           Ptr.moveInto(Result);
8019           return CallScope.destroy();
8020         } else {
8021           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8022         }
8023       }
8024     } else
8025       return Error(E);
8026 
8027     // Evaluate the arguments now if we've not already done so.
8028     if (!Call) {
8029       Call = Info.CurrentCall->createCall(FD);
8030       if (!EvaluateArgs(Args, Call, Info, FD))
8031         return false;
8032     }
8033 
8034     SmallVector<QualType, 4> CovariantAdjustmentPath;
8035     if (This) {
8036       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8037       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8038         // Perform virtual dispatch, if necessary.
8039         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8040                                    CovariantAdjustmentPath);
8041         if (!FD)
8042           return false;
8043       } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8044         // Check that the 'this' pointer points to an object of the right type.
8045         // FIXME: If this is an assignment operator call, we may need to change
8046         // the active union member before we check this.
8047         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8048           return false;
8049       }
8050     }
8051 
8052     // Destructor calls are different enough that they have their own codepath.
8053     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8054       assert(This && "no 'this' pointer for destructor call");
8055       return HandleDestruction(Info, E, *This,
8056                                Info.Ctx.getRecordType(DD->getParent())) &&
8057              CallScope.destroy();
8058     }
8059 
8060     const FunctionDecl *Definition = nullptr;
8061     Stmt *Body = FD->getBody(Definition);
8062 
8063     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8064         !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8065                             Body, Info, Result, ResultSlot))
8066       return false;
8067 
8068     if (!CovariantAdjustmentPath.empty() &&
8069         !HandleCovariantReturnAdjustment(Info, E, Result,
8070                                          CovariantAdjustmentPath))
8071       return false;
8072 
8073     return CallScope.destroy();
8074   }
8075 
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)8076   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8077     return StmtVisitorTy::Visit(E->getInitializer());
8078   }
VisitInitListExpr(const InitListExpr * E)8079   bool VisitInitListExpr(const InitListExpr *E) {
8080     if (E->getNumInits() == 0)
8081       return DerivedZeroInitialization(E);
8082     if (E->getNumInits() == 1)
8083       return StmtVisitorTy::Visit(E->getInit(0));
8084     return Error(E);
8085   }
VisitImplicitValueInitExpr(const ImplicitValueInitExpr * E)8086   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8087     return DerivedZeroInitialization(E);
8088   }
VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr * E)8089   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8090     return DerivedZeroInitialization(E);
8091   }
VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr * E)8092   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8093     return DerivedZeroInitialization(E);
8094   }
8095 
8096   /// A member expression where the object is a prvalue is itself a prvalue.
VisitMemberExpr(const MemberExpr * E)8097   bool VisitMemberExpr(const MemberExpr *E) {
8098     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8099            "missing temporary materialization conversion");
8100     assert(!E->isArrow() && "missing call to bound member function?");
8101 
8102     APValue Val;
8103     if (!Evaluate(Val, Info, E->getBase()))
8104       return false;
8105 
8106     QualType BaseTy = E->getBase()->getType();
8107 
8108     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8109     if (!FD) return Error(E);
8110     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8111     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8112            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8113 
8114     // Note: there is no lvalue base here. But this case should only ever
8115     // happen in C or in C++98, where we cannot be evaluating a constexpr
8116     // constructor, which is the only case the base matters.
8117     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8118     SubobjectDesignator Designator(BaseTy);
8119     Designator.addDeclUnchecked(FD);
8120 
8121     APValue Result;
8122     return extractSubobject(Info, E, Obj, Designator, Result) &&
8123            DerivedSuccess(Result, E);
8124   }
8125 
VisitExtVectorElementExpr(const ExtVectorElementExpr * E)8126   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8127     APValue Val;
8128     if (!Evaluate(Val, Info, E->getBase()))
8129       return false;
8130 
8131     if (Val.isVector()) {
8132       SmallVector<uint32_t, 4> Indices;
8133       E->getEncodedElementAccess(Indices);
8134       if (Indices.size() == 1) {
8135         // Return scalar.
8136         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8137       } else {
8138         // Construct new APValue vector.
8139         SmallVector<APValue, 4> Elts;
8140         for (unsigned I = 0; I < Indices.size(); ++I) {
8141           Elts.push_back(Val.getVectorElt(Indices[I]));
8142         }
8143         APValue VecResult(Elts.data(), Indices.size());
8144         return DerivedSuccess(VecResult, E);
8145       }
8146     }
8147 
8148     return false;
8149   }
8150 
VisitCastExpr(const CastExpr * E)8151   bool VisitCastExpr(const CastExpr *E) {
8152     switch (E->getCastKind()) {
8153     default:
8154       break;
8155 
8156     case CK_AtomicToNonAtomic: {
8157       APValue AtomicVal;
8158       // This does not need to be done in place even for class/array types:
8159       // atomic-to-non-atomic conversion implies copying the object
8160       // representation.
8161       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8162         return false;
8163       return DerivedSuccess(AtomicVal, E);
8164     }
8165 
8166     case CK_NoOp:
8167     case CK_UserDefinedConversion:
8168       return StmtVisitorTy::Visit(E->getSubExpr());
8169 
8170     case CK_LValueToRValue: {
8171       LValue LVal;
8172       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8173         return false;
8174       APValue RVal;
8175       // Note, we use the subexpression's type in order to retain cv-qualifiers.
8176       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8177                                           LVal, RVal))
8178         return false;
8179       return DerivedSuccess(RVal, E);
8180     }
8181     case CK_LValueToRValueBitCast: {
8182       APValue DestValue, SourceValue;
8183       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8184         return false;
8185       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8186         return false;
8187       return DerivedSuccess(DestValue, E);
8188     }
8189 
8190     case CK_AddressSpaceConversion: {
8191       APValue Value;
8192       if (!Evaluate(Value, Info, E->getSubExpr()))
8193         return false;
8194       return DerivedSuccess(Value, E);
8195     }
8196     }
8197 
8198     return Error(E);
8199   }
8200 
VisitUnaryPostInc(const UnaryOperator * UO)8201   bool VisitUnaryPostInc(const UnaryOperator *UO) {
8202     return VisitUnaryPostIncDec(UO);
8203   }
VisitUnaryPostDec(const UnaryOperator * UO)8204   bool VisitUnaryPostDec(const UnaryOperator *UO) {
8205     return VisitUnaryPostIncDec(UO);
8206   }
VisitUnaryPostIncDec(const UnaryOperator * UO)8207   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8208     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8209       return Error(UO);
8210 
8211     LValue LVal;
8212     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8213       return false;
8214     APValue RVal;
8215     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8216                       UO->isIncrementOp(), &RVal))
8217       return false;
8218     return DerivedSuccess(RVal, UO);
8219   }
8220 
VisitStmtExpr(const StmtExpr * E)8221   bool VisitStmtExpr(const StmtExpr *E) {
8222     // We will have checked the full-expressions inside the statement expression
8223     // when they were completed, and don't need to check them again now.
8224     llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8225                                           false);
8226 
8227     const CompoundStmt *CS = E->getSubStmt();
8228     if (CS->body_empty())
8229       return true;
8230 
8231     BlockScopeRAII Scope(Info);
8232     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8233                                            BE = CS->body_end();
8234          /**/; ++BI) {
8235       if (BI + 1 == BE) {
8236         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8237         if (!FinalExpr) {
8238           Info.FFDiag((*BI)->getBeginLoc(),
8239                       diag::note_constexpr_stmt_expr_unsupported);
8240           return false;
8241         }
8242         return this->Visit(FinalExpr) && Scope.destroy();
8243       }
8244 
8245       APValue ReturnValue;
8246       StmtResult Result = { ReturnValue, nullptr };
8247       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8248       if (ESR != ESR_Succeeded) {
8249         // FIXME: If the statement-expression terminated due to 'return',
8250         // 'break', or 'continue', it would be nice to propagate that to
8251         // the outer statement evaluation rather than bailing out.
8252         if (ESR != ESR_Failed)
8253           Info.FFDiag((*BI)->getBeginLoc(),
8254                       diag::note_constexpr_stmt_expr_unsupported);
8255         return false;
8256       }
8257     }
8258 
8259     llvm_unreachable("Return from function from the loop above.");
8260   }
8261 
8262   /// Visit a value which is evaluated, but whose value is ignored.
VisitIgnoredValue(const Expr * E)8263   void VisitIgnoredValue(const Expr *E) {
8264     EvaluateIgnoredValue(Info, E);
8265   }
8266 
8267   /// Potentially visit a MemberExpr's base expression.
VisitIgnoredBaseExpression(const Expr * E)8268   void VisitIgnoredBaseExpression(const Expr *E) {
8269     // While MSVC doesn't evaluate the base expression, it does diagnose the
8270     // presence of side-effecting behavior.
8271     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8272       return;
8273     VisitIgnoredValue(E);
8274   }
8275 };
8276 
8277 } // namespace
8278 
8279 //===----------------------------------------------------------------------===//
8280 // Common base class for lvalue and temporary evaluation.
8281 //===----------------------------------------------------------------------===//
8282 namespace {
8283 template<class Derived>
8284 class LValueExprEvaluatorBase
8285   : public ExprEvaluatorBase<Derived> {
8286 protected:
8287   LValue &Result;
8288   bool InvalidBaseOK;
8289   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8290   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8291 
Success(APValue::LValueBase B)8292   bool Success(APValue::LValueBase B) {
8293     Result.set(B);
8294     return true;
8295   }
8296 
evaluatePointer(const Expr * E,LValue & Result)8297   bool evaluatePointer(const Expr *E, LValue &Result) {
8298     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8299   }
8300 
8301 public:
LValueExprEvaluatorBase(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)8302   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8303       : ExprEvaluatorBaseTy(Info), Result(Result),
8304         InvalidBaseOK(InvalidBaseOK) {}
8305 
Success(const APValue & V,const Expr * E)8306   bool Success(const APValue &V, const Expr *E) {
8307     Result.setFrom(this->Info.Ctx, V);
8308     return true;
8309   }
8310 
VisitMemberExpr(const MemberExpr * E)8311   bool VisitMemberExpr(const MemberExpr *E) {
8312     // Handle non-static data members.
8313     QualType BaseTy;
8314     bool EvalOK;
8315     if (E->isArrow()) {
8316       EvalOK = evaluatePointer(E->getBase(), Result);
8317       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8318     } else if (E->getBase()->isPRValue()) {
8319       assert(E->getBase()->getType()->isRecordType());
8320       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8321       BaseTy = E->getBase()->getType();
8322     } else {
8323       EvalOK = this->Visit(E->getBase());
8324       BaseTy = E->getBase()->getType();
8325     }
8326     if (!EvalOK) {
8327       if (!InvalidBaseOK)
8328         return false;
8329       Result.setInvalid(E);
8330       return true;
8331     }
8332 
8333     const ValueDecl *MD = E->getMemberDecl();
8334     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8335       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8336              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8337       (void)BaseTy;
8338       if (!HandleLValueMember(this->Info, E, Result, FD))
8339         return false;
8340     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8341       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8342         return false;
8343     } else
8344       return this->Error(E);
8345 
8346     if (MD->getType()->isReferenceType()) {
8347       APValue RefValue;
8348       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8349                                           RefValue))
8350         return false;
8351       return Success(RefValue, E);
8352     }
8353     return true;
8354   }
8355 
VisitBinaryOperator(const BinaryOperator * E)8356   bool VisitBinaryOperator(const BinaryOperator *E) {
8357     switch (E->getOpcode()) {
8358     default:
8359       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8360 
8361     case BO_PtrMemD:
8362     case BO_PtrMemI:
8363       return HandleMemberPointerAccess(this->Info, E, Result);
8364     }
8365   }
8366 
VisitCastExpr(const CastExpr * E)8367   bool VisitCastExpr(const CastExpr *E) {
8368     switch (E->getCastKind()) {
8369     default:
8370       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8371 
8372     case CK_DerivedToBase:
8373     case CK_UncheckedDerivedToBase:
8374       if (!this->Visit(E->getSubExpr()))
8375         return false;
8376 
8377       // Now figure out the necessary offset to add to the base LV to get from
8378       // the derived class to the base class.
8379       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8380                                   Result);
8381     }
8382   }
8383 };
8384 }
8385 
8386 //===----------------------------------------------------------------------===//
8387 // LValue Evaluation
8388 //
8389 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8390 // function designators (in C), decl references to void objects (in C), and
8391 // temporaries (if building with -Wno-address-of-temporary).
8392 //
8393 // LValue evaluation produces values comprising a base expression of one of the
8394 // following types:
8395 // - Declarations
8396 //  * VarDecl
8397 //  * FunctionDecl
8398 // - Literals
8399 //  * CompoundLiteralExpr in C (and in global scope in C++)
8400 //  * StringLiteral
8401 //  * PredefinedExpr
8402 //  * ObjCStringLiteralExpr
8403 //  * ObjCEncodeExpr
8404 //  * AddrLabelExpr
8405 //  * BlockExpr
8406 //  * CallExpr for a MakeStringConstant builtin
8407 // - typeid(T) expressions, as TypeInfoLValues
8408 // - Locals and temporaries
8409 //  * MaterializeTemporaryExpr
8410 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8411 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8412 //    from the AST (FIXME).
8413 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8414 //    CallIndex, for a lifetime-extended temporary.
8415 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8416 //    immediate invocation.
8417 // plus an offset in bytes.
8418 //===----------------------------------------------------------------------===//
8419 namespace {
8420 class LValueExprEvaluator
8421   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8422 public:
LValueExprEvaluator(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)8423   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8424     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8425 
8426   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8427   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8428 
8429   bool VisitCallExpr(const CallExpr *E);
8430   bool VisitDeclRefExpr(const DeclRefExpr *E);
VisitPredefinedExpr(const PredefinedExpr * E)8431   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8432   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8433   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8434   bool VisitMemberExpr(const MemberExpr *E);
VisitStringLiteral(const StringLiteral * E)8435   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
VisitObjCEncodeExpr(const ObjCEncodeExpr * E)8436   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8437   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8438   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8439   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8440   bool VisitUnaryDeref(const UnaryOperator *E);
8441   bool VisitUnaryReal(const UnaryOperator *E);
8442   bool VisitUnaryImag(const UnaryOperator *E);
VisitUnaryPreInc(const UnaryOperator * UO)8443   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8444     return VisitUnaryPreIncDec(UO);
8445   }
VisitUnaryPreDec(const UnaryOperator * UO)8446   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8447     return VisitUnaryPreIncDec(UO);
8448   }
8449   bool VisitBinAssign(const BinaryOperator *BO);
8450   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8451 
VisitCastExpr(const CastExpr * E)8452   bool VisitCastExpr(const CastExpr *E) {
8453     switch (E->getCastKind()) {
8454     default:
8455       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8456 
8457     case CK_LValueBitCast:
8458       this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8459           << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8460       if (!Visit(E->getSubExpr()))
8461         return false;
8462       Result.Designator.setInvalid();
8463       return true;
8464 
8465     case CK_BaseToDerived:
8466       if (!Visit(E->getSubExpr()))
8467         return false;
8468       return HandleBaseToDerivedCast(Info, E, Result);
8469 
8470     case CK_Dynamic:
8471       if (!Visit(E->getSubExpr()))
8472         return false;
8473       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8474     }
8475   }
8476 };
8477 } // end anonymous namespace
8478 
8479 /// Evaluate an expression as an lvalue. This can be legitimately called on
8480 /// expressions which are not glvalues, in three cases:
8481 ///  * function designators in C, and
8482 ///  * "extern void" objects
8483 ///  * @selector() expressions in Objective-C
EvaluateLValue(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)8484 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8485                            bool InvalidBaseOK) {
8486   assert(!E->isValueDependent());
8487   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8488          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8489   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8490 }
8491 
VisitDeclRefExpr(const DeclRefExpr * E)8492 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8493   const NamedDecl *D = E->getDecl();
8494   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8495           UnnamedGlobalConstantDecl>(D))
8496     return Success(cast<ValueDecl>(D));
8497   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8498     return VisitVarDecl(E, VD);
8499   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8500     return Visit(BD->getBinding());
8501   return Error(E);
8502 }
8503 
8504 
VisitVarDecl(const Expr * E,const VarDecl * VD)8505 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8506 
8507   // If we are within a lambda's call operator, check whether the 'VD' referred
8508   // to within 'E' actually represents a lambda-capture that maps to a
8509   // data-member/field within the closure object, and if so, evaluate to the
8510   // field or what the field refers to.
8511   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8512       isa<DeclRefExpr>(E) &&
8513       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8514     // We don't always have a complete capture-map when checking or inferring if
8515     // the function call operator meets the requirements of a constexpr function
8516     // - but we don't need to evaluate the captures to determine constexprness
8517     // (dcl.constexpr C++17).
8518     if (Info.checkingPotentialConstantExpression())
8519       return false;
8520 
8521     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8522       const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
8523 
8524       // Static lambda function call operators can't have captures. We already
8525       // diagnosed this, so bail out here.
8526       if (MD->isStatic()) {
8527         assert(Info.CurrentCall->This == nullptr &&
8528                "This should not be set for a static call operator");
8529         return false;
8530       }
8531 
8532       // Start with 'Result' referring to the complete closure object...
8533       if (MD->isExplicitObjectMemberFunction()) {
8534         APValue *RefValue =
8535             Info.getParamSlot(Info.CurrentCall->Arguments, MD->getParamDecl(0));
8536         Result.setFrom(Info.Ctx, *RefValue);
8537       } else
8538         Result = *Info.CurrentCall->This;
8539 
8540       // ... then update it to refer to the field of the closure object
8541       // that represents the capture.
8542       if (!HandleLValueMember(Info, E, Result, FD))
8543         return false;
8544       // And if the field is of reference type, update 'Result' to refer to what
8545       // the field refers to.
8546       if (FD->getType()->isReferenceType()) {
8547         APValue RVal;
8548         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8549                                             RVal))
8550           return false;
8551         Result.setFrom(Info.Ctx, RVal);
8552       }
8553       return true;
8554     }
8555   }
8556 
8557   CallStackFrame *Frame = nullptr;
8558   unsigned Version = 0;
8559   if (VD->hasLocalStorage()) {
8560     // Only if a local variable was declared in the function currently being
8561     // evaluated, do we expect to be able to find its value in the current
8562     // frame. (Otherwise it was likely declared in an enclosing context and
8563     // could either have a valid evaluatable value (for e.g. a constexpr
8564     // variable) or be ill-formed (and trigger an appropriate evaluation
8565     // diagnostic)).
8566     CallStackFrame *CurrFrame = Info.CurrentCall;
8567     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8568       // Function parameters are stored in some caller's frame. (Usually the
8569       // immediate caller, but for an inherited constructor they may be more
8570       // distant.)
8571       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8572         if (CurrFrame->Arguments) {
8573           VD = CurrFrame->Arguments.getOrigParam(PVD);
8574           Frame =
8575               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8576           Version = CurrFrame->Arguments.Version;
8577         }
8578       } else {
8579         Frame = CurrFrame;
8580         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8581       }
8582     }
8583   }
8584 
8585   if (!VD->getType()->isReferenceType()) {
8586     if (Frame) {
8587       Result.set({VD, Frame->Index, Version});
8588       return true;
8589     }
8590     return Success(VD);
8591   }
8592 
8593   if (!Info.getLangOpts().CPlusPlus11) {
8594     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8595         << VD << VD->getType();
8596     Info.Note(VD->getLocation(), diag::note_declared_at);
8597   }
8598 
8599   APValue *V;
8600   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8601     return false;
8602   if (!V->hasValue()) {
8603     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8604     // adjust the diagnostic to say that.
8605     if (!Info.checkingPotentialConstantExpression())
8606       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8607     return false;
8608   }
8609   return Success(*V, E);
8610 }
8611 
VisitCallExpr(const CallExpr * E)8612 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8613   if (!IsConstantEvaluatedBuiltinCall(E))
8614     return ExprEvaluatorBaseTy::VisitCallExpr(E);
8615 
8616   switch (E->getBuiltinCallee()) {
8617   default:
8618     return false;
8619   case Builtin::BIas_const:
8620   case Builtin::BIforward:
8621   case Builtin::BIforward_like:
8622   case Builtin::BImove:
8623   case Builtin::BImove_if_noexcept:
8624     if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8625       return Visit(E->getArg(0));
8626     break;
8627   }
8628 
8629   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8630 }
8631 
VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * E)8632 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8633     const MaterializeTemporaryExpr *E) {
8634   // Walk through the expression to find the materialized temporary itself.
8635   SmallVector<const Expr *, 2> CommaLHSs;
8636   SmallVector<SubobjectAdjustment, 2> Adjustments;
8637   const Expr *Inner =
8638       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8639 
8640   // If we passed any comma operators, evaluate their LHSs.
8641   for (const Expr *E : CommaLHSs)
8642     if (!EvaluateIgnoredValue(Info, E))
8643       return false;
8644 
8645   // A materialized temporary with static storage duration can appear within the
8646   // result of a constant expression evaluation, so we need to preserve its
8647   // value for use outside this evaluation.
8648   APValue *Value;
8649   if (E->getStorageDuration() == SD_Static) {
8650     if (Info.EvalMode == EvalInfo::EM_ConstantFold)
8651       return false;
8652     // FIXME: What about SD_Thread?
8653     Value = E->getOrCreateValue(true);
8654     *Value = APValue();
8655     Result.set(E);
8656   } else {
8657     Value = &Info.CurrentCall->createTemporary(
8658         E, Inner->getType(),
8659         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8660                                                      : ScopeKind::Block,
8661         Result);
8662   }
8663 
8664   QualType Type = Inner->getType();
8665 
8666   // Materialize the temporary itself.
8667   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8668     *Value = APValue();
8669     return false;
8670   }
8671 
8672   // Adjust our lvalue to refer to the desired subobject.
8673   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8674     --I;
8675     switch (Adjustments[I].Kind) {
8676     case SubobjectAdjustment::DerivedToBaseAdjustment:
8677       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8678                                 Type, Result))
8679         return false;
8680       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8681       break;
8682 
8683     case SubobjectAdjustment::FieldAdjustment:
8684       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8685         return false;
8686       Type = Adjustments[I].Field->getType();
8687       break;
8688 
8689     case SubobjectAdjustment::MemberPointerAdjustment:
8690       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8691                                      Adjustments[I].Ptr.RHS))
8692         return false;
8693       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8694       break;
8695     }
8696   }
8697 
8698   return true;
8699 }
8700 
8701 bool
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)8702 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8703   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8704          "lvalue compound literal in c++?");
8705   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8706   // only see this when folding in C, so there's no standard to follow here.
8707   return Success(E);
8708 }
8709 
VisitCXXTypeidExpr(const CXXTypeidExpr * E)8710 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8711   TypeInfoLValue TypeInfo;
8712 
8713   if (!E->isPotentiallyEvaluated()) {
8714     if (E->isTypeOperand())
8715       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8716     else
8717       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8718   } else {
8719     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8720       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8721         << E->getExprOperand()->getType()
8722         << E->getExprOperand()->getSourceRange();
8723     }
8724 
8725     if (!Visit(E->getExprOperand()))
8726       return false;
8727 
8728     std::optional<DynamicType> DynType =
8729         ComputeDynamicType(Info, E, Result, AK_TypeId);
8730     if (!DynType)
8731       return false;
8732 
8733     TypeInfo =
8734         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8735   }
8736 
8737   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8738 }
8739 
VisitCXXUuidofExpr(const CXXUuidofExpr * E)8740 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8741   return Success(E->getGuidDecl());
8742 }
8743 
VisitMemberExpr(const MemberExpr * E)8744 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8745   // Handle static data members.
8746   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8747     VisitIgnoredBaseExpression(E->getBase());
8748     return VisitVarDecl(E, VD);
8749   }
8750 
8751   // Handle static member functions.
8752   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8753     if (MD->isStatic()) {
8754       VisitIgnoredBaseExpression(E->getBase());
8755       return Success(MD);
8756     }
8757   }
8758 
8759   // Handle non-static data members.
8760   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8761 }
8762 
VisitArraySubscriptExpr(const ArraySubscriptExpr * E)8763 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8764   // FIXME: Deal with vectors as array subscript bases.
8765   if (E->getBase()->getType()->isVectorType() ||
8766       E->getBase()->getType()->isSveVLSBuiltinType())
8767     return Error(E);
8768 
8769   APSInt Index;
8770   bool Success = true;
8771 
8772   // C++17's rules require us to evaluate the LHS first, regardless of which
8773   // side is the base.
8774   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8775     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8776                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8777       if (!Info.noteFailure())
8778         return false;
8779       Success = false;
8780     }
8781   }
8782 
8783   return Success &&
8784          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8785 }
8786 
VisitUnaryDeref(const UnaryOperator * E)8787 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8788   return evaluatePointer(E->getSubExpr(), Result);
8789 }
8790 
VisitUnaryReal(const UnaryOperator * E)8791 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8792   if (!Visit(E->getSubExpr()))
8793     return false;
8794   // __real is a no-op on scalar lvalues.
8795   if (E->getSubExpr()->getType()->isAnyComplexType())
8796     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8797   return true;
8798 }
8799 
VisitUnaryImag(const UnaryOperator * E)8800 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8801   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8802          "lvalue __imag__ on scalar?");
8803   if (!Visit(E->getSubExpr()))
8804     return false;
8805   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8806   return true;
8807 }
8808 
VisitUnaryPreIncDec(const UnaryOperator * UO)8809 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8810   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8811     return Error(UO);
8812 
8813   if (!this->Visit(UO->getSubExpr()))
8814     return false;
8815 
8816   return handleIncDec(
8817       this->Info, UO, Result, UO->getSubExpr()->getType(),
8818       UO->isIncrementOp(), nullptr);
8819 }
8820 
VisitCompoundAssignOperator(const CompoundAssignOperator * CAO)8821 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8822     const CompoundAssignOperator *CAO) {
8823   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8824     return Error(CAO);
8825 
8826   bool Success = true;
8827 
8828   // C++17 onwards require that we evaluate the RHS first.
8829   APValue RHS;
8830   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8831     if (!Info.noteFailure())
8832       return false;
8833     Success = false;
8834   }
8835 
8836   // The overall lvalue result is the result of evaluating the LHS.
8837   if (!this->Visit(CAO->getLHS()) || !Success)
8838     return false;
8839 
8840   return handleCompoundAssignment(
8841       this->Info, CAO,
8842       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8843       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8844 }
8845 
VisitBinAssign(const BinaryOperator * E)8846 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8847   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8848     return Error(E);
8849 
8850   bool Success = true;
8851 
8852   // C++17 onwards require that we evaluate the RHS first.
8853   APValue NewVal;
8854   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8855     if (!Info.noteFailure())
8856       return false;
8857     Success = false;
8858   }
8859 
8860   if (!this->Visit(E->getLHS()) || !Success)
8861     return false;
8862 
8863   if (Info.getLangOpts().CPlusPlus20 &&
8864       !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8865     return false;
8866 
8867   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8868                           NewVal);
8869 }
8870 
8871 //===----------------------------------------------------------------------===//
8872 // Pointer Evaluation
8873 //===----------------------------------------------------------------------===//
8874 
8875 /// Attempts to compute the number of bytes available at the pointer
8876 /// returned by a function with the alloc_size attribute. Returns true if we
8877 /// were successful. Places an unsigned number into `Result`.
8878 ///
8879 /// This expects the given CallExpr to be a call to a function with an
8880 /// alloc_size attribute.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const CallExpr * Call,llvm::APInt & Result)8881 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8882                                             const CallExpr *Call,
8883                                             llvm::APInt &Result) {
8884   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8885 
8886   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8887   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8888   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8889   if (Call->getNumArgs() <= SizeArgNo)
8890     return false;
8891 
8892   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8893     Expr::EvalResult ExprResult;
8894     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8895       return false;
8896     Into = ExprResult.Val.getInt();
8897     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8898       return false;
8899     Into = Into.zext(BitsInSizeT);
8900     return true;
8901   };
8902 
8903   APSInt SizeOfElem;
8904   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8905     return false;
8906 
8907   if (!AllocSize->getNumElemsParam().isValid()) {
8908     Result = std::move(SizeOfElem);
8909     return true;
8910   }
8911 
8912   APSInt NumberOfElems;
8913   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8914   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8915     return false;
8916 
8917   bool Overflow;
8918   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8919   if (Overflow)
8920     return false;
8921 
8922   Result = std::move(BytesAvailable);
8923   return true;
8924 }
8925 
8926 /// Convenience function. LVal's base must be a call to an alloc_size
8927 /// function.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const LValue & LVal,llvm::APInt & Result)8928 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8929                                             const LValue &LVal,
8930                                             llvm::APInt &Result) {
8931   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8932          "Can't get the size of a non alloc_size function");
8933   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8934   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8935   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8936 }
8937 
8938 /// Attempts to evaluate the given LValueBase as the result of a call to
8939 /// a function with the alloc_size attribute. If it was possible to do so, this
8940 /// function will return true, make Result's Base point to said function call,
8941 /// and mark Result's Base as invalid.
evaluateLValueAsAllocSize(EvalInfo & Info,APValue::LValueBase Base,LValue & Result)8942 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8943                                       LValue &Result) {
8944   if (Base.isNull())
8945     return false;
8946 
8947   // Because we do no form of static analysis, we only support const variables.
8948   //
8949   // Additionally, we can't support parameters, nor can we support static
8950   // variables (in the latter case, use-before-assign isn't UB; in the former,
8951   // we have no clue what they'll be assigned to).
8952   const auto *VD =
8953       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8954   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8955     return false;
8956 
8957   const Expr *Init = VD->getAnyInitializer();
8958   if (!Init || Init->getType().isNull())
8959     return false;
8960 
8961   const Expr *E = Init->IgnoreParens();
8962   if (!tryUnwrapAllocSizeCall(E))
8963     return false;
8964 
8965   // Store E instead of E unwrapped so that the type of the LValue's base is
8966   // what the user wanted.
8967   Result.setInvalid(E);
8968 
8969   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8970   Result.addUnsizedArray(Info, E, Pointee);
8971   return true;
8972 }
8973 
8974 namespace {
8975 class PointerExprEvaluator
8976   : public ExprEvaluatorBase<PointerExprEvaluator> {
8977   LValue &Result;
8978   bool InvalidBaseOK;
8979 
Success(const Expr * E)8980   bool Success(const Expr *E) {
8981     Result.set(E);
8982     return true;
8983   }
8984 
evaluateLValue(const Expr * E,LValue & Result)8985   bool evaluateLValue(const Expr *E, LValue &Result) {
8986     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8987   }
8988 
evaluatePointer(const Expr * E,LValue & Result)8989   bool evaluatePointer(const Expr *E, LValue &Result) {
8990     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8991   }
8992 
8993   bool visitNonBuiltinCallExpr(const CallExpr *E);
8994 public:
8995 
PointerExprEvaluator(EvalInfo & info,LValue & Result,bool InvalidBaseOK)8996   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8997       : ExprEvaluatorBaseTy(info), Result(Result),
8998         InvalidBaseOK(InvalidBaseOK) {}
8999 
Success(const APValue & V,const Expr * E)9000   bool Success(const APValue &V, const Expr *E) {
9001     Result.setFrom(Info.Ctx, V);
9002     return true;
9003   }
ZeroInitialization(const Expr * E)9004   bool ZeroInitialization(const Expr *E) {
9005     Result.setNull(Info.Ctx, E->getType());
9006     return true;
9007   }
9008 
9009   bool VisitBinaryOperator(const BinaryOperator *E);
9010   bool VisitCastExpr(const CastExpr* E);
9011   bool VisitUnaryAddrOf(const UnaryOperator *E);
VisitObjCStringLiteral(const ObjCStringLiteral * E)9012   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9013       { return Success(E); }
VisitObjCBoxedExpr(const ObjCBoxedExpr * E)9014   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9015     if (E->isExpressibleAsConstantInitializer())
9016       return Success(E);
9017     if (Info.noteFailure())
9018       EvaluateIgnoredValue(Info, E->getSubExpr());
9019     return Error(E);
9020   }
VisitAddrLabelExpr(const AddrLabelExpr * E)9021   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9022       { return Success(E); }
9023   bool VisitCallExpr(const CallExpr *E);
9024   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
VisitBlockExpr(const BlockExpr * E)9025   bool VisitBlockExpr(const BlockExpr *E) {
9026     if (!E->getBlockDecl()->hasCaptures())
9027       return Success(E);
9028     return Error(E);
9029   }
VisitCXXThisExpr(const CXXThisExpr * E)9030   bool VisitCXXThisExpr(const CXXThisExpr *E) {
9031     // Can't look at 'this' when checking a potential constant expression.
9032     if (Info.checkingPotentialConstantExpression())
9033       return false;
9034     if (!Info.CurrentCall->This) {
9035       if (Info.getLangOpts().CPlusPlus11)
9036         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9037       else
9038         Info.FFDiag(E);
9039       return false;
9040     }
9041     Result = *Info.CurrentCall->This;
9042 
9043     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9044       // Ensure we actually have captured 'this'. If something was wrong with
9045       // 'this' capture, the error would have been previously reported.
9046       // Otherwise we can be inside of a default initialization of an object
9047       // declared by lambda's body, so no need to return false.
9048       if (!Info.CurrentCall->LambdaThisCaptureField)
9049         return true;
9050 
9051       // If we have captured 'this',  the 'this' expression refers
9052       // to the enclosing '*this' object (either by value or reference) which is
9053       // either copied into the closure object's field that represents the
9054       // '*this' or refers to '*this'.
9055       // Update 'Result' to refer to the data member/field of the closure object
9056       // that represents the '*this' capture.
9057       if (!HandleLValueMember(Info, E, Result,
9058                              Info.CurrentCall->LambdaThisCaptureField))
9059         return false;
9060       // If we captured '*this' by reference, replace the field with its referent.
9061       if (Info.CurrentCall->LambdaThisCaptureField->getType()
9062               ->isPointerType()) {
9063         APValue RVal;
9064         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
9065                                             RVal))
9066           return false;
9067 
9068         Result.setFrom(Info.Ctx, RVal);
9069       }
9070     }
9071     return true;
9072   }
9073 
9074   bool VisitCXXNewExpr(const CXXNewExpr *E);
9075 
VisitSourceLocExpr(const SourceLocExpr * E)9076   bool VisitSourceLocExpr(const SourceLocExpr *E) {
9077     assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9078     APValue LValResult = E->EvaluateInContext(
9079         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9080     Result.setFrom(Info.Ctx, LValResult);
9081     return true;
9082   }
9083 
VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr * E)9084   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9085     std::string ResultStr = E->ComputeName(Info.Ctx);
9086 
9087     QualType CharTy = Info.Ctx.CharTy.withConst();
9088     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9089                ResultStr.size() + 1);
9090     QualType ArrayTy = Info.Ctx.getConstantArrayType(
9091         CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9092 
9093     StringLiteral *SL =
9094         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9095                               /*Pascal*/ false, ArrayTy, E->getLocation());
9096 
9097     evaluateLValue(SL, Result);
9098     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9099     return true;
9100   }
9101 
9102   // FIXME: Missing: @protocol, @selector
9103 };
9104 } // end anonymous namespace
9105 
EvaluatePointer(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)9106 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9107                             bool InvalidBaseOK) {
9108   assert(!E->isValueDependent());
9109   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9110   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9111 }
9112 
VisitBinaryOperator(const BinaryOperator * E)9113 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9114   if (E->getOpcode() != BO_Add &&
9115       E->getOpcode() != BO_Sub)
9116     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9117 
9118   const Expr *PExp = E->getLHS();
9119   const Expr *IExp = E->getRHS();
9120   if (IExp->getType()->isPointerType())
9121     std::swap(PExp, IExp);
9122 
9123   bool EvalPtrOK = evaluatePointer(PExp, Result);
9124   if (!EvalPtrOK && !Info.noteFailure())
9125     return false;
9126 
9127   llvm::APSInt Offset;
9128   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9129     return false;
9130 
9131   if (E->getOpcode() == BO_Sub)
9132     negateAsSigned(Offset);
9133 
9134   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9135   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9136 }
9137 
VisitUnaryAddrOf(const UnaryOperator * E)9138 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9139   return evaluateLValue(E->getSubExpr(), Result);
9140 }
9141 
9142 // Is the provided decl 'std::source_location::current'?
IsDeclSourceLocationCurrent(const FunctionDecl * FD)9143 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
9144   if (!FD)
9145     return false;
9146   const IdentifierInfo *FnII = FD->getIdentifier();
9147   if (!FnII || !FnII->isStr("current"))
9148     return false;
9149 
9150   const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9151   if (!RD)
9152     return false;
9153 
9154   const IdentifierInfo *ClassII = RD->getIdentifier();
9155   return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9156 }
9157 
VisitCastExpr(const CastExpr * E)9158 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9159   const Expr *SubExpr = E->getSubExpr();
9160 
9161   switch (E->getCastKind()) {
9162   default:
9163     break;
9164   case CK_BitCast:
9165   case CK_CPointerToObjCPointerCast:
9166   case CK_BlockPointerToObjCPointerCast:
9167   case CK_AnyPointerToBlockPointerCast:
9168   case CK_AddressSpaceConversion:
9169     if (!Visit(SubExpr))
9170       return false;
9171     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9172     // permitted in constant expressions in C++11. Bitcasts from cv void* are
9173     // also static_casts, but we disallow them as a resolution to DR1312.
9174     if (!E->getType()->isVoidPointerType()) {
9175       // In some circumstances, we permit casting from void* to cv1 T*, when the
9176       // actual pointee object is actually a cv2 T.
9177       bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9178                             !Result.IsNullPtr;
9179       bool VoidPtrCastMaybeOK =
9180           HasValidResult &&
9181           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
9182                                           E->getType()->getPointeeType());
9183       // 1. We'll allow it in std::allocator::allocate, and anything which that
9184       //    calls.
9185       // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9186       //    <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9187       //    We'll allow it in the body of std::source_location::current.  GCC's
9188       //    implementation had a parameter of type `void*`, and casts from
9189       //    that back to `const __impl*` in its body.
9190       if (VoidPtrCastMaybeOK &&
9191           (Info.getStdAllocatorCaller("allocate") ||
9192            IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9193            Info.getLangOpts().CPlusPlus26)) {
9194         // Permitted.
9195       } else {
9196         if (SubExpr->getType()->isVoidPointerType()) {
9197           if (HasValidResult)
9198             CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9199                 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9200                 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9201                 << E->getType()->getPointeeType();
9202           else
9203             CCEDiag(E, diag::note_constexpr_invalid_cast)
9204                 << 3 << SubExpr->getType();
9205         } else
9206           CCEDiag(E, diag::note_constexpr_invalid_cast)
9207               << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9208         Result.Designator.setInvalid();
9209       }
9210     }
9211     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9212       ZeroInitialization(E);
9213     return true;
9214 
9215   case CK_DerivedToBase:
9216   case CK_UncheckedDerivedToBase:
9217     if (!evaluatePointer(E->getSubExpr(), Result))
9218       return false;
9219     if (!Result.Base && Result.Offset.isZero())
9220       return true;
9221 
9222     // Now figure out the necessary offset to add to the base LV to get from
9223     // the derived class to the base class.
9224     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9225                                   castAs<PointerType>()->getPointeeType(),
9226                                 Result);
9227 
9228   case CK_BaseToDerived:
9229     if (!Visit(E->getSubExpr()))
9230       return false;
9231     if (!Result.Base && Result.Offset.isZero())
9232       return true;
9233     return HandleBaseToDerivedCast(Info, E, Result);
9234 
9235   case CK_Dynamic:
9236     if (!Visit(E->getSubExpr()))
9237       return false;
9238     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9239 
9240   case CK_NullToPointer:
9241     VisitIgnoredValue(E->getSubExpr());
9242     return ZeroInitialization(E);
9243 
9244   case CK_IntegralToPointer: {
9245     CCEDiag(E, diag::note_constexpr_invalid_cast)
9246         << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9247 
9248     APValue Value;
9249     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9250       break;
9251 
9252     if (Value.isInt()) {
9253       unsigned Size = Info.Ctx.getTypeSize(E->getType());
9254       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9255       Result.Base = (Expr*)nullptr;
9256       Result.InvalidBase = false;
9257       Result.Offset = CharUnits::fromQuantity(N);
9258       Result.Designator.setInvalid();
9259       Result.IsNullPtr = false;
9260       return true;
9261     } else {
9262       // Cast is of an lvalue, no need to change value.
9263       Result.setFrom(Info.Ctx, Value);
9264       return true;
9265     }
9266   }
9267 
9268   case CK_ArrayToPointerDecay: {
9269     if (SubExpr->isGLValue()) {
9270       if (!evaluateLValue(SubExpr, Result))
9271         return false;
9272     } else {
9273       APValue &Value = Info.CurrentCall->createTemporary(
9274           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9275       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9276         return false;
9277     }
9278     // The result is a pointer to the first element of the array.
9279     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9280     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9281       Result.addArray(Info, E, CAT);
9282     else
9283       Result.addUnsizedArray(Info, E, AT->getElementType());
9284     return true;
9285   }
9286 
9287   case CK_FunctionToPointerDecay:
9288     return evaluateLValue(SubExpr, Result);
9289 
9290   case CK_LValueToRValue: {
9291     LValue LVal;
9292     if (!evaluateLValue(E->getSubExpr(), LVal))
9293       return false;
9294 
9295     APValue RVal;
9296     // Note, we use the subexpression's type in order to retain cv-qualifiers.
9297     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9298                                         LVal, RVal))
9299       return InvalidBaseOK &&
9300              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9301     return Success(RVal, E);
9302   }
9303   }
9304 
9305   return ExprEvaluatorBaseTy::VisitCastExpr(E);
9306 }
9307 
GetAlignOfType(EvalInfo & Info,QualType T,UnaryExprOrTypeTrait ExprKind)9308 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
9309                                 UnaryExprOrTypeTrait ExprKind) {
9310   // C++ [expr.alignof]p3:
9311   //     When alignof is applied to a reference type, the result is the
9312   //     alignment of the referenced type.
9313   T = T.getNonReferenceType();
9314 
9315   if (T.getQualifiers().hasUnaligned())
9316     return CharUnits::One();
9317 
9318   const bool AlignOfReturnsPreferred =
9319       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9320 
9321   // __alignof is defined to return the preferred alignment.
9322   // Before 8, clang returned the preferred alignment for alignof and _Alignof
9323   // as well.
9324   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9325     return Info.Ctx.toCharUnitsFromBits(
9326       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9327   // alignof and _Alignof are defined to return the ABI alignment.
9328   else if (ExprKind == UETT_AlignOf)
9329     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9330   else
9331     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9332 }
9333 
GetAlignOfExpr(EvalInfo & Info,const Expr * E,UnaryExprOrTypeTrait ExprKind)9334 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9335                                 UnaryExprOrTypeTrait ExprKind) {
9336   E = E->IgnoreParens();
9337 
9338   // The kinds of expressions that we have special-case logic here for
9339   // should be kept up to date with the special checks for those
9340   // expressions in Sema.
9341 
9342   // alignof decl is always accepted, even if it doesn't make sense: we default
9343   // to 1 in those cases.
9344   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9345     return Info.Ctx.getDeclAlign(DRE->getDecl(),
9346                                  /*RefAsPointee*/true);
9347 
9348   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9349     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9350                                  /*RefAsPointee*/true);
9351 
9352   return GetAlignOfType(Info, E->getType(), ExprKind);
9353 }
9354 
getBaseAlignment(EvalInfo & Info,const LValue & Value)9355 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9356   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9357     return Info.Ctx.getDeclAlign(VD);
9358   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9359     return GetAlignOfExpr(Info, E, UETT_AlignOf);
9360   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9361 }
9362 
9363 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9364 /// __builtin_is_aligned and __builtin_assume_aligned.
getAlignmentArgument(const Expr * E,QualType ForType,EvalInfo & Info,APSInt & Alignment)9365 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9366                                  EvalInfo &Info, APSInt &Alignment) {
9367   if (!EvaluateInteger(E, Alignment, Info))
9368     return false;
9369   if (Alignment < 0 || !Alignment.isPowerOf2()) {
9370     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9371     return false;
9372   }
9373   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9374   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9375   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9376     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9377         << MaxValue << ForType << Alignment;
9378     return false;
9379   }
9380   // Ensure both alignment and source value have the same bit width so that we
9381   // don't assert when computing the resulting value.
9382   APSInt ExtAlignment =
9383       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9384   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9385          "Alignment should not be changed by ext/trunc");
9386   Alignment = ExtAlignment;
9387   assert(Alignment.getBitWidth() == SrcWidth);
9388   return true;
9389 }
9390 
9391 // To be clear: this happily visits unsupported builtins. Better name welcomed.
visitNonBuiltinCallExpr(const CallExpr * E)9392 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9393   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9394     return true;
9395 
9396   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9397     return false;
9398 
9399   Result.setInvalid(E);
9400   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9401   Result.addUnsizedArray(Info, E, PointeeTy);
9402   return true;
9403 }
9404 
VisitCallExpr(const CallExpr * E)9405 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9406   if (!IsConstantEvaluatedBuiltinCall(E))
9407     return visitNonBuiltinCallExpr(E);
9408   return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9409 }
9410 
9411 // Determine if T is a character type for which we guarantee that
9412 // sizeof(T) == 1.
isOneByteCharacterType(QualType T)9413 static bool isOneByteCharacterType(QualType T) {
9414   return T->isCharType() || T->isChar8Type();
9415 }
9416 
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)9417 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9418                                                 unsigned BuiltinOp) {
9419   if (IsNoOpCall(E))
9420     return Success(E);
9421 
9422   switch (BuiltinOp) {
9423   case Builtin::BIaddressof:
9424   case Builtin::BI__addressof:
9425   case Builtin::BI__builtin_addressof:
9426     return evaluateLValue(E->getArg(0), Result);
9427   case Builtin::BI__builtin_assume_aligned: {
9428     // We need to be very careful here because: if the pointer does not have the
9429     // asserted alignment, then the behavior is undefined, and undefined
9430     // behavior is non-constant.
9431     if (!evaluatePointer(E->getArg(0), Result))
9432       return false;
9433 
9434     LValue OffsetResult(Result);
9435     APSInt Alignment;
9436     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9437                               Alignment))
9438       return false;
9439     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9440 
9441     if (E->getNumArgs() > 2) {
9442       APSInt Offset;
9443       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9444         return false;
9445 
9446       int64_t AdditionalOffset = -Offset.getZExtValue();
9447       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9448     }
9449 
9450     // If there is a base object, then it must have the correct alignment.
9451     if (OffsetResult.Base) {
9452       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9453 
9454       if (BaseAlignment < Align) {
9455         Result.Designator.setInvalid();
9456         // FIXME: Add support to Diagnostic for long / long long.
9457         CCEDiag(E->getArg(0),
9458                 diag::note_constexpr_baa_insufficient_alignment) << 0
9459           << (unsigned)BaseAlignment.getQuantity()
9460           << (unsigned)Align.getQuantity();
9461         return false;
9462       }
9463     }
9464 
9465     // The offset must also have the correct alignment.
9466     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9467       Result.Designator.setInvalid();
9468 
9469       (OffsetResult.Base
9470            ? CCEDiag(E->getArg(0),
9471                      diag::note_constexpr_baa_insufficient_alignment) << 1
9472            : CCEDiag(E->getArg(0),
9473                      diag::note_constexpr_baa_value_insufficient_alignment))
9474         << (int)OffsetResult.Offset.getQuantity()
9475         << (unsigned)Align.getQuantity();
9476       return false;
9477     }
9478 
9479     return true;
9480   }
9481   case Builtin::BI__builtin_align_up:
9482   case Builtin::BI__builtin_align_down: {
9483     if (!evaluatePointer(E->getArg(0), Result))
9484       return false;
9485     APSInt Alignment;
9486     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9487                               Alignment))
9488       return false;
9489     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9490     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9491     // For align_up/align_down, we can return the same value if the alignment
9492     // is known to be greater or equal to the requested value.
9493     if (PtrAlign.getQuantity() >= Alignment)
9494       return true;
9495 
9496     // The alignment could be greater than the minimum at run-time, so we cannot
9497     // infer much about the resulting pointer value. One case is possible:
9498     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9499     // can infer the correct index if the requested alignment is smaller than
9500     // the base alignment so we can perform the computation on the offset.
9501     if (BaseAlignment.getQuantity() >= Alignment) {
9502       assert(Alignment.getBitWidth() <= 64 &&
9503              "Cannot handle > 64-bit address-space");
9504       uint64_t Alignment64 = Alignment.getZExtValue();
9505       CharUnits NewOffset = CharUnits::fromQuantity(
9506           BuiltinOp == Builtin::BI__builtin_align_down
9507               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9508               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9509       Result.adjustOffset(NewOffset - Result.Offset);
9510       // TODO: diagnose out-of-bounds values/only allow for arrays?
9511       return true;
9512     }
9513     // Otherwise, we cannot constant-evaluate the result.
9514     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9515         << Alignment;
9516     return false;
9517   }
9518   case Builtin::BI__builtin_operator_new:
9519     return HandleOperatorNewCall(Info, E, Result);
9520   case Builtin::BI__builtin_launder:
9521     return evaluatePointer(E->getArg(0), Result);
9522   case Builtin::BIstrchr:
9523   case Builtin::BIwcschr:
9524   case Builtin::BImemchr:
9525   case Builtin::BIwmemchr:
9526     if (Info.getLangOpts().CPlusPlus11)
9527       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9528           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9529           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9530     else
9531       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9532     [[fallthrough]];
9533   case Builtin::BI__builtin_strchr:
9534   case Builtin::BI__builtin_wcschr:
9535   case Builtin::BI__builtin_memchr:
9536   case Builtin::BI__builtin_char_memchr:
9537   case Builtin::BI__builtin_wmemchr: {
9538     if (!Visit(E->getArg(0)))
9539       return false;
9540     APSInt Desired;
9541     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9542       return false;
9543     uint64_t MaxLength = uint64_t(-1);
9544     if (BuiltinOp != Builtin::BIstrchr &&
9545         BuiltinOp != Builtin::BIwcschr &&
9546         BuiltinOp != Builtin::BI__builtin_strchr &&
9547         BuiltinOp != Builtin::BI__builtin_wcschr) {
9548       APSInt N;
9549       if (!EvaluateInteger(E->getArg(2), N, Info))
9550         return false;
9551       MaxLength = N.getZExtValue();
9552     }
9553     // We cannot find the value if there are no candidates to match against.
9554     if (MaxLength == 0u)
9555       return ZeroInitialization(E);
9556     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9557         Result.Designator.Invalid)
9558       return false;
9559     QualType CharTy = Result.Designator.getType(Info.Ctx);
9560     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9561                      BuiltinOp == Builtin::BI__builtin_memchr;
9562     assert(IsRawByte ||
9563            Info.Ctx.hasSameUnqualifiedType(
9564                CharTy, E->getArg(0)->getType()->getPointeeType()));
9565     // Pointers to const void may point to objects of incomplete type.
9566     if (IsRawByte && CharTy->isIncompleteType()) {
9567       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9568       return false;
9569     }
9570     // Give up on byte-oriented matching against multibyte elements.
9571     // FIXME: We can compare the bytes in the correct order.
9572     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9573       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9574           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
9575           << CharTy;
9576       return false;
9577     }
9578     // Figure out what value we're actually looking for (after converting to
9579     // the corresponding unsigned type if necessary).
9580     uint64_t DesiredVal;
9581     bool StopAtNull = false;
9582     switch (BuiltinOp) {
9583     case Builtin::BIstrchr:
9584     case Builtin::BI__builtin_strchr:
9585       // strchr compares directly to the passed integer, and therefore
9586       // always fails if given an int that is not a char.
9587       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9588                                                   E->getArg(1)->getType(),
9589                                                   Desired),
9590                                Desired))
9591         return ZeroInitialization(E);
9592       StopAtNull = true;
9593       [[fallthrough]];
9594     case Builtin::BImemchr:
9595     case Builtin::BI__builtin_memchr:
9596     case Builtin::BI__builtin_char_memchr:
9597       // memchr compares by converting both sides to unsigned char. That's also
9598       // correct for strchr if we get this far (to cope with plain char being
9599       // unsigned in the strchr case).
9600       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9601       break;
9602 
9603     case Builtin::BIwcschr:
9604     case Builtin::BI__builtin_wcschr:
9605       StopAtNull = true;
9606       [[fallthrough]];
9607     case Builtin::BIwmemchr:
9608     case Builtin::BI__builtin_wmemchr:
9609       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9610       DesiredVal = Desired.getZExtValue();
9611       break;
9612     }
9613 
9614     for (; MaxLength; --MaxLength) {
9615       APValue Char;
9616       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9617           !Char.isInt())
9618         return false;
9619       if (Char.getInt().getZExtValue() == DesiredVal)
9620         return true;
9621       if (StopAtNull && !Char.getInt())
9622         break;
9623       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9624         return false;
9625     }
9626     // Not found: return nullptr.
9627     return ZeroInitialization(E);
9628   }
9629 
9630   case Builtin::BImemcpy:
9631   case Builtin::BImemmove:
9632   case Builtin::BIwmemcpy:
9633   case Builtin::BIwmemmove:
9634     if (Info.getLangOpts().CPlusPlus11)
9635       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9636           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9637           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9638     else
9639       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9640     [[fallthrough]];
9641   case Builtin::BI__builtin_memcpy:
9642   case Builtin::BI__builtin_memmove:
9643   case Builtin::BI__builtin_wmemcpy:
9644   case Builtin::BI__builtin_wmemmove: {
9645     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9646                  BuiltinOp == Builtin::BIwmemmove ||
9647                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9648                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9649     bool Move = BuiltinOp == Builtin::BImemmove ||
9650                 BuiltinOp == Builtin::BIwmemmove ||
9651                 BuiltinOp == Builtin::BI__builtin_memmove ||
9652                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9653 
9654     // The result of mem* is the first argument.
9655     if (!Visit(E->getArg(0)))
9656       return false;
9657     LValue Dest = Result;
9658 
9659     LValue Src;
9660     if (!EvaluatePointer(E->getArg(1), Src, Info))
9661       return false;
9662 
9663     APSInt N;
9664     if (!EvaluateInteger(E->getArg(2), N, Info))
9665       return false;
9666     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9667 
9668     // If the size is zero, we treat this as always being a valid no-op.
9669     // (Even if one of the src and dest pointers is null.)
9670     if (!N)
9671       return true;
9672 
9673     // Otherwise, if either of the operands is null, we can't proceed. Don't
9674     // try to determine the type of the copied objects, because there aren't
9675     // any.
9676     if (!Src.Base || !Dest.Base) {
9677       APValue Val;
9678       (!Src.Base ? Src : Dest).moveInto(Val);
9679       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9680           << Move << WChar << !!Src.Base
9681           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9682       return false;
9683     }
9684     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9685       return false;
9686 
9687     // We require that Src and Dest are both pointers to arrays of
9688     // trivially-copyable type. (For the wide version, the designator will be
9689     // invalid if the designated object is not a wchar_t.)
9690     QualType T = Dest.Designator.getType(Info.Ctx);
9691     QualType SrcT = Src.Designator.getType(Info.Ctx);
9692     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9693       // FIXME: Consider using our bit_cast implementation to support this.
9694       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9695       return false;
9696     }
9697     if (T->isIncompleteType()) {
9698       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9699       return false;
9700     }
9701     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9702       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9703       return false;
9704     }
9705 
9706     // Figure out how many T's we're copying.
9707     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9708     if (TSize == 0)
9709       return false;
9710     if (!WChar) {
9711       uint64_t Remainder;
9712       llvm::APInt OrigN = N;
9713       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9714       if (Remainder) {
9715         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9716             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9717             << (unsigned)TSize;
9718         return false;
9719       }
9720     }
9721 
9722     // Check that the copying will remain within the arrays, just so that we
9723     // can give a more meaningful diagnostic. This implicitly also checks that
9724     // N fits into 64 bits.
9725     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9726     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9727     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9728       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9729           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9730           << toString(N, 10, /*Signed*/false);
9731       return false;
9732     }
9733     uint64_t NElems = N.getZExtValue();
9734     uint64_t NBytes = NElems * TSize;
9735 
9736     // Check for overlap.
9737     int Direction = 1;
9738     if (HasSameBase(Src, Dest)) {
9739       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9740       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9741       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9742         // Dest is inside the source region.
9743         if (!Move) {
9744           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9745           return false;
9746         }
9747         // For memmove and friends, copy backwards.
9748         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9749             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9750           return false;
9751         Direction = -1;
9752       } else if (!Move && SrcOffset >= DestOffset &&
9753                  SrcOffset - DestOffset < NBytes) {
9754         // Src is inside the destination region for memcpy: invalid.
9755         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9756         return false;
9757       }
9758     }
9759 
9760     while (true) {
9761       APValue Val;
9762       // FIXME: Set WantObjectRepresentation to true if we're copying a
9763       // char-like type?
9764       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9765           !handleAssignment(Info, E, Dest, T, Val))
9766         return false;
9767       // Do not iterate past the last element; if we're copying backwards, that
9768       // might take us off the start of the array.
9769       if (--NElems == 0)
9770         return true;
9771       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9772           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9773         return false;
9774     }
9775   }
9776 
9777   default:
9778     return false;
9779   }
9780 }
9781 
9782 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9783                                      APValue &Result, const InitListExpr *ILE,
9784                                      QualType AllocType);
9785 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9786                                           APValue &Result,
9787                                           const CXXConstructExpr *CCE,
9788                                           QualType AllocType);
9789 
VisitCXXNewExpr(const CXXNewExpr * E)9790 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9791   if (!Info.getLangOpts().CPlusPlus20)
9792     Info.CCEDiag(E, diag::note_constexpr_new);
9793 
9794   // We cannot speculatively evaluate a delete expression.
9795   if (Info.SpeculativeEvaluationDepth)
9796     return false;
9797 
9798   FunctionDecl *OperatorNew = E->getOperatorNew();
9799 
9800   bool IsNothrow = false;
9801   bool IsPlacement = false;
9802   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9803       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9804     // FIXME Support array placement new.
9805     assert(E->getNumPlacementArgs() == 1);
9806     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9807       return false;
9808     if (Result.Designator.Invalid)
9809       return false;
9810     IsPlacement = true;
9811   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9812     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9813         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9814     return false;
9815   } else if (E->getNumPlacementArgs()) {
9816     // The only new-placement list we support is of the form (std::nothrow).
9817     //
9818     // FIXME: There is no restriction on this, but it's not clear that any
9819     // other form makes any sense. We get here for cases such as:
9820     //
9821     //   new (std::align_val_t{N}) X(int)
9822     //
9823     // (which should presumably be valid only if N is a multiple of
9824     // alignof(int), and in any case can't be deallocated unless N is
9825     // alignof(X) and X has new-extended alignment).
9826     if (E->getNumPlacementArgs() != 1 ||
9827         !E->getPlacementArg(0)->getType()->isNothrowT())
9828       return Error(E, diag::note_constexpr_new_placement);
9829 
9830     LValue Nothrow;
9831     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9832       return false;
9833     IsNothrow = true;
9834   }
9835 
9836   const Expr *Init = E->getInitializer();
9837   const InitListExpr *ResizedArrayILE = nullptr;
9838   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9839   bool ValueInit = false;
9840 
9841   QualType AllocType = E->getAllocatedType();
9842   if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
9843     const Expr *Stripped = *ArraySize;
9844     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9845          Stripped = ICE->getSubExpr())
9846       if (ICE->getCastKind() != CK_NoOp &&
9847           ICE->getCastKind() != CK_IntegralCast)
9848         break;
9849 
9850     llvm::APSInt ArrayBound;
9851     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9852       return false;
9853 
9854     // C++ [expr.new]p9:
9855     //   The expression is erroneous if:
9856     //   -- [...] its value before converting to size_t [or] applying the
9857     //      second standard conversion sequence is less than zero
9858     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9859       if (IsNothrow)
9860         return ZeroInitialization(E);
9861 
9862       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9863           << ArrayBound << (*ArraySize)->getSourceRange();
9864       return false;
9865     }
9866 
9867     //   -- its value is such that the size of the allocated object would
9868     //      exceed the implementation-defined limit
9869     if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
9870                              ConstantArrayType::getNumAddressingBits(
9871                                  Info.Ctx, AllocType, ArrayBound),
9872                              ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
9873       if (IsNothrow)
9874         return ZeroInitialization(E);
9875       return false;
9876     }
9877 
9878     //   -- the new-initializer is a braced-init-list and the number of
9879     //      array elements for which initializers are provided [...]
9880     //      exceeds the number of elements to initialize
9881     if (!Init) {
9882       // No initialization is performed.
9883     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9884                isa<ImplicitValueInitExpr>(Init)) {
9885       ValueInit = true;
9886     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9887       ResizedArrayCCE = CCE;
9888     } else {
9889       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9890       assert(CAT && "unexpected type for array initializer");
9891 
9892       unsigned Bits =
9893           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9894       llvm::APInt InitBound = CAT->getSize().zext(Bits);
9895       llvm::APInt AllocBound = ArrayBound.zext(Bits);
9896       if (InitBound.ugt(AllocBound)) {
9897         if (IsNothrow)
9898           return ZeroInitialization(E);
9899 
9900         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9901             << toString(AllocBound, 10, /*Signed=*/false)
9902             << toString(InitBound, 10, /*Signed=*/false)
9903             << (*ArraySize)->getSourceRange();
9904         return false;
9905       }
9906 
9907       // If the sizes differ, we must have an initializer list, and we need
9908       // special handling for this case when we initialize.
9909       if (InitBound != AllocBound)
9910         ResizedArrayILE = cast<InitListExpr>(Init);
9911     }
9912 
9913     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9914                                               ArraySizeModifier::Normal, 0);
9915   } else {
9916     assert(!AllocType->isArrayType() &&
9917            "array allocation with non-array new");
9918   }
9919 
9920   APValue *Val;
9921   if (IsPlacement) {
9922     AccessKinds AK = AK_Construct;
9923     struct FindObjectHandler {
9924       EvalInfo &Info;
9925       const Expr *E;
9926       QualType AllocType;
9927       const AccessKinds AccessKind;
9928       APValue *Value;
9929 
9930       typedef bool result_type;
9931       bool failed() { return false; }
9932       bool found(APValue &Subobj, QualType SubobjType) {
9933         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9934         // old name of the object to be used to name the new object.
9935         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9936           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9937             SubobjType << AllocType;
9938           return false;
9939         }
9940         Value = &Subobj;
9941         return true;
9942       }
9943       bool found(APSInt &Value, QualType SubobjType) {
9944         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9945         return false;
9946       }
9947       bool found(APFloat &Value, QualType SubobjType) {
9948         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9949         return false;
9950       }
9951     } Handler = {Info, E, AllocType, AK, nullptr};
9952 
9953     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9954     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9955       return false;
9956 
9957     Val = Handler.Value;
9958 
9959     // [basic.life]p1:
9960     //   The lifetime of an object o of type T ends when [...] the storage
9961     //   which the object occupies is [...] reused by an object that is not
9962     //   nested within o (6.6.2).
9963     *Val = APValue();
9964   } else {
9965     // Perform the allocation and obtain a pointer to the resulting object.
9966     Val = Info.createHeapAlloc(E, AllocType, Result);
9967     if (!Val)
9968       return false;
9969   }
9970 
9971   if (ValueInit) {
9972     ImplicitValueInitExpr VIE(AllocType);
9973     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9974       return false;
9975   } else if (ResizedArrayILE) {
9976     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9977                                   AllocType))
9978       return false;
9979   } else if (ResizedArrayCCE) {
9980     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9981                                        AllocType))
9982       return false;
9983   } else if (Init) {
9984     if (!EvaluateInPlace(*Val, Info, Result, Init))
9985       return false;
9986   } else if (!handleDefaultInitValue(AllocType, *Val)) {
9987     return false;
9988   }
9989 
9990   // Array new returns a pointer to the first element, not a pointer to the
9991   // array.
9992   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9993     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9994 
9995   return true;
9996 }
9997 //===----------------------------------------------------------------------===//
9998 // Member Pointer Evaluation
9999 //===----------------------------------------------------------------------===//
10000 
10001 namespace {
10002 class MemberPointerExprEvaluator
10003   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10004   MemberPtr &Result;
10005 
Success(const ValueDecl * D)10006   bool Success(const ValueDecl *D) {
10007     Result = MemberPtr(D);
10008     return true;
10009   }
10010 public:
10011 
MemberPointerExprEvaluator(EvalInfo & Info,MemberPtr & Result)10012   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10013     : ExprEvaluatorBaseTy(Info), Result(Result) {}
10014 
Success(const APValue & V,const Expr * E)10015   bool Success(const APValue &V, const Expr *E) {
10016     Result.setFrom(V);
10017     return true;
10018   }
ZeroInitialization(const Expr * E)10019   bool ZeroInitialization(const Expr *E) {
10020     return Success((const ValueDecl*)nullptr);
10021   }
10022 
10023   bool VisitCastExpr(const CastExpr *E);
10024   bool VisitUnaryAddrOf(const UnaryOperator *E);
10025 };
10026 } // end anonymous namespace
10027 
EvaluateMemberPointer(const Expr * E,MemberPtr & Result,EvalInfo & Info)10028 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10029                                   EvalInfo &Info) {
10030   assert(!E->isValueDependent());
10031   assert(E->isPRValue() && E->getType()->isMemberPointerType());
10032   return MemberPointerExprEvaluator(Info, Result).Visit(E);
10033 }
10034 
VisitCastExpr(const CastExpr * E)10035 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10036   switch (E->getCastKind()) {
10037   default:
10038     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10039 
10040   case CK_NullToMemberPointer:
10041     VisitIgnoredValue(E->getSubExpr());
10042     return ZeroInitialization(E);
10043 
10044   case CK_BaseToDerivedMemberPointer: {
10045     if (!Visit(E->getSubExpr()))
10046       return false;
10047     if (E->path_empty())
10048       return true;
10049     // Base-to-derived member pointer casts store the path in derived-to-base
10050     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10051     // the wrong end of the derived->base arc, so stagger the path by one class.
10052     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10053     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10054          PathI != PathE; ++PathI) {
10055       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10056       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10057       if (!Result.castToDerived(Derived))
10058         return Error(E);
10059     }
10060     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
10061     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
10062       return Error(E);
10063     return true;
10064   }
10065 
10066   case CK_DerivedToBaseMemberPointer:
10067     if (!Visit(E->getSubExpr()))
10068       return false;
10069     for (CastExpr::path_const_iterator PathI = E->path_begin(),
10070          PathE = E->path_end(); PathI != PathE; ++PathI) {
10071       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10072       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10073       if (!Result.castToBase(Base))
10074         return Error(E);
10075     }
10076     return true;
10077   }
10078 }
10079 
VisitUnaryAddrOf(const UnaryOperator * E)10080 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10081   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10082   // member can be formed.
10083   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10084 }
10085 
10086 //===----------------------------------------------------------------------===//
10087 // Record Evaluation
10088 //===----------------------------------------------------------------------===//
10089 
10090 namespace {
10091   class RecordExprEvaluator
10092   : public ExprEvaluatorBase<RecordExprEvaluator> {
10093     const LValue &This;
10094     APValue &Result;
10095   public:
10096 
RecordExprEvaluator(EvalInfo & info,const LValue & This,APValue & Result)10097     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10098       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10099 
Success(const APValue & V,const Expr * E)10100     bool Success(const APValue &V, const Expr *E) {
10101       Result = V;
10102       return true;
10103     }
ZeroInitialization(const Expr * E)10104     bool ZeroInitialization(const Expr *E) {
10105       return ZeroInitialization(E, E->getType());
10106     }
10107     bool ZeroInitialization(const Expr *E, QualType T);
10108 
VisitCallExpr(const CallExpr * E)10109     bool VisitCallExpr(const CallExpr *E) {
10110       return handleCallExpr(E, Result, &This);
10111     }
10112     bool VisitCastExpr(const CastExpr *E);
10113     bool VisitInitListExpr(const InitListExpr *E);
VisitCXXConstructExpr(const CXXConstructExpr * E)10114     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10115       return VisitCXXConstructExpr(E, E->getType());
10116     }
10117     bool VisitLambdaExpr(const LambdaExpr *E);
10118     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10119     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10120     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10121     bool VisitBinCmp(const BinaryOperator *E);
10122     bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10123     bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10124                                          ArrayRef<Expr *> Args);
10125   };
10126 }
10127 
10128 /// Perform zero-initialization on an object of non-union class type.
10129 /// C++11 [dcl.init]p5:
10130 ///  To zero-initialize an object or reference of type T means:
10131 ///    [...]
10132 ///    -- if T is a (possibly cv-qualified) non-union class type,
10133 ///       each non-static data member and each base-class subobject is
10134 ///       zero-initialized
HandleClassZeroInitialization(EvalInfo & Info,const Expr * E,const RecordDecl * RD,const LValue & This,APValue & Result)10135 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10136                                           const RecordDecl *RD,
10137                                           const LValue &This, APValue &Result) {
10138   assert(!RD->isUnion() && "Expected non-union class type");
10139   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10140   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10141                    std::distance(RD->field_begin(), RD->field_end()));
10142 
10143   if (RD->isInvalidDecl()) return false;
10144   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10145 
10146   if (CD) {
10147     unsigned Index = 0;
10148     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
10149            End = CD->bases_end(); I != End; ++I, ++Index) {
10150       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10151       LValue Subobject = This;
10152       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10153         return false;
10154       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10155                                          Result.getStructBase(Index)))
10156         return false;
10157     }
10158   }
10159 
10160   for (const auto *I : RD->fields()) {
10161     // -- if T is a reference type, no initialization is performed.
10162     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
10163       continue;
10164 
10165     LValue Subobject = This;
10166     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10167       return false;
10168 
10169     ImplicitValueInitExpr VIE(I->getType());
10170     if (!EvaluateInPlace(
10171           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10172       return false;
10173   }
10174 
10175   return true;
10176 }
10177 
ZeroInitialization(const Expr * E,QualType T)10178 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10179   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
10180   if (RD->isInvalidDecl()) return false;
10181   if (RD->isUnion()) {
10182     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10183     // object's first non-static named data member is zero-initialized
10184     RecordDecl::field_iterator I = RD->field_begin();
10185     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
10186       ++I;
10187     if (I == RD->field_end()) {
10188       Result = APValue((const FieldDecl*)nullptr);
10189       return true;
10190     }
10191 
10192     LValue Subobject = This;
10193     if (!HandleLValueMember(Info, E, Subobject, *I))
10194       return false;
10195     Result = APValue(*I);
10196     ImplicitValueInitExpr VIE(I->getType());
10197     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10198   }
10199 
10200   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10201     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10202     return false;
10203   }
10204 
10205   return HandleClassZeroInitialization(Info, E, RD, This, Result);
10206 }
10207 
VisitCastExpr(const CastExpr * E)10208 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10209   switch (E->getCastKind()) {
10210   default:
10211     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10212 
10213   case CK_ConstructorConversion:
10214     return Visit(E->getSubExpr());
10215 
10216   case CK_DerivedToBase:
10217   case CK_UncheckedDerivedToBase: {
10218     APValue DerivedObject;
10219     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10220       return false;
10221     if (!DerivedObject.isStruct())
10222       return Error(E->getSubExpr());
10223 
10224     // Derived-to-base rvalue conversion: just slice off the derived part.
10225     APValue *Value = &DerivedObject;
10226     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10227     for (CastExpr::path_const_iterator PathI = E->path_begin(),
10228          PathE = E->path_end(); PathI != PathE; ++PathI) {
10229       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10230       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10231       Value = &Value->getStructBase(getBaseIndex(RD, Base));
10232       RD = Base;
10233     }
10234     Result = *Value;
10235     return true;
10236   }
10237   }
10238 }
10239 
VisitInitListExpr(const InitListExpr * E)10240 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10241   if (E->isTransparent())
10242     return Visit(E->getInit(0));
10243   return VisitCXXParenListOrInitListExpr(E, E->inits());
10244 }
10245 
VisitCXXParenListOrInitListExpr(const Expr * ExprToVisit,ArrayRef<Expr * > Args)10246 bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10247     const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10248   const RecordDecl *RD =
10249       ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10250   if (RD->isInvalidDecl()) return false;
10251   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10252   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10253 
10254   EvalInfo::EvaluatingConstructorRAII EvalObj(
10255       Info,
10256       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10257       CXXRD && CXXRD->getNumBases());
10258 
10259   if (RD->isUnion()) {
10260     const FieldDecl *Field;
10261     if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10262       Field = ILE->getInitializedFieldInUnion();
10263     } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10264       Field = PLIE->getInitializedFieldInUnion();
10265     } else {
10266       llvm_unreachable(
10267           "Expression is neither an init list nor a C++ paren list");
10268     }
10269 
10270     Result = APValue(Field);
10271     if (!Field)
10272       return true;
10273 
10274     // If the initializer list for a union does not contain any elements, the
10275     // first element of the union is value-initialized.
10276     // FIXME: The element should be initialized from an initializer list.
10277     //        Is this difference ever observable for initializer lists which
10278     //        we don't build?
10279     ImplicitValueInitExpr VIE(Field->getType());
10280     const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10281 
10282     LValue Subobject = This;
10283     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10284       return false;
10285 
10286     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10287     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10288                                   isa<CXXDefaultInitExpr>(InitExpr));
10289 
10290     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10291       if (Field->isBitField())
10292         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10293                                      Field);
10294       return true;
10295     }
10296 
10297     return false;
10298   }
10299 
10300   if (!Result.hasValue())
10301     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10302                      std::distance(RD->field_begin(), RD->field_end()));
10303   unsigned ElementNo = 0;
10304   bool Success = true;
10305 
10306   // Initialize base classes.
10307   if (CXXRD && CXXRD->getNumBases()) {
10308     for (const auto &Base : CXXRD->bases()) {
10309       assert(ElementNo < Args.size() && "missing init for base class");
10310       const Expr *Init = Args[ElementNo];
10311 
10312       LValue Subobject = This;
10313       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10314         return false;
10315 
10316       APValue &FieldVal = Result.getStructBase(ElementNo);
10317       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10318         if (!Info.noteFailure())
10319           return false;
10320         Success = false;
10321       }
10322       ++ElementNo;
10323     }
10324 
10325     EvalObj.finishedConstructingBases();
10326   }
10327 
10328   // Initialize members.
10329   for (const auto *Field : RD->fields()) {
10330     // Anonymous bit-fields are not considered members of the class for
10331     // purposes of aggregate initialization.
10332     if (Field->isUnnamedBitfield())
10333       continue;
10334 
10335     LValue Subobject = This;
10336 
10337     bool HaveInit = ElementNo < Args.size();
10338 
10339     // FIXME: Diagnostics here should point to the end of the initializer
10340     // list, not the start.
10341     if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10342                             Subobject, Field, &Layout))
10343       return false;
10344 
10345     // Perform an implicit value-initialization for members beyond the end of
10346     // the initializer list.
10347     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10348     const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10349 
10350     if (Field->getType()->isIncompleteArrayType()) {
10351       if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10352         if (!CAT->getSize().isZero()) {
10353           // Bail out for now. This might sort of "work", but the rest of the
10354           // code isn't really prepared to handle it.
10355           Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10356           return false;
10357         }
10358       }
10359     }
10360 
10361     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10362     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10363                                   isa<CXXDefaultInitExpr>(Init));
10364 
10365     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10366     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10367         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10368                                                        FieldVal, Field))) {
10369       if (!Info.noteFailure())
10370         return false;
10371       Success = false;
10372     }
10373   }
10374 
10375   EvalObj.finishedConstructingFields();
10376 
10377   return Success;
10378 }
10379 
VisitCXXConstructExpr(const CXXConstructExpr * E,QualType T)10380 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10381                                                 QualType T) {
10382   // Note that E's type is not necessarily the type of our class here; we might
10383   // be initializing an array element instead.
10384   const CXXConstructorDecl *FD = E->getConstructor();
10385   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10386 
10387   bool ZeroInit = E->requiresZeroInitialization();
10388   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10389     // If we've already performed zero-initialization, we're already done.
10390     if (Result.hasValue())
10391       return true;
10392 
10393     if (ZeroInit)
10394       return ZeroInitialization(E, T);
10395 
10396     return handleDefaultInitValue(T, Result);
10397   }
10398 
10399   const FunctionDecl *Definition = nullptr;
10400   auto Body = FD->getBody(Definition);
10401 
10402   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10403     return false;
10404 
10405   // Avoid materializing a temporary for an elidable copy/move constructor.
10406   if (E->isElidable() && !ZeroInit) {
10407     // FIXME: This only handles the simplest case, where the source object
10408     //        is passed directly as the first argument to the constructor.
10409     //        This should also handle stepping though implicit casts and
10410     //        and conversion sequences which involve two steps, with a
10411     //        conversion operator followed by a converting constructor.
10412     const Expr *SrcObj = E->getArg(0);
10413     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10414     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10415     if (const MaterializeTemporaryExpr *ME =
10416             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10417       return Visit(ME->getSubExpr());
10418   }
10419 
10420   if (ZeroInit && !ZeroInitialization(E, T))
10421     return false;
10422 
10423   auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10424   return HandleConstructorCall(E, This, Args,
10425                                cast<CXXConstructorDecl>(Definition), Info,
10426                                Result);
10427 }
10428 
VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr * E)10429 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10430     const CXXInheritedCtorInitExpr *E) {
10431   if (!Info.CurrentCall) {
10432     assert(Info.checkingPotentialConstantExpression());
10433     return false;
10434   }
10435 
10436   const CXXConstructorDecl *FD = E->getConstructor();
10437   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10438     return false;
10439 
10440   const FunctionDecl *Definition = nullptr;
10441   auto Body = FD->getBody(Definition);
10442 
10443   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10444     return false;
10445 
10446   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10447                                cast<CXXConstructorDecl>(Definition), Info,
10448                                Result);
10449 }
10450 
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)10451 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10452     const CXXStdInitializerListExpr *E) {
10453   const ConstantArrayType *ArrayType =
10454       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10455 
10456   LValue Array;
10457   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10458     return false;
10459 
10460   assert(ArrayType && "unexpected type for array initializer");
10461 
10462   // Get a pointer to the first element of the array.
10463   Array.addArray(Info, E, ArrayType);
10464 
10465   auto InvalidType = [&] {
10466     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10467       << E->getType();
10468     return false;
10469   };
10470 
10471   // FIXME: Perform the checks on the field types in SemaInit.
10472   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10473   RecordDecl::field_iterator Field = Record->field_begin();
10474   if (Field == Record->field_end())
10475     return InvalidType();
10476 
10477   // Start pointer.
10478   if (!Field->getType()->isPointerType() ||
10479       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10480                             ArrayType->getElementType()))
10481     return InvalidType();
10482 
10483   // FIXME: What if the initializer_list type has base classes, etc?
10484   Result = APValue(APValue::UninitStruct(), 0, 2);
10485   Array.moveInto(Result.getStructField(0));
10486 
10487   if (++Field == Record->field_end())
10488     return InvalidType();
10489 
10490   if (Field->getType()->isPointerType() &&
10491       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10492                            ArrayType->getElementType())) {
10493     // End pointer.
10494     if (!HandleLValueArrayAdjustment(Info, E, Array,
10495                                      ArrayType->getElementType(),
10496                                      ArrayType->getSize().getZExtValue()))
10497       return false;
10498     Array.moveInto(Result.getStructField(1));
10499   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10500     // Length.
10501     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10502   else
10503     return InvalidType();
10504 
10505   if (++Field != Record->field_end())
10506     return InvalidType();
10507 
10508   return true;
10509 }
10510 
VisitLambdaExpr(const LambdaExpr * E)10511 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10512   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10513   if (ClosureClass->isInvalidDecl())
10514     return false;
10515 
10516   const size_t NumFields =
10517       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10518 
10519   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10520                                             E->capture_init_end()) &&
10521          "The number of lambda capture initializers should equal the number of "
10522          "fields within the closure type");
10523 
10524   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10525   // Iterate through all the lambda's closure object's fields and initialize
10526   // them.
10527   auto *CaptureInitIt = E->capture_init_begin();
10528   bool Success = true;
10529   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10530   for (const auto *Field : ClosureClass->fields()) {
10531     assert(CaptureInitIt != E->capture_init_end());
10532     // Get the initializer for this field
10533     Expr *const CurFieldInit = *CaptureInitIt++;
10534 
10535     // If there is no initializer, either this is a VLA or an error has
10536     // occurred.
10537     if (!CurFieldInit)
10538       return Error(E);
10539 
10540     LValue Subobject = This;
10541 
10542     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10543       return false;
10544 
10545     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10546     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10547       if (!Info.keepEvaluatingAfterFailure())
10548         return false;
10549       Success = false;
10550     }
10551   }
10552   return Success;
10553 }
10554 
EvaluateRecord(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)10555 static bool EvaluateRecord(const Expr *E, const LValue &This,
10556                            APValue &Result, EvalInfo &Info) {
10557   assert(!E->isValueDependent());
10558   assert(E->isPRValue() && E->getType()->isRecordType() &&
10559          "can't evaluate expression as a record rvalue");
10560   return RecordExprEvaluator(Info, This, Result).Visit(E);
10561 }
10562 
10563 //===----------------------------------------------------------------------===//
10564 // Temporary Evaluation
10565 //
10566 // Temporaries are represented in the AST as rvalues, but generally behave like
10567 // lvalues. The full-object of which the temporary is a subobject is implicitly
10568 // materialized so that a reference can bind to it.
10569 //===----------------------------------------------------------------------===//
10570 namespace {
10571 class TemporaryExprEvaluator
10572   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10573 public:
TemporaryExprEvaluator(EvalInfo & Info,LValue & Result)10574   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10575     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10576 
10577   /// Visit an expression which constructs the value of this temporary.
VisitConstructExpr(const Expr * E)10578   bool VisitConstructExpr(const Expr *E) {
10579     APValue &Value = Info.CurrentCall->createTemporary(
10580         E, E->getType(), ScopeKind::FullExpression, Result);
10581     return EvaluateInPlace(Value, Info, Result, E);
10582   }
10583 
VisitCastExpr(const CastExpr * E)10584   bool VisitCastExpr(const CastExpr *E) {
10585     switch (E->getCastKind()) {
10586     default:
10587       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10588 
10589     case CK_ConstructorConversion:
10590       return VisitConstructExpr(E->getSubExpr());
10591     }
10592   }
VisitInitListExpr(const InitListExpr * E)10593   bool VisitInitListExpr(const InitListExpr *E) {
10594     return VisitConstructExpr(E);
10595   }
VisitCXXConstructExpr(const CXXConstructExpr * E)10596   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10597     return VisitConstructExpr(E);
10598   }
VisitCallExpr(const CallExpr * E)10599   bool VisitCallExpr(const CallExpr *E) {
10600     return VisitConstructExpr(E);
10601   }
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)10602   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10603     return VisitConstructExpr(E);
10604   }
VisitLambdaExpr(const LambdaExpr * E)10605   bool VisitLambdaExpr(const LambdaExpr *E) {
10606     return VisitConstructExpr(E);
10607   }
10608 };
10609 } // end anonymous namespace
10610 
10611 /// Evaluate an expression of record type as a temporary.
EvaluateTemporary(const Expr * E,LValue & Result,EvalInfo & Info)10612 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10613   assert(!E->isValueDependent());
10614   assert(E->isPRValue() && E->getType()->isRecordType());
10615   return TemporaryExprEvaluator(Info, Result).Visit(E);
10616 }
10617 
10618 //===----------------------------------------------------------------------===//
10619 // Vector Evaluation
10620 //===----------------------------------------------------------------------===//
10621 
10622 namespace {
10623   class VectorExprEvaluator
10624   : public ExprEvaluatorBase<VectorExprEvaluator> {
10625     APValue &Result;
10626   public:
10627 
VectorExprEvaluator(EvalInfo & info,APValue & Result)10628     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10629       : ExprEvaluatorBaseTy(info), Result(Result) {}
10630 
Success(ArrayRef<APValue> V,const Expr * E)10631     bool Success(ArrayRef<APValue> V, const Expr *E) {
10632       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10633       // FIXME: remove this APValue copy.
10634       Result = APValue(V.data(), V.size());
10635       return true;
10636     }
Success(const APValue & V,const Expr * E)10637     bool Success(const APValue &V, const Expr *E) {
10638       assert(V.isVector());
10639       Result = V;
10640       return true;
10641     }
10642     bool ZeroInitialization(const Expr *E);
10643 
VisitUnaryReal(const UnaryOperator * E)10644     bool VisitUnaryReal(const UnaryOperator *E)
10645       { return Visit(E->getSubExpr()); }
10646     bool VisitCastExpr(const CastExpr* E);
10647     bool VisitInitListExpr(const InitListExpr *E);
10648     bool VisitUnaryImag(const UnaryOperator *E);
10649     bool VisitBinaryOperator(const BinaryOperator *E);
10650     bool VisitUnaryOperator(const UnaryOperator *E);
10651     // FIXME: Missing: conditional operator (for GNU
10652     //                 conditional select), shufflevector, ExtVectorElementExpr
10653   };
10654 } // end anonymous namespace
10655 
EvaluateVector(const Expr * E,APValue & Result,EvalInfo & Info)10656 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10657   assert(E->isPRValue() && E->getType()->isVectorType() &&
10658          "not a vector prvalue");
10659   return VectorExprEvaluator(Info, Result).Visit(E);
10660 }
10661 
VisitCastExpr(const CastExpr * E)10662 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10663   const VectorType *VTy = E->getType()->castAs<VectorType>();
10664   unsigned NElts = VTy->getNumElements();
10665 
10666   const Expr *SE = E->getSubExpr();
10667   QualType SETy = SE->getType();
10668 
10669   switch (E->getCastKind()) {
10670   case CK_VectorSplat: {
10671     APValue Val = APValue();
10672     if (SETy->isIntegerType()) {
10673       APSInt IntResult;
10674       if (!EvaluateInteger(SE, IntResult, Info))
10675         return false;
10676       Val = APValue(std::move(IntResult));
10677     } else if (SETy->isRealFloatingType()) {
10678       APFloat FloatResult(0.0);
10679       if (!EvaluateFloat(SE, FloatResult, Info))
10680         return false;
10681       Val = APValue(std::move(FloatResult));
10682     } else {
10683       return Error(E);
10684     }
10685 
10686     // Splat and create vector APValue.
10687     SmallVector<APValue, 4> Elts(NElts, Val);
10688     return Success(Elts, E);
10689   }
10690   case CK_BitCast: {
10691     APValue SVal;
10692     if (!Evaluate(SVal, Info, SE))
10693       return false;
10694 
10695     if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
10696       // Give up if the input isn't an int, float, or vector.  For example, we
10697       // reject "(v4i16)(intptr_t)&a".
10698       Info.FFDiag(E, diag::note_constexpr_invalid_cast)
10699           << 2 << Info.Ctx.getLangOpts().CPlusPlus;
10700       return false;
10701     }
10702 
10703     if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
10704       return false;
10705 
10706     return true;
10707   }
10708   default:
10709     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10710   }
10711 }
10712 
10713 bool
VisitInitListExpr(const InitListExpr * E)10714 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10715   const VectorType *VT = E->getType()->castAs<VectorType>();
10716   unsigned NumInits = E->getNumInits();
10717   unsigned NumElements = VT->getNumElements();
10718 
10719   QualType EltTy = VT->getElementType();
10720   SmallVector<APValue, 4> Elements;
10721 
10722   // The number of initializers can be less than the number of
10723   // vector elements. For OpenCL, this can be due to nested vector
10724   // initialization. For GCC compatibility, missing trailing elements
10725   // should be initialized with zeroes.
10726   unsigned CountInits = 0, CountElts = 0;
10727   while (CountElts < NumElements) {
10728     // Handle nested vector initialization.
10729     if (CountInits < NumInits
10730         && E->getInit(CountInits)->getType()->isVectorType()) {
10731       APValue v;
10732       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10733         return Error(E);
10734       unsigned vlen = v.getVectorLength();
10735       for (unsigned j = 0; j < vlen; j++)
10736         Elements.push_back(v.getVectorElt(j));
10737       CountElts += vlen;
10738     } else if (EltTy->isIntegerType()) {
10739       llvm::APSInt sInt(32);
10740       if (CountInits < NumInits) {
10741         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10742           return false;
10743       } else // trailing integer zero.
10744         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10745       Elements.push_back(APValue(sInt));
10746       CountElts++;
10747     } else {
10748       llvm::APFloat f(0.0);
10749       if (CountInits < NumInits) {
10750         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10751           return false;
10752       } else // trailing float zero.
10753         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10754       Elements.push_back(APValue(f));
10755       CountElts++;
10756     }
10757     CountInits++;
10758   }
10759   return Success(Elements, E);
10760 }
10761 
10762 bool
ZeroInitialization(const Expr * E)10763 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10764   const auto *VT = E->getType()->castAs<VectorType>();
10765   QualType EltTy = VT->getElementType();
10766   APValue ZeroElement;
10767   if (EltTy->isIntegerType())
10768     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10769   else
10770     ZeroElement =
10771         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10772 
10773   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10774   return Success(Elements, E);
10775 }
10776 
VisitUnaryImag(const UnaryOperator * E)10777 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10778   VisitIgnoredValue(E->getSubExpr());
10779   return ZeroInitialization(E);
10780 }
10781 
VisitBinaryOperator(const BinaryOperator * E)10782 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10783   BinaryOperatorKind Op = E->getOpcode();
10784   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10785          "Operation not supported on vector types");
10786 
10787   if (Op == BO_Comma)
10788     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10789 
10790   Expr *LHS = E->getLHS();
10791   Expr *RHS = E->getRHS();
10792 
10793   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10794          "Must both be vector types");
10795   // Checking JUST the types are the same would be fine, except shifts don't
10796   // need to have their types be the same (since you always shift by an int).
10797   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10798              E->getType()->castAs<VectorType>()->getNumElements() &&
10799          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10800              E->getType()->castAs<VectorType>()->getNumElements() &&
10801          "All operands must be the same size.");
10802 
10803   APValue LHSValue;
10804   APValue RHSValue;
10805   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10806   if (!LHSOK && !Info.noteFailure())
10807     return false;
10808   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10809     return false;
10810 
10811   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10812     return false;
10813 
10814   return Success(LHSValue, E);
10815 }
10816 
handleVectorUnaryOperator(ASTContext & Ctx,QualType ResultTy,UnaryOperatorKind Op,APValue Elt)10817 static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10818                                                         QualType ResultTy,
10819                                                         UnaryOperatorKind Op,
10820                                                         APValue Elt) {
10821   switch (Op) {
10822   case UO_Plus:
10823     // Nothing to do here.
10824     return Elt;
10825   case UO_Minus:
10826     if (Elt.getKind() == APValue::Int) {
10827       Elt.getInt().negate();
10828     } else {
10829       assert(Elt.getKind() == APValue::Float &&
10830              "Vector can only be int or float type");
10831       Elt.getFloat().changeSign();
10832     }
10833     return Elt;
10834   case UO_Not:
10835     // This is only valid for integral types anyway, so we don't have to handle
10836     // float here.
10837     assert(Elt.getKind() == APValue::Int &&
10838            "Vector operator ~ can only be int");
10839     Elt.getInt().flipAllBits();
10840     return Elt;
10841   case UO_LNot: {
10842     if (Elt.getKind() == APValue::Int) {
10843       Elt.getInt() = !Elt.getInt();
10844       // operator ! on vectors returns -1 for 'truth', so negate it.
10845       Elt.getInt().negate();
10846       return Elt;
10847     }
10848     assert(Elt.getKind() == APValue::Float &&
10849            "Vector can only be int or float type");
10850     // Float types result in an int of the same size, but -1 for true, or 0 for
10851     // false.
10852     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10853                      ResultTy->isUnsignedIntegerType()};
10854     if (Elt.getFloat().isZero())
10855       EltResult.setAllBits();
10856     else
10857       EltResult.clearAllBits();
10858 
10859     return APValue{EltResult};
10860   }
10861   default:
10862     // FIXME: Implement the rest of the unary operators.
10863     return std::nullopt;
10864   }
10865 }
10866 
VisitUnaryOperator(const UnaryOperator * E)10867 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10868   Expr *SubExpr = E->getSubExpr();
10869   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10870   // This result element type differs in the case of negating a floating point
10871   // vector, since the result type is the a vector of the equivilant sized
10872   // integer.
10873   const QualType ResultEltTy = VD->getElementType();
10874   UnaryOperatorKind Op = E->getOpcode();
10875 
10876   APValue SubExprValue;
10877   if (!Evaluate(SubExprValue, Info, SubExpr))
10878     return false;
10879 
10880   // FIXME: This vector evaluator someday needs to be changed to be LValue
10881   // aware/keep LValue information around, rather than dealing with just vector
10882   // types directly. Until then, we cannot handle cases where the operand to
10883   // these unary operators is an LValue. The only case I've been able to see
10884   // cause this is operator++ assigning to a member expression (only valid in
10885   // altivec compilations) in C mode, so this shouldn't limit us too much.
10886   if (SubExprValue.isLValue())
10887     return false;
10888 
10889   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10890          "Vector length doesn't match type?");
10891 
10892   SmallVector<APValue, 4> ResultElements;
10893   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10894     std::optional<APValue> Elt = handleVectorUnaryOperator(
10895         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10896     if (!Elt)
10897       return false;
10898     ResultElements.push_back(*Elt);
10899   }
10900   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10901 }
10902 
10903 //===----------------------------------------------------------------------===//
10904 // Array Evaluation
10905 //===----------------------------------------------------------------------===//
10906 
10907 namespace {
10908   class ArrayExprEvaluator
10909   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10910     const LValue &This;
10911     APValue &Result;
10912   public:
10913 
ArrayExprEvaluator(EvalInfo & Info,const LValue & This,APValue & Result)10914     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10915       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10916 
Success(const APValue & V,const Expr * E)10917     bool Success(const APValue &V, const Expr *E) {
10918       assert(V.isArray() && "expected array");
10919       Result = V;
10920       return true;
10921     }
10922 
ZeroInitialization(const Expr * E)10923     bool ZeroInitialization(const Expr *E) {
10924       const ConstantArrayType *CAT =
10925           Info.Ctx.getAsConstantArrayType(E->getType());
10926       if (!CAT) {
10927         if (E->getType()->isIncompleteArrayType()) {
10928           // We can be asked to zero-initialize a flexible array member; this
10929           // is represented as an ImplicitValueInitExpr of incomplete array
10930           // type. In this case, the array has zero elements.
10931           Result = APValue(APValue::UninitArray(), 0, 0);
10932           return true;
10933         }
10934         // FIXME: We could handle VLAs here.
10935         return Error(E);
10936       }
10937 
10938       Result = APValue(APValue::UninitArray(), 0,
10939                        CAT->getSize().getZExtValue());
10940       if (!Result.hasArrayFiller())
10941         return true;
10942 
10943       // Zero-initialize all elements.
10944       LValue Subobject = This;
10945       Subobject.addArray(Info, E, CAT);
10946       ImplicitValueInitExpr VIE(CAT->getElementType());
10947       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10948     }
10949 
VisitCallExpr(const CallExpr * E)10950     bool VisitCallExpr(const CallExpr *E) {
10951       return handleCallExpr(E, Result, &This);
10952     }
10953     bool VisitInitListExpr(const InitListExpr *E,
10954                            QualType AllocType = QualType());
10955     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10956     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10957     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10958                                const LValue &Subobject,
10959                                APValue *Value, QualType Type);
VisitStringLiteral(const StringLiteral * E,QualType AllocType=QualType ())10960     bool VisitStringLiteral(const StringLiteral *E,
10961                             QualType AllocType = QualType()) {
10962       expandStringLiteral(Info, E, Result, AllocType);
10963       return true;
10964     }
10965     bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10966     bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10967                                          ArrayRef<Expr *> Args,
10968                                          const Expr *ArrayFiller,
10969                                          QualType AllocType = QualType());
10970   };
10971 } // end anonymous namespace
10972 
EvaluateArray(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)10973 static bool EvaluateArray(const Expr *E, const LValue &This,
10974                           APValue &Result, EvalInfo &Info) {
10975   assert(!E->isValueDependent());
10976   assert(E->isPRValue() && E->getType()->isArrayType() &&
10977          "not an array prvalue");
10978   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10979 }
10980 
EvaluateArrayNewInitList(EvalInfo & Info,LValue & This,APValue & Result,const InitListExpr * ILE,QualType AllocType)10981 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10982                                      APValue &Result, const InitListExpr *ILE,
10983                                      QualType AllocType) {
10984   assert(!ILE->isValueDependent());
10985   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10986          "not an array prvalue");
10987   return ArrayExprEvaluator(Info, This, Result)
10988       .VisitInitListExpr(ILE, AllocType);
10989 }
10990 
EvaluateArrayNewConstructExpr(EvalInfo & Info,LValue & This,APValue & Result,const CXXConstructExpr * CCE,QualType AllocType)10991 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10992                                           APValue &Result,
10993                                           const CXXConstructExpr *CCE,
10994                                           QualType AllocType) {
10995   assert(!CCE->isValueDependent());
10996   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10997          "not an array prvalue");
10998   return ArrayExprEvaluator(Info, This, Result)
10999       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
11000 }
11001 
11002 // Return true iff the given array filler may depend on the element index.
MaybeElementDependentArrayFiller(const Expr * FillerExpr)11003 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
11004   // For now, just allow non-class value-initialization and initialization
11005   // lists comprised of them.
11006   if (isa<ImplicitValueInitExpr>(FillerExpr))
11007     return false;
11008   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
11009     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
11010       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
11011         return true;
11012     }
11013 
11014     if (ILE->hasArrayFiller() &&
11015         MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
11016       return true;
11017 
11018     return false;
11019   }
11020   return true;
11021 }
11022 
VisitInitListExpr(const InitListExpr * E,QualType AllocType)11023 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
11024                                            QualType AllocType) {
11025   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11026       AllocType.isNull() ? E->getType() : AllocType);
11027   if (!CAT)
11028     return Error(E);
11029 
11030   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
11031   // an appropriately-typed string literal enclosed in braces.
11032   if (E->isStringLiteralInit()) {
11033     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
11034     // FIXME: Support ObjCEncodeExpr here once we support it in
11035     // ArrayExprEvaluator generally.
11036     if (!SL)
11037       return Error(E);
11038     return VisitStringLiteral(SL, AllocType);
11039   }
11040   // Any other transparent list init will need proper handling of the
11041   // AllocType; we can't just recurse to the inner initializer.
11042   assert(!E->isTransparent() &&
11043          "transparent array list initialization is not string literal init?");
11044 
11045   return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
11046                                          AllocType);
11047 }
11048 
VisitCXXParenListOrInitListExpr(const Expr * ExprToVisit,ArrayRef<Expr * > Args,const Expr * ArrayFiller,QualType AllocType)11049 bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
11050     const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
11051     QualType AllocType) {
11052   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11053       AllocType.isNull() ? ExprToVisit->getType() : AllocType);
11054 
11055   bool Success = true;
11056 
11057   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
11058          "zero-initialized array shouldn't have any initialized elts");
11059   APValue Filler;
11060   if (Result.isArray() && Result.hasArrayFiller())
11061     Filler = Result.getArrayFiller();
11062 
11063   unsigned NumEltsToInit = Args.size();
11064   unsigned NumElts = CAT->getSize().getZExtValue();
11065 
11066   // If the initializer might depend on the array index, run it for each
11067   // array element.
11068   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(ArrayFiller))
11069     NumEltsToInit = NumElts;
11070 
11071   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
11072                           << NumEltsToInit << ".\n");
11073 
11074   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
11075 
11076   // If the array was previously zero-initialized, preserve the
11077   // zero-initialized values.
11078   if (Filler.hasValue()) {
11079     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
11080       Result.getArrayInitializedElt(I) = Filler;
11081     if (Result.hasArrayFiller())
11082       Result.getArrayFiller() = Filler;
11083   }
11084 
11085   LValue Subobject = This;
11086   Subobject.addArray(Info, ExprToVisit, CAT);
11087   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
11088     const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
11089     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11090                          Info, Subobject, Init) ||
11091         !HandleLValueArrayAdjustment(Info, Init, Subobject,
11092                                      CAT->getElementType(), 1)) {
11093       if (!Info.noteFailure())
11094         return false;
11095       Success = false;
11096     }
11097   }
11098 
11099   if (!Result.hasArrayFiller())
11100     return Success;
11101 
11102   // If we get here, we have a trivial filler, which we can just evaluate
11103   // once and splat over the rest of the array elements.
11104   assert(ArrayFiller && "no array filler for incomplete init list");
11105   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
11106                          ArrayFiller) &&
11107          Success;
11108 }
11109 
VisitArrayInitLoopExpr(const ArrayInitLoopExpr * E)11110 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
11111   LValue CommonLV;
11112   if (E->getCommonExpr() &&
11113       !Evaluate(Info.CurrentCall->createTemporary(
11114                     E->getCommonExpr(),
11115                     getStorageType(Info.Ctx, E->getCommonExpr()),
11116                     ScopeKind::FullExpression, CommonLV),
11117                 Info, E->getCommonExpr()->getSourceExpr()))
11118     return false;
11119 
11120   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
11121 
11122   uint64_t Elements = CAT->getSize().getZExtValue();
11123   Result = APValue(APValue::UninitArray(), Elements, Elements);
11124 
11125   LValue Subobject = This;
11126   Subobject.addArray(Info, E, CAT);
11127 
11128   bool Success = true;
11129   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
11130     // C++ [class.temporary]/5
11131     // There are four contexts in which temporaries are destroyed at a different
11132     // point than the end of the full-expression. [...] The second context is
11133     // when a copy constructor is called to copy an element of an array while
11134     // the entire array is copied [...]. In either case, if the constructor has
11135     // one or more default arguments, the destruction of every temporary created
11136     // in a default argument is sequenced before the construction of the next
11137     // array element, if any.
11138     FullExpressionRAII Scope(Info);
11139 
11140     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11141                          Info, Subobject, E->getSubExpr()) ||
11142         !HandleLValueArrayAdjustment(Info, E, Subobject,
11143                                      CAT->getElementType(), 1)) {
11144       if (!Info.noteFailure())
11145         return false;
11146       Success = false;
11147     }
11148 
11149     // Make sure we run the destructors too.
11150     Scope.destroy();
11151   }
11152 
11153   return Success;
11154 }
11155 
VisitCXXConstructExpr(const CXXConstructExpr * E)11156 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
11157   return VisitCXXConstructExpr(E, This, &Result, E->getType());
11158 }
11159 
VisitCXXConstructExpr(const CXXConstructExpr * E,const LValue & Subobject,APValue * Value,QualType Type)11160 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11161                                                const LValue &Subobject,
11162                                                APValue *Value,
11163                                                QualType Type) {
11164   bool HadZeroInit = Value->hasValue();
11165 
11166   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
11167     unsigned FinalSize = CAT->getSize().getZExtValue();
11168 
11169     // Preserve the array filler if we had prior zero-initialization.
11170     APValue Filler =
11171       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
11172                                              : APValue();
11173 
11174     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
11175     if (FinalSize == 0)
11176       return true;
11177 
11178     bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
11179         Info, E->getExprLoc(), E->getConstructor(),
11180         E->requiresZeroInitialization());
11181     LValue ArrayElt = Subobject;
11182     ArrayElt.addArray(Info, E, CAT);
11183     // We do the whole initialization in two passes, first for just one element,
11184     // then for the whole array. It's possible we may find out we can't do const
11185     // init in the first pass, in which case we avoid allocating a potentially
11186     // large array. We don't do more passes because expanding array requires
11187     // copying the data, which is wasteful.
11188     for (const unsigned N : {1u, FinalSize}) {
11189       unsigned OldElts = Value->getArrayInitializedElts();
11190       if (OldElts == N)
11191         break;
11192 
11193       // Expand the array to appropriate size.
11194       APValue NewValue(APValue::UninitArray(), N, FinalSize);
11195       for (unsigned I = 0; I < OldElts; ++I)
11196         NewValue.getArrayInitializedElt(I).swap(
11197             Value->getArrayInitializedElt(I));
11198       Value->swap(NewValue);
11199 
11200       if (HadZeroInit)
11201         for (unsigned I = OldElts; I < N; ++I)
11202           Value->getArrayInitializedElt(I) = Filler;
11203 
11204       if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
11205         // If we have a trivial constructor, only evaluate it once and copy
11206         // the result into all the array elements.
11207         APValue &FirstResult = Value->getArrayInitializedElt(0);
11208         for (unsigned I = OldElts; I < FinalSize; ++I)
11209           Value->getArrayInitializedElt(I) = FirstResult;
11210       } else {
11211         for (unsigned I = OldElts; I < N; ++I) {
11212           if (!VisitCXXConstructExpr(E, ArrayElt,
11213                                      &Value->getArrayInitializedElt(I),
11214                                      CAT->getElementType()) ||
11215               !HandleLValueArrayAdjustment(Info, E, ArrayElt,
11216                                            CAT->getElementType(), 1))
11217             return false;
11218           // When checking for const initilization any diagnostic is considered
11219           // an error.
11220           if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
11221               !Info.keepEvaluatingAfterFailure())
11222             return false;
11223         }
11224       }
11225     }
11226 
11227     return true;
11228   }
11229 
11230   if (!Type->isRecordType())
11231     return Error(E);
11232 
11233   return RecordExprEvaluator(Info, Subobject, *Value)
11234              .VisitCXXConstructExpr(E, Type);
11235 }
11236 
VisitCXXParenListInitExpr(const CXXParenListInitExpr * E)11237 bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
11238     const CXXParenListInitExpr *E) {
11239   assert(dyn_cast<ConstantArrayType>(E->getType()) &&
11240          "Expression result is not a constant array type");
11241 
11242   return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
11243                                          E->getArrayFiller());
11244 }
11245 
11246 //===----------------------------------------------------------------------===//
11247 // Integer Evaluation
11248 //
11249 // As a GNU extension, we support casting pointers to sufficiently-wide integer
11250 // types and back in constant folding. Integer values are thus represented
11251 // either as an integer-valued APValue, or as an lvalue-valued APValue.
11252 //===----------------------------------------------------------------------===//
11253 
11254 namespace {
11255 class IntExprEvaluator
11256         : public ExprEvaluatorBase<IntExprEvaluator> {
11257   APValue &Result;
11258 public:
IntExprEvaluator(EvalInfo & info,APValue & result)11259   IntExprEvaluator(EvalInfo &info, APValue &result)
11260       : ExprEvaluatorBaseTy(info), Result(result) {}
11261 
Success(const llvm::APSInt & SI,const Expr * E,APValue & Result)11262   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
11263     assert(E->getType()->isIntegralOrEnumerationType() &&
11264            "Invalid evaluation result.");
11265     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
11266            "Invalid evaluation result.");
11267     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11268            "Invalid evaluation result.");
11269     Result = APValue(SI);
11270     return true;
11271   }
Success(const llvm::APSInt & SI,const Expr * E)11272   bool Success(const llvm::APSInt &SI, const Expr *E) {
11273     return Success(SI, E, Result);
11274   }
11275 
Success(const llvm::APInt & I,const Expr * E,APValue & Result)11276   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
11277     assert(E->getType()->isIntegralOrEnumerationType() &&
11278            "Invalid evaluation result.");
11279     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11280            "Invalid evaluation result.");
11281     Result = APValue(APSInt(I));
11282     Result.getInt().setIsUnsigned(
11283                             E->getType()->isUnsignedIntegerOrEnumerationType());
11284     return true;
11285   }
Success(const llvm::APInt & I,const Expr * E)11286   bool Success(const llvm::APInt &I, const Expr *E) {
11287     return Success(I, E, Result);
11288   }
11289 
Success(uint64_t Value,const Expr * E,APValue & Result)11290   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11291     assert(E->getType()->isIntegralOrEnumerationType() &&
11292            "Invalid evaluation result.");
11293     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11294     return true;
11295   }
Success(uint64_t Value,const Expr * E)11296   bool Success(uint64_t Value, const Expr *E) {
11297     return Success(Value, E, Result);
11298   }
11299 
Success(CharUnits Size,const Expr * E)11300   bool Success(CharUnits Size, const Expr *E) {
11301     return Success(Size.getQuantity(), E);
11302   }
11303 
Success(const APValue & V,const Expr * E)11304   bool Success(const APValue &V, const Expr *E) {
11305     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
11306       Result = V;
11307       return true;
11308     }
11309     return Success(V.getInt(), E);
11310   }
11311 
ZeroInitialization(const Expr * E)11312   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11313 
11314   //===--------------------------------------------------------------------===//
11315   //                            Visitor Methods
11316   //===--------------------------------------------------------------------===//
11317 
VisitIntegerLiteral(const IntegerLiteral * E)11318   bool VisitIntegerLiteral(const IntegerLiteral *E) {
11319     return Success(E->getValue(), E);
11320   }
VisitCharacterLiteral(const CharacterLiteral * E)11321   bool VisitCharacterLiteral(const CharacterLiteral *E) {
11322     return Success(E->getValue(), E);
11323   }
11324 
11325   bool CheckReferencedDecl(const Expr *E, const Decl *D);
VisitDeclRefExpr(const DeclRefExpr * E)11326   bool VisitDeclRefExpr(const DeclRefExpr *E) {
11327     if (CheckReferencedDecl(E, E->getDecl()))
11328       return true;
11329 
11330     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11331   }
VisitMemberExpr(const MemberExpr * E)11332   bool VisitMemberExpr(const MemberExpr *E) {
11333     if (CheckReferencedDecl(E, E->getMemberDecl())) {
11334       VisitIgnoredBaseExpression(E->getBase());
11335       return true;
11336     }
11337 
11338     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11339   }
11340 
11341   bool VisitCallExpr(const CallExpr *E);
11342   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11343   bool VisitBinaryOperator(const BinaryOperator *E);
11344   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11345   bool VisitUnaryOperator(const UnaryOperator *E);
11346 
11347   bool VisitCastExpr(const CastExpr* E);
11348   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11349 
VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr * E)11350   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11351     return Success(E->getValue(), E);
11352   }
11353 
VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr * E)11354   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11355     return Success(E->getValue(), E);
11356   }
11357 
VisitArrayInitIndexExpr(const ArrayInitIndexExpr * E)11358   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11359     if (Info.ArrayInitIndex == uint64_t(-1)) {
11360       // We were asked to evaluate this subexpression independent of the
11361       // enclosing ArrayInitLoopExpr. We can't do that.
11362       Info.FFDiag(E);
11363       return false;
11364     }
11365     return Success(Info.ArrayInitIndex, E);
11366   }
11367 
11368   // Note, GNU defines __null as an integer, not a pointer.
VisitGNUNullExpr(const GNUNullExpr * E)11369   bool VisitGNUNullExpr(const GNUNullExpr *E) {
11370     return ZeroInitialization(E);
11371   }
11372 
VisitTypeTraitExpr(const TypeTraitExpr * E)11373   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11374     return Success(E->getValue(), E);
11375   }
11376 
VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr * E)11377   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11378     return Success(E->getValue(), E);
11379   }
11380 
VisitExpressionTraitExpr(const ExpressionTraitExpr * E)11381   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11382     return Success(E->getValue(), E);
11383   }
11384 
11385   bool VisitUnaryReal(const UnaryOperator *E);
11386   bool VisitUnaryImag(const UnaryOperator *E);
11387 
11388   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11389   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11390   bool VisitSourceLocExpr(const SourceLocExpr *E);
11391   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11392   bool VisitRequiresExpr(const RequiresExpr *E);
11393   // FIXME: Missing: array subscript of vector, member of vector
11394 };
11395 
11396 class FixedPointExprEvaluator
11397     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11398   APValue &Result;
11399 
11400  public:
FixedPointExprEvaluator(EvalInfo & info,APValue & result)11401   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11402       : ExprEvaluatorBaseTy(info), Result(result) {}
11403 
Success(const llvm::APInt & I,const Expr * E)11404   bool Success(const llvm::APInt &I, const Expr *E) {
11405     return Success(
11406         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11407   }
11408 
Success(uint64_t Value,const Expr * E)11409   bool Success(uint64_t Value, const Expr *E) {
11410     return Success(
11411         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11412   }
11413 
Success(const APValue & V,const Expr * E)11414   bool Success(const APValue &V, const Expr *E) {
11415     return Success(V.getFixedPoint(), E);
11416   }
11417 
Success(const APFixedPoint & V,const Expr * E)11418   bool Success(const APFixedPoint &V, const Expr *E) {
11419     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11420     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11421            "Invalid evaluation result.");
11422     Result = APValue(V);
11423     return true;
11424   }
11425 
11426   //===--------------------------------------------------------------------===//
11427   //                            Visitor Methods
11428   //===--------------------------------------------------------------------===//
11429 
VisitFixedPointLiteral(const FixedPointLiteral * E)11430   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11431     return Success(E->getValue(), E);
11432   }
11433 
11434   bool VisitCastExpr(const CastExpr *E);
11435   bool VisitUnaryOperator(const UnaryOperator *E);
11436   bool VisitBinaryOperator(const BinaryOperator *E);
11437 };
11438 } // end anonymous namespace
11439 
11440 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11441 /// produce either the integer value or a pointer.
11442 ///
11443 /// GCC has a heinous extension which folds casts between pointer types and
11444 /// pointer-sized integral types. We support this by allowing the evaluation of
11445 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11446 /// Some simple arithmetic on such values is supported (they are treated much
11447 /// like char*).
EvaluateIntegerOrLValue(const Expr * E,APValue & Result,EvalInfo & Info)11448 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11449                                     EvalInfo &Info) {
11450   assert(!E->isValueDependent());
11451   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11452   return IntExprEvaluator(Info, Result).Visit(E);
11453 }
11454 
EvaluateInteger(const Expr * E,APSInt & Result,EvalInfo & Info)11455 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11456   assert(!E->isValueDependent());
11457   APValue Val;
11458   if (!EvaluateIntegerOrLValue(E, Val, Info))
11459     return false;
11460   if (!Val.isInt()) {
11461     // FIXME: It would be better to produce the diagnostic for casting
11462     //        a pointer to an integer.
11463     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11464     return false;
11465   }
11466   Result = Val.getInt();
11467   return true;
11468 }
11469 
VisitSourceLocExpr(const SourceLocExpr * E)11470 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11471   APValue Evaluated = E->EvaluateInContext(
11472       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11473   return Success(Evaluated, E);
11474 }
11475 
EvaluateFixedPoint(const Expr * E,APFixedPoint & Result,EvalInfo & Info)11476 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11477                                EvalInfo &Info) {
11478   assert(!E->isValueDependent());
11479   if (E->getType()->isFixedPointType()) {
11480     APValue Val;
11481     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11482       return false;
11483     if (!Val.isFixedPoint())
11484       return false;
11485 
11486     Result = Val.getFixedPoint();
11487     return true;
11488   }
11489   return false;
11490 }
11491 
EvaluateFixedPointOrInteger(const Expr * E,APFixedPoint & Result,EvalInfo & Info)11492 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11493                                         EvalInfo &Info) {
11494   assert(!E->isValueDependent());
11495   if (E->getType()->isIntegerType()) {
11496     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11497     APSInt Val;
11498     if (!EvaluateInteger(E, Val, Info))
11499       return false;
11500     Result = APFixedPoint(Val, FXSema);
11501     return true;
11502   } else if (E->getType()->isFixedPointType()) {
11503     return EvaluateFixedPoint(E, Result, Info);
11504   }
11505   return false;
11506 }
11507 
11508 /// Check whether the given declaration can be directly converted to an integral
11509 /// rvalue. If not, no diagnostic is produced; there are other things we can
11510 /// try.
CheckReferencedDecl(const Expr * E,const Decl * D)11511 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11512   // Enums are integer constant exprs.
11513   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11514     // Check for signedness/width mismatches between E type and ECD value.
11515     bool SameSign = (ECD->getInitVal().isSigned()
11516                      == E->getType()->isSignedIntegerOrEnumerationType());
11517     bool SameWidth = (ECD->getInitVal().getBitWidth()
11518                       == Info.Ctx.getIntWidth(E->getType()));
11519     if (SameSign && SameWidth)
11520       return Success(ECD->getInitVal(), E);
11521     else {
11522       // Get rid of mismatch (otherwise Success assertions will fail)
11523       // by computing a new value matching the type of E.
11524       llvm::APSInt Val = ECD->getInitVal();
11525       if (!SameSign)
11526         Val.setIsSigned(!ECD->getInitVal().isSigned());
11527       if (!SameWidth)
11528         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11529       return Success(Val, E);
11530     }
11531   }
11532   return false;
11533 }
11534 
11535 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11536 /// as GCC.
EvaluateBuiltinClassifyType(QualType T,const LangOptions & LangOpts)11537 GCCTypeClass EvaluateBuiltinClassifyType(QualType T,
11538                                          const LangOptions &LangOpts) {
11539   assert(!T->isDependentType() && "unexpected dependent type");
11540 
11541   QualType CanTy = T.getCanonicalType();
11542 
11543   switch (CanTy->getTypeClass()) {
11544 #define TYPE(ID, BASE)
11545 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11546 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11547 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11548 #include "clang/AST/TypeNodes.inc"
11549   case Type::Auto:
11550   case Type::DeducedTemplateSpecialization:
11551       llvm_unreachable("unexpected non-canonical or dependent type");
11552 
11553   case Type::Builtin:
11554       switch (cast<BuiltinType>(CanTy)->getKind()) {
11555 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11556 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11557     case BuiltinType::ID: return GCCTypeClass::Integer;
11558 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11559     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11560 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11561     case BuiltinType::ID: break;
11562 #include "clang/AST/BuiltinTypes.def"
11563     case BuiltinType::Void:
11564       return GCCTypeClass::Void;
11565 
11566     case BuiltinType::Bool:
11567       return GCCTypeClass::Bool;
11568 
11569     case BuiltinType::Char_U:
11570     case BuiltinType::UChar:
11571     case BuiltinType::WChar_U:
11572     case BuiltinType::Char8:
11573     case BuiltinType::Char16:
11574     case BuiltinType::Char32:
11575     case BuiltinType::UShort:
11576     case BuiltinType::UInt:
11577     case BuiltinType::ULong:
11578     case BuiltinType::ULongLong:
11579     case BuiltinType::UInt128:
11580       return GCCTypeClass::Integer;
11581 
11582     case BuiltinType::UShortAccum:
11583     case BuiltinType::UAccum:
11584     case BuiltinType::ULongAccum:
11585     case BuiltinType::UShortFract:
11586     case BuiltinType::UFract:
11587     case BuiltinType::ULongFract:
11588     case BuiltinType::SatUShortAccum:
11589     case BuiltinType::SatUAccum:
11590     case BuiltinType::SatULongAccum:
11591     case BuiltinType::SatUShortFract:
11592     case BuiltinType::SatUFract:
11593     case BuiltinType::SatULongFract:
11594       return GCCTypeClass::None;
11595 
11596     case BuiltinType::NullPtr:
11597 
11598     case BuiltinType::ObjCId:
11599     case BuiltinType::ObjCClass:
11600     case BuiltinType::ObjCSel:
11601 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11602     case BuiltinType::Id:
11603 #include "clang/Basic/OpenCLImageTypes.def"
11604 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11605     case BuiltinType::Id:
11606 #include "clang/Basic/OpenCLExtensionTypes.def"
11607     case BuiltinType::OCLSampler:
11608     case BuiltinType::OCLEvent:
11609     case BuiltinType::OCLClkEvent:
11610     case BuiltinType::OCLQueue:
11611     case BuiltinType::OCLReserveID:
11612 #define SVE_TYPE(Name, Id, SingletonId) \
11613     case BuiltinType::Id:
11614 #include "clang/Basic/AArch64SVEACLETypes.def"
11615 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11616     case BuiltinType::Id:
11617 #include "clang/Basic/PPCTypes.def"
11618 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11619 #include "clang/Basic/RISCVVTypes.def"
11620 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11621 #include "clang/Basic/WebAssemblyReferenceTypes.def"
11622       return GCCTypeClass::None;
11623 
11624     case BuiltinType::Dependent:
11625       llvm_unreachable("unexpected dependent type");
11626     };
11627     llvm_unreachable("unexpected placeholder type");
11628 
11629   case Type::Enum:
11630     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11631 
11632   case Type::Pointer:
11633   case Type::ConstantArray:
11634   case Type::VariableArray:
11635   case Type::IncompleteArray:
11636   case Type::FunctionNoProto:
11637   case Type::FunctionProto:
11638     return GCCTypeClass::Pointer;
11639 
11640   case Type::MemberPointer:
11641     return CanTy->isMemberDataPointerType()
11642                ? GCCTypeClass::PointerToDataMember
11643                : GCCTypeClass::PointerToMemberFunction;
11644 
11645   case Type::Complex:
11646     return GCCTypeClass::Complex;
11647 
11648   case Type::Record:
11649     return CanTy->isUnionType() ? GCCTypeClass::Union
11650                                 : GCCTypeClass::ClassOrStruct;
11651 
11652   case Type::Atomic:
11653     // GCC classifies _Atomic T the same as T.
11654     return EvaluateBuiltinClassifyType(
11655         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11656 
11657   case Type::Vector:
11658   case Type::ExtVector:
11659     return GCCTypeClass::Vector;
11660 
11661   case Type::BlockPointer:
11662   case Type::ConstantMatrix:
11663   case Type::ObjCObject:
11664   case Type::ObjCInterface:
11665   case Type::ObjCObjectPointer:
11666   case Type::Pipe:
11667     // Classify all other types that don't fit into the regular
11668     // classification the same way.
11669     return GCCTypeClass::None;
11670 
11671   case Type::BitInt:
11672     return GCCTypeClass::BitInt;
11673 
11674   case Type::LValueReference:
11675   case Type::RValueReference:
11676     llvm_unreachable("invalid type for expression");
11677   }
11678 
11679   llvm_unreachable("unexpected type class");
11680 }
11681 
11682 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11683 /// as GCC.
11684 static GCCTypeClass
EvaluateBuiltinClassifyType(const CallExpr * E,const LangOptions & LangOpts)11685 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11686   // If no argument was supplied, default to None. This isn't
11687   // ideal, however it is what gcc does.
11688   if (E->getNumArgs() == 0)
11689     return GCCTypeClass::None;
11690 
11691   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11692   // being an ICE, but still folds it to a constant using the type of the first
11693   // argument.
11694   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11695 }
11696 
11697 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11698 /// __builtin_constant_p when applied to the given pointer.
11699 ///
11700 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11701 /// or it points to the first character of a string literal.
EvaluateBuiltinConstantPForLValue(const APValue & LV)11702 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11703   APValue::LValueBase Base = LV.getLValueBase();
11704   if (Base.isNull()) {
11705     // A null base is acceptable.
11706     return true;
11707   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11708     if (!isa<StringLiteral>(E))
11709       return false;
11710     return LV.getLValueOffset().isZero();
11711   } else if (Base.is<TypeInfoLValue>()) {
11712     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11713     // evaluate to true.
11714     return true;
11715   } else {
11716     // Any other base is not constant enough for GCC.
11717     return false;
11718   }
11719 }
11720 
11721 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11722 /// GCC as we can manage.
EvaluateBuiltinConstantP(EvalInfo & Info,const Expr * Arg)11723 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11724   // This evaluation is not permitted to have side-effects, so evaluate it in
11725   // a speculative evaluation context.
11726   SpeculativeEvaluationRAII SpeculativeEval(Info);
11727 
11728   // Constant-folding is always enabled for the operand of __builtin_constant_p
11729   // (even when the enclosing evaluation context otherwise requires a strict
11730   // language-specific constant expression).
11731   FoldConstant Fold(Info, true);
11732 
11733   QualType ArgType = Arg->getType();
11734 
11735   // __builtin_constant_p always has one operand. The rules which gcc follows
11736   // are not precisely documented, but are as follows:
11737   //
11738   //  - If the operand is of integral, floating, complex or enumeration type,
11739   //    and can be folded to a known value of that type, it returns 1.
11740   //  - If the operand can be folded to a pointer to the first character
11741   //    of a string literal (or such a pointer cast to an integral type)
11742   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11743   //
11744   // Otherwise, it returns 0.
11745   //
11746   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11747   // its support for this did not work prior to GCC 9 and is not yet well
11748   // understood.
11749   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11750       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11751       ArgType->isNullPtrType()) {
11752     APValue V;
11753     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11754       Fold.keepDiagnostics();
11755       return false;
11756     }
11757 
11758     // For a pointer (possibly cast to integer), there are special rules.
11759     if (V.getKind() == APValue::LValue)
11760       return EvaluateBuiltinConstantPForLValue(V);
11761 
11762     // Otherwise, any constant value is good enough.
11763     return V.hasValue();
11764   }
11765 
11766   // Anything else isn't considered to be sufficiently constant.
11767   return false;
11768 }
11769 
11770 /// Retrieves the "underlying object type" of the given expression,
11771 /// as used by __builtin_object_size.
getObjectType(APValue::LValueBase B)11772 static QualType getObjectType(APValue::LValueBase B) {
11773   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11774     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11775       return VD->getType();
11776   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11777     if (isa<CompoundLiteralExpr>(E))
11778       return E->getType();
11779   } else if (B.is<TypeInfoLValue>()) {
11780     return B.getTypeInfoType();
11781   } else if (B.is<DynamicAllocLValue>()) {
11782     return B.getDynamicAllocType();
11783   }
11784 
11785   return QualType();
11786 }
11787 
11788 /// A more selective version of E->IgnoreParenCasts for
11789 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11790 /// to change the type of E.
11791 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11792 ///
11793 /// Always returns an RValue with a pointer representation.
ignorePointerCastsAndParens(const Expr * E)11794 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11795   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11796 
11797   auto *NoParens = E->IgnoreParens();
11798   auto *Cast = dyn_cast<CastExpr>(NoParens);
11799   if (Cast == nullptr)
11800     return NoParens;
11801 
11802   // We only conservatively allow a few kinds of casts, because this code is
11803   // inherently a simple solution that seeks to support the common case.
11804   auto CastKind = Cast->getCastKind();
11805   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11806       CastKind != CK_AddressSpaceConversion)
11807     return NoParens;
11808 
11809   auto *SubExpr = Cast->getSubExpr();
11810   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11811     return NoParens;
11812   return ignorePointerCastsAndParens(SubExpr);
11813 }
11814 
11815 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11816 /// record layout. e.g.
11817 ///   struct { struct { int a, b; } fst, snd; } obj;
11818 ///   obj.fst   // no
11819 ///   obj.snd   // yes
11820 ///   obj.fst.a // no
11821 ///   obj.fst.b // no
11822 ///   obj.snd.a // no
11823 ///   obj.snd.b // yes
11824 ///
11825 /// Please note: this function is specialized for how __builtin_object_size
11826 /// views "objects".
11827 ///
11828 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11829 /// correct result, it will always return true.
isDesignatorAtObjectEnd(const ASTContext & Ctx,const LValue & LVal)11830 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11831   assert(!LVal.Designator.Invalid);
11832 
11833   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11834     const RecordDecl *Parent = FD->getParent();
11835     Invalid = Parent->isInvalidDecl();
11836     if (Invalid || Parent->isUnion())
11837       return true;
11838     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11839     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11840   };
11841 
11842   auto &Base = LVal.getLValueBase();
11843   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11844     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11845       bool Invalid;
11846       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11847         return Invalid;
11848     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11849       for (auto *FD : IFD->chain()) {
11850         bool Invalid;
11851         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11852           return Invalid;
11853       }
11854     }
11855   }
11856 
11857   unsigned I = 0;
11858   QualType BaseType = getType(Base);
11859   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11860     // If we don't know the array bound, conservatively assume we're looking at
11861     // the final array element.
11862     ++I;
11863     if (BaseType->isIncompleteArrayType())
11864       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11865     else
11866       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11867   }
11868 
11869   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11870     const auto &Entry = LVal.Designator.Entries[I];
11871     if (BaseType->isArrayType()) {
11872       // Because __builtin_object_size treats arrays as objects, we can ignore
11873       // the index iff this is the last array in the Designator.
11874       if (I + 1 == E)
11875         return true;
11876       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11877       uint64_t Index = Entry.getAsArrayIndex();
11878       if (Index + 1 != CAT->getSize())
11879         return false;
11880       BaseType = CAT->getElementType();
11881     } else if (BaseType->isAnyComplexType()) {
11882       const auto *CT = BaseType->castAs<ComplexType>();
11883       uint64_t Index = Entry.getAsArrayIndex();
11884       if (Index != 1)
11885         return false;
11886       BaseType = CT->getElementType();
11887     } else if (auto *FD = getAsField(Entry)) {
11888       bool Invalid;
11889       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11890         return Invalid;
11891       BaseType = FD->getType();
11892     } else {
11893       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11894       return false;
11895     }
11896   }
11897   return true;
11898 }
11899 
11900 /// Tests to see if the LValue has a user-specified designator (that isn't
11901 /// necessarily valid). Note that this always returns 'true' if the LValue has
11902 /// an unsized array as its first designator entry, because there's currently no
11903 /// way to tell if the user typed *foo or foo[0].
refersToCompleteObject(const LValue & LVal)11904 static bool refersToCompleteObject(const LValue &LVal) {
11905   if (LVal.Designator.Invalid)
11906     return false;
11907 
11908   if (!LVal.Designator.Entries.empty())
11909     return LVal.Designator.isMostDerivedAnUnsizedArray();
11910 
11911   if (!LVal.InvalidBase)
11912     return true;
11913 
11914   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11915   // the LValueBase.
11916   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11917   return !E || !isa<MemberExpr>(E);
11918 }
11919 
11920 /// Attempts to detect a user writing into a piece of memory that's impossible
11921 /// to figure out the size of by just using types.
isUserWritingOffTheEnd(const ASTContext & Ctx,const LValue & LVal)11922 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11923   const SubobjectDesignator &Designator = LVal.Designator;
11924   // Notes:
11925   // - Users can only write off of the end when we have an invalid base. Invalid
11926   //   bases imply we don't know where the memory came from.
11927   // - We used to be a bit more aggressive here; we'd only be conservative if
11928   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11929   //   broke some common standard library extensions (PR30346), but was
11930   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11931   //   with some sort of list. OTOH, it seems that GCC is always
11932   //   conservative with the last element in structs (if it's an array), so our
11933   //   current behavior is more compatible than an explicit list approach would
11934   //   be.
11935   auto isFlexibleArrayMember = [&] {
11936     using FAMKind = LangOptions::StrictFlexArraysLevelKind;
11937     FAMKind StrictFlexArraysLevel =
11938         Ctx.getLangOpts().getStrictFlexArraysLevel();
11939 
11940     if (Designator.isMostDerivedAnUnsizedArray())
11941       return true;
11942 
11943     if (StrictFlexArraysLevel == FAMKind::Default)
11944       return true;
11945 
11946     if (Designator.getMostDerivedArraySize() == 0 &&
11947         StrictFlexArraysLevel != FAMKind::IncompleteOnly)
11948       return true;
11949 
11950     if (Designator.getMostDerivedArraySize() == 1 &&
11951         StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
11952       return true;
11953 
11954     return false;
11955   };
11956 
11957   return LVal.InvalidBase &&
11958          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11959          Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
11960          isDesignatorAtObjectEnd(Ctx, LVal);
11961 }
11962 
11963 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11964 /// Fails if the conversion would cause loss of precision.
convertUnsignedAPIntToCharUnits(const llvm::APInt & Int,CharUnits & Result)11965 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11966                                             CharUnits &Result) {
11967   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11968   if (Int.ugt(CharUnitsMax))
11969     return false;
11970   Result = CharUnits::fromQuantity(Int.getZExtValue());
11971   return true;
11972 }
11973 
11974 /// If we're evaluating the object size of an instance of a struct that
11975 /// contains a flexible array member, add the size of the initializer.
addFlexibleArrayMemberInitSize(EvalInfo & Info,const QualType & T,const LValue & LV,CharUnits & Size)11976 static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
11977                                            const LValue &LV, CharUnits &Size) {
11978   if (!T.isNull() && T->isStructureType() &&
11979       T->getAsStructureType()->getDecl()->hasFlexibleArrayMember())
11980     if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
11981       if (const auto *VD = dyn_cast<VarDecl>(V))
11982         if (VD->hasInit())
11983           Size += VD->getFlexibleArrayInitChars(Info.Ctx);
11984 }
11985 
11986 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11987 /// determine how many bytes exist from the beginning of the object to either
11988 /// the end of the current subobject, or the end of the object itself, depending
11989 /// on what the LValue looks like + the value of Type.
11990 ///
11991 /// If this returns false, the value of Result is undefined.
determineEndOffset(EvalInfo & Info,SourceLocation ExprLoc,unsigned Type,const LValue & LVal,CharUnits & EndOffset)11992 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11993                                unsigned Type, const LValue &LVal,
11994                                CharUnits &EndOffset) {
11995   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11996 
11997   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11998     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11999       return false;
12000     return HandleSizeof(Info, ExprLoc, Ty, Result);
12001   };
12002 
12003   // We want to evaluate the size of the entire object. This is a valid fallback
12004   // for when Type=1 and the designator is invalid, because we're asked for an
12005   // upper-bound.
12006   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
12007     // Type=3 wants a lower bound, so we can't fall back to this.
12008     if (Type == 3 && !DetermineForCompleteObject)
12009       return false;
12010 
12011     llvm::APInt APEndOffset;
12012     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12013         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12014       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12015 
12016     if (LVal.InvalidBase)
12017       return false;
12018 
12019     QualType BaseTy = getObjectType(LVal.getLValueBase());
12020     const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
12021     addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
12022     return Ret;
12023   }
12024 
12025   // We want to evaluate the size of a subobject.
12026   const SubobjectDesignator &Designator = LVal.Designator;
12027 
12028   // The following is a moderately common idiom in C:
12029   //
12030   // struct Foo { int a; char c[1]; };
12031   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
12032   // strcpy(&F->c[0], Bar);
12033   //
12034   // In order to not break too much legacy code, we need to support it.
12035   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
12036     // If we can resolve this to an alloc_size call, we can hand that back,
12037     // because we know for certain how many bytes there are to write to.
12038     llvm::APInt APEndOffset;
12039     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12040         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12041       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12042 
12043     // If we cannot determine the size of the initial allocation, then we can't
12044     // given an accurate upper-bound. However, we are still able to give
12045     // conservative lower-bounds for Type=3.
12046     if (Type == 1)
12047       return false;
12048   }
12049 
12050   CharUnits BytesPerElem;
12051   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
12052     return false;
12053 
12054   // According to the GCC documentation, we want the size of the subobject
12055   // denoted by the pointer. But that's not quite right -- what we actually
12056   // want is the size of the immediately-enclosing array, if there is one.
12057   int64_t ElemsRemaining;
12058   if (Designator.MostDerivedIsArrayElement &&
12059       Designator.Entries.size() == Designator.MostDerivedPathLength) {
12060     uint64_t ArraySize = Designator.getMostDerivedArraySize();
12061     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
12062     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
12063   } else {
12064     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
12065   }
12066 
12067   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
12068   return true;
12069 }
12070 
12071 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
12072 /// returns true and stores the result in @p Size.
12073 ///
12074 /// If @p WasError is non-null, this will report whether the failure to evaluate
12075 /// is to be treated as an Error in IntExprEvaluator.
tryEvaluateBuiltinObjectSize(const Expr * E,unsigned Type,EvalInfo & Info,uint64_t & Size)12076 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
12077                                          EvalInfo &Info, uint64_t &Size) {
12078   // Determine the denoted object.
12079   LValue LVal;
12080   {
12081     // The operand of __builtin_object_size is never evaluated for side-effects.
12082     // If there are any, but we can determine the pointed-to object anyway, then
12083     // ignore the side-effects.
12084     SpeculativeEvaluationRAII SpeculativeEval(Info);
12085     IgnoreSideEffectsRAII Fold(Info);
12086 
12087     if (E->isGLValue()) {
12088       // It's possible for us to be given GLValues if we're called via
12089       // Expr::tryEvaluateObjectSize.
12090       APValue RVal;
12091       if (!EvaluateAsRValue(Info, E, RVal))
12092         return false;
12093       LVal.setFrom(Info.Ctx, RVal);
12094     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
12095                                 /*InvalidBaseOK=*/true))
12096       return false;
12097   }
12098 
12099   // If we point to before the start of the object, there are no accessible
12100   // bytes.
12101   if (LVal.getLValueOffset().isNegative()) {
12102     Size = 0;
12103     return true;
12104   }
12105 
12106   CharUnits EndOffset;
12107   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
12108     return false;
12109 
12110   // If we've fallen outside of the end offset, just pretend there's nothing to
12111   // write to/read from.
12112   if (EndOffset <= LVal.getLValueOffset())
12113     Size = 0;
12114   else
12115     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
12116   return true;
12117 }
12118 
VisitCallExpr(const CallExpr * E)12119 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
12120   if (!IsConstantEvaluatedBuiltinCall(E))
12121     return ExprEvaluatorBaseTy::VisitCallExpr(E);
12122   return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
12123 }
12124 
getBuiltinAlignArguments(const CallExpr * E,EvalInfo & Info,APValue & Val,APSInt & Alignment)12125 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
12126                                      APValue &Val, APSInt &Alignment) {
12127   QualType SrcTy = E->getArg(0)->getType();
12128   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
12129     return false;
12130   // Even though we are evaluating integer expressions we could get a pointer
12131   // argument for the __builtin_is_aligned() case.
12132   if (SrcTy->isPointerType()) {
12133     LValue Ptr;
12134     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
12135       return false;
12136     Ptr.moveInto(Val);
12137   } else if (!SrcTy->isIntegralOrEnumerationType()) {
12138     Info.FFDiag(E->getArg(0));
12139     return false;
12140   } else {
12141     APSInt SrcInt;
12142     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
12143       return false;
12144     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
12145            "Bit widths must be the same");
12146     Val = APValue(SrcInt);
12147   }
12148   assert(Val.hasValue());
12149   return true;
12150 }
12151 
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)12152 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
12153                                             unsigned BuiltinOp) {
12154   switch (BuiltinOp) {
12155   default:
12156     return false;
12157 
12158   case Builtin::BI__builtin_dynamic_object_size:
12159   case Builtin::BI__builtin_object_size: {
12160     // The type was checked when we built the expression.
12161     unsigned Type =
12162         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12163     assert(Type <= 3 && "unexpected type");
12164 
12165     uint64_t Size;
12166     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
12167       return Success(Size, E);
12168 
12169     if (E->getArg(0)->HasSideEffects(Info.Ctx))
12170       return Success((Type & 2) ? 0 : -1, E);
12171 
12172     // Expression had no side effects, but we couldn't statically determine the
12173     // size of the referenced object.
12174     switch (Info.EvalMode) {
12175     case EvalInfo::EM_ConstantExpression:
12176     case EvalInfo::EM_ConstantFold:
12177     case EvalInfo::EM_IgnoreSideEffects:
12178       // Leave it to IR generation.
12179       return Error(E);
12180     case EvalInfo::EM_ConstantExpressionUnevaluated:
12181       // Reduce it to a constant now.
12182       return Success((Type & 2) ? 0 : -1, E);
12183     }
12184 
12185     llvm_unreachable("unexpected EvalMode");
12186   }
12187 
12188   case Builtin::BI__builtin_os_log_format_buffer_size: {
12189     analyze_os_log::OSLogBufferLayout Layout;
12190     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
12191     return Success(Layout.size().getQuantity(), E);
12192   }
12193 
12194   case Builtin::BI__builtin_is_aligned: {
12195     APValue Src;
12196     APSInt Alignment;
12197     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12198       return false;
12199     if (Src.isLValue()) {
12200       // If we evaluated a pointer, check the minimum known alignment.
12201       LValue Ptr;
12202       Ptr.setFrom(Info.Ctx, Src);
12203       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
12204       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
12205       // We can return true if the known alignment at the computed offset is
12206       // greater than the requested alignment.
12207       assert(PtrAlign.isPowerOfTwo());
12208       assert(Alignment.isPowerOf2());
12209       if (PtrAlign.getQuantity() >= Alignment)
12210         return Success(1, E);
12211       // If the alignment is not known to be sufficient, some cases could still
12212       // be aligned at run time. However, if the requested alignment is less or
12213       // equal to the base alignment and the offset is not aligned, we know that
12214       // the run-time value can never be aligned.
12215       if (BaseAlignment.getQuantity() >= Alignment &&
12216           PtrAlign.getQuantity() < Alignment)
12217         return Success(0, E);
12218       // Otherwise we can't infer whether the value is sufficiently aligned.
12219       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
12220       //  in cases where we can't fully evaluate the pointer.
12221       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
12222           << Alignment;
12223       return false;
12224     }
12225     assert(Src.isInt());
12226     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
12227   }
12228   case Builtin::BI__builtin_align_up: {
12229     APValue Src;
12230     APSInt Alignment;
12231     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12232       return false;
12233     if (!Src.isInt())
12234       return Error(E);
12235     APSInt AlignedVal =
12236         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
12237                Src.getInt().isUnsigned());
12238     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12239     return Success(AlignedVal, E);
12240   }
12241   case Builtin::BI__builtin_align_down: {
12242     APValue Src;
12243     APSInt Alignment;
12244     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12245       return false;
12246     if (!Src.isInt())
12247       return Error(E);
12248     APSInt AlignedVal =
12249         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
12250     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12251     return Success(AlignedVal, E);
12252   }
12253 
12254   case Builtin::BI__builtin_bitreverse8:
12255   case Builtin::BI__builtin_bitreverse16:
12256   case Builtin::BI__builtin_bitreverse32:
12257   case Builtin::BI__builtin_bitreverse64: {
12258     APSInt Val;
12259     if (!EvaluateInteger(E->getArg(0), Val, Info))
12260       return false;
12261 
12262     return Success(Val.reverseBits(), E);
12263   }
12264 
12265   case Builtin::BI__builtin_bswap16:
12266   case Builtin::BI__builtin_bswap32:
12267   case Builtin::BI__builtin_bswap64: {
12268     APSInt Val;
12269     if (!EvaluateInteger(E->getArg(0), Val, Info))
12270       return false;
12271 
12272     return Success(Val.byteSwap(), E);
12273   }
12274 
12275   case Builtin::BI__builtin_classify_type:
12276     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12277 
12278   case Builtin::BI__builtin_clrsb:
12279   case Builtin::BI__builtin_clrsbl:
12280   case Builtin::BI__builtin_clrsbll: {
12281     APSInt Val;
12282     if (!EvaluateInteger(E->getArg(0), Val, Info))
12283       return false;
12284 
12285     return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
12286   }
12287 
12288   case Builtin::BI__builtin_clz:
12289   case Builtin::BI__builtin_clzl:
12290   case Builtin::BI__builtin_clzll:
12291   case Builtin::BI__builtin_clzs:
12292   case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
12293   case Builtin::BI__lzcnt:
12294   case Builtin::BI__lzcnt64: {
12295     APSInt Val;
12296     if (!EvaluateInteger(E->getArg(0), Val, Info))
12297       return false;
12298 
12299     // When the argument is 0, the result of GCC builtins is undefined, whereas
12300     // for Microsoft intrinsics, the result is the bit-width of the argument.
12301     bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
12302                            BuiltinOp != Builtin::BI__lzcnt &&
12303                            BuiltinOp != Builtin::BI__lzcnt64;
12304 
12305     if (ZeroIsUndefined && !Val)
12306       return Error(E);
12307 
12308     return Success(Val.countl_zero(), E);
12309   }
12310 
12311   case Builtin::BI__builtin_constant_p: {
12312     const Expr *Arg = E->getArg(0);
12313     if (EvaluateBuiltinConstantP(Info, Arg))
12314       return Success(true, E);
12315     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
12316       // Outside a constant context, eagerly evaluate to false in the presence
12317       // of side-effects in order to avoid -Wunsequenced false-positives in
12318       // a branch on __builtin_constant_p(expr).
12319       return Success(false, E);
12320     }
12321     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12322     return false;
12323   }
12324 
12325   case Builtin::BI__builtin_is_constant_evaluated: {
12326     const auto *Callee = Info.CurrentCall->getCallee();
12327     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12328         (Info.CallStackDepth == 1 ||
12329          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12330           Callee->getIdentifier() &&
12331           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12332       // FIXME: Find a better way to avoid duplicated diagnostics.
12333       if (Info.EvalStatus.Diag)
12334         Info.report((Info.CallStackDepth == 1)
12335                         ? E->getExprLoc()
12336                         : Info.CurrentCall->getCallRange().getBegin(),
12337                     diag::warn_is_constant_evaluated_always_true_constexpr)
12338             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12339                                          : "std::is_constant_evaluated");
12340     }
12341 
12342     return Success(Info.InConstantContext, E);
12343   }
12344 
12345   case Builtin::BI__builtin_ctz:
12346   case Builtin::BI__builtin_ctzl:
12347   case Builtin::BI__builtin_ctzll:
12348   case Builtin::BI__builtin_ctzs: {
12349     APSInt Val;
12350     if (!EvaluateInteger(E->getArg(0), Val, Info))
12351       return false;
12352     if (!Val)
12353       return Error(E);
12354 
12355     return Success(Val.countr_zero(), E);
12356   }
12357 
12358   case Builtin::BI__builtin_eh_return_data_regno: {
12359     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12360     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
12361     return Success(Operand, E);
12362   }
12363 
12364   case Builtin::BI__builtin_expect:
12365   case Builtin::BI__builtin_expect_with_probability:
12366     return Visit(E->getArg(0));
12367 
12368   case Builtin::BI__builtin_ffs:
12369   case Builtin::BI__builtin_ffsl:
12370   case Builtin::BI__builtin_ffsll: {
12371     APSInt Val;
12372     if (!EvaluateInteger(E->getArg(0), Val, Info))
12373       return false;
12374 
12375     unsigned N = Val.countr_zero();
12376     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12377   }
12378 
12379   case Builtin::BI__builtin_fpclassify: {
12380     APFloat Val(0.0);
12381     if (!EvaluateFloat(E->getArg(5), Val, Info))
12382       return false;
12383     unsigned Arg;
12384     switch (Val.getCategory()) {
12385     case APFloat::fcNaN: Arg = 0; break;
12386     case APFloat::fcInfinity: Arg = 1; break;
12387     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12388     case APFloat::fcZero: Arg = 4; break;
12389     }
12390     return Visit(E->getArg(Arg));
12391   }
12392 
12393   case Builtin::BI__builtin_isinf_sign: {
12394     APFloat Val(0.0);
12395     return EvaluateFloat(E->getArg(0), Val, Info) &&
12396            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12397   }
12398 
12399   case Builtin::BI__builtin_isinf: {
12400     APFloat Val(0.0);
12401     return EvaluateFloat(E->getArg(0), Val, Info) &&
12402            Success(Val.isInfinity() ? 1 : 0, E);
12403   }
12404 
12405   case Builtin::BI__builtin_isfinite: {
12406     APFloat Val(0.0);
12407     return EvaluateFloat(E->getArg(0), Val, Info) &&
12408            Success(Val.isFinite() ? 1 : 0, E);
12409   }
12410 
12411   case Builtin::BI__builtin_isnan: {
12412     APFloat Val(0.0);
12413     return EvaluateFloat(E->getArg(0), Val, Info) &&
12414            Success(Val.isNaN() ? 1 : 0, E);
12415   }
12416 
12417   case Builtin::BI__builtin_isnormal: {
12418     APFloat Val(0.0);
12419     return EvaluateFloat(E->getArg(0), Val, Info) &&
12420            Success(Val.isNormal() ? 1 : 0, E);
12421   }
12422 
12423   case Builtin::BI__builtin_issubnormal: {
12424     APFloat Val(0.0);
12425     return EvaluateFloat(E->getArg(0), Val, Info) &&
12426            Success(Val.isDenormal() ? 1 : 0, E);
12427   }
12428 
12429   case Builtin::BI__builtin_iszero: {
12430     APFloat Val(0.0);
12431     return EvaluateFloat(E->getArg(0), Val, Info) &&
12432            Success(Val.isZero() ? 1 : 0, E);
12433   }
12434 
12435   case Builtin::BI__builtin_issignaling: {
12436     APFloat Val(0.0);
12437     return EvaluateFloat(E->getArg(0), Val, Info) &&
12438            Success(Val.isSignaling() ? 1 : 0, E);
12439   }
12440 
12441   case Builtin::BI__builtin_isfpclass: {
12442     APSInt MaskVal;
12443     if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
12444       return false;
12445     unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
12446     APFloat Val(0.0);
12447     return EvaluateFloat(E->getArg(0), Val, Info) &&
12448            Success((Val.classify() & Test) ? 1 : 0, E);
12449   }
12450 
12451   case Builtin::BI__builtin_parity:
12452   case Builtin::BI__builtin_parityl:
12453   case Builtin::BI__builtin_parityll: {
12454     APSInt Val;
12455     if (!EvaluateInteger(E->getArg(0), Val, Info))
12456       return false;
12457 
12458     return Success(Val.popcount() % 2, E);
12459   }
12460 
12461   case Builtin::BI__builtin_popcount:
12462   case Builtin::BI__builtin_popcountl:
12463   case Builtin::BI__builtin_popcountll:
12464   case Builtin::BI__popcnt16: // Microsoft variants of popcount
12465   case Builtin::BI__popcnt:
12466   case Builtin::BI__popcnt64: {
12467     APSInt Val;
12468     if (!EvaluateInteger(E->getArg(0), Val, Info))
12469       return false;
12470 
12471     return Success(Val.popcount(), E);
12472   }
12473 
12474   case Builtin::BI__builtin_rotateleft8:
12475   case Builtin::BI__builtin_rotateleft16:
12476   case Builtin::BI__builtin_rotateleft32:
12477   case Builtin::BI__builtin_rotateleft64:
12478   case Builtin::BI_rotl8: // Microsoft variants of rotate right
12479   case Builtin::BI_rotl16:
12480   case Builtin::BI_rotl:
12481   case Builtin::BI_lrotl:
12482   case Builtin::BI_rotl64: {
12483     APSInt Val, Amt;
12484     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12485         !EvaluateInteger(E->getArg(1), Amt, Info))
12486       return false;
12487 
12488     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12489   }
12490 
12491   case Builtin::BI__builtin_rotateright8:
12492   case Builtin::BI__builtin_rotateright16:
12493   case Builtin::BI__builtin_rotateright32:
12494   case Builtin::BI__builtin_rotateright64:
12495   case Builtin::BI_rotr8: // Microsoft variants of rotate right
12496   case Builtin::BI_rotr16:
12497   case Builtin::BI_rotr:
12498   case Builtin::BI_lrotr:
12499   case Builtin::BI_rotr64: {
12500     APSInt Val, Amt;
12501     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12502         !EvaluateInteger(E->getArg(1), Amt, Info))
12503       return false;
12504 
12505     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12506   }
12507 
12508   case Builtin::BIstrlen:
12509   case Builtin::BIwcslen:
12510     // A call to strlen is not a constant expression.
12511     if (Info.getLangOpts().CPlusPlus11)
12512       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12513           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12514           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12515     else
12516       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12517     [[fallthrough]];
12518   case Builtin::BI__builtin_strlen:
12519   case Builtin::BI__builtin_wcslen: {
12520     // As an extension, we support __builtin_strlen() as a constant expression,
12521     // and support folding strlen() to a constant.
12522     uint64_t StrLen;
12523     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12524       return Success(StrLen, E);
12525     return false;
12526   }
12527 
12528   case Builtin::BIstrcmp:
12529   case Builtin::BIwcscmp:
12530   case Builtin::BIstrncmp:
12531   case Builtin::BIwcsncmp:
12532   case Builtin::BImemcmp:
12533   case Builtin::BIbcmp:
12534   case Builtin::BIwmemcmp:
12535     // A call to strlen is not a constant expression.
12536     if (Info.getLangOpts().CPlusPlus11)
12537       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12538           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12539           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12540     else
12541       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12542     [[fallthrough]];
12543   case Builtin::BI__builtin_strcmp:
12544   case Builtin::BI__builtin_wcscmp:
12545   case Builtin::BI__builtin_strncmp:
12546   case Builtin::BI__builtin_wcsncmp:
12547   case Builtin::BI__builtin_memcmp:
12548   case Builtin::BI__builtin_bcmp:
12549   case Builtin::BI__builtin_wmemcmp: {
12550     LValue String1, String2;
12551     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12552         !EvaluatePointer(E->getArg(1), String2, Info))
12553       return false;
12554 
12555     uint64_t MaxLength = uint64_t(-1);
12556     if (BuiltinOp != Builtin::BIstrcmp &&
12557         BuiltinOp != Builtin::BIwcscmp &&
12558         BuiltinOp != Builtin::BI__builtin_strcmp &&
12559         BuiltinOp != Builtin::BI__builtin_wcscmp) {
12560       APSInt N;
12561       if (!EvaluateInteger(E->getArg(2), N, Info))
12562         return false;
12563       MaxLength = N.getZExtValue();
12564     }
12565 
12566     // Empty substrings compare equal by definition.
12567     if (MaxLength == 0u)
12568       return Success(0, E);
12569 
12570     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12571         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12572         String1.Designator.Invalid || String2.Designator.Invalid)
12573       return false;
12574 
12575     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12576     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12577 
12578     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12579                      BuiltinOp == Builtin::BIbcmp ||
12580                      BuiltinOp == Builtin::BI__builtin_memcmp ||
12581                      BuiltinOp == Builtin::BI__builtin_bcmp;
12582 
12583     assert(IsRawByte ||
12584            (Info.Ctx.hasSameUnqualifiedType(
12585                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12586             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12587 
12588     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12589     // 'char8_t', but no other types.
12590     if (IsRawByte &&
12591         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12592       // FIXME: Consider using our bit_cast implementation to support this.
12593       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12594           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
12595           << CharTy1 << CharTy2;
12596       return false;
12597     }
12598 
12599     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12600       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12601              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12602              Char1.isInt() && Char2.isInt();
12603     };
12604     const auto &AdvanceElems = [&] {
12605       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12606              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12607     };
12608 
12609     bool StopAtNull =
12610         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12611          BuiltinOp != Builtin::BIwmemcmp &&
12612          BuiltinOp != Builtin::BI__builtin_memcmp &&
12613          BuiltinOp != Builtin::BI__builtin_bcmp &&
12614          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12615     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12616                   BuiltinOp == Builtin::BIwcsncmp ||
12617                   BuiltinOp == Builtin::BIwmemcmp ||
12618                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12619                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12620                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12621 
12622     for (; MaxLength; --MaxLength) {
12623       APValue Char1, Char2;
12624       if (!ReadCurElems(Char1, Char2))
12625         return false;
12626       if (Char1.getInt().ne(Char2.getInt())) {
12627         if (IsWide) // wmemcmp compares with wchar_t signedness.
12628           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12629         // memcmp always compares unsigned chars.
12630         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12631       }
12632       if (StopAtNull && !Char1.getInt())
12633         return Success(0, E);
12634       assert(!(StopAtNull && !Char2.getInt()));
12635       if (!AdvanceElems())
12636         return false;
12637     }
12638     // We hit the strncmp / memcmp limit.
12639     return Success(0, E);
12640   }
12641 
12642   case Builtin::BI__atomic_always_lock_free:
12643   case Builtin::BI__atomic_is_lock_free:
12644   case Builtin::BI__c11_atomic_is_lock_free: {
12645     APSInt SizeVal;
12646     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12647       return false;
12648 
12649     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12650     // of two less than or equal to the maximum inline atomic width, we know it
12651     // is lock-free.  If the size isn't a power of two, or greater than the
12652     // maximum alignment where we promote atomics, we know it is not lock-free
12653     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12654     // the answer can only be determined at runtime; for example, 16-byte
12655     // atomics have lock-free implementations on some, but not all,
12656     // x86-64 processors.
12657 
12658     // Check power-of-two.
12659     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12660     if (Size.isPowerOfTwo()) {
12661       // Check against inlining width.
12662       unsigned InlineWidthBits =
12663           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12664       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12665         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12666             Size == CharUnits::One() ||
12667             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12668                                                 Expr::NPC_NeverValueDependent))
12669           // OK, we will inline appropriately-aligned operations of this size,
12670           // and _Atomic(T) is appropriately-aligned.
12671           return Success(1, E);
12672 
12673         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12674           castAs<PointerType>()->getPointeeType();
12675         if (!PointeeType->isIncompleteType() &&
12676             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12677           // OK, we will inline operations on this object.
12678           return Success(1, E);
12679         }
12680       }
12681     }
12682 
12683     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12684         Success(0, E) : Error(E);
12685   }
12686   case Builtin::BI__builtin_add_overflow:
12687   case Builtin::BI__builtin_sub_overflow:
12688   case Builtin::BI__builtin_mul_overflow:
12689   case Builtin::BI__builtin_sadd_overflow:
12690   case Builtin::BI__builtin_uadd_overflow:
12691   case Builtin::BI__builtin_uaddl_overflow:
12692   case Builtin::BI__builtin_uaddll_overflow:
12693   case Builtin::BI__builtin_usub_overflow:
12694   case Builtin::BI__builtin_usubl_overflow:
12695   case Builtin::BI__builtin_usubll_overflow:
12696   case Builtin::BI__builtin_umul_overflow:
12697   case Builtin::BI__builtin_umull_overflow:
12698   case Builtin::BI__builtin_umulll_overflow:
12699   case Builtin::BI__builtin_saddl_overflow:
12700   case Builtin::BI__builtin_saddll_overflow:
12701   case Builtin::BI__builtin_ssub_overflow:
12702   case Builtin::BI__builtin_ssubl_overflow:
12703   case Builtin::BI__builtin_ssubll_overflow:
12704   case Builtin::BI__builtin_smul_overflow:
12705   case Builtin::BI__builtin_smull_overflow:
12706   case Builtin::BI__builtin_smulll_overflow: {
12707     LValue ResultLValue;
12708     APSInt LHS, RHS;
12709 
12710     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12711     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12712         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12713         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12714       return false;
12715 
12716     APSInt Result;
12717     bool DidOverflow = false;
12718 
12719     // If the types don't have to match, enlarge all 3 to the largest of them.
12720     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12721         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12722         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12723       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12724                       ResultType->isSignedIntegerOrEnumerationType();
12725       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12726                       ResultType->isSignedIntegerOrEnumerationType();
12727       uint64_t LHSSize = LHS.getBitWidth();
12728       uint64_t RHSSize = RHS.getBitWidth();
12729       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12730       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12731 
12732       // Add an additional bit if the signedness isn't uniformly agreed to. We
12733       // could do this ONLY if there is a signed and an unsigned that both have
12734       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12735       // caught in the shrink-to-result later anyway.
12736       if (IsSigned && !AllSigned)
12737         ++MaxBits;
12738 
12739       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12740       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12741       Result = APSInt(MaxBits, !IsSigned);
12742     }
12743 
12744     // Find largest int.
12745     switch (BuiltinOp) {
12746     default:
12747       llvm_unreachable("Invalid value for BuiltinOp");
12748     case Builtin::BI__builtin_add_overflow:
12749     case Builtin::BI__builtin_sadd_overflow:
12750     case Builtin::BI__builtin_saddl_overflow:
12751     case Builtin::BI__builtin_saddll_overflow:
12752     case Builtin::BI__builtin_uadd_overflow:
12753     case Builtin::BI__builtin_uaddl_overflow:
12754     case Builtin::BI__builtin_uaddll_overflow:
12755       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12756                               : LHS.uadd_ov(RHS, DidOverflow);
12757       break;
12758     case Builtin::BI__builtin_sub_overflow:
12759     case Builtin::BI__builtin_ssub_overflow:
12760     case Builtin::BI__builtin_ssubl_overflow:
12761     case Builtin::BI__builtin_ssubll_overflow:
12762     case Builtin::BI__builtin_usub_overflow:
12763     case Builtin::BI__builtin_usubl_overflow:
12764     case Builtin::BI__builtin_usubll_overflow:
12765       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12766                               : LHS.usub_ov(RHS, DidOverflow);
12767       break;
12768     case Builtin::BI__builtin_mul_overflow:
12769     case Builtin::BI__builtin_smul_overflow:
12770     case Builtin::BI__builtin_smull_overflow:
12771     case Builtin::BI__builtin_smulll_overflow:
12772     case Builtin::BI__builtin_umul_overflow:
12773     case Builtin::BI__builtin_umull_overflow:
12774     case Builtin::BI__builtin_umulll_overflow:
12775       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12776                               : LHS.umul_ov(RHS, DidOverflow);
12777       break;
12778     }
12779 
12780     // In the case where multiple sizes are allowed, truncate and see if
12781     // the values are the same.
12782     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12783         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12784         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12785       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12786       // since it will give us the behavior of a TruncOrSelf in the case where
12787       // its parameter <= its size.  We previously set Result to be at least the
12788       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12789       // will work exactly like TruncOrSelf.
12790       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12791       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12792 
12793       if (!APSInt::isSameValue(Temp, Result))
12794         DidOverflow = true;
12795       Result = Temp;
12796     }
12797 
12798     APValue APV{Result};
12799     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12800       return false;
12801     return Success(DidOverflow, E);
12802   }
12803   }
12804 }
12805 
12806 /// Determine whether this is a pointer past the end of the complete
12807 /// object referred to by the lvalue.
isOnePastTheEndOfCompleteObject(const ASTContext & Ctx,const LValue & LV)12808 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12809                                             const LValue &LV) {
12810   // A null pointer can be viewed as being "past the end" but we don't
12811   // choose to look at it that way here.
12812   if (!LV.getLValueBase())
12813     return false;
12814 
12815   // If the designator is valid and refers to a subobject, we're not pointing
12816   // past the end.
12817   if (!LV.getLValueDesignator().Invalid &&
12818       !LV.getLValueDesignator().isOnePastTheEnd())
12819     return false;
12820 
12821   // A pointer to an incomplete type might be past-the-end if the type's size is
12822   // zero.  We cannot tell because the type is incomplete.
12823   QualType Ty = getType(LV.getLValueBase());
12824   if (Ty->isIncompleteType())
12825     return true;
12826 
12827   // We're a past-the-end pointer if we point to the byte after the object,
12828   // no matter what our type or path is.
12829   auto Size = Ctx.getTypeSizeInChars(Ty);
12830   return LV.getLValueOffset() == Size;
12831 }
12832 
12833 namespace {
12834 
12835 /// Data recursive integer evaluator of certain binary operators.
12836 ///
12837 /// We use a data recursive algorithm for binary operators so that we are able
12838 /// to handle extreme cases of chained binary operators without causing stack
12839 /// overflow.
12840 class DataRecursiveIntBinOpEvaluator {
12841   struct EvalResult {
12842     APValue Val;
12843     bool Failed = false;
12844 
12845     EvalResult() = default;
12846 
swap__anonbf0ddd822a11::DataRecursiveIntBinOpEvaluator::EvalResult12847     void swap(EvalResult &RHS) {
12848       Val.swap(RHS.Val);
12849       Failed = RHS.Failed;
12850       RHS.Failed = false;
12851     }
12852   };
12853 
12854   struct Job {
12855     const Expr *E;
12856     EvalResult LHSResult; // meaningful only for binary operator expression.
12857     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12858 
12859     Job() = default;
12860     Job(Job &&) = default;
12861 
startSpeculativeEval__anonbf0ddd822a11::DataRecursiveIntBinOpEvaluator::Job12862     void startSpeculativeEval(EvalInfo &Info) {
12863       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12864     }
12865 
12866   private:
12867     SpeculativeEvaluationRAII SpecEvalRAII;
12868   };
12869 
12870   SmallVector<Job, 16> Queue;
12871 
12872   IntExprEvaluator &IntEval;
12873   EvalInfo &Info;
12874   APValue &FinalResult;
12875 
12876 public:
DataRecursiveIntBinOpEvaluator(IntExprEvaluator & IntEval,APValue & Result)12877   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12878     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12879 
12880   /// True if \param E is a binary operator that we are going to handle
12881   /// data recursively.
12882   /// We handle binary operators that are comma, logical, or that have operands
12883   /// with integral or enumeration type.
shouldEnqueue(const BinaryOperator * E)12884   static bool shouldEnqueue(const BinaryOperator *E) {
12885     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12886            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12887             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12888             E->getRHS()->getType()->isIntegralOrEnumerationType());
12889   }
12890 
Traverse(const BinaryOperator * E)12891   bool Traverse(const BinaryOperator *E) {
12892     enqueue(E);
12893     EvalResult PrevResult;
12894     while (!Queue.empty())
12895       process(PrevResult);
12896 
12897     if (PrevResult.Failed) return false;
12898 
12899     FinalResult.swap(PrevResult.Val);
12900     return true;
12901   }
12902 
12903 private:
Success(uint64_t Value,const Expr * E,APValue & Result)12904   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12905     return IntEval.Success(Value, E, Result);
12906   }
Success(const APSInt & Value,const Expr * E,APValue & Result)12907   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12908     return IntEval.Success(Value, E, Result);
12909   }
Error(const Expr * E)12910   bool Error(const Expr *E) {
12911     return IntEval.Error(E);
12912   }
Error(const Expr * E,diag::kind D)12913   bool Error(const Expr *E, diag::kind D) {
12914     return IntEval.Error(E, D);
12915   }
12916 
CCEDiag(const Expr * E,diag::kind D)12917   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12918     return Info.CCEDiag(E, D);
12919   }
12920 
12921   // Returns true if visiting the RHS is necessary, false otherwise.
12922   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12923                          bool &SuppressRHSDiags);
12924 
12925   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12926                   const BinaryOperator *E, APValue &Result);
12927 
EvaluateExpr(const Expr * E,EvalResult & Result)12928   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12929     Result.Failed = !Evaluate(Result.Val, Info, E);
12930     if (Result.Failed)
12931       Result.Val = APValue();
12932   }
12933 
12934   void process(EvalResult &Result);
12935 
enqueue(const Expr * E)12936   void enqueue(const Expr *E) {
12937     E = E->IgnoreParens();
12938     Queue.resize(Queue.size()+1);
12939     Queue.back().E = E;
12940     Queue.back().Kind = Job::AnyExprKind;
12941   }
12942 };
12943 
12944 }
12945 
12946 bool DataRecursiveIntBinOpEvaluator::
VisitBinOpLHSOnly(EvalResult & LHSResult,const BinaryOperator * E,bool & SuppressRHSDiags)12947        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12948                          bool &SuppressRHSDiags) {
12949   if (E->getOpcode() == BO_Comma) {
12950     // Ignore LHS but note if we could not evaluate it.
12951     if (LHSResult.Failed)
12952       return Info.noteSideEffect();
12953     return true;
12954   }
12955 
12956   if (E->isLogicalOp()) {
12957     bool LHSAsBool;
12958     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12959       // We were able to evaluate the LHS, see if we can get away with not
12960       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12961       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12962         Success(LHSAsBool, E, LHSResult.Val);
12963         return false; // Ignore RHS
12964       }
12965     } else {
12966       LHSResult.Failed = true;
12967 
12968       // Since we weren't able to evaluate the left hand side, it
12969       // might have had side effects.
12970       if (!Info.noteSideEffect())
12971         return false;
12972 
12973       // We can't evaluate the LHS; however, sometimes the result
12974       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12975       // Don't ignore RHS and suppress diagnostics from this arm.
12976       SuppressRHSDiags = true;
12977     }
12978 
12979     return true;
12980   }
12981 
12982   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12983          E->getRHS()->getType()->isIntegralOrEnumerationType());
12984 
12985   if (LHSResult.Failed && !Info.noteFailure())
12986     return false; // Ignore RHS;
12987 
12988   return true;
12989 }
12990 
addOrSubLValueAsInteger(APValue & LVal,const APSInt & Index,bool IsSub)12991 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12992                                     bool IsSub) {
12993   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12994   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12995   // offsets.
12996   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12997   CharUnits &Offset = LVal.getLValueOffset();
12998   uint64_t Offset64 = Offset.getQuantity();
12999   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
13000   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
13001                                          : Offset64 + Index64);
13002 }
13003 
13004 bool DataRecursiveIntBinOpEvaluator::
VisitBinOp(const EvalResult & LHSResult,const EvalResult & RHSResult,const BinaryOperator * E,APValue & Result)13005        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13006                   const BinaryOperator *E, APValue &Result) {
13007   if (E->getOpcode() == BO_Comma) {
13008     if (RHSResult.Failed)
13009       return false;
13010     Result = RHSResult.Val;
13011     return true;
13012   }
13013 
13014   if (E->isLogicalOp()) {
13015     bool lhsResult, rhsResult;
13016     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
13017     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
13018 
13019     if (LHSIsOK) {
13020       if (RHSIsOK) {
13021         if (E->getOpcode() == BO_LOr)
13022           return Success(lhsResult || rhsResult, E, Result);
13023         else
13024           return Success(lhsResult && rhsResult, E, Result);
13025       }
13026     } else {
13027       if (RHSIsOK) {
13028         // We can't evaluate the LHS; however, sometimes the result
13029         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13030         if (rhsResult == (E->getOpcode() == BO_LOr))
13031           return Success(rhsResult, E, Result);
13032       }
13033     }
13034 
13035     return false;
13036   }
13037 
13038   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13039          E->getRHS()->getType()->isIntegralOrEnumerationType());
13040 
13041   if (LHSResult.Failed || RHSResult.Failed)
13042     return false;
13043 
13044   const APValue &LHSVal = LHSResult.Val;
13045   const APValue &RHSVal = RHSResult.Val;
13046 
13047   // Handle cases like (unsigned long)&a + 4.
13048   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
13049     Result = LHSVal;
13050     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
13051     return true;
13052   }
13053 
13054   // Handle cases like 4 + (unsigned long)&a
13055   if (E->getOpcode() == BO_Add &&
13056       RHSVal.isLValue() && LHSVal.isInt()) {
13057     Result = RHSVal;
13058     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
13059     return true;
13060   }
13061 
13062   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
13063     // Handle (intptr_t)&&A - (intptr_t)&&B.
13064     if (!LHSVal.getLValueOffset().isZero() ||
13065         !RHSVal.getLValueOffset().isZero())
13066       return false;
13067     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
13068     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
13069     if (!LHSExpr || !RHSExpr)
13070       return false;
13071     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13072     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13073     if (!LHSAddrExpr || !RHSAddrExpr)
13074       return false;
13075     // Make sure both labels come from the same function.
13076     if (LHSAddrExpr->getLabel()->getDeclContext() !=
13077         RHSAddrExpr->getLabel()->getDeclContext())
13078       return false;
13079     Result = APValue(LHSAddrExpr, RHSAddrExpr);
13080     return true;
13081   }
13082 
13083   // All the remaining cases expect both operands to be an integer
13084   if (!LHSVal.isInt() || !RHSVal.isInt())
13085     return Error(E);
13086 
13087   // Set up the width and signedness manually, in case it can't be deduced
13088   // from the operation we're performing.
13089   // FIXME: Don't do this in the cases where we can deduce it.
13090   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
13091                E->getType()->isUnsignedIntegerOrEnumerationType());
13092   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
13093                          RHSVal.getInt(), Value))
13094     return false;
13095   return Success(Value, E, Result);
13096 }
13097 
process(EvalResult & Result)13098 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
13099   Job &job = Queue.back();
13100 
13101   switch (job.Kind) {
13102     case Job::AnyExprKind: {
13103       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
13104         if (shouldEnqueue(Bop)) {
13105           job.Kind = Job::BinOpKind;
13106           enqueue(Bop->getLHS());
13107           return;
13108         }
13109       }
13110 
13111       EvaluateExpr(job.E, Result);
13112       Queue.pop_back();
13113       return;
13114     }
13115 
13116     case Job::BinOpKind: {
13117       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
13118       bool SuppressRHSDiags = false;
13119       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
13120         Queue.pop_back();
13121         return;
13122       }
13123       if (SuppressRHSDiags)
13124         job.startSpeculativeEval(Info);
13125       job.LHSResult.swap(Result);
13126       job.Kind = Job::BinOpVisitedLHSKind;
13127       enqueue(Bop->getRHS());
13128       return;
13129     }
13130 
13131     case Job::BinOpVisitedLHSKind: {
13132       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
13133       EvalResult RHS;
13134       RHS.swap(Result);
13135       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
13136       Queue.pop_back();
13137       return;
13138     }
13139   }
13140 
13141   llvm_unreachable("Invalid Job::Kind!");
13142 }
13143 
13144 namespace {
13145 enum class CmpResult {
13146   Unequal,
13147   Less,
13148   Equal,
13149   Greater,
13150   Unordered,
13151 };
13152 }
13153 
13154 template <class SuccessCB, class AfterCB>
13155 static bool
EvaluateComparisonBinaryOperator(EvalInfo & Info,const BinaryOperator * E,SuccessCB && Success,AfterCB && DoAfter)13156 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
13157                                  SuccessCB &&Success, AfterCB &&DoAfter) {
13158   assert(!E->isValueDependent());
13159   assert(E->isComparisonOp() && "expected comparison operator");
13160   assert((E->getOpcode() == BO_Cmp ||
13161           E->getType()->isIntegralOrEnumerationType()) &&
13162          "unsupported binary expression evaluation");
13163   auto Error = [&](const Expr *E) {
13164     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13165     return false;
13166   };
13167 
13168   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
13169   bool IsEquality = E->isEqualityOp();
13170 
13171   QualType LHSTy = E->getLHS()->getType();
13172   QualType RHSTy = E->getRHS()->getType();
13173 
13174   if (LHSTy->isIntegralOrEnumerationType() &&
13175       RHSTy->isIntegralOrEnumerationType()) {
13176     APSInt LHS, RHS;
13177     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
13178     if (!LHSOK && !Info.noteFailure())
13179       return false;
13180     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
13181       return false;
13182     if (LHS < RHS)
13183       return Success(CmpResult::Less, E);
13184     if (LHS > RHS)
13185       return Success(CmpResult::Greater, E);
13186     return Success(CmpResult::Equal, E);
13187   }
13188 
13189   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
13190     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
13191     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
13192 
13193     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
13194     if (!LHSOK && !Info.noteFailure())
13195       return false;
13196     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
13197       return false;
13198     if (LHSFX < RHSFX)
13199       return Success(CmpResult::Less, E);
13200     if (LHSFX > RHSFX)
13201       return Success(CmpResult::Greater, E);
13202     return Success(CmpResult::Equal, E);
13203   }
13204 
13205   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
13206     ComplexValue LHS, RHS;
13207     bool LHSOK;
13208     if (E->isAssignmentOp()) {
13209       LValue LV;
13210       EvaluateLValue(E->getLHS(), LV, Info);
13211       LHSOK = false;
13212     } else if (LHSTy->isRealFloatingType()) {
13213       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
13214       if (LHSOK) {
13215         LHS.makeComplexFloat();
13216         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
13217       }
13218     } else {
13219       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
13220     }
13221     if (!LHSOK && !Info.noteFailure())
13222       return false;
13223 
13224     if (E->getRHS()->getType()->isRealFloatingType()) {
13225       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
13226         return false;
13227       RHS.makeComplexFloat();
13228       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
13229     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13230       return false;
13231 
13232     if (LHS.isComplexFloat()) {
13233       APFloat::cmpResult CR_r =
13234         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
13235       APFloat::cmpResult CR_i =
13236         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
13237       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
13238       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13239     } else {
13240       assert(IsEquality && "invalid complex comparison");
13241       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
13242                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
13243       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13244     }
13245   }
13246 
13247   if (LHSTy->isRealFloatingType() &&
13248       RHSTy->isRealFloatingType()) {
13249     APFloat RHS(0.0), LHS(0.0);
13250 
13251     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
13252     if (!LHSOK && !Info.noteFailure())
13253       return false;
13254 
13255     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
13256       return false;
13257 
13258     assert(E->isComparisonOp() && "Invalid binary operator!");
13259     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
13260     if (!Info.InConstantContext &&
13261         APFloatCmpResult == APFloat::cmpUnordered &&
13262         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
13263       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
13264       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
13265       return false;
13266     }
13267     auto GetCmpRes = [&]() {
13268       switch (APFloatCmpResult) {
13269       case APFloat::cmpEqual:
13270         return CmpResult::Equal;
13271       case APFloat::cmpLessThan:
13272         return CmpResult::Less;
13273       case APFloat::cmpGreaterThan:
13274         return CmpResult::Greater;
13275       case APFloat::cmpUnordered:
13276         return CmpResult::Unordered;
13277       }
13278       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
13279     };
13280     return Success(GetCmpRes(), E);
13281   }
13282 
13283   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
13284     LValue LHSValue, RHSValue;
13285 
13286     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13287     if (!LHSOK && !Info.noteFailure())
13288       return false;
13289 
13290     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13291       return false;
13292 
13293     // Reject differing bases from the normal codepath; we special-case
13294     // comparisons to null.
13295     if (!HasSameBase(LHSValue, RHSValue)) {
13296       auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
13297         std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
13298         std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
13299         Info.FFDiag(E, DiagID)
13300             << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
13301         return false;
13302       };
13303       // Inequalities and subtractions between unrelated pointers have
13304       // unspecified or undefined behavior.
13305       if (!IsEquality)
13306         return DiagComparison(
13307             diag::note_constexpr_pointer_comparison_unspecified);
13308       // A constant address may compare equal to the address of a symbol.
13309       // The one exception is that address of an object cannot compare equal
13310       // to a null pointer constant.
13311       // TODO: Should we restrict this to actual null pointers, and exclude the
13312       // case of zero cast to pointer type?
13313       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
13314           (!RHSValue.Base && !RHSValue.Offset.isZero()))
13315         return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
13316                               !RHSValue.Base);
13317       // It's implementation-defined whether distinct literals will have
13318       // distinct addresses. In clang, the result of such a comparison is
13319       // unspecified, so it is not a constant expression. However, we do know
13320       // that the address of a literal will be non-null.
13321       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
13322           LHSValue.Base && RHSValue.Base)
13323         return DiagComparison(diag::note_constexpr_literal_comparison);
13324       // We can't tell whether weak symbols will end up pointing to the same
13325       // object.
13326       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
13327         return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
13328                               !IsWeakLValue(LHSValue));
13329       // We can't compare the address of the start of one object with the
13330       // past-the-end address of another object, per C++ DR1652.
13331       if (LHSValue.Base && LHSValue.Offset.isZero() &&
13332           isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
13333         return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13334                               true);
13335       if (RHSValue.Base && RHSValue.Offset.isZero() &&
13336            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
13337         return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13338                               false);
13339       // We can't tell whether an object is at the same address as another
13340       // zero sized object.
13341       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
13342           (LHSValue.Base && isZeroSized(RHSValue)))
13343         return DiagComparison(
13344             diag::note_constexpr_pointer_comparison_zero_sized);
13345       return Success(CmpResult::Unequal, E);
13346     }
13347 
13348     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13349     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13350 
13351     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13352     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13353 
13354     // C++11 [expr.rel]p3:
13355     //   Pointers to void (after pointer conversions) can be compared, with a
13356     //   result defined as follows: If both pointers represent the same
13357     //   address or are both the null pointer value, the result is true if the
13358     //   operator is <= or >= and false otherwise; otherwise the result is
13359     //   unspecified.
13360     // We interpret this as applying to pointers to *cv* void.
13361     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
13362       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
13363 
13364     // C++11 [expr.rel]p2:
13365     // - If two pointers point to non-static data members of the same object,
13366     //   or to subobjects or array elements fo such members, recursively, the
13367     //   pointer to the later declared member compares greater provided the
13368     //   two members have the same access control and provided their class is
13369     //   not a union.
13370     //   [...]
13371     // - Otherwise pointer comparisons are unspecified.
13372     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
13373       bool WasArrayIndex;
13374       unsigned Mismatch = FindDesignatorMismatch(
13375           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13376       // At the point where the designators diverge, the comparison has a
13377       // specified value if:
13378       //  - we are comparing array indices
13379       //  - we are comparing fields of a union, or fields with the same access
13380       // Otherwise, the result is unspecified and thus the comparison is not a
13381       // constant expression.
13382       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
13383           Mismatch < RHSDesignator.Entries.size()) {
13384         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13385         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13386         if (!LF && !RF)
13387           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13388         else if (!LF)
13389           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13390               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13391               << RF->getParent() << RF;
13392         else if (!RF)
13393           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13394               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13395               << LF->getParent() << LF;
13396         else if (!LF->getParent()->isUnion() &&
13397                  LF->getAccess() != RF->getAccess())
13398           Info.CCEDiag(E,
13399                        diag::note_constexpr_pointer_comparison_differing_access)
13400               << LF << LF->getAccess() << RF << RF->getAccess()
13401               << LF->getParent();
13402       }
13403     }
13404 
13405     // The comparison here must be unsigned, and performed with the same
13406     // width as the pointer.
13407     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13408     uint64_t CompareLHS = LHSOffset.getQuantity();
13409     uint64_t CompareRHS = RHSOffset.getQuantity();
13410     assert(PtrSize <= 64 && "Unexpected pointer width");
13411     uint64_t Mask = ~0ULL >> (64 - PtrSize);
13412     CompareLHS &= Mask;
13413     CompareRHS &= Mask;
13414 
13415     // If there is a base and this is a relational operator, we can only
13416     // compare pointers within the object in question; otherwise, the result
13417     // depends on where the object is located in memory.
13418     if (!LHSValue.Base.isNull() && IsRelational) {
13419       QualType BaseTy = getType(LHSValue.Base);
13420       if (BaseTy->isIncompleteType())
13421         return Error(E);
13422       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13423       uint64_t OffsetLimit = Size.getQuantity();
13424       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13425         return Error(E);
13426     }
13427 
13428     if (CompareLHS < CompareRHS)
13429       return Success(CmpResult::Less, E);
13430     if (CompareLHS > CompareRHS)
13431       return Success(CmpResult::Greater, E);
13432     return Success(CmpResult::Equal, E);
13433   }
13434 
13435   if (LHSTy->isMemberPointerType()) {
13436     assert(IsEquality && "unexpected member pointer operation");
13437     assert(RHSTy->isMemberPointerType() && "invalid comparison");
13438 
13439     MemberPtr LHSValue, RHSValue;
13440 
13441     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13442     if (!LHSOK && !Info.noteFailure())
13443       return false;
13444 
13445     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13446       return false;
13447 
13448     // If either operand is a pointer to a weak function, the comparison is not
13449     // constant.
13450     if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
13451       Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13452           << LHSValue.getDecl();
13453       return false;
13454     }
13455     if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
13456       Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13457           << RHSValue.getDecl();
13458       return false;
13459     }
13460 
13461     // C++11 [expr.eq]p2:
13462     //   If both operands are null, they compare equal. Otherwise if only one is
13463     //   null, they compare unequal.
13464     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13465       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13466       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13467     }
13468 
13469     //   Otherwise if either is a pointer to a virtual member function, the
13470     //   result is unspecified.
13471     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13472       if (MD->isVirtual())
13473         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13474     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13475       if (MD->isVirtual())
13476         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13477 
13478     //   Otherwise they compare equal if and only if they would refer to the
13479     //   same member of the same most derived object or the same subobject if
13480     //   they were dereferenced with a hypothetical object of the associated
13481     //   class type.
13482     bool Equal = LHSValue == RHSValue;
13483     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13484   }
13485 
13486   if (LHSTy->isNullPtrType()) {
13487     assert(E->isComparisonOp() && "unexpected nullptr operation");
13488     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13489     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13490     // are compared, the result is true of the operator is <=, >= or ==, and
13491     // false otherwise.
13492     LValue Res;
13493     if (!EvaluatePointer(E->getLHS(), Res, Info) ||
13494         !EvaluatePointer(E->getRHS(), Res, Info))
13495       return false;
13496     return Success(CmpResult::Equal, E);
13497   }
13498 
13499   return DoAfter();
13500 }
13501 
VisitBinCmp(const BinaryOperator * E)13502 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13503   if (!CheckLiteralType(Info, E))
13504     return false;
13505 
13506   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13507     ComparisonCategoryResult CCR;
13508     switch (CR) {
13509     case CmpResult::Unequal:
13510       llvm_unreachable("should never produce Unequal for three-way comparison");
13511     case CmpResult::Less:
13512       CCR = ComparisonCategoryResult::Less;
13513       break;
13514     case CmpResult::Equal:
13515       CCR = ComparisonCategoryResult::Equal;
13516       break;
13517     case CmpResult::Greater:
13518       CCR = ComparisonCategoryResult::Greater;
13519       break;
13520     case CmpResult::Unordered:
13521       CCR = ComparisonCategoryResult::Unordered;
13522       break;
13523     }
13524     // Evaluation succeeded. Lookup the information for the comparison category
13525     // type and fetch the VarDecl for the result.
13526     const ComparisonCategoryInfo &CmpInfo =
13527         Info.Ctx.CompCategories.getInfoForType(E->getType());
13528     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13529     // Check and evaluate the result as a constant expression.
13530     LValue LV;
13531     LV.set(VD);
13532     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13533       return false;
13534     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13535                                    ConstantExprKind::Normal);
13536   };
13537   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13538     return ExprEvaluatorBaseTy::VisitBinCmp(E);
13539   });
13540 }
13541 
VisitCXXParenListInitExpr(const CXXParenListInitExpr * E)13542 bool RecordExprEvaluator::VisitCXXParenListInitExpr(
13543     const CXXParenListInitExpr *E) {
13544   return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
13545 }
13546 
VisitBinaryOperator(const BinaryOperator * E)13547 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13548   // We don't support assignment in C. C++ assignments don't get here because
13549   // assignment is an lvalue in C++.
13550   if (E->isAssignmentOp()) {
13551     Error(E);
13552     if (!Info.noteFailure())
13553       return false;
13554   }
13555 
13556   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13557     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13558 
13559   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13560           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13561          "DataRecursiveIntBinOpEvaluator should have handled integral types");
13562 
13563   if (E->isComparisonOp()) {
13564     // Evaluate builtin binary comparisons by evaluating them as three-way
13565     // comparisons and then translating the result.
13566     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13567       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13568              "should only produce Unequal for equality comparisons");
13569       bool IsEqual   = CR == CmpResult::Equal,
13570            IsLess    = CR == CmpResult::Less,
13571            IsGreater = CR == CmpResult::Greater;
13572       auto Op = E->getOpcode();
13573       switch (Op) {
13574       default:
13575         llvm_unreachable("unsupported binary operator");
13576       case BO_EQ:
13577       case BO_NE:
13578         return Success(IsEqual == (Op == BO_EQ), E);
13579       case BO_LT:
13580         return Success(IsLess, E);
13581       case BO_GT:
13582         return Success(IsGreater, E);
13583       case BO_LE:
13584         return Success(IsEqual || IsLess, E);
13585       case BO_GE:
13586         return Success(IsEqual || IsGreater, E);
13587       }
13588     };
13589     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13590       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13591     });
13592   }
13593 
13594   QualType LHSTy = E->getLHS()->getType();
13595   QualType RHSTy = E->getRHS()->getType();
13596 
13597   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13598       E->getOpcode() == BO_Sub) {
13599     LValue LHSValue, RHSValue;
13600 
13601     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13602     if (!LHSOK && !Info.noteFailure())
13603       return false;
13604 
13605     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13606       return false;
13607 
13608     // Reject differing bases from the normal codepath; we special-case
13609     // comparisons to null.
13610     if (!HasSameBase(LHSValue, RHSValue)) {
13611       // Handle &&A - &&B.
13612       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13613         return Error(E);
13614       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13615       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13616       if (!LHSExpr || !RHSExpr)
13617         return Error(E);
13618       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13619       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13620       if (!LHSAddrExpr || !RHSAddrExpr)
13621         return Error(E);
13622       // Make sure both labels come from the same function.
13623       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13624           RHSAddrExpr->getLabel()->getDeclContext())
13625         return Error(E);
13626       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13627     }
13628     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13629     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13630 
13631     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13632     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13633 
13634     // C++11 [expr.add]p6:
13635     //   Unless both pointers point to elements of the same array object, or
13636     //   one past the last element of the array object, the behavior is
13637     //   undefined.
13638     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13639         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13640                                 RHSDesignator))
13641       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13642 
13643     QualType Type = E->getLHS()->getType();
13644     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13645 
13646     CharUnits ElementSize;
13647     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13648       return false;
13649 
13650     // As an extension, a type may have zero size (empty struct or union in
13651     // C, array of zero length). Pointer subtraction in such cases has
13652     // undefined behavior, so is not constant.
13653     if (ElementSize.isZero()) {
13654       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13655           << ElementType;
13656       return false;
13657     }
13658 
13659     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13660     // and produce incorrect results when it overflows. Such behavior
13661     // appears to be non-conforming, but is common, so perhaps we should
13662     // assume the standard intended for such cases to be undefined behavior
13663     // and check for them.
13664 
13665     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13666     // overflow in the final conversion to ptrdiff_t.
13667     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13668     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13669     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13670                     false);
13671     APSInt TrueResult = (LHS - RHS) / ElemSize;
13672     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13673 
13674     if (Result.extend(65) != TrueResult &&
13675         !HandleOverflow(Info, E, TrueResult, E->getType()))
13676       return false;
13677     return Success(Result, E);
13678   }
13679 
13680   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13681 }
13682 
13683 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13684 /// a result as the expression's type.
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)13685 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13686                                     const UnaryExprOrTypeTraitExpr *E) {
13687   switch(E->getKind()) {
13688   case UETT_PreferredAlignOf:
13689   case UETT_AlignOf: {
13690     if (E->isArgumentType())
13691       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13692                      E);
13693     else
13694       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13695                      E);
13696   }
13697 
13698   case UETT_VecStep: {
13699     QualType Ty = E->getTypeOfArgument();
13700 
13701     if (Ty->isVectorType()) {
13702       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13703 
13704       // The vec_step built-in functions that take a 3-component
13705       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13706       if (n == 3)
13707         n = 4;
13708 
13709       return Success(n, E);
13710     } else
13711       return Success(1, E);
13712   }
13713 
13714   case UETT_DataSizeOf:
13715   case UETT_SizeOf: {
13716     QualType SrcTy = E->getTypeOfArgument();
13717     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13718     //   the result is the size of the referenced type."
13719     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13720       SrcTy = Ref->getPointeeType();
13721 
13722     CharUnits Sizeof;
13723     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
13724                       E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
13725                                                       : SizeOfType::SizeOf)) {
13726       return false;
13727     }
13728     return Success(Sizeof, E);
13729   }
13730   case UETT_OpenMPRequiredSimdAlign:
13731     assert(E->isArgumentType());
13732     return Success(
13733         Info.Ctx.toCharUnitsFromBits(
13734                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13735             .getQuantity(),
13736         E);
13737   case UETT_VectorElements: {
13738     QualType Ty = E->getTypeOfArgument();
13739     // If the vector has a fixed size, we can determine the number of elements
13740     // at compile time.
13741     if (Ty->isVectorType())
13742       return Success(Ty->castAs<VectorType>()->getNumElements(), E);
13743 
13744     assert(Ty->isSizelessVectorType());
13745     if (Info.InConstantContext)
13746       Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
13747           << E->getSourceRange();
13748 
13749     return false;
13750   }
13751   }
13752 
13753   llvm_unreachable("unknown expr/type trait");
13754 }
13755 
VisitOffsetOfExpr(const OffsetOfExpr * OOE)13756 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13757   CharUnits Result;
13758   unsigned n = OOE->getNumComponents();
13759   if (n == 0)
13760     return Error(OOE);
13761   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13762   for (unsigned i = 0; i != n; ++i) {
13763     OffsetOfNode ON = OOE->getComponent(i);
13764     switch (ON.getKind()) {
13765     case OffsetOfNode::Array: {
13766       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13767       APSInt IdxResult;
13768       if (!EvaluateInteger(Idx, IdxResult, Info))
13769         return false;
13770       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13771       if (!AT)
13772         return Error(OOE);
13773       CurrentType = AT->getElementType();
13774       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13775       Result += IdxResult.getSExtValue() * ElementSize;
13776       break;
13777     }
13778 
13779     case OffsetOfNode::Field: {
13780       FieldDecl *MemberDecl = ON.getField();
13781       const RecordType *RT = CurrentType->getAs<RecordType>();
13782       if (!RT)
13783         return Error(OOE);
13784       RecordDecl *RD = RT->getDecl();
13785       if (RD->isInvalidDecl()) return false;
13786       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13787       unsigned i = MemberDecl->getFieldIndex();
13788       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13789       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13790       CurrentType = MemberDecl->getType().getNonReferenceType();
13791       break;
13792     }
13793 
13794     case OffsetOfNode::Identifier:
13795       llvm_unreachable("dependent __builtin_offsetof");
13796 
13797     case OffsetOfNode::Base: {
13798       CXXBaseSpecifier *BaseSpec = ON.getBase();
13799       if (BaseSpec->isVirtual())
13800         return Error(OOE);
13801 
13802       // Find the layout of the class whose base we are looking into.
13803       const RecordType *RT = CurrentType->getAs<RecordType>();
13804       if (!RT)
13805         return Error(OOE);
13806       RecordDecl *RD = RT->getDecl();
13807       if (RD->isInvalidDecl()) return false;
13808       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13809 
13810       // Find the base class itself.
13811       CurrentType = BaseSpec->getType();
13812       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13813       if (!BaseRT)
13814         return Error(OOE);
13815 
13816       // Add the offset to the base.
13817       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13818       break;
13819     }
13820     }
13821   }
13822   return Success(Result, OOE);
13823 }
13824 
VisitUnaryOperator(const UnaryOperator * E)13825 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13826   switch (E->getOpcode()) {
13827   default:
13828     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13829     // See C99 6.6p3.
13830     return Error(E);
13831   case UO_Extension:
13832     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13833     // If so, we could clear the diagnostic ID.
13834     return Visit(E->getSubExpr());
13835   case UO_Plus:
13836     // The result is just the value.
13837     return Visit(E->getSubExpr());
13838   case UO_Minus: {
13839     if (!Visit(E->getSubExpr()))
13840       return false;
13841     if (!Result.isInt()) return Error(E);
13842     const APSInt &Value = Result.getInt();
13843     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
13844       if (Info.checkingForUndefinedBehavior())
13845         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13846                                          diag::warn_integer_constant_overflow)
13847             << toString(Value, 10) << E->getType() << E->getSourceRange();
13848 
13849       if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13850                           E->getType()))
13851         return false;
13852     }
13853     return Success(-Value, E);
13854   }
13855   case UO_Not: {
13856     if (!Visit(E->getSubExpr()))
13857       return false;
13858     if (!Result.isInt()) return Error(E);
13859     return Success(~Result.getInt(), E);
13860   }
13861   case UO_LNot: {
13862     bool bres;
13863     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13864       return false;
13865     return Success(!bres, E);
13866   }
13867   }
13868 }
13869 
13870 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13871 /// result type is integer.
VisitCastExpr(const CastExpr * E)13872 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13873   const Expr *SubExpr = E->getSubExpr();
13874   QualType DestType = E->getType();
13875   QualType SrcType = SubExpr->getType();
13876 
13877   switch (E->getCastKind()) {
13878   case CK_BaseToDerived:
13879   case CK_DerivedToBase:
13880   case CK_UncheckedDerivedToBase:
13881   case CK_Dynamic:
13882   case CK_ToUnion:
13883   case CK_ArrayToPointerDecay:
13884   case CK_FunctionToPointerDecay:
13885   case CK_NullToPointer:
13886   case CK_NullToMemberPointer:
13887   case CK_BaseToDerivedMemberPointer:
13888   case CK_DerivedToBaseMemberPointer:
13889   case CK_ReinterpretMemberPointer:
13890   case CK_ConstructorConversion:
13891   case CK_IntegralToPointer:
13892   case CK_ToVoid:
13893   case CK_VectorSplat:
13894   case CK_IntegralToFloating:
13895   case CK_FloatingCast:
13896   case CK_CPointerToObjCPointerCast:
13897   case CK_BlockPointerToObjCPointerCast:
13898   case CK_AnyPointerToBlockPointerCast:
13899   case CK_ObjCObjectLValueCast:
13900   case CK_FloatingRealToComplex:
13901   case CK_FloatingComplexToReal:
13902   case CK_FloatingComplexCast:
13903   case CK_FloatingComplexToIntegralComplex:
13904   case CK_IntegralRealToComplex:
13905   case CK_IntegralComplexCast:
13906   case CK_IntegralComplexToFloatingComplex:
13907   case CK_BuiltinFnToFnPtr:
13908   case CK_ZeroToOCLOpaqueType:
13909   case CK_NonAtomicToAtomic:
13910   case CK_AddressSpaceConversion:
13911   case CK_IntToOCLSampler:
13912   case CK_FloatingToFixedPoint:
13913   case CK_FixedPointToFloating:
13914   case CK_FixedPointCast:
13915   case CK_IntegralToFixedPoint:
13916   case CK_MatrixCast:
13917     llvm_unreachable("invalid cast kind for integral value");
13918 
13919   case CK_BitCast:
13920   case CK_Dependent:
13921   case CK_LValueBitCast:
13922   case CK_ARCProduceObject:
13923   case CK_ARCConsumeObject:
13924   case CK_ARCReclaimReturnedObject:
13925   case CK_ARCExtendBlockObject:
13926   case CK_CopyAndAutoreleaseBlockObject:
13927     return Error(E);
13928 
13929   case CK_UserDefinedConversion:
13930   case CK_LValueToRValue:
13931   case CK_AtomicToNonAtomic:
13932   case CK_NoOp:
13933   case CK_LValueToRValueBitCast:
13934     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13935 
13936   case CK_MemberPointerToBoolean:
13937   case CK_PointerToBoolean:
13938   case CK_IntegralToBoolean:
13939   case CK_FloatingToBoolean:
13940   case CK_BooleanToSignedIntegral:
13941   case CK_FloatingComplexToBoolean:
13942   case CK_IntegralComplexToBoolean: {
13943     bool BoolResult;
13944     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13945       return false;
13946     uint64_t IntResult = BoolResult;
13947     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13948       IntResult = (uint64_t)-1;
13949     return Success(IntResult, E);
13950   }
13951 
13952   case CK_FixedPointToIntegral: {
13953     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13954     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13955       return false;
13956     bool Overflowed;
13957     llvm::APSInt Result = Src.convertToInt(
13958         Info.Ctx.getIntWidth(DestType),
13959         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13960     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13961       return false;
13962     return Success(Result, E);
13963   }
13964 
13965   case CK_FixedPointToBoolean: {
13966     // Unsigned padding does not affect this.
13967     APValue Val;
13968     if (!Evaluate(Val, Info, SubExpr))
13969       return false;
13970     return Success(Val.getFixedPoint().getBoolValue(), E);
13971   }
13972 
13973   case CK_IntegralCast: {
13974     if (!Visit(SubExpr))
13975       return false;
13976 
13977     if (!Result.isInt()) {
13978       // Allow casts of address-of-label differences if they are no-ops
13979       // or narrowing.  (The narrowing case isn't actually guaranteed to
13980       // be constant-evaluatable except in some narrow cases which are hard
13981       // to detect here.  We let it through on the assumption the user knows
13982       // what they are doing.)
13983       if (Result.isAddrLabelDiff())
13984         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13985       // Only allow casts of lvalues if they are lossless.
13986       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13987     }
13988 
13989     if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
13990         Info.EvalMode == EvalInfo::EM_ConstantExpression &&
13991         DestType->isEnumeralType()) {
13992 
13993       bool ConstexprVar = true;
13994 
13995       // We know if we are here that we are in a context that we might require
13996       // a constant expression or a context that requires a constant
13997       // value. But if we are initializing a value we don't know if it is a
13998       // constexpr variable or not. We can check the EvaluatingDecl to determine
13999       // if it constexpr or not. If not then we don't want to emit a diagnostic.
14000       if (const auto *VD = dyn_cast_or_null<VarDecl>(
14001               Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
14002         ConstexprVar = VD->isConstexpr();
14003 
14004       const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
14005       const EnumDecl *ED = ET->getDecl();
14006       // Check that the value is within the range of the enumeration values.
14007       //
14008       // This corressponds to [expr.static.cast]p10 which says:
14009       // A value of integral or enumeration type can be explicitly converted
14010       // to a complete enumeration type ... If the enumeration type does not
14011       // have a fixed underlying type, the value is unchanged if the original
14012       // value is within the range of the enumeration values ([dcl.enum]), and
14013       // otherwise, the behavior is undefined.
14014       //
14015       // This was resolved as part of DR2338 which has CD5 status.
14016       if (!ED->isFixed()) {
14017         llvm::APInt Min;
14018         llvm::APInt Max;
14019 
14020         ED->getValueRange(Max, Min);
14021         --Max;
14022 
14023         if (ED->getNumNegativeBits() && ConstexprVar &&
14024             (Max.slt(Result.getInt().getSExtValue()) ||
14025              Min.sgt(Result.getInt().getSExtValue())))
14026           Info.Ctx.getDiagnostics().Report(
14027               E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
14028               << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
14029               << Max.getSExtValue() << ED;
14030         else if (!ED->getNumNegativeBits() && ConstexprVar &&
14031                  Max.ult(Result.getInt().getZExtValue()))
14032           Info.Ctx.getDiagnostics().Report(
14033               E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
14034               << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
14035               << Max.getZExtValue() << ED;
14036       }
14037     }
14038 
14039     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
14040                                       Result.getInt()), E);
14041   }
14042 
14043   case CK_PointerToIntegral: {
14044     CCEDiag(E, diag::note_constexpr_invalid_cast)
14045         << 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
14046 
14047     LValue LV;
14048     if (!EvaluatePointer(SubExpr, LV, Info))
14049       return false;
14050 
14051     if (LV.getLValueBase()) {
14052       // Only allow based lvalue casts if they are lossless.
14053       // FIXME: Allow a larger integer size than the pointer size, and allow
14054       // narrowing back down to pointer width in subsequent integral casts.
14055       // FIXME: Check integer type's active bits, not its type size.
14056       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
14057         return Error(E);
14058 
14059       LV.Designator.setInvalid();
14060       LV.moveInto(Result);
14061       return true;
14062     }
14063 
14064     APSInt AsInt;
14065     APValue V;
14066     LV.moveInto(V);
14067     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
14068       llvm_unreachable("Can't cast this!");
14069 
14070     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
14071   }
14072 
14073   case CK_IntegralComplexToReal: {
14074     ComplexValue C;
14075     if (!EvaluateComplex(SubExpr, C, Info))
14076       return false;
14077     return Success(C.getComplexIntReal(), E);
14078   }
14079 
14080   case CK_FloatingToIntegral: {
14081     APFloat F(0.0);
14082     if (!EvaluateFloat(SubExpr, F, Info))
14083       return false;
14084 
14085     APSInt Value;
14086     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
14087       return false;
14088     return Success(Value, E);
14089   }
14090   }
14091 
14092   llvm_unreachable("unknown cast resulting in integral value");
14093 }
14094 
VisitUnaryReal(const UnaryOperator * E)14095 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14096   if (E->getSubExpr()->getType()->isAnyComplexType()) {
14097     ComplexValue LV;
14098     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
14099       return false;
14100     if (!LV.isComplexInt())
14101       return Error(E);
14102     return Success(LV.getComplexIntReal(), E);
14103   }
14104 
14105   return Visit(E->getSubExpr());
14106 }
14107 
VisitUnaryImag(const UnaryOperator * E)14108 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14109   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
14110     ComplexValue LV;
14111     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
14112       return false;
14113     if (!LV.isComplexInt())
14114       return Error(E);
14115     return Success(LV.getComplexIntImag(), E);
14116   }
14117 
14118   VisitIgnoredValue(E->getSubExpr());
14119   return Success(0, E);
14120 }
14121 
VisitSizeOfPackExpr(const SizeOfPackExpr * E)14122 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
14123   return Success(E->getPackLength(), E);
14124 }
14125 
VisitCXXNoexceptExpr(const CXXNoexceptExpr * E)14126 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
14127   return Success(E->getValue(), E);
14128 }
14129 
VisitConceptSpecializationExpr(const ConceptSpecializationExpr * E)14130 bool IntExprEvaluator::VisitConceptSpecializationExpr(
14131        const ConceptSpecializationExpr *E) {
14132   return Success(E->isSatisfied(), E);
14133 }
14134 
VisitRequiresExpr(const RequiresExpr * E)14135 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
14136   return Success(E->isSatisfied(), E);
14137 }
14138 
VisitUnaryOperator(const UnaryOperator * E)14139 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14140   switch (E->getOpcode()) {
14141     default:
14142       // Invalid unary operators
14143       return Error(E);
14144     case UO_Plus:
14145       // The result is just the value.
14146       return Visit(E->getSubExpr());
14147     case UO_Minus: {
14148       if (!Visit(E->getSubExpr())) return false;
14149       if (!Result.isFixedPoint())
14150         return Error(E);
14151       bool Overflowed;
14152       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
14153       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
14154         return false;
14155       return Success(Negated, E);
14156     }
14157     case UO_LNot: {
14158       bool bres;
14159       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14160         return false;
14161       return Success(!bres, E);
14162     }
14163   }
14164 }
14165 
VisitCastExpr(const CastExpr * E)14166 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
14167   const Expr *SubExpr = E->getSubExpr();
14168   QualType DestType = E->getType();
14169   assert(DestType->isFixedPointType() &&
14170          "Expected destination type to be a fixed point type");
14171   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
14172 
14173   switch (E->getCastKind()) {
14174   case CK_FixedPointCast: {
14175     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14176     if (!EvaluateFixedPoint(SubExpr, Src, Info))
14177       return false;
14178     bool Overflowed;
14179     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
14180     if (Overflowed) {
14181       if (Info.checkingForUndefinedBehavior())
14182         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14183                                          diag::warn_fixedpoint_constant_overflow)
14184           << Result.toString() << E->getType();
14185       if (!HandleOverflow(Info, E, Result, E->getType()))
14186         return false;
14187     }
14188     return Success(Result, E);
14189   }
14190   case CK_IntegralToFixedPoint: {
14191     APSInt Src;
14192     if (!EvaluateInteger(SubExpr, Src, Info))
14193       return false;
14194 
14195     bool Overflowed;
14196     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
14197         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
14198 
14199     if (Overflowed) {
14200       if (Info.checkingForUndefinedBehavior())
14201         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14202                                          diag::warn_fixedpoint_constant_overflow)
14203           << IntResult.toString() << E->getType();
14204       if (!HandleOverflow(Info, E, IntResult, E->getType()))
14205         return false;
14206     }
14207 
14208     return Success(IntResult, E);
14209   }
14210   case CK_FloatingToFixedPoint: {
14211     APFloat Src(0.0);
14212     if (!EvaluateFloat(SubExpr, Src, Info))
14213       return false;
14214 
14215     bool Overflowed;
14216     APFixedPoint Result = APFixedPoint::getFromFloatValue(
14217         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
14218 
14219     if (Overflowed) {
14220       if (Info.checkingForUndefinedBehavior())
14221         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14222                                          diag::warn_fixedpoint_constant_overflow)
14223           << Result.toString() << E->getType();
14224       if (!HandleOverflow(Info, E, Result, E->getType()))
14225         return false;
14226     }
14227 
14228     return Success(Result, E);
14229   }
14230   case CK_NoOp:
14231   case CK_LValueToRValue:
14232     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14233   default:
14234     return Error(E);
14235   }
14236 }
14237 
VisitBinaryOperator(const BinaryOperator * E)14238 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14239   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14240     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14241 
14242   const Expr *LHS = E->getLHS();
14243   const Expr *RHS = E->getRHS();
14244   FixedPointSemantics ResultFXSema =
14245       Info.Ctx.getFixedPointSemantics(E->getType());
14246 
14247   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
14248   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
14249     return false;
14250   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
14251   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
14252     return false;
14253 
14254   bool OpOverflow = false, ConversionOverflow = false;
14255   APFixedPoint Result(LHSFX.getSemantics());
14256   switch (E->getOpcode()) {
14257   case BO_Add: {
14258     Result = LHSFX.add(RHSFX, &OpOverflow)
14259                   .convert(ResultFXSema, &ConversionOverflow);
14260     break;
14261   }
14262   case BO_Sub: {
14263     Result = LHSFX.sub(RHSFX, &OpOverflow)
14264                   .convert(ResultFXSema, &ConversionOverflow);
14265     break;
14266   }
14267   case BO_Mul: {
14268     Result = LHSFX.mul(RHSFX, &OpOverflow)
14269                   .convert(ResultFXSema, &ConversionOverflow);
14270     break;
14271   }
14272   case BO_Div: {
14273     if (RHSFX.getValue() == 0) {
14274       Info.FFDiag(E, diag::note_expr_divide_by_zero);
14275       return false;
14276     }
14277     Result = LHSFX.div(RHSFX, &OpOverflow)
14278                   .convert(ResultFXSema, &ConversionOverflow);
14279     break;
14280   }
14281   case BO_Shl:
14282   case BO_Shr: {
14283     FixedPointSemantics LHSSema = LHSFX.getSemantics();
14284     llvm::APSInt RHSVal = RHSFX.getValue();
14285 
14286     unsigned ShiftBW =
14287         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
14288     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
14289     // Embedded-C 4.1.6.2.2:
14290     //   The right operand must be nonnegative and less than the total number
14291     //   of (nonpadding) bits of the fixed-point operand ...
14292     if (RHSVal.isNegative())
14293       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
14294     else if (Amt != RHSVal)
14295       Info.CCEDiag(E, diag::note_constexpr_large_shift)
14296           << RHSVal << E->getType() << ShiftBW;
14297 
14298     if (E->getOpcode() == BO_Shl)
14299       Result = LHSFX.shl(Amt, &OpOverflow);
14300     else
14301       Result = LHSFX.shr(Amt, &OpOverflow);
14302     break;
14303   }
14304   default:
14305     return false;
14306   }
14307   if (OpOverflow || ConversionOverflow) {
14308     if (Info.checkingForUndefinedBehavior())
14309       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14310                                        diag::warn_fixedpoint_constant_overflow)
14311         << Result.toString() << E->getType();
14312     if (!HandleOverflow(Info, E, Result, E->getType()))
14313       return false;
14314   }
14315   return Success(Result, E);
14316 }
14317 
14318 //===----------------------------------------------------------------------===//
14319 // Float Evaluation
14320 //===----------------------------------------------------------------------===//
14321 
14322 namespace {
14323 class FloatExprEvaluator
14324   : public ExprEvaluatorBase<FloatExprEvaluator> {
14325   APFloat &Result;
14326 public:
FloatExprEvaluator(EvalInfo & info,APFloat & result)14327   FloatExprEvaluator(EvalInfo &info, APFloat &result)
14328     : ExprEvaluatorBaseTy(info), Result(result) {}
14329 
Success(const APValue & V,const Expr * e)14330   bool Success(const APValue &V, const Expr *e) {
14331     Result = V.getFloat();
14332     return true;
14333   }
14334 
ZeroInitialization(const Expr * E)14335   bool ZeroInitialization(const Expr *E) {
14336     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
14337     return true;
14338   }
14339 
14340   bool VisitCallExpr(const CallExpr *E);
14341 
14342   bool VisitUnaryOperator(const UnaryOperator *E);
14343   bool VisitBinaryOperator(const BinaryOperator *E);
14344   bool VisitFloatingLiteral(const FloatingLiteral *E);
14345   bool VisitCastExpr(const CastExpr *E);
14346 
14347   bool VisitUnaryReal(const UnaryOperator *E);
14348   bool VisitUnaryImag(const UnaryOperator *E);
14349 
14350   // FIXME: Missing: array subscript of vector, member of vector
14351 };
14352 } // end anonymous namespace
14353 
EvaluateFloat(const Expr * E,APFloat & Result,EvalInfo & Info)14354 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
14355   assert(!E->isValueDependent());
14356   assert(E->isPRValue() && E->getType()->isRealFloatingType());
14357   return FloatExprEvaluator(Info, Result).Visit(E);
14358 }
14359 
TryEvaluateBuiltinNaN(const ASTContext & Context,QualType ResultTy,const Expr * Arg,bool SNaN,llvm::APFloat & Result)14360 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
14361                                   QualType ResultTy,
14362                                   const Expr *Arg,
14363                                   bool SNaN,
14364                                   llvm::APFloat &Result) {
14365   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
14366   if (!S) return false;
14367 
14368   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
14369 
14370   llvm::APInt fill;
14371 
14372   // Treat empty strings as if they were zero.
14373   if (S->getString().empty())
14374     fill = llvm::APInt(32, 0);
14375   else if (S->getString().getAsInteger(0, fill))
14376     return false;
14377 
14378   if (Context.getTargetInfo().isNan2008()) {
14379     if (SNaN)
14380       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14381     else
14382       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14383   } else {
14384     // Prior to IEEE 754-2008, architectures were allowed to choose whether
14385     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
14386     // a different encoding to what became a standard in 2008, and for pre-
14387     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
14388     // sNaN. This is now known as "legacy NaN" encoding.
14389     if (SNaN)
14390       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14391     else
14392       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14393   }
14394 
14395   return true;
14396 }
14397 
VisitCallExpr(const CallExpr * E)14398 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
14399   if (!IsConstantEvaluatedBuiltinCall(E))
14400     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14401 
14402   switch (E->getBuiltinCallee()) {
14403   default:
14404     return false;
14405 
14406   case Builtin::BI__builtin_huge_val:
14407   case Builtin::BI__builtin_huge_valf:
14408   case Builtin::BI__builtin_huge_vall:
14409   case Builtin::BI__builtin_huge_valf16:
14410   case Builtin::BI__builtin_huge_valf128:
14411   case Builtin::BI__builtin_inf:
14412   case Builtin::BI__builtin_inff:
14413   case Builtin::BI__builtin_infl:
14414   case Builtin::BI__builtin_inff16:
14415   case Builtin::BI__builtin_inff128: {
14416     const llvm::fltSemantics &Sem =
14417       Info.Ctx.getFloatTypeSemantics(E->getType());
14418     Result = llvm::APFloat::getInf(Sem);
14419     return true;
14420   }
14421 
14422   case Builtin::BI__builtin_nans:
14423   case Builtin::BI__builtin_nansf:
14424   case Builtin::BI__builtin_nansl:
14425   case Builtin::BI__builtin_nansf16:
14426   case Builtin::BI__builtin_nansf128:
14427     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14428                                true, Result))
14429       return Error(E);
14430     return true;
14431 
14432   case Builtin::BI__builtin_nan:
14433   case Builtin::BI__builtin_nanf:
14434   case Builtin::BI__builtin_nanl:
14435   case Builtin::BI__builtin_nanf16:
14436   case Builtin::BI__builtin_nanf128:
14437     // If this is __builtin_nan() turn this into a nan, otherwise we
14438     // can't constant fold it.
14439     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14440                                false, Result))
14441       return Error(E);
14442     return true;
14443 
14444   case Builtin::BI__builtin_fabs:
14445   case Builtin::BI__builtin_fabsf:
14446   case Builtin::BI__builtin_fabsl:
14447   case Builtin::BI__builtin_fabsf128:
14448     // The C standard says "fabs raises no floating-point exceptions,
14449     // even if x is a signaling NaN. The returned value is independent of
14450     // the current rounding direction mode."  Therefore constant folding can
14451     // proceed without regard to the floating point settings.
14452     // Reference, WG14 N2478 F.10.4.3
14453     if (!EvaluateFloat(E->getArg(0), Result, Info))
14454       return false;
14455 
14456     if (Result.isNegative())
14457       Result.changeSign();
14458     return true;
14459 
14460   case Builtin::BI__arithmetic_fence:
14461     return EvaluateFloat(E->getArg(0), Result, Info);
14462 
14463   // FIXME: Builtin::BI__builtin_powi
14464   // FIXME: Builtin::BI__builtin_powif
14465   // FIXME: Builtin::BI__builtin_powil
14466 
14467   case Builtin::BI__builtin_copysign:
14468   case Builtin::BI__builtin_copysignf:
14469   case Builtin::BI__builtin_copysignl:
14470   case Builtin::BI__builtin_copysignf128: {
14471     APFloat RHS(0.);
14472     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14473         !EvaluateFloat(E->getArg(1), RHS, Info))
14474       return false;
14475     Result.copySign(RHS);
14476     return true;
14477   }
14478 
14479   case Builtin::BI__builtin_fmax:
14480   case Builtin::BI__builtin_fmaxf:
14481   case Builtin::BI__builtin_fmaxl:
14482   case Builtin::BI__builtin_fmaxf16:
14483   case Builtin::BI__builtin_fmaxf128: {
14484     // TODO: Handle sNaN.
14485     APFloat RHS(0.);
14486     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14487         !EvaluateFloat(E->getArg(1), RHS, Info))
14488       return false;
14489     // When comparing zeroes, return +0.0 if one of the zeroes is positive.
14490     if (Result.isZero() && RHS.isZero() && Result.isNegative())
14491       Result = RHS;
14492     else if (Result.isNaN() || RHS > Result)
14493       Result = RHS;
14494     return true;
14495   }
14496 
14497   case Builtin::BI__builtin_fmin:
14498   case Builtin::BI__builtin_fminf:
14499   case Builtin::BI__builtin_fminl:
14500   case Builtin::BI__builtin_fminf16:
14501   case Builtin::BI__builtin_fminf128: {
14502     // TODO: Handle sNaN.
14503     APFloat RHS(0.);
14504     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14505         !EvaluateFloat(E->getArg(1), RHS, Info))
14506       return false;
14507     // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14508     if (Result.isZero() && RHS.isZero() && RHS.isNegative())
14509       Result = RHS;
14510     else if (Result.isNaN() || RHS < Result)
14511       Result = RHS;
14512     return true;
14513   }
14514   }
14515 }
14516 
VisitUnaryReal(const UnaryOperator * E)14517 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14518   if (E->getSubExpr()->getType()->isAnyComplexType()) {
14519     ComplexValue CV;
14520     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14521       return false;
14522     Result = CV.FloatReal;
14523     return true;
14524   }
14525 
14526   return Visit(E->getSubExpr());
14527 }
14528 
VisitUnaryImag(const UnaryOperator * E)14529 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14530   if (E->getSubExpr()->getType()->isAnyComplexType()) {
14531     ComplexValue CV;
14532     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14533       return false;
14534     Result = CV.FloatImag;
14535     return true;
14536   }
14537 
14538   VisitIgnoredValue(E->getSubExpr());
14539   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
14540   Result = llvm::APFloat::getZero(Sem);
14541   return true;
14542 }
14543 
VisitUnaryOperator(const UnaryOperator * E)14544 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14545   switch (E->getOpcode()) {
14546   default: return Error(E);
14547   case UO_Plus:
14548     return EvaluateFloat(E->getSubExpr(), Result, Info);
14549   case UO_Minus:
14550     // In C standard, WG14 N2478 F.3 p4
14551     // "the unary - raises no floating point exceptions,
14552     // even if the operand is signalling."
14553     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
14554       return false;
14555     Result.changeSign();
14556     return true;
14557   }
14558 }
14559 
VisitBinaryOperator(const BinaryOperator * E)14560 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14561   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14562     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14563 
14564   APFloat RHS(0.0);
14565   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14566   if (!LHSOK && !Info.noteFailure())
14567     return false;
14568   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14569          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14570 }
14571 
VisitFloatingLiteral(const FloatingLiteral * E)14572 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14573   Result = E->getValue();
14574   return true;
14575 }
14576 
VisitCastExpr(const CastExpr * E)14577 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14578   const Expr* SubExpr = E->getSubExpr();
14579 
14580   switch (E->getCastKind()) {
14581   default:
14582     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14583 
14584   case CK_IntegralToFloating: {
14585     APSInt IntResult;
14586     const FPOptions FPO = E->getFPFeaturesInEffect(
14587                                   Info.Ctx.getLangOpts());
14588     return EvaluateInteger(SubExpr, IntResult, Info) &&
14589            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14590                                 IntResult, E->getType(), Result);
14591   }
14592 
14593   case CK_FixedPointToFloating: {
14594     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14595     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14596       return false;
14597     Result =
14598         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14599     return true;
14600   }
14601 
14602   case CK_FloatingCast: {
14603     if (!Visit(SubExpr))
14604       return false;
14605     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14606                                   Result);
14607   }
14608 
14609   case CK_FloatingComplexToReal: {
14610     ComplexValue V;
14611     if (!EvaluateComplex(SubExpr, V, Info))
14612       return false;
14613     Result = V.getComplexFloatReal();
14614     return true;
14615   }
14616   }
14617 }
14618 
14619 //===----------------------------------------------------------------------===//
14620 // Complex Evaluation (for float and integer)
14621 //===----------------------------------------------------------------------===//
14622 
14623 namespace {
14624 class ComplexExprEvaluator
14625   : public ExprEvaluatorBase<ComplexExprEvaluator> {
14626   ComplexValue &Result;
14627 
14628 public:
ComplexExprEvaluator(EvalInfo & info,ComplexValue & Result)14629   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14630     : ExprEvaluatorBaseTy(info), Result(Result) {}
14631 
Success(const APValue & V,const Expr * e)14632   bool Success(const APValue &V, const Expr *e) {
14633     Result.setFrom(V);
14634     return true;
14635   }
14636 
14637   bool ZeroInitialization(const Expr *E);
14638 
14639   //===--------------------------------------------------------------------===//
14640   //                            Visitor Methods
14641   //===--------------------------------------------------------------------===//
14642 
14643   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14644   bool VisitCastExpr(const CastExpr *E);
14645   bool VisitBinaryOperator(const BinaryOperator *E);
14646   bool VisitUnaryOperator(const UnaryOperator *E);
14647   bool VisitInitListExpr(const InitListExpr *E);
14648   bool VisitCallExpr(const CallExpr *E);
14649 };
14650 } // end anonymous namespace
14651 
EvaluateComplex(const Expr * E,ComplexValue & Result,EvalInfo & Info)14652 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14653                             EvalInfo &Info) {
14654   assert(!E->isValueDependent());
14655   assert(E->isPRValue() && E->getType()->isAnyComplexType());
14656   return ComplexExprEvaluator(Info, Result).Visit(E);
14657 }
14658 
ZeroInitialization(const Expr * E)14659 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14660   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14661   if (ElemTy->isRealFloatingType()) {
14662     Result.makeComplexFloat();
14663     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14664     Result.FloatReal = Zero;
14665     Result.FloatImag = Zero;
14666   } else {
14667     Result.makeComplexInt();
14668     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14669     Result.IntReal = Zero;
14670     Result.IntImag = Zero;
14671   }
14672   return true;
14673 }
14674 
VisitImaginaryLiteral(const ImaginaryLiteral * E)14675 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14676   const Expr* SubExpr = E->getSubExpr();
14677 
14678   if (SubExpr->getType()->isRealFloatingType()) {
14679     Result.makeComplexFloat();
14680     APFloat &Imag = Result.FloatImag;
14681     if (!EvaluateFloat(SubExpr, Imag, Info))
14682       return false;
14683 
14684     Result.FloatReal = APFloat(Imag.getSemantics());
14685     return true;
14686   } else {
14687     assert(SubExpr->getType()->isIntegerType() &&
14688            "Unexpected imaginary literal.");
14689 
14690     Result.makeComplexInt();
14691     APSInt &Imag = Result.IntImag;
14692     if (!EvaluateInteger(SubExpr, Imag, Info))
14693       return false;
14694 
14695     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14696     return true;
14697   }
14698 }
14699 
VisitCastExpr(const CastExpr * E)14700 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14701 
14702   switch (E->getCastKind()) {
14703   case CK_BitCast:
14704   case CK_BaseToDerived:
14705   case CK_DerivedToBase:
14706   case CK_UncheckedDerivedToBase:
14707   case CK_Dynamic:
14708   case CK_ToUnion:
14709   case CK_ArrayToPointerDecay:
14710   case CK_FunctionToPointerDecay:
14711   case CK_NullToPointer:
14712   case CK_NullToMemberPointer:
14713   case CK_BaseToDerivedMemberPointer:
14714   case CK_DerivedToBaseMemberPointer:
14715   case CK_MemberPointerToBoolean:
14716   case CK_ReinterpretMemberPointer:
14717   case CK_ConstructorConversion:
14718   case CK_IntegralToPointer:
14719   case CK_PointerToIntegral:
14720   case CK_PointerToBoolean:
14721   case CK_ToVoid:
14722   case CK_VectorSplat:
14723   case CK_IntegralCast:
14724   case CK_BooleanToSignedIntegral:
14725   case CK_IntegralToBoolean:
14726   case CK_IntegralToFloating:
14727   case CK_FloatingToIntegral:
14728   case CK_FloatingToBoolean:
14729   case CK_FloatingCast:
14730   case CK_CPointerToObjCPointerCast:
14731   case CK_BlockPointerToObjCPointerCast:
14732   case CK_AnyPointerToBlockPointerCast:
14733   case CK_ObjCObjectLValueCast:
14734   case CK_FloatingComplexToReal:
14735   case CK_FloatingComplexToBoolean:
14736   case CK_IntegralComplexToReal:
14737   case CK_IntegralComplexToBoolean:
14738   case CK_ARCProduceObject:
14739   case CK_ARCConsumeObject:
14740   case CK_ARCReclaimReturnedObject:
14741   case CK_ARCExtendBlockObject:
14742   case CK_CopyAndAutoreleaseBlockObject:
14743   case CK_BuiltinFnToFnPtr:
14744   case CK_ZeroToOCLOpaqueType:
14745   case CK_NonAtomicToAtomic:
14746   case CK_AddressSpaceConversion:
14747   case CK_IntToOCLSampler:
14748   case CK_FloatingToFixedPoint:
14749   case CK_FixedPointToFloating:
14750   case CK_FixedPointCast:
14751   case CK_FixedPointToBoolean:
14752   case CK_FixedPointToIntegral:
14753   case CK_IntegralToFixedPoint:
14754   case CK_MatrixCast:
14755     llvm_unreachable("invalid cast kind for complex value");
14756 
14757   case CK_LValueToRValue:
14758   case CK_AtomicToNonAtomic:
14759   case CK_NoOp:
14760   case CK_LValueToRValueBitCast:
14761     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14762 
14763   case CK_Dependent:
14764   case CK_LValueBitCast:
14765   case CK_UserDefinedConversion:
14766     return Error(E);
14767 
14768   case CK_FloatingRealToComplex: {
14769     APFloat &Real = Result.FloatReal;
14770     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14771       return false;
14772 
14773     Result.makeComplexFloat();
14774     Result.FloatImag = APFloat(Real.getSemantics());
14775     return true;
14776   }
14777 
14778   case CK_FloatingComplexCast: {
14779     if (!Visit(E->getSubExpr()))
14780       return false;
14781 
14782     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14783     QualType From
14784       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14785 
14786     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14787            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14788   }
14789 
14790   case CK_FloatingComplexToIntegralComplex: {
14791     if (!Visit(E->getSubExpr()))
14792       return false;
14793 
14794     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14795     QualType From
14796       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14797     Result.makeComplexInt();
14798     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14799                                 To, Result.IntReal) &&
14800            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14801                                 To, Result.IntImag);
14802   }
14803 
14804   case CK_IntegralRealToComplex: {
14805     APSInt &Real = Result.IntReal;
14806     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14807       return false;
14808 
14809     Result.makeComplexInt();
14810     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14811     return true;
14812   }
14813 
14814   case CK_IntegralComplexCast: {
14815     if (!Visit(E->getSubExpr()))
14816       return false;
14817 
14818     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14819     QualType From
14820       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14821 
14822     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14823     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14824     return true;
14825   }
14826 
14827   case CK_IntegralComplexToFloatingComplex: {
14828     if (!Visit(E->getSubExpr()))
14829       return false;
14830 
14831     const FPOptions FPO = E->getFPFeaturesInEffect(
14832                                   Info.Ctx.getLangOpts());
14833     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14834     QualType From
14835       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14836     Result.makeComplexFloat();
14837     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14838                                 To, Result.FloatReal) &&
14839            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14840                                 To, Result.FloatImag);
14841   }
14842   }
14843 
14844   llvm_unreachable("unknown cast resulting in complex value");
14845 }
14846 
VisitBinaryOperator(const BinaryOperator * E)14847 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14848   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14849     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14850 
14851   // Track whether the LHS or RHS is real at the type system level. When this is
14852   // the case we can simplify our evaluation strategy.
14853   bool LHSReal = false, RHSReal = false;
14854 
14855   bool LHSOK;
14856   if (E->getLHS()->getType()->isRealFloatingType()) {
14857     LHSReal = true;
14858     APFloat &Real = Result.FloatReal;
14859     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14860     if (LHSOK) {
14861       Result.makeComplexFloat();
14862       Result.FloatImag = APFloat(Real.getSemantics());
14863     }
14864   } else {
14865     LHSOK = Visit(E->getLHS());
14866   }
14867   if (!LHSOK && !Info.noteFailure())
14868     return false;
14869 
14870   ComplexValue RHS;
14871   if (E->getRHS()->getType()->isRealFloatingType()) {
14872     RHSReal = true;
14873     APFloat &Real = RHS.FloatReal;
14874     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14875       return false;
14876     RHS.makeComplexFloat();
14877     RHS.FloatImag = APFloat(Real.getSemantics());
14878   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14879     return false;
14880 
14881   assert(!(LHSReal && RHSReal) &&
14882          "Cannot have both operands of a complex operation be real.");
14883   switch (E->getOpcode()) {
14884   default: return Error(E);
14885   case BO_Add:
14886     if (Result.isComplexFloat()) {
14887       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14888                                        APFloat::rmNearestTiesToEven);
14889       if (LHSReal)
14890         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14891       else if (!RHSReal)
14892         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14893                                          APFloat::rmNearestTiesToEven);
14894     } else {
14895       Result.getComplexIntReal() += RHS.getComplexIntReal();
14896       Result.getComplexIntImag() += RHS.getComplexIntImag();
14897     }
14898     break;
14899   case BO_Sub:
14900     if (Result.isComplexFloat()) {
14901       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14902                                             APFloat::rmNearestTiesToEven);
14903       if (LHSReal) {
14904         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14905         Result.getComplexFloatImag().changeSign();
14906       } else if (!RHSReal) {
14907         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14908                                               APFloat::rmNearestTiesToEven);
14909       }
14910     } else {
14911       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14912       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14913     }
14914     break;
14915   case BO_Mul:
14916     if (Result.isComplexFloat()) {
14917       // This is an implementation of complex multiplication according to the
14918       // constraints laid out in C11 Annex G. The implementation uses the
14919       // following naming scheme:
14920       //   (a + ib) * (c + id)
14921       ComplexValue LHS = Result;
14922       APFloat &A = LHS.getComplexFloatReal();
14923       APFloat &B = LHS.getComplexFloatImag();
14924       APFloat &C = RHS.getComplexFloatReal();
14925       APFloat &D = RHS.getComplexFloatImag();
14926       APFloat &ResR = Result.getComplexFloatReal();
14927       APFloat &ResI = Result.getComplexFloatImag();
14928       if (LHSReal) {
14929         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14930         ResR = A * C;
14931         ResI = A * D;
14932       } else if (RHSReal) {
14933         ResR = C * A;
14934         ResI = C * B;
14935       } else {
14936         // In the fully general case, we need to handle NaNs and infinities
14937         // robustly.
14938         APFloat AC = A * C;
14939         APFloat BD = B * D;
14940         APFloat AD = A * D;
14941         APFloat BC = B * C;
14942         ResR = AC - BD;
14943         ResI = AD + BC;
14944         if (ResR.isNaN() && ResI.isNaN()) {
14945           bool Recalc = false;
14946           if (A.isInfinity() || B.isInfinity()) {
14947             A = APFloat::copySign(
14948                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14949             B = APFloat::copySign(
14950                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14951             if (C.isNaN())
14952               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14953             if (D.isNaN())
14954               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14955             Recalc = true;
14956           }
14957           if (C.isInfinity() || D.isInfinity()) {
14958             C = APFloat::copySign(
14959                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14960             D = APFloat::copySign(
14961                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14962             if (A.isNaN())
14963               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14964             if (B.isNaN())
14965               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14966             Recalc = true;
14967           }
14968           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14969                           AD.isInfinity() || BC.isInfinity())) {
14970             if (A.isNaN())
14971               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14972             if (B.isNaN())
14973               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14974             if (C.isNaN())
14975               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14976             if (D.isNaN())
14977               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14978             Recalc = true;
14979           }
14980           if (Recalc) {
14981             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14982             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14983           }
14984         }
14985       }
14986     } else {
14987       ComplexValue LHS = Result;
14988       Result.getComplexIntReal() =
14989         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14990          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14991       Result.getComplexIntImag() =
14992         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14993          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14994     }
14995     break;
14996   case BO_Div:
14997     if (Result.isComplexFloat()) {
14998       // This is an implementation of complex division according to the
14999       // constraints laid out in C11 Annex G. The implementation uses the
15000       // following naming scheme:
15001       //   (a + ib) / (c + id)
15002       ComplexValue LHS = Result;
15003       APFloat &A = LHS.getComplexFloatReal();
15004       APFloat &B = LHS.getComplexFloatImag();
15005       APFloat &C = RHS.getComplexFloatReal();
15006       APFloat &D = RHS.getComplexFloatImag();
15007       APFloat &ResR = Result.getComplexFloatReal();
15008       APFloat &ResI = Result.getComplexFloatImag();
15009       if (RHSReal) {
15010         ResR = A / C;
15011         ResI = B / C;
15012       } else {
15013         if (LHSReal) {
15014           // No real optimizations we can do here, stub out with zero.
15015           B = APFloat::getZero(A.getSemantics());
15016         }
15017         int DenomLogB = 0;
15018         APFloat MaxCD = maxnum(abs(C), abs(D));
15019         if (MaxCD.isFinite()) {
15020           DenomLogB = ilogb(MaxCD);
15021           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
15022           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
15023         }
15024         APFloat Denom = C * C + D * D;
15025         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
15026                       APFloat::rmNearestTiesToEven);
15027         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
15028                       APFloat::rmNearestTiesToEven);
15029         if (ResR.isNaN() && ResI.isNaN()) {
15030           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
15031             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
15032             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
15033           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
15034                      D.isFinite()) {
15035             A = APFloat::copySign(
15036                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
15037             B = APFloat::copySign(
15038                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
15039             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
15040             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
15041           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
15042             C = APFloat::copySign(
15043                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
15044             D = APFloat::copySign(
15045                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
15046             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
15047             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
15048           }
15049         }
15050       }
15051     } else {
15052       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
15053         return Error(E, diag::note_expr_divide_by_zero);
15054 
15055       ComplexValue LHS = Result;
15056       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
15057         RHS.getComplexIntImag() * RHS.getComplexIntImag();
15058       Result.getComplexIntReal() =
15059         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
15060          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
15061       Result.getComplexIntImag() =
15062         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
15063          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
15064     }
15065     break;
15066   }
15067 
15068   return true;
15069 }
15070 
VisitUnaryOperator(const UnaryOperator * E)15071 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15072   // Get the operand value into 'Result'.
15073   if (!Visit(E->getSubExpr()))
15074     return false;
15075 
15076   switch (E->getOpcode()) {
15077   default:
15078     return Error(E);
15079   case UO_Extension:
15080     return true;
15081   case UO_Plus:
15082     // The result is always just the subexpr.
15083     return true;
15084   case UO_Minus:
15085     if (Result.isComplexFloat()) {
15086       Result.getComplexFloatReal().changeSign();
15087       Result.getComplexFloatImag().changeSign();
15088     }
15089     else {
15090       Result.getComplexIntReal() = -Result.getComplexIntReal();
15091       Result.getComplexIntImag() = -Result.getComplexIntImag();
15092     }
15093     return true;
15094   case UO_Not:
15095     if (Result.isComplexFloat())
15096       Result.getComplexFloatImag().changeSign();
15097     else
15098       Result.getComplexIntImag() = -Result.getComplexIntImag();
15099     return true;
15100   }
15101 }
15102 
VisitInitListExpr(const InitListExpr * E)15103 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
15104   if (E->getNumInits() == 2) {
15105     if (E->getType()->isComplexType()) {
15106       Result.makeComplexFloat();
15107       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
15108         return false;
15109       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
15110         return false;
15111     } else {
15112       Result.makeComplexInt();
15113       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
15114         return false;
15115       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
15116         return false;
15117     }
15118     return true;
15119   }
15120   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
15121 }
15122 
VisitCallExpr(const CallExpr * E)15123 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
15124   if (!IsConstantEvaluatedBuiltinCall(E))
15125     return ExprEvaluatorBaseTy::VisitCallExpr(E);
15126 
15127   switch (E->getBuiltinCallee()) {
15128   case Builtin::BI__builtin_complex:
15129     Result.makeComplexFloat();
15130     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
15131       return false;
15132     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
15133       return false;
15134     return true;
15135 
15136   default:
15137     return false;
15138   }
15139 }
15140 
15141 //===----------------------------------------------------------------------===//
15142 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
15143 // implicit conversion.
15144 //===----------------------------------------------------------------------===//
15145 
15146 namespace {
15147 class AtomicExprEvaluator :
15148     public ExprEvaluatorBase<AtomicExprEvaluator> {
15149   const LValue *This;
15150   APValue &Result;
15151 public:
AtomicExprEvaluator(EvalInfo & Info,const LValue * This,APValue & Result)15152   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
15153       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
15154 
Success(const APValue & V,const Expr * E)15155   bool Success(const APValue &V, const Expr *E) {
15156     Result = V;
15157     return true;
15158   }
15159 
ZeroInitialization(const Expr * E)15160   bool ZeroInitialization(const Expr *E) {
15161     ImplicitValueInitExpr VIE(
15162         E->getType()->castAs<AtomicType>()->getValueType());
15163     // For atomic-qualified class (and array) types in C++, initialize the
15164     // _Atomic-wrapped subobject directly, in-place.
15165     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
15166                 : Evaluate(Result, Info, &VIE);
15167   }
15168 
VisitCastExpr(const CastExpr * E)15169   bool VisitCastExpr(const CastExpr *E) {
15170     switch (E->getCastKind()) {
15171     default:
15172       return ExprEvaluatorBaseTy::VisitCastExpr(E);
15173     case CK_NullToPointer:
15174       VisitIgnoredValue(E->getSubExpr());
15175       return ZeroInitialization(E);
15176     case CK_NonAtomicToAtomic:
15177       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
15178                   : Evaluate(Result, Info, E->getSubExpr());
15179     }
15180   }
15181 };
15182 } // end anonymous namespace
15183 
EvaluateAtomic(const Expr * E,const LValue * This,APValue & Result,EvalInfo & Info)15184 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
15185                            EvalInfo &Info) {
15186   assert(!E->isValueDependent());
15187   assert(E->isPRValue() && E->getType()->isAtomicType());
15188   return AtomicExprEvaluator(Info, This, Result).Visit(E);
15189 }
15190 
15191 //===----------------------------------------------------------------------===//
15192 // Void expression evaluation, primarily for a cast to void on the LHS of a
15193 // comma operator
15194 //===----------------------------------------------------------------------===//
15195 
15196 namespace {
15197 class VoidExprEvaluator
15198   : public ExprEvaluatorBase<VoidExprEvaluator> {
15199 public:
VoidExprEvaluator(EvalInfo & Info)15200   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
15201 
Success(const APValue & V,const Expr * e)15202   bool Success(const APValue &V, const Expr *e) { return true; }
15203 
ZeroInitialization(const Expr * E)15204   bool ZeroInitialization(const Expr *E) { return true; }
15205 
VisitCastExpr(const CastExpr * E)15206   bool VisitCastExpr(const CastExpr *E) {
15207     switch (E->getCastKind()) {
15208     default:
15209       return ExprEvaluatorBaseTy::VisitCastExpr(E);
15210     case CK_ToVoid:
15211       VisitIgnoredValue(E->getSubExpr());
15212       return true;
15213     }
15214   }
15215 
VisitCallExpr(const CallExpr * E)15216   bool VisitCallExpr(const CallExpr *E) {
15217     if (!IsConstantEvaluatedBuiltinCall(E))
15218       return ExprEvaluatorBaseTy::VisitCallExpr(E);
15219 
15220     switch (E->getBuiltinCallee()) {
15221     case Builtin::BI__assume:
15222     case Builtin::BI__builtin_assume:
15223       // The argument is not evaluated!
15224       return true;
15225 
15226     case Builtin::BI__builtin_operator_delete:
15227       return HandleOperatorDeleteCall(Info, E);
15228 
15229     default:
15230       return false;
15231     }
15232   }
15233 
15234   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
15235 };
15236 } // end anonymous namespace
15237 
VisitCXXDeleteExpr(const CXXDeleteExpr * E)15238 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
15239   // We cannot speculatively evaluate a delete expression.
15240   if (Info.SpeculativeEvaluationDepth)
15241     return false;
15242 
15243   FunctionDecl *OperatorDelete = E->getOperatorDelete();
15244   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
15245     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
15246         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
15247     return false;
15248   }
15249 
15250   const Expr *Arg = E->getArgument();
15251 
15252   LValue Pointer;
15253   if (!EvaluatePointer(Arg, Pointer, Info))
15254     return false;
15255   if (Pointer.Designator.Invalid)
15256     return false;
15257 
15258   // Deleting a null pointer has no effect.
15259   if (Pointer.isNullPointer()) {
15260     // This is the only case where we need to produce an extension warning:
15261     // the only other way we can succeed is if we find a dynamic allocation,
15262     // and we will have warned when we allocated it in that case.
15263     if (!Info.getLangOpts().CPlusPlus20)
15264       Info.CCEDiag(E, diag::note_constexpr_new);
15265     return true;
15266   }
15267 
15268   std::optional<DynAlloc *> Alloc = CheckDeleteKind(
15269       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
15270   if (!Alloc)
15271     return false;
15272   QualType AllocType = Pointer.Base.getDynamicAllocType();
15273 
15274   // For the non-array case, the designator must be empty if the static type
15275   // does not have a virtual destructor.
15276   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
15277       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
15278     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
15279         << Arg->getType()->getPointeeType() << AllocType;
15280     return false;
15281   }
15282 
15283   // For a class type with a virtual destructor, the selected operator delete
15284   // is the one looked up when building the destructor.
15285   if (!E->isArrayForm() && !E->isGlobalDelete()) {
15286     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
15287     if (VirtualDelete &&
15288         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
15289       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
15290           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
15291       return false;
15292     }
15293   }
15294 
15295   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
15296                          (*Alloc)->Value, AllocType))
15297     return false;
15298 
15299   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
15300     // The element was already erased. This means the destructor call also
15301     // deleted the object.
15302     // FIXME: This probably results in undefined behavior before we get this
15303     // far, and should be diagnosed elsewhere first.
15304     Info.FFDiag(E, diag::note_constexpr_double_delete);
15305     return false;
15306   }
15307 
15308   return true;
15309 }
15310 
EvaluateVoid(const Expr * E,EvalInfo & Info)15311 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
15312   assert(!E->isValueDependent());
15313   assert(E->isPRValue() && E->getType()->isVoidType());
15314   return VoidExprEvaluator(Info).Visit(E);
15315 }
15316 
15317 //===----------------------------------------------------------------------===//
15318 // Top level Expr::EvaluateAsRValue method.
15319 //===----------------------------------------------------------------------===//
15320 
Evaluate(APValue & Result,EvalInfo & Info,const Expr * E)15321 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
15322   assert(!E->isValueDependent());
15323   // In C, function designators are not lvalues, but we evaluate them as if they
15324   // are.
15325   QualType T = E->getType();
15326   if (E->isGLValue() || T->isFunctionType()) {
15327     LValue LV;
15328     if (!EvaluateLValue(E, LV, Info))
15329       return false;
15330     LV.moveInto(Result);
15331   } else if (T->isVectorType()) {
15332     if (!EvaluateVector(E, Result, Info))
15333       return false;
15334   } else if (T->isIntegralOrEnumerationType()) {
15335     if (!IntExprEvaluator(Info, Result).Visit(E))
15336       return false;
15337   } else if (T->hasPointerRepresentation()) {
15338     LValue LV;
15339     if (!EvaluatePointer(E, LV, Info))
15340       return false;
15341     LV.moveInto(Result);
15342   } else if (T->isRealFloatingType()) {
15343     llvm::APFloat F(0.0);
15344     if (!EvaluateFloat(E, F, Info))
15345       return false;
15346     Result = APValue(F);
15347   } else if (T->isAnyComplexType()) {
15348     ComplexValue C;
15349     if (!EvaluateComplex(E, C, Info))
15350       return false;
15351     C.moveInto(Result);
15352   } else if (T->isFixedPointType()) {
15353     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
15354   } else if (T->isMemberPointerType()) {
15355     MemberPtr P;
15356     if (!EvaluateMemberPointer(E, P, Info))
15357       return false;
15358     P.moveInto(Result);
15359     return true;
15360   } else if (T->isArrayType()) {
15361     LValue LV;
15362     APValue &Value =
15363         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15364     if (!EvaluateArray(E, LV, Value, Info))
15365       return false;
15366     Result = Value;
15367   } else if (T->isRecordType()) {
15368     LValue LV;
15369     APValue &Value =
15370         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15371     if (!EvaluateRecord(E, LV, Value, Info))
15372       return false;
15373     Result = Value;
15374   } else if (T->isVoidType()) {
15375     if (!Info.getLangOpts().CPlusPlus11)
15376       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
15377         << E->getType();
15378     if (!EvaluateVoid(E, Info))
15379       return false;
15380   } else if (T->isAtomicType()) {
15381     QualType Unqual = T.getAtomicUnqualifiedType();
15382     if (Unqual->isArrayType() || Unqual->isRecordType()) {
15383       LValue LV;
15384       APValue &Value = Info.CurrentCall->createTemporary(
15385           E, Unqual, ScopeKind::FullExpression, LV);
15386       if (!EvaluateAtomic(E, &LV, Value, Info))
15387         return false;
15388       Result = Value;
15389     } else {
15390       if (!EvaluateAtomic(E, nullptr, Result, Info))
15391         return false;
15392     }
15393   } else if (Info.getLangOpts().CPlusPlus11) {
15394     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
15395     return false;
15396   } else {
15397     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15398     return false;
15399   }
15400 
15401   return true;
15402 }
15403 
15404 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15405 /// cases, the in-place evaluation is essential, since later initializers for
15406 /// an object can indirectly refer to subobjects which were initialized earlier.
EvaluateInPlace(APValue & Result,EvalInfo & Info,const LValue & This,const Expr * E,bool AllowNonLiteralTypes)15407 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
15408                             const Expr *E, bool AllowNonLiteralTypes) {
15409   assert(!E->isValueDependent());
15410 
15411   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
15412     return false;
15413 
15414   if (E->isPRValue()) {
15415     // Evaluate arrays and record types in-place, so that later initializers can
15416     // refer to earlier-initialized members of the object.
15417     QualType T = E->getType();
15418     if (T->isArrayType())
15419       return EvaluateArray(E, This, Result, Info);
15420     else if (T->isRecordType())
15421       return EvaluateRecord(E, This, Result, Info);
15422     else if (T->isAtomicType()) {
15423       QualType Unqual = T.getAtomicUnqualifiedType();
15424       if (Unqual->isArrayType() || Unqual->isRecordType())
15425         return EvaluateAtomic(E, &This, Result, Info);
15426     }
15427   }
15428 
15429   // For any other type, in-place evaluation is unimportant.
15430   return Evaluate(Result, Info, E);
15431 }
15432 
15433 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15434 /// lvalue-to-rvalue cast if it is an lvalue.
EvaluateAsRValue(EvalInfo & Info,const Expr * E,APValue & Result)15435 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
15436   assert(!E->isValueDependent());
15437 
15438   if (E->getType().isNull())
15439     return false;
15440 
15441   if (!CheckLiteralType(Info, E))
15442     return false;
15443 
15444   if (Info.EnableNewConstInterp) {
15445     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
15446       return false;
15447     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15448                                    ConstantExprKind::Normal);
15449   }
15450 
15451   if (!::Evaluate(Result, Info, E))
15452     return false;
15453 
15454   // Implicit lvalue-to-rvalue cast.
15455   if (E->isGLValue()) {
15456     LValue LV;
15457     LV.setFrom(Info.Ctx, Result);
15458     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15459       return false;
15460   }
15461 
15462   // Check this core constant expression is a constant expression.
15463   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15464                                  ConstantExprKind::Normal) &&
15465          CheckMemoryLeaks(Info);
15466 }
15467 
FastEvaluateAsRValue(const Expr * Exp,Expr::EvalResult & Result,const ASTContext & Ctx,bool & IsConst)15468 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
15469                                  const ASTContext &Ctx, bool &IsConst) {
15470   // Fast-path evaluations of integer literals, since we sometimes see files
15471   // containing vast quantities of these.
15472   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
15473     Result.Val = APValue(APSInt(L->getValue(),
15474                                 L->getType()->isUnsignedIntegerType()));
15475     IsConst = true;
15476     return true;
15477   }
15478 
15479   if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
15480     Result.Val = APValue(APSInt(APInt(1, L->getValue())));
15481     IsConst = true;
15482     return true;
15483   }
15484 
15485   if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
15486     if (CE->hasAPValueResult()) {
15487       Result.Val = CE->getAPValueResult();
15488       IsConst = true;
15489       return true;
15490     }
15491 
15492     // The SubExpr is usually just an IntegerLiteral.
15493     return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
15494   }
15495 
15496   // This case should be rare, but we need to check it before we check on
15497   // the type below.
15498   if (Exp->getType().isNull()) {
15499     IsConst = false;
15500     return true;
15501   }
15502 
15503   return false;
15504 }
15505 
hasUnacceptableSideEffect(Expr::EvalStatus & Result,Expr::SideEffectsKind SEK)15506 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
15507                                       Expr::SideEffectsKind SEK) {
15508   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
15509          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
15510 }
15511 
EvaluateAsRValue(const Expr * E,Expr::EvalResult & Result,const ASTContext & Ctx,EvalInfo & Info)15512 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
15513                              const ASTContext &Ctx, EvalInfo &Info) {
15514   assert(!E->isValueDependent());
15515   bool IsConst;
15516   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
15517     return IsConst;
15518 
15519   return EvaluateAsRValue(Info, E, Result.Val);
15520 }
15521 
EvaluateAsInt(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)15522 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
15523                           const ASTContext &Ctx,
15524                           Expr::SideEffectsKind AllowSideEffects,
15525                           EvalInfo &Info) {
15526   assert(!E->isValueDependent());
15527   if (!E->getType()->isIntegralOrEnumerationType())
15528     return false;
15529 
15530   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
15531       !ExprResult.Val.isInt() ||
15532       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15533     return false;
15534 
15535   return true;
15536 }
15537 
EvaluateAsFixedPoint(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)15538 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
15539                                  const ASTContext &Ctx,
15540                                  Expr::SideEffectsKind AllowSideEffects,
15541                                  EvalInfo &Info) {
15542   assert(!E->isValueDependent());
15543   if (!E->getType()->isFixedPointType())
15544     return false;
15545 
15546   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
15547     return false;
15548 
15549   if (!ExprResult.Val.isFixedPoint() ||
15550       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15551     return false;
15552 
15553   return true;
15554 }
15555 
15556 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
15557 /// any crazy technique (that has nothing to do with language standards) that
15558 /// we want to.  If this function returns true, it returns the folded constant
15559 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
15560 /// will be applied to the result.
EvaluateAsRValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const15561 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
15562                             bool InConstantContext) const {
15563   assert(!isValueDependent() &&
15564          "Expression evaluator can't be called on a dependent expression.");
15565   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
15566   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15567   Info.InConstantContext = InConstantContext;
15568   return ::EvaluateAsRValue(this, Result, Ctx, Info);
15569 }
15570 
EvaluateAsBooleanCondition(bool & Result,const ASTContext & Ctx,bool InConstantContext) const15571 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
15572                                       bool InConstantContext) const {
15573   assert(!isValueDependent() &&
15574          "Expression evaluator can't be called on a dependent expression.");
15575   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
15576   EvalResult Scratch;
15577   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
15578          HandleConversionToBool(Scratch.Val, Result);
15579 }
15580 
EvaluateAsInt(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const15581 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
15582                          SideEffectsKind AllowSideEffects,
15583                          bool InConstantContext) const {
15584   assert(!isValueDependent() &&
15585          "Expression evaluator can't be called on a dependent expression.");
15586   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
15587   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15588   Info.InConstantContext = InConstantContext;
15589   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15590 }
15591 
EvaluateAsFixedPoint(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const15592 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
15593                                 SideEffectsKind AllowSideEffects,
15594                                 bool InConstantContext) const {
15595   assert(!isValueDependent() &&
15596          "Expression evaluator can't be called on a dependent expression.");
15597   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
15598   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15599   Info.InConstantContext = InConstantContext;
15600   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15601 }
15602 
EvaluateAsFloat(APFloat & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const15603 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15604                            SideEffectsKind AllowSideEffects,
15605                            bool InConstantContext) const {
15606   assert(!isValueDependent() &&
15607          "Expression evaluator can't be called on a dependent expression.");
15608 
15609   if (!getType()->isRealFloatingType())
15610     return false;
15611 
15612   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
15613   EvalResult ExprResult;
15614   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15615       !ExprResult.Val.isFloat() ||
15616       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15617     return false;
15618 
15619   Result = ExprResult.Val.getFloat();
15620   return true;
15621 }
15622 
EvaluateAsLValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const15623 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
15624                             bool InConstantContext) const {
15625   assert(!isValueDependent() &&
15626          "Expression evaluator can't be called on a dependent expression.");
15627 
15628   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
15629   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15630   Info.InConstantContext = InConstantContext;
15631   LValue LV;
15632   CheckedTemporaries CheckedTemps;
15633   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
15634       Result.HasSideEffects ||
15635       !CheckLValueConstantExpression(Info, getExprLoc(),
15636                                      Ctx.getLValueReferenceType(getType()), LV,
15637                                      ConstantExprKind::Normal, CheckedTemps))
15638     return false;
15639 
15640   LV.moveInto(Result.Val);
15641   return true;
15642 }
15643 
EvaluateDestruction(const ASTContext & Ctx,APValue::LValueBase Base,APValue DestroyedValue,QualType Type,SourceLocation Loc,Expr::EvalStatus & EStatus,bool IsConstantDestruction)15644 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15645                                 APValue DestroyedValue, QualType Type,
15646                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
15647                                 bool IsConstantDestruction) {
15648   EvalInfo Info(Ctx, EStatus,
15649                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15650                                       : EvalInfo::EM_ConstantFold);
15651   Info.setEvaluatingDecl(Base, DestroyedValue,
15652                          EvalInfo::EvaluatingDeclKind::Dtor);
15653   Info.InConstantContext = IsConstantDestruction;
15654 
15655   LValue LVal;
15656   LVal.set(Base);
15657 
15658   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15659       EStatus.HasSideEffects)
15660     return false;
15661 
15662   if (!Info.discardCleanups())
15663     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15664 
15665   return true;
15666 }
15667 
EvaluateAsConstantExpr(EvalResult & Result,const ASTContext & Ctx,ConstantExprKind Kind) const15668 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15669                                   ConstantExprKind Kind) const {
15670   assert(!isValueDependent() &&
15671          "Expression evaluator can't be called on a dependent expression.");
15672   bool IsConst;
15673   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
15674     return true;
15675 
15676   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
15677   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15678   EvalInfo Info(Ctx, Result, EM);
15679   Info.InConstantContext = true;
15680 
15681   if (Info.EnableNewConstInterp) {
15682     if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val))
15683       return false;
15684     return CheckConstantExpression(Info, getExprLoc(),
15685                                    getStorageType(Ctx, this), Result.Val, Kind);
15686   }
15687 
15688   // The type of the object we're initializing is 'const T' for a class NTTP.
15689   QualType T = getType();
15690   if (Kind == ConstantExprKind::ClassTemplateArgument)
15691     T.addConst();
15692 
15693   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15694   // represent the result of the evaluation. CheckConstantExpression ensures
15695   // this doesn't escape.
15696   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15697   APValue::LValueBase Base(&BaseMTE);
15698   Info.setEvaluatingDecl(Base, Result.Val);
15699 
15700   if (Info.EnableNewConstInterp) {
15701     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, this, Result.Val))
15702       return false;
15703   } else {
15704     LValue LVal;
15705     LVal.set(Base);
15706     // C++23 [intro.execution]/p5
15707     // A full-expression is [...] a constant-expression
15708     // So we need to make sure temporary objects are destroyed after having
15709     // evaluating the expression (per C++23 [class.temporary]/p4).
15710     FullExpressionRAII Scope(Info);
15711     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
15712         Result.HasSideEffects || !Scope.destroy())
15713       return false;
15714 
15715     if (!Info.discardCleanups())
15716       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15717   }
15718 
15719   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15720                                Result.Val, Kind))
15721     return false;
15722   if (!CheckMemoryLeaks(Info))
15723     return false;
15724 
15725   // If this is a class template argument, it's required to have constant
15726   // destruction too.
15727   if (Kind == ConstantExprKind::ClassTemplateArgument &&
15728       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15729                             true) ||
15730        Result.HasSideEffects)) {
15731     // FIXME: Prefix a note to indicate that the problem is lack of constant
15732     // destruction.
15733     return false;
15734   }
15735 
15736   return true;
15737 }
15738 
EvaluateAsInitializer(APValue & Value,const ASTContext & Ctx,const VarDecl * VD,SmallVectorImpl<PartialDiagnosticAt> & Notes,bool IsConstantInitialization) const15739 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15740                                  const VarDecl *VD,
15741                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
15742                                  bool IsConstantInitialization) const {
15743   assert(!isValueDependent() &&
15744          "Expression evaluator can't be called on a dependent expression.");
15745 
15746   llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
15747     std::string Name;
15748     llvm::raw_string_ostream OS(Name);
15749     VD->printQualifiedName(OS);
15750     return Name;
15751   });
15752 
15753   Expr::EvalStatus EStatus;
15754   EStatus.Diag = &Notes;
15755 
15756   EvalInfo Info(Ctx, EStatus,
15757                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus)
15758                     ? EvalInfo::EM_ConstantExpression
15759                     : EvalInfo::EM_ConstantFold);
15760   Info.setEvaluatingDecl(VD, Value);
15761   Info.InConstantContext = IsConstantInitialization;
15762 
15763   SourceLocation DeclLoc = VD->getLocation();
15764   QualType DeclTy = VD->getType();
15765 
15766   if (Info.EnableNewConstInterp) {
15767     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15768     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15769       return false;
15770 
15771     return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15772                                    ConstantExprKind::Normal);
15773   } else {
15774     LValue LVal;
15775     LVal.set(VD);
15776 
15777     {
15778       // C++23 [intro.execution]/p5
15779       // A full-expression is ... an init-declarator ([dcl.decl]) or a
15780       // mem-initializer.
15781       // So we need to make sure temporary objects are destroyed after having
15782       // evaluated the expression (per C++23 [class.temporary]/p4).
15783       //
15784       // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
15785       // serialization code calls ParmVarDecl::getDefaultArg() which strips the
15786       // outermost FullExpr, such as ExprWithCleanups.
15787       FullExpressionRAII Scope(Info);
15788       if (!EvaluateInPlace(Value, Info, LVal, this,
15789                            /*AllowNonLiteralTypes=*/true) ||
15790           EStatus.HasSideEffects)
15791         return false;
15792     }
15793 
15794     // At this point, any lifetime-extended temporaries are completely
15795     // initialized.
15796     Info.performLifetimeExtension();
15797 
15798     if (!Info.discardCleanups())
15799       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15800   }
15801 
15802   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15803                                  ConstantExprKind::Normal) &&
15804          CheckMemoryLeaks(Info);
15805 }
15806 
evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> & Notes) const15807 bool VarDecl::evaluateDestruction(
15808     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15809   Expr::EvalStatus EStatus;
15810   EStatus.Diag = &Notes;
15811 
15812   // Only treat the destruction as constant destruction if we formally have
15813   // constant initialization (or are usable in a constant expression).
15814   bool IsConstantDestruction = hasConstantInitialization();
15815 
15816   // Make a copy of the value for the destructor to mutate, if we know it.
15817   // Otherwise, treat the value as default-initialized; if the destructor works
15818   // anyway, then the destruction is constant (and must be essentially empty).
15819   APValue DestroyedValue;
15820   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15821     DestroyedValue = *getEvaluatedValue();
15822   else if (!handleDefaultInitValue(getType(), DestroyedValue))
15823     return false;
15824 
15825   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15826                            getType(), getLocation(), EStatus,
15827                            IsConstantDestruction) ||
15828       EStatus.HasSideEffects)
15829     return false;
15830 
15831   ensureEvaluatedStmt()->HasConstantDestruction = true;
15832   return true;
15833 }
15834 
15835 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15836 /// constant folded, but discard the result.
isEvaluatable(const ASTContext & Ctx,SideEffectsKind SEK) const15837 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15838   assert(!isValueDependent() &&
15839          "Expression evaluator can't be called on a dependent expression.");
15840 
15841   EvalResult Result;
15842   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15843          !hasUnacceptableSideEffect(Result, SEK);
15844 }
15845 
EvaluateKnownConstInt(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const15846 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15847                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15848   assert(!isValueDependent() &&
15849          "Expression evaluator can't be called on a dependent expression.");
15850 
15851   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
15852   EvalResult EVResult;
15853   EVResult.Diag = Diag;
15854   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15855   Info.InConstantContext = true;
15856 
15857   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15858   (void)Result;
15859   assert(Result && "Could not evaluate expression");
15860   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15861 
15862   return EVResult.Val.getInt();
15863 }
15864 
EvaluateKnownConstIntCheckOverflow(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const15865 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15866     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15867   assert(!isValueDependent() &&
15868          "Expression evaluator can't be called on a dependent expression.");
15869 
15870   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
15871   EvalResult EVResult;
15872   EVResult.Diag = Diag;
15873   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15874   Info.InConstantContext = true;
15875   Info.CheckingForUndefinedBehavior = true;
15876 
15877   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15878   (void)Result;
15879   assert(Result && "Could not evaluate expression");
15880   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15881 
15882   return EVResult.Val.getInt();
15883 }
15884 
EvaluateForOverflow(const ASTContext & Ctx) const15885 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15886   assert(!isValueDependent() &&
15887          "Expression evaluator can't be called on a dependent expression.");
15888 
15889   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
15890   bool IsConst;
15891   EvalResult EVResult;
15892   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15893     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15894     Info.CheckingForUndefinedBehavior = true;
15895     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15896   }
15897 }
15898 
isGlobalLValue() const15899 bool Expr::EvalResult::isGlobalLValue() const {
15900   assert(Val.isLValue());
15901   return IsGlobalLValue(Val.getLValueBase());
15902 }
15903 
15904 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15905 /// an integer constant expression.
15906 
15907 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15908 /// comma, etc
15909 
15910 // CheckICE - This function does the fundamental ICE checking: the returned
15911 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15912 // and a (possibly null) SourceLocation indicating the location of the problem.
15913 //
15914 // Note that to reduce code duplication, this helper does no evaluation
15915 // itself; the caller checks whether the expression is evaluatable, and
15916 // in the rare cases where CheckICE actually cares about the evaluated
15917 // value, it calls into Evaluate.
15918 
15919 namespace {
15920 
15921 enum ICEKind {
15922   /// This expression is an ICE.
15923   IK_ICE,
15924   /// This expression is not an ICE, but if it isn't evaluated, it's
15925   /// a legal subexpression for an ICE. This return value is used to handle
15926   /// the comma operator in C99 mode, and non-constant subexpressions.
15927   IK_ICEIfUnevaluated,
15928   /// This expression is not an ICE, and is not a legal subexpression for one.
15929   IK_NotICE
15930 };
15931 
15932 struct ICEDiag {
15933   ICEKind Kind;
15934   SourceLocation Loc;
15935 
ICEDiag__anonbf0ddd823911::ICEDiag15936   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15937 };
15938 
15939 }
15940 
NoDiag()15941 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15942 
Worst(ICEDiag A,ICEDiag B)15943 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15944 
CheckEvalInICE(const Expr * E,const ASTContext & Ctx)15945 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15946   Expr::EvalResult EVResult;
15947   Expr::EvalStatus Status;
15948   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15949 
15950   Info.InConstantContext = true;
15951   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15952       !EVResult.Val.isInt())
15953     return ICEDiag(IK_NotICE, E->getBeginLoc());
15954 
15955   return NoDiag();
15956 }
15957 
CheckICE(const Expr * E,const ASTContext & Ctx)15958 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15959   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15960   if (!E->getType()->isIntegralOrEnumerationType())
15961     return ICEDiag(IK_NotICE, E->getBeginLoc());
15962 
15963   switch (E->getStmtClass()) {
15964 #define ABSTRACT_STMT(Node)
15965 #define STMT(Node, Base) case Expr::Node##Class:
15966 #define EXPR(Node, Base)
15967 #include "clang/AST/StmtNodes.inc"
15968   case Expr::PredefinedExprClass:
15969   case Expr::FloatingLiteralClass:
15970   case Expr::ImaginaryLiteralClass:
15971   case Expr::StringLiteralClass:
15972   case Expr::ArraySubscriptExprClass:
15973   case Expr::MatrixSubscriptExprClass:
15974   case Expr::OMPArraySectionExprClass:
15975   case Expr::OMPArrayShapingExprClass:
15976   case Expr::OMPIteratorExprClass:
15977   case Expr::MemberExprClass:
15978   case Expr::CompoundAssignOperatorClass:
15979   case Expr::CompoundLiteralExprClass:
15980   case Expr::ExtVectorElementExprClass:
15981   case Expr::DesignatedInitExprClass:
15982   case Expr::ArrayInitLoopExprClass:
15983   case Expr::ArrayInitIndexExprClass:
15984   case Expr::NoInitExprClass:
15985   case Expr::DesignatedInitUpdateExprClass:
15986   case Expr::ImplicitValueInitExprClass:
15987   case Expr::ParenListExprClass:
15988   case Expr::VAArgExprClass:
15989   case Expr::AddrLabelExprClass:
15990   case Expr::StmtExprClass:
15991   case Expr::CXXMemberCallExprClass:
15992   case Expr::CUDAKernelCallExprClass:
15993   case Expr::CXXAddrspaceCastExprClass:
15994   case Expr::CXXDynamicCastExprClass:
15995   case Expr::CXXTypeidExprClass:
15996   case Expr::CXXUuidofExprClass:
15997   case Expr::MSPropertyRefExprClass:
15998   case Expr::MSPropertySubscriptExprClass:
15999   case Expr::CXXNullPtrLiteralExprClass:
16000   case Expr::UserDefinedLiteralClass:
16001   case Expr::CXXThisExprClass:
16002   case Expr::CXXThrowExprClass:
16003   case Expr::CXXNewExprClass:
16004   case Expr::CXXDeleteExprClass:
16005   case Expr::CXXPseudoDestructorExprClass:
16006   case Expr::UnresolvedLookupExprClass:
16007   case Expr::TypoExprClass:
16008   case Expr::RecoveryExprClass:
16009   case Expr::DependentScopeDeclRefExprClass:
16010   case Expr::CXXConstructExprClass:
16011   case Expr::CXXInheritedCtorInitExprClass:
16012   case Expr::CXXStdInitializerListExprClass:
16013   case Expr::CXXBindTemporaryExprClass:
16014   case Expr::ExprWithCleanupsClass:
16015   case Expr::CXXTemporaryObjectExprClass:
16016   case Expr::CXXUnresolvedConstructExprClass:
16017   case Expr::CXXDependentScopeMemberExprClass:
16018   case Expr::UnresolvedMemberExprClass:
16019   case Expr::ObjCStringLiteralClass:
16020   case Expr::ObjCBoxedExprClass:
16021   case Expr::ObjCArrayLiteralClass:
16022   case Expr::ObjCDictionaryLiteralClass:
16023   case Expr::ObjCEncodeExprClass:
16024   case Expr::ObjCMessageExprClass:
16025   case Expr::ObjCSelectorExprClass:
16026   case Expr::ObjCProtocolExprClass:
16027   case Expr::ObjCIvarRefExprClass:
16028   case Expr::ObjCPropertyRefExprClass:
16029   case Expr::ObjCSubscriptRefExprClass:
16030   case Expr::ObjCIsaExprClass:
16031   case Expr::ObjCAvailabilityCheckExprClass:
16032   case Expr::ShuffleVectorExprClass:
16033   case Expr::ConvertVectorExprClass:
16034   case Expr::BlockExprClass:
16035   case Expr::NoStmtClass:
16036   case Expr::OpaqueValueExprClass:
16037   case Expr::PackExpansionExprClass:
16038   case Expr::SubstNonTypeTemplateParmPackExprClass:
16039   case Expr::FunctionParmPackExprClass:
16040   case Expr::AsTypeExprClass:
16041   case Expr::ObjCIndirectCopyRestoreExprClass:
16042   case Expr::MaterializeTemporaryExprClass:
16043   case Expr::PseudoObjectExprClass:
16044   case Expr::AtomicExprClass:
16045   case Expr::LambdaExprClass:
16046   case Expr::CXXFoldExprClass:
16047   case Expr::CoawaitExprClass:
16048   case Expr::DependentCoawaitExprClass:
16049   case Expr::CoyieldExprClass:
16050   case Expr::SYCLUniqueStableNameExprClass:
16051   case Expr::CXXParenListInitExprClass:
16052     return ICEDiag(IK_NotICE, E->getBeginLoc());
16053 
16054   case Expr::InitListExprClass: {
16055     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
16056     // form "T x = { a };" is equivalent to "T x = a;".
16057     // Unless we're initializing a reference, T is a scalar as it is known to be
16058     // of integral or enumeration type.
16059     if (E->isPRValue())
16060       if (cast<InitListExpr>(E)->getNumInits() == 1)
16061         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
16062     return ICEDiag(IK_NotICE, E->getBeginLoc());
16063   }
16064 
16065   case Expr::SizeOfPackExprClass:
16066   case Expr::GNUNullExprClass:
16067   case Expr::SourceLocExprClass:
16068     return NoDiag();
16069 
16070   case Expr::SubstNonTypeTemplateParmExprClass:
16071     return
16072       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
16073 
16074   case Expr::ConstantExprClass:
16075     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
16076 
16077   case Expr::ParenExprClass:
16078     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
16079   case Expr::GenericSelectionExprClass:
16080     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
16081   case Expr::IntegerLiteralClass:
16082   case Expr::FixedPointLiteralClass:
16083   case Expr::CharacterLiteralClass:
16084   case Expr::ObjCBoolLiteralExprClass:
16085   case Expr::CXXBoolLiteralExprClass:
16086   case Expr::CXXScalarValueInitExprClass:
16087   case Expr::TypeTraitExprClass:
16088   case Expr::ConceptSpecializationExprClass:
16089   case Expr::RequiresExprClass:
16090   case Expr::ArrayTypeTraitExprClass:
16091   case Expr::ExpressionTraitExprClass:
16092   case Expr::CXXNoexceptExprClass:
16093     return NoDiag();
16094   case Expr::CallExprClass:
16095   case Expr::CXXOperatorCallExprClass: {
16096     // C99 6.6/3 allows function calls within unevaluated subexpressions of
16097     // constant expressions, but they can never be ICEs because an ICE cannot
16098     // contain an operand of (pointer to) function type.
16099     const CallExpr *CE = cast<CallExpr>(E);
16100     if (CE->getBuiltinCallee())
16101       return CheckEvalInICE(E, Ctx);
16102     return ICEDiag(IK_NotICE, E->getBeginLoc());
16103   }
16104   case Expr::CXXRewrittenBinaryOperatorClass:
16105     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
16106                     Ctx);
16107   case Expr::DeclRefExprClass: {
16108     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
16109     if (isa<EnumConstantDecl>(D))
16110       return NoDiag();
16111 
16112     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
16113     // integer variables in constant expressions:
16114     //
16115     // C++ 7.1.5.1p2
16116     //   A variable of non-volatile const-qualified integral or enumeration
16117     //   type initialized by an ICE can be used in ICEs.
16118     //
16119     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
16120     // that mode, use of reference variables should not be allowed.
16121     const VarDecl *VD = dyn_cast<VarDecl>(D);
16122     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
16123         !VD->getType()->isReferenceType())
16124       return NoDiag();
16125 
16126     return ICEDiag(IK_NotICE, E->getBeginLoc());
16127   }
16128   case Expr::UnaryOperatorClass: {
16129     const UnaryOperator *Exp = cast<UnaryOperator>(E);
16130     switch (Exp->getOpcode()) {
16131     case UO_PostInc:
16132     case UO_PostDec:
16133     case UO_PreInc:
16134     case UO_PreDec:
16135     case UO_AddrOf:
16136     case UO_Deref:
16137     case UO_Coawait:
16138       // C99 6.6/3 allows increment and decrement within unevaluated
16139       // subexpressions of constant expressions, but they can never be ICEs
16140       // because an ICE cannot contain an lvalue operand.
16141       return ICEDiag(IK_NotICE, E->getBeginLoc());
16142     case UO_Extension:
16143     case UO_LNot:
16144     case UO_Plus:
16145     case UO_Minus:
16146     case UO_Not:
16147     case UO_Real:
16148     case UO_Imag:
16149       return CheckICE(Exp->getSubExpr(), Ctx);
16150     }
16151     llvm_unreachable("invalid unary operator class");
16152   }
16153   case Expr::OffsetOfExprClass: {
16154     // Note that per C99, offsetof must be an ICE. And AFAIK, using
16155     // EvaluateAsRValue matches the proposed gcc behavior for cases like
16156     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
16157     // compliance: we should warn earlier for offsetof expressions with
16158     // array subscripts that aren't ICEs, and if the array subscripts
16159     // are ICEs, the value of the offsetof must be an integer constant.
16160     return CheckEvalInICE(E, Ctx);
16161   }
16162   case Expr::UnaryExprOrTypeTraitExprClass: {
16163     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
16164     if ((Exp->getKind() ==  UETT_SizeOf) &&
16165         Exp->getTypeOfArgument()->isVariableArrayType())
16166       return ICEDiag(IK_NotICE, E->getBeginLoc());
16167     return NoDiag();
16168   }
16169   case Expr::BinaryOperatorClass: {
16170     const BinaryOperator *Exp = cast<BinaryOperator>(E);
16171     switch (Exp->getOpcode()) {
16172     case BO_PtrMemD:
16173     case BO_PtrMemI:
16174     case BO_Assign:
16175     case BO_MulAssign:
16176     case BO_DivAssign:
16177     case BO_RemAssign:
16178     case BO_AddAssign:
16179     case BO_SubAssign:
16180     case BO_ShlAssign:
16181     case BO_ShrAssign:
16182     case BO_AndAssign:
16183     case BO_XorAssign:
16184     case BO_OrAssign:
16185       // C99 6.6/3 allows assignments within unevaluated subexpressions of
16186       // constant expressions, but they can never be ICEs because an ICE cannot
16187       // contain an lvalue operand.
16188       return ICEDiag(IK_NotICE, E->getBeginLoc());
16189 
16190     case BO_Mul:
16191     case BO_Div:
16192     case BO_Rem:
16193     case BO_Add:
16194     case BO_Sub:
16195     case BO_Shl:
16196     case BO_Shr:
16197     case BO_LT:
16198     case BO_GT:
16199     case BO_LE:
16200     case BO_GE:
16201     case BO_EQ:
16202     case BO_NE:
16203     case BO_And:
16204     case BO_Xor:
16205     case BO_Or:
16206     case BO_Comma:
16207     case BO_Cmp: {
16208       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
16209       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
16210       if (Exp->getOpcode() == BO_Div ||
16211           Exp->getOpcode() == BO_Rem) {
16212         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
16213         // we don't evaluate one.
16214         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
16215           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
16216           if (REval == 0)
16217             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16218           if (REval.isSigned() && REval.isAllOnes()) {
16219             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
16220             if (LEval.isMinSignedValue())
16221               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16222           }
16223         }
16224       }
16225       if (Exp->getOpcode() == BO_Comma) {
16226         if (Ctx.getLangOpts().C99) {
16227           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
16228           // if it isn't evaluated.
16229           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
16230             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16231         } else {
16232           // In both C89 and C++, commas in ICEs are illegal.
16233           return ICEDiag(IK_NotICE, E->getBeginLoc());
16234         }
16235       }
16236       return Worst(LHSResult, RHSResult);
16237     }
16238     case BO_LAnd:
16239     case BO_LOr: {
16240       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
16241       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
16242       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
16243         // Rare case where the RHS has a comma "side-effect"; we need
16244         // to actually check the condition to see whether the side
16245         // with the comma is evaluated.
16246         if ((Exp->getOpcode() == BO_LAnd) !=
16247             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
16248           return RHSResult;
16249         return NoDiag();
16250       }
16251 
16252       return Worst(LHSResult, RHSResult);
16253     }
16254     }
16255     llvm_unreachable("invalid binary operator kind");
16256   }
16257   case Expr::ImplicitCastExprClass:
16258   case Expr::CStyleCastExprClass:
16259   case Expr::CXXFunctionalCastExprClass:
16260   case Expr::CXXStaticCastExprClass:
16261   case Expr::CXXReinterpretCastExprClass:
16262   case Expr::CXXConstCastExprClass:
16263   case Expr::ObjCBridgedCastExprClass: {
16264     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
16265     if (isa<ExplicitCastExpr>(E)) {
16266       if (const FloatingLiteral *FL
16267             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
16268         unsigned DestWidth = Ctx.getIntWidth(E->getType());
16269         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
16270         APSInt IgnoredVal(DestWidth, !DestSigned);
16271         bool Ignored;
16272         // If the value does not fit in the destination type, the behavior is
16273         // undefined, so we are not required to treat it as a constant
16274         // expression.
16275         if (FL->getValue().convertToInteger(IgnoredVal,
16276                                             llvm::APFloat::rmTowardZero,
16277                                             &Ignored) & APFloat::opInvalidOp)
16278           return ICEDiag(IK_NotICE, E->getBeginLoc());
16279         return NoDiag();
16280       }
16281     }
16282     switch (cast<CastExpr>(E)->getCastKind()) {
16283     case CK_LValueToRValue:
16284     case CK_AtomicToNonAtomic:
16285     case CK_NonAtomicToAtomic:
16286     case CK_NoOp:
16287     case CK_IntegralToBoolean:
16288     case CK_IntegralCast:
16289       return CheckICE(SubExpr, Ctx);
16290     default:
16291       return ICEDiag(IK_NotICE, E->getBeginLoc());
16292     }
16293   }
16294   case Expr::BinaryConditionalOperatorClass: {
16295     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
16296     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
16297     if (CommonResult.Kind == IK_NotICE) return CommonResult;
16298     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16299     if (FalseResult.Kind == IK_NotICE) return FalseResult;
16300     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
16301     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
16302         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
16303     return FalseResult;
16304   }
16305   case Expr::ConditionalOperatorClass: {
16306     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
16307     // If the condition (ignoring parens) is a __builtin_constant_p call,
16308     // then only the true side is actually considered in an integer constant
16309     // expression, and it is fully evaluated.  This is an important GNU
16310     // extension.  See GCC PR38377 for discussion.
16311     if (const CallExpr *CallCE
16312         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
16313       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
16314         return CheckEvalInICE(E, Ctx);
16315     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
16316     if (CondResult.Kind == IK_NotICE)
16317       return CondResult;
16318 
16319     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
16320     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16321 
16322     if (TrueResult.Kind == IK_NotICE)
16323       return TrueResult;
16324     if (FalseResult.Kind == IK_NotICE)
16325       return FalseResult;
16326     if (CondResult.Kind == IK_ICEIfUnevaluated)
16327       return CondResult;
16328     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
16329       return NoDiag();
16330     // Rare case where the diagnostics depend on which side is evaluated
16331     // Note that if we get here, CondResult is 0, and at least one of
16332     // TrueResult and FalseResult is non-zero.
16333     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
16334       return FalseResult;
16335     return TrueResult;
16336   }
16337   case Expr::CXXDefaultArgExprClass:
16338     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
16339   case Expr::CXXDefaultInitExprClass:
16340     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
16341   case Expr::ChooseExprClass: {
16342     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
16343   }
16344   case Expr::BuiltinBitCastExprClass: {
16345     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
16346       return ICEDiag(IK_NotICE, E->getBeginLoc());
16347     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
16348   }
16349   }
16350 
16351   llvm_unreachable("Invalid StmtClass!");
16352 }
16353 
16354 /// Evaluate an expression as a C++11 integral constant expression.
EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext & Ctx,const Expr * E,llvm::APSInt * Value,SourceLocation * Loc)16355 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
16356                                                     const Expr *E,
16357                                                     llvm::APSInt *Value,
16358                                                     SourceLocation *Loc) {
16359   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16360     if (Loc) *Loc = E->getExprLoc();
16361     return false;
16362   }
16363 
16364   APValue Result;
16365   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
16366     return false;
16367 
16368   if (!Result.isInt()) {
16369     if (Loc) *Loc = E->getExprLoc();
16370     return false;
16371   }
16372 
16373   if (Value) *Value = Result.getInt();
16374   return true;
16375 }
16376 
isIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc) const16377 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
16378                                  SourceLocation *Loc) const {
16379   assert(!isValueDependent() &&
16380          "Expression evaluator can't be called on a dependent expression.");
16381 
16382   ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
16383 
16384   if (Ctx.getLangOpts().CPlusPlus11)
16385     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
16386 
16387   ICEDiag D = CheckICE(this, Ctx);
16388   if (D.Kind != IK_ICE) {
16389     if (Loc) *Loc = D.Loc;
16390     return false;
16391   }
16392   return true;
16393 }
16394 
16395 std::optional<llvm::APSInt>
getIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc) const16396 Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc) const {
16397   if (isValueDependent()) {
16398     // Expression evaluator can't succeed on a dependent expression.
16399     return std::nullopt;
16400   }
16401 
16402   APSInt Value;
16403 
16404   if (Ctx.getLangOpts().CPlusPlus11) {
16405     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
16406       return Value;
16407     return std::nullopt;
16408   }
16409 
16410   if (!isIntegerConstantExpr(Ctx, Loc))
16411     return std::nullopt;
16412 
16413   // The only possible side-effects here are due to UB discovered in the
16414   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
16415   // required to treat the expression as an ICE, so we produce the folded
16416   // value.
16417   EvalResult ExprResult;
16418   Expr::EvalStatus Status;
16419   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
16420   Info.InConstantContext = true;
16421 
16422   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
16423     llvm_unreachable("ICE cannot be evaluated!");
16424 
16425   return ExprResult.Val.getInt();
16426 }
16427 
isCXX98IntegralConstantExpr(const ASTContext & Ctx) const16428 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
16429   assert(!isValueDependent() &&
16430          "Expression evaluator can't be called on a dependent expression.");
16431 
16432   return CheckICE(this, Ctx).Kind == IK_ICE;
16433 }
16434 
isCXX11ConstantExpr(const ASTContext & Ctx,APValue * Result,SourceLocation * Loc) const16435 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
16436                                SourceLocation *Loc) const {
16437   assert(!isValueDependent() &&
16438          "Expression evaluator can't be called on a dependent expression.");
16439 
16440   // We support this checking in C++98 mode in order to diagnose compatibility
16441   // issues.
16442   assert(Ctx.getLangOpts().CPlusPlus);
16443 
16444   // Build evaluation settings.
16445   Expr::EvalStatus Status;
16446   SmallVector<PartialDiagnosticAt, 8> Diags;
16447   Status.Diag = &Diags;
16448   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16449 
16450   APValue Scratch;
16451   bool IsConstExpr =
16452       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
16453       // FIXME: We don't produce a diagnostic for this, but the callers that
16454       // call us on arbitrary full-expressions should generally not care.
16455       Info.discardCleanups() && !Status.HasSideEffects;
16456 
16457   if (!Diags.empty()) {
16458     IsConstExpr = false;
16459     if (Loc) *Loc = Diags[0].first;
16460   } else if (!IsConstExpr) {
16461     // FIXME: This shouldn't happen.
16462     if (Loc) *Loc = getExprLoc();
16463   }
16464 
16465   return IsConstExpr;
16466 }
16467 
EvaluateWithSubstitution(APValue & Value,ASTContext & Ctx,const FunctionDecl * Callee,ArrayRef<const Expr * > Args,const Expr * This) const16468 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
16469                                     const FunctionDecl *Callee,
16470                                     ArrayRef<const Expr*> Args,
16471                                     const Expr *This) const {
16472   assert(!isValueDependent() &&
16473          "Expression evaluator can't be called on a dependent expression.");
16474 
16475   llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
16476     std::string Name;
16477     llvm::raw_string_ostream OS(Name);
16478     Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
16479                                  /*Qualified=*/true);
16480     return Name;
16481   });
16482 
16483   Expr::EvalStatus Status;
16484   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
16485   Info.InConstantContext = true;
16486 
16487   LValue ThisVal;
16488   const LValue *ThisPtr = nullptr;
16489   if (This) {
16490 #ifndef NDEBUG
16491     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
16492     assert(MD && "Don't provide `this` for non-methods.");
16493     assert(MD->isImplicitObjectMemberFunction() &&
16494            "Don't provide `this` for methods without an implicit object.");
16495 #endif
16496     if (!This->isValueDependent() &&
16497         EvaluateObjectArgument(Info, This, ThisVal) &&
16498         !Info.EvalStatus.HasSideEffects)
16499       ThisPtr = &ThisVal;
16500 
16501     // Ignore any side-effects from a failed evaluation. This is safe because
16502     // they can't interfere with any other argument evaluation.
16503     Info.EvalStatus.HasSideEffects = false;
16504   }
16505 
16506   CallRef Call = Info.CurrentCall->createCall(Callee);
16507   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
16508        I != E; ++I) {
16509     unsigned Idx = I - Args.begin();
16510     if (Idx >= Callee->getNumParams())
16511       break;
16512     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
16513     if ((*I)->isValueDependent() ||
16514         !EvaluateCallArg(PVD, *I, Call, Info) ||
16515         Info.EvalStatus.HasSideEffects) {
16516       // If evaluation fails, throw away the argument entirely.
16517       if (APValue *Slot = Info.getParamSlot(Call, PVD))
16518         *Slot = APValue();
16519     }
16520 
16521     // Ignore any side-effects from a failed evaluation. This is safe because
16522     // they can't interfere with any other argument evaluation.
16523     Info.EvalStatus.HasSideEffects = false;
16524   }
16525 
16526   // Parameter cleanups happen in the caller and are not part of this
16527   // evaluation.
16528   Info.discardCleanups();
16529   Info.EvalStatus.HasSideEffects = false;
16530 
16531   // Build fake call to Callee.
16532   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
16533                        Call);
16534   // FIXME: Missing ExprWithCleanups in enable_if conditions?
16535   FullExpressionRAII Scope(Info);
16536   return Evaluate(Value, Info, this) && Scope.destroy() &&
16537          !Info.EvalStatus.HasSideEffects;
16538 }
16539 
isPotentialConstantExpr(const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)16540 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
16541                                    SmallVectorImpl<
16542                                      PartialDiagnosticAt> &Diags) {
16543   // FIXME: It would be useful to check constexpr function templates, but at the
16544   // moment the constant expression evaluator cannot cope with the non-rigorous
16545   // ASTs which we build for dependent expressions.
16546   if (FD->isDependentContext())
16547     return true;
16548 
16549   llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
16550     std::string Name;
16551     llvm::raw_string_ostream OS(Name);
16552     FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
16553                              /*Qualified=*/true);
16554     return Name;
16555   });
16556 
16557   Expr::EvalStatus Status;
16558   Status.Diag = &Diags;
16559 
16560   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
16561   Info.InConstantContext = true;
16562   Info.CheckingPotentialConstantExpression = true;
16563 
16564   // The constexpr VM attempts to compile all methods to bytecode here.
16565   if (Info.EnableNewConstInterp) {
16566     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
16567     return Diags.empty();
16568   }
16569 
16570   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
16571   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
16572 
16573   // Fabricate an arbitrary expression on the stack and pretend that it
16574   // is a temporary being used as the 'this' pointer.
16575   LValue This;
16576   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
16577   This.set({&VIE, Info.CurrentCall->Index});
16578 
16579   ArrayRef<const Expr*> Args;
16580 
16581   APValue Scratch;
16582   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
16583     // Evaluate the call as a constant initializer, to allow the construction
16584     // of objects of non-literal types.
16585     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
16586     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
16587   } else {
16588     SourceLocation Loc = FD->getLocation();
16589     HandleFunctionCall(
16590         Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
16591         &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
16592         /*ResultSlot=*/nullptr);
16593   }
16594 
16595   return Diags.empty();
16596 }
16597 
isPotentialConstantExprUnevaluated(Expr * E,const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)16598 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
16599                                               const FunctionDecl *FD,
16600                                               SmallVectorImpl<
16601                                                 PartialDiagnosticAt> &Diags) {
16602   assert(!E->isValueDependent() &&
16603          "Expression evaluator can't be called on a dependent expression.");
16604 
16605   Expr::EvalStatus Status;
16606   Status.Diag = &Diags;
16607 
16608   EvalInfo Info(FD->getASTContext(), Status,
16609                 EvalInfo::EM_ConstantExpressionUnevaluated);
16610   Info.InConstantContext = true;
16611   Info.CheckingPotentialConstantExpression = true;
16612 
16613   // Fabricate a call stack frame to give the arguments a plausible cover story.
16614   CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
16615                        /*CallExpr=*/nullptr, CallRef());
16616 
16617   APValue ResultScratch;
16618   Evaluate(ResultScratch, Info, E);
16619   return Diags.empty();
16620 }
16621 
tryEvaluateObjectSize(uint64_t & Result,ASTContext & Ctx,unsigned Type) const16622 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
16623                                  unsigned Type) const {
16624   if (!getType()->isPointerType())
16625     return false;
16626 
16627   Expr::EvalStatus Status;
16628   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16629   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
16630 }
16631 
EvaluateBuiltinStrLen(const Expr * E,uint64_t & Result,EvalInfo & Info)16632 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
16633                                   EvalInfo &Info) {
16634   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
16635     return false;
16636 
16637   LValue String;
16638 
16639   if (!EvaluatePointer(E, String, Info))
16640     return false;
16641 
16642   QualType CharTy = E->getType()->getPointeeType();
16643 
16644   // Fast path: if it's a string literal, search the string value.
16645   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
16646           String.getLValueBase().dyn_cast<const Expr *>())) {
16647     StringRef Str = S->getBytes();
16648     int64_t Off = String.Offset.getQuantity();
16649     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
16650         S->getCharByteWidth() == 1 &&
16651         // FIXME: Add fast-path for wchar_t too.
16652         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
16653       Str = Str.substr(Off);
16654 
16655       StringRef::size_type Pos = Str.find(0);
16656       if (Pos != StringRef::npos)
16657         Str = Str.substr(0, Pos);
16658 
16659       Result = Str.size();
16660       return true;
16661     }
16662 
16663     // Fall through to slow path.
16664   }
16665 
16666   // Slow path: scan the bytes of the string looking for the terminating 0.
16667   for (uint64_t Strlen = 0; /**/; ++Strlen) {
16668     APValue Char;
16669     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16670         !Char.isInt())
16671       return false;
16672     if (!Char.getInt()) {
16673       Result = Strlen;
16674       return true;
16675     }
16676     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16677       return false;
16678   }
16679 }
16680 
EvaluateCharRangeAsString(std::string & Result,const Expr * SizeExpression,const Expr * PtrExpression,ASTContext & Ctx,EvalResult & Status) const16681 bool Expr::EvaluateCharRangeAsString(std::string &Result,
16682                                      const Expr *SizeExpression,
16683                                      const Expr *PtrExpression, ASTContext &Ctx,
16684                                      EvalResult &Status) const {
16685   LValue String;
16686   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16687   Info.InConstantContext = true;
16688 
16689   FullExpressionRAII Scope(Info);
16690   APSInt SizeValue;
16691   if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
16692     return false;
16693 
16694   int64_t Size = SizeValue.getExtValue();
16695 
16696   if (!::EvaluatePointer(PtrExpression, String, Info))
16697     return false;
16698 
16699   QualType CharTy = PtrExpression->getType()->getPointeeType();
16700   for (int64_t I = 0; I < Size; ++I) {
16701     APValue Char;
16702     if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
16703                                         Char))
16704       return false;
16705 
16706     APSInt C = Char.getInt();
16707     Result.push_back(static_cast<char>(C.getExtValue()));
16708     if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
16709       return false;
16710   }
16711   if (!Scope.destroy())
16712     return false;
16713 
16714   if (!CheckMemoryLeaks(Info))
16715     return false;
16716 
16717   return true;
16718 }
16719 
tryEvaluateStrLen(uint64_t & Result,ASTContext & Ctx) const16720 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
16721   Expr::EvalStatus Status;
16722   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16723   return EvaluateBuiltinStrLen(this, Result, Info);
16724 }
16725