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 "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "llvm/ADT/APFixedPoint.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62 
63 #define DEBUG_TYPE "exprconstant"
64 
65 using namespace clang;
66 using llvm::APFixedPoint;
67 using llvm::APInt;
68 using llvm::APSInt;
69 using llvm::APFloat;
70 using llvm::FixedPointSemantics;
71 using llvm::Optional;
72 
73 namespace {
74   struct LValue;
75   class CallStackFrame;
76   class EvalInfo;
77 
78   using SourceLocExprScopeGuard =
79       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80 
getType(APValue::LValueBase B)81   static QualType getType(APValue::LValueBase B) {
82     return B.getType();
83   }
84 
85   /// Get an LValue path entry, which is known to not be an array index, as a
86   /// field declaration.
getAsField(APValue::LValuePathEntry E)87   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
88     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
89   }
90   /// Get an LValue path entry, which is known to not be an array index, as a
91   /// base class declaration.
getAsBaseClass(APValue::LValuePathEntry E)92   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
93     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
94   }
95   /// Determine whether this LValue path entry for a base class names a virtual
96   /// base class.
isVirtualBaseClass(APValue::LValuePathEntry E)97   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
98     return E.getAsBaseOrMember().getInt();
99   }
100 
101   /// Given an expression, determine the type used to store the result of
102   /// evaluating that expression.
getStorageType(const ASTContext & Ctx,const Expr * E)103   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104     if (E->isPRValue())
105       return E->getType();
106     return Ctx.getLValueReferenceType(E->getType());
107   }
108 
109   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
getAllocSizeAttr(const CallExpr * CE)110   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111     if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
112       return DirectCallee->getAttr<AllocSizeAttr>();
113     if (const Decl *IndirectCallee = CE->getCalleeDecl())
114       return IndirectCallee->getAttr<AllocSizeAttr>();
115     return nullptr;
116   }
117 
118   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119   /// This will look through a single cast.
120   ///
121   /// Returns null if we couldn't unwrap a function with alloc_size.
tryUnwrapAllocSizeCall(const Expr * E)122   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123     if (!E->getType()->isPointerType())
124       return nullptr;
125 
126     E = E->IgnoreParens();
127     // If we're doing a variable assignment from e.g. malloc(N), there will
128     // probably be a cast of some kind. In exotic cases, we might also see a
129     // top-level ExprWithCleanups. Ignore them either way.
130     if (const auto *FE = dyn_cast<FullExpr>(E))
131       E = FE->getSubExpr()->IgnoreParens();
132 
133     if (const auto *Cast = dyn_cast<CastExpr>(E))
134       E = Cast->getSubExpr()->IgnoreParens();
135 
136     if (const auto *CE = dyn_cast<CallExpr>(E))
137       return getAllocSizeAttr(CE) ? CE : nullptr;
138     return nullptr;
139   }
140 
141   /// Determines whether or not the given Base contains a call to a function
142   /// with the alloc_size attribute.
isBaseAnAllocSizeCall(APValue::LValueBase Base)143   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144     const auto *E = Base.dyn_cast<const Expr *>();
145     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146   }
147 
148   /// Determines whether the given kind of constant expression is only ever
149   /// used for name mangling. If so, it's permitted to reference things that we
150   /// can't generate code for (in particular, dllimported functions).
isForManglingOnly(ConstantExprKind Kind)151   static bool isForManglingOnly(ConstantExprKind Kind) {
152     switch (Kind) {
153     case ConstantExprKind::Normal:
154     case ConstantExprKind::ClassTemplateArgument:
155     case ConstantExprKind::ImmediateInvocation:
156       // Note that non-type template arguments of class type are emitted as
157       // template parameter objects.
158       return false;
159 
160     case ConstantExprKind::NonClassTemplateArgument:
161       return true;
162     }
163     llvm_unreachable("unknown ConstantExprKind");
164   }
165 
isTemplateArgument(ConstantExprKind Kind)166   static bool isTemplateArgument(ConstantExprKind Kind) {
167     switch (Kind) {
168     case ConstantExprKind::Normal:
169     case ConstantExprKind::ImmediateInvocation:
170       return false;
171 
172     case ConstantExprKind::ClassTemplateArgument:
173     case ConstantExprKind::NonClassTemplateArgument:
174       return true;
175     }
176     llvm_unreachable("unknown ConstantExprKind");
177   }
178 
179   /// The bound to claim that an array of unknown bound has.
180   /// The value in MostDerivedArraySize is undefined in this case. So, set it
181   /// to an arbitrary value that's likely to loudly break things if it's used.
182   static const uint64_t AssumedSizeForUnsizedArray =
183       std::numeric_limits<uint64_t>::max() / 2;
184 
185   /// Determines if an LValue with the given LValueBase will have an unsized
186   /// array in its designator.
187   /// Find the path length and type of the most-derived subobject in the given
188   /// path, and find the size of the containing array, if any.
189   static unsigned
findMostDerivedSubobject(ASTContext & Ctx,APValue::LValueBase Base,ArrayRef<APValue::LValuePathEntry> Path,uint64_t & ArraySize,QualType & Type,bool & IsArray,bool & FirstEntryIsUnsizedArray)190   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191                            ArrayRef<APValue::LValuePathEntry> Path,
192                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
193                            bool &FirstEntryIsUnsizedArray) {
194     // This only accepts LValueBases from APValues, and APValues don't support
195     // arrays that lack size info.
196     assert(!isBaseAnAllocSizeCall(Base) &&
197            "Unsized arrays shouldn't appear here");
198     unsigned MostDerivedLength = 0;
199     Type = getType(Base);
200 
201     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
202       if (Type->isArrayType()) {
203         const ArrayType *AT = Ctx.getAsArrayType(Type);
204         Type = AT->getElementType();
205         MostDerivedLength = I + 1;
206         IsArray = true;
207 
208         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
209           ArraySize = CAT->getSize().getZExtValue();
210         } else {
211           assert(I == 0 && "unexpected unsized array designator");
212           FirstEntryIsUnsizedArray = true;
213           ArraySize = AssumedSizeForUnsizedArray;
214         }
215       } else if (Type->isAnyComplexType()) {
216         const ComplexType *CT = Type->castAs<ComplexType>();
217         Type = CT->getElementType();
218         ArraySize = 2;
219         MostDerivedLength = I + 1;
220         IsArray = true;
221       } else if (const FieldDecl *FD = getAsField(Path[I])) {
222         Type = FD->getType();
223         ArraySize = 0;
224         MostDerivedLength = I + 1;
225         IsArray = false;
226       } else {
227         // Path[I] describes a base class.
228         ArraySize = 0;
229         IsArray = false;
230       }
231     }
232     return MostDerivedLength;
233   }
234 
235   /// A path from a glvalue to a subobject of that glvalue.
236   struct SubobjectDesignator {
237     /// True if the subobject was named in a manner not supported by C++11. Such
238     /// lvalues can still be folded, but they are not core constant expressions
239     /// and we cannot perform lvalue-to-rvalue conversions on them.
240     unsigned Invalid : 1;
241 
242     /// Is this a pointer one past the end of an object?
243     unsigned IsOnePastTheEnd : 1;
244 
245     /// Indicator of whether the first entry is an unsized array.
246     unsigned FirstEntryIsAnUnsizedArray : 1;
247 
248     /// Indicator of whether the most-derived object is an array element.
249     unsigned MostDerivedIsArrayElement : 1;
250 
251     /// The length of the path to the most-derived object of which this is a
252     /// subobject.
253     unsigned MostDerivedPathLength : 28;
254 
255     /// The size of the array of which the most-derived object is an element.
256     /// This will always be 0 if the most-derived object is not an array
257     /// element. 0 is not an indicator of whether or not the most-derived object
258     /// is an array, however, because 0-length arrays are allowed.
259     ///
260     /// If the current array is an unsized array, the value of this is
261     /// undefined.
262     uint64_t MostDerivedArraySize;
263 
264     /// The type of the most derived object referred to by this address.
265     QualType MostDerivedType;
266 
267     typedef APValue::LValuePathEntry PathEntry;
268 
269     /// The entries on the path from the glvalue to the designated subobject.
270     SmallVector<PathEntry, 8> Entries;
271 
SubobjectDesignator__anon7a1fdcea0111::SubobjectDesignator272     SubobjectDesignator() : Invalid(true) {}
273 
SubobjectDesignator__anon7a1fdcea0111::SubobjectDesignator274     explicit SubobjectDesignator(QualType T)
275         : Invalid(false), IsOnePastTheEnd(false),
276           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277           MostDerivedPathLength(0), MostDerivedArraySize(0),
278           MostDerivedType(T) {}
279 
SubobjectDesignator__anon7a1fdcea0111::SubobjectDesignator280     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
281         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
282           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
283           MostDerivedPathLength(0), MostDerivedArraySize(0) {
284       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
285       if (!Invalid) {
286         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
287         ArrayRef<PathEntry> VEntries = V.getLValuePath();
288         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
289         if (V.getLValueBase()) {
290           bool IsArray = false;
291           bool FirstIsUnsizedArray = false;
292           MostDerivedPathLength = findMostDerivedSubobject(
293               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
294               MostDerivedType, IsArray, FirstIsUnsizedArray);
295           MostDerivedIsArrayElement = IsArray;
296           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297         }
298       }
299     }
300 
truncate__anon7a1fdcea0111::SubobjectDesignator301     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
302                   unsigned NewLength) {
303       if (Invalid)
304         return;
305 
306       assert(Base && "cannot truncate path for null pointer");
307       assert(NewLength <= Entries.size() && "not a truncation");
308 
309       if (NewLength == Entries.size())
310         return;
311       Entries.resize(NewLength);
312 
313       bool IsArray = false;
314       bool FirstIsUnsizedArray = false;
315       MostDerivedPathLength = findMostDerivedSubobject(
316           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
317           FirstIsUnsizedArray);
318       MostDerivedIsArrayElement = IsArray;
319       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
320     }
321 
setInvalid__anon7a1fdcea0111::SubobjectDesignator322     void setInvalid() {
323       Invalid = true;
324       Entries.clear();
325     }
326 
327     /// Determine whether the most derived subobject is an array without a
328     /// known bound.
isMostDerivedAnUnsizedArray__anon7a1fdcea0111::SubobjectDesignator329     bool isMostDerivedAnUnsizedArray() const {
330       assert(!Invalid && "Calling this makes no sense on invalid designators");
331       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
332     }
333 
334     /// Determine what the most derived array's size is. Results in an assertion
335     /// failure if the most derived array lacks a size.
getMostDerivedArraySize__anon7a1fdcea0111::SubobjectDesignator336     uint64_t getMostDerivedArraySize() const {
337       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
338       return MostDerivedArraySize;
339     }
340 
341     /// Determine whether this is a one-past-the-end pointer.
isOnePastTheEnd__anon7a1fdcea0111::SubobjectDesignator342     bool isOnePastTheEnd() const {
343       assert(!Invalid);
344       if (IsOnePastTheEnd)
345         return true;
346       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
347           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
348               MostDerivedArraySize)
349         return true;
350       return false;
351     }
352 
353     /// Get the range of valid index adjustments in the form
354     ///   {maximum value that can be subtracted from this pointer,
355     ///    maximum value that can be added to this pointer}
validIndexAdjustments__anon7a1fdcea0111::SubobjectDesignator356     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
357       if (Invalid || isMostDerivedAnUnsizedArray())
358         return {0, 0};
359 
360       // [expr.add]p4: For the purposes of these operators, a pointer to a
361       // nonarray object behaves the same as a pointer to the first element of
362       // an array of length one with the type of the object as its element type.
363       bool IsArray = MostDerivedPathLength == Entries.size() &&
364                      MostDerivedIsArrayElement;
365       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
366                                     : (uint64_t)IsOnePastTheEnd;
367       uint64_t ArraySize =
368           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
369       return {ArrayIndex, ArraySize - ArrayIndex};
370     }
371 
372     /// Check that this refers to a valid subobject.
isValidSubobject__anon7a1fdcea0111::SubobjectDesignator373     bool isValidSubobject() const {
374       if (Invalid)
375         return false;
376       return !isOnePastTheEnd();
377     }
378     /// Check that this refers to a valid subobject, and if not, produce a
379     /// relevant diagnostic and set the designator as invalid.
380     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
381 
382     /// Get the type of the designated object.
getType__anon7a1fdcea0111::SubobjectDesignator383     QualType getType(ASTContext &Ctx) const {
384       assert(!Invalid && "invalid designator has no subobject type");
385       return MostDerivedPathLength == Entries.size()
386                  ? MostDerivedType
387                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
388     }
389 
390     /// Update this designator to refer to the first element within this array.
addArrayUnchecked__anon7a1fdcea0111::SubobjectDesignator391     void addArrayUnchecked(const ConstantArrayType *CAT) {
392       Entries.push_back(PathEntry::ArrayIndex(0));
393 
394       // This is a most-derived object.
395       MostDerivedType = CAT->getElementType();
396       MostDerivedIsArrayElement = true;
397       MostDerivedArraySize = CAT->getSize().getZExtValue();
398       MostDerivedPathLength = Entries.size();
399     }
400     /// Update this designator to refer to the first element within the array of
401     /// elements of type T. This is an array of unknown size.
addUnsizedArrayUnchecked__anon7a1fdcea0111::SubobjectDesignator402     void addUnsizedArrayUnchecked(QualType ElemTy) {
403       Entries.push_back(PathEntry::ArrayIndex(0));
404 
405       MostDerivedType = ElemTy;
406       MostDerivedIsArrayElement = true;
407       // The value in MostDerivedArraySize is undefined in this case. So, set it
408       // to an arbitrary value that's likely to loudly break things if it's
409       // used.
410       MostDerivedArraySize = AssumedSizeForUnsizedArray;
411       MostDerivedPathLength = Entries.size();
412     }
413     /// Update this designator to refer to the given base or member of this
414     /// object.
addDeclUnchecked__anon7a1fdcea0111::SubobjectDesignator415     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
416       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
417 
418       // If this isn't a base class, it's a new most-derived object.
419       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
420         MostDerivedType = FD->getType();
421         MostDerivedIsArrayElement = false;
422         MostDerivedArraySize = 0;
423         MostDerivedPathLength = Entries.size();
424       }
425     }
426     /// Update this designator to refer to the given complex component.
addComplexUnchecked__anon7a1fdcea0111::SubobjectDesignator427     void addComplexUnchecked(QualType EltTy, bool Imag) {
428       Entries.push_back(PathEntry::ArrayIndex(Imag));
429 
430       // This is technically a most-derived object, though in practice this
431       // is unlikely to matter.
432       MostDerivedType = EltTy;
433       MostDerivedIsArrayElement = true;
434       MostDerivedArraySize = 2;
435       MostDerivedPathLength = Entries.size();
436     }
437     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
438     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
439                                    const APSInt &N);
440     /// Add N to the address of this subobject.
adjustIndex__anon7a1fdcea0111::SubobjectDesignator441     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
442       if (Invalid || !N) return;
443       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
444       if (isMostDerivedAnUnsizedArray()) {
445         diagnoseUnsizedArrayPointerArithmetic(Info, E);
446         // Can't verify -- trust that the user is doing the right thing (or if
447         // not, trust that the caller will catch the bad behavior).
448         // FIXME: Should we reject if this overflows, at least?
449         Entries.back() = PathEntry::ArrayIndex(
450             Entries.back().getAsArrayIndex() + TruncatedN);
451         return;
452       }
453 
454       // [expr.add]p4: For the purposes of these operators, a pointer to a
455       // nonarray object behaves the same as a pointer to the first element of
456       // an array of length one with the type of the object as its element type.
457       bool IsArray = MostDerivedPathLength == Entries.size() &&
458                      MostDerivedIsArrayElement;
459       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
460                                     : (uint64_t)IsOnePastTheEnd;
461       uint64_t ArraySize =
462           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
463 
464       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
465         // Calculate the actual index in a wide enough type, so we can include
466         // it in the note.
467         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
468         (llvm::APInt&)N += ArrayIndex;
469         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
470         diagnosePointerArithmetic(Info, E, N);
471         setInvalid();
472         return;
473       }
474 
475       ArrayIndex += TruncatedN;
476       assert(ArrayIndex <= ArraySize &&
477              "bounds check succeeded for out-of-bounds index");
478 
479       if (IsArray)
480         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
481       else
482         IsOnePastTheEnd = (ArrayIndex != 0);
483     }
484   };
485 
486   /// A scope at the end of which an object can need to be destroyed.
487   enum class ScopeKind {
488     Block,
489     FullExpression,
490     Call
491   };
492 
493   /// A reference to a particular call and its arguments.
494   struct CallRef {
CallRef__anon7a1fdcea0111::CallRef495     CallRef() : OrigCallee(), CallIndex(0), Version() {}
CallRef__anon7a1fdcea0111::CallRef496     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
498 
operator bool__anon7a1fdcea0111::CallRef499     explicit operator bool() const { return OrigCallee; }
500 
501     /// Get the parameter that the caller initialized, corresponding to the
502     /// given parameter in the callee.
getOrigParam__anon7a1fdcea0111::CallRef503     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
504       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
505                         : PVD;
506     }
507 
508     /// The callee at the point where the arguments were evaluated. This might
509     /// be different from the actual callee (a different redeclaration, or a
510     /// virtual override), but this function's parameters are the ones that
511     /// appear in the parameter map.
512     const FunctionDecl *OrigCallee;
513     /// The call index of the frame that holds the argument values.
514     unsigned CallIndex;
515     /// The version of the parameters corresponding to this call.
516     unsigned Version;
517   };
518 
519   /// A stack frame in the constexpr call stack.
520   class CallStackFrame : public interp::Frame {
521   public:
522     EvalInfo &Info;
523 
524     /// Parent - The caller of this stack frame.
525     CallStackFrame *Caller;
526 
527     /// Callee - The function which was called.
528     const FunctionDecl *Callee;
529 
530     /// This - The binding for the this pointer in this call, if any.
531     const LValue *This;
532 
533     /// Information on how to find the arguments to this call. Our arguments
534     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
535     /// key and this value as the version.
536     CallRef Arguments;
537 
538     /// Source location information about the default argument or default
539     /// initializer expression we're evaluating, if any.
540     CurrentSourceLocExprScope CurSourceLocExprScope;
541 
542     // Note that we intentionally use std::map here so that references to
543     // values are stable.
544     typedef std::pair<const void *, unsigned> MapKeyTy;
545     typedef std::map<MapKeyTy, APValue> MapTy;
546     /// Temporaries - Temporary lvalues materialized within this stack frame.
547     MapTy Temporaries;
548 
549     /// CallLoc - The location of the call expression for this call.
550     SourceLocation CallLoc;
551 
552     /// Index - The call index of this call.
553     unsigned Index;
554 
555     /// The stack of integers for tracking version numbers for temporaries.
556     SmallVector<unsigned, 2> TempVersionStack = {1};
557     unsigned CurTempVersion = TempVersionStack.back();
558 
getTempVersion() const559     unsigned getTempVersion() const { return TempVersionStack.back(); }
560 
pushTempVersion()561     void pushTempVersion() {
562       TempVersionStack.push_back(++CurTempVersion);
563     }
564 
popTempVersion()565     void popTempVersion() {
566       TempVersionStack.pop_back();
567     }
568 
createCall(const FunctionDecl * Callee)569     CallRef createCall(const FunctionDecl *Callee) {
570       return {Callee, Index, ++CurTempVersion};
571     }
572 
573     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
574     // on the overall stack usage of deeply-recursing constexpr evaluations.
575     // (We should cache this map rather than recomputing it repeatedly.)
576     // But let's try this and see how it goes; we can look into caching the map
577     // as a later change.
578 
579     /// LambdaCaptureFields - Mapping from captured variables/this to
580     /// corresponding data members in the closure class.
581     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
582     FieldDecl *LambdaThisCaptureField;
583 
584     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
585                    const FunctionDecl *Callee, const LValue *This,
586                    CallRef Arguments);
587     ~CallStackFrame();
588 
589     // Return the temporary for Key whose version number is Version.
getTemporary(const void * Key,unsigned Version)590     APValue *getTemporary(const void *Key, unsigned Version) {
591       MapKeyTy KV(Key, Version);
592       auto LB = Temporaries.lower_bound(KV);
593       if (LB != Temporaries.end() && LB->first == KV)
594         return &LB->second;
595       // Pair (Key,Version) wasn't found in the map. Check that no elements
596       // in the map have 'Key' as their key.
597       assert((LB == Temporaries.end() || LB->first.first != Key) &&
598              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
599              "Element with key 'Key' found in map");
600       return nullptr;
601     }
602 
603     // Return the current temporary for Key in the map.
getCurrentTemporary(const void * Key)604     APValue *getCurrentTemporary(const void *Key) {
605       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
606       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
607         return &std::prev(UB)->second;
608       return nullptr;
609     }
610 
611     // Return the version number of the current temporary for Key.
getCurrentTemporaryVersion(const void * Key) const612     unsigned getCurrentTemporaryVersion(const void *Key) const {
613       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
614       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
615         return std::prev(UB)->first.second;
616       return 0;
617     }
618 
619     /// Allocate storage for an object of type T in this stack frame.
620     /// Populates LV with a handle to the created object. Key identifies
621     /// the temporary within the stack frame, and must not be reused without
622     /// bumping the temporary version number.
623     template<typename KeyT>
624     APValue &createTemporary(const KeyT *Key, QualType T,
625                              ScopeKind Scope, LValue &LV);
626 
627     /// Allocate storage for a parameter of a function call made in this frame.
628     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
629 
630     void describe(llvm::raw_ostream &OS) override;
631 
getCaller() const632     Frame *getCaller() const override { return Caller; }
getCallLocation() const633     SourceLocation getCallLocation() const override { return CallLoc; }
getCallee() const634     const FunctionDecl *getCallee() const override { return Callee; }
635 
isStdFunction() const636     bool isStdFunction() const {
637       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
638         if (DC->isStdNamespace())
639           return true;
640       return false;
641     }
642 
643   private:
644     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
645                          ScopeKind Scope);
646   };
647 
648   /// Temporarily override 'this'.
649   class ThisOverrideRAII {
650   public:
ThisOverrideRAII(CallStackFrame & Frame,const LValue * NewThis,bool Enable)651     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
652         : Frame(Frame), OldThis(Frame.This) {
653       if (Enable)
654         Frame.This = NewThis;
655     }
~ThisOverrideRAII()656     ~ThisOverrideRAII() {
657       Frame.This = OldThis;
658     }
659   private:
660     CallStackFrame &Frame;
661     const LValue *OldThis;
662   };
663 }
664 
665 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
666                               const LValue &This, QualType ThisType);
667 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
668                               APValue::LValueBase LVBase, APValue &Value,
669                               QualType T);
670 
671 namespace {
672   /// A cleanup, and a flag indicating whether it is lifetime-extended.
673   class Cleanup {
674     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
675     APValue::LValueBase Base;
676     QualType T;
677 
678   public:
Cleanup(APValue * Val,APValue::LValueBase Base,QualType T,ScopeKind Scope)679     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
680             ScopeKind Scope)
681         : Value(Val, Scope), Base(Base), T(T) {}
682 
683     /// Determine whether this cleanup should be performed at the end of the
684     /// given kind of scope.
isDestroyedAtEndOf(ScopeKind K) const685     bool isDestroyedAtEndOf(ScopeKind K) const {
686       return (int)Value.getInt() >= (int)K;
687     }
endLifetime(EvalInfo & Info,bool RunDestructors)688     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
689       if (RunDestructors) {
690         SourceLocation Loc;
691         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
692           Loc = VD->getLocation();
693         else if (const Expr *E = Base.dyn_cast<const Expr*>())
694           Loc = E->getExprLoc();
695         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
696       }
697       *Value.getPointer() = APValue();
698       return true;
699     }
700 
hasSideEffect()701     bool hasSideEffect() {
702       return T.isDestructedType();
703     }
704   };
705 
706   /// A reference to an object whose construction we are currently evaluating.
707   struct ObjectUnderConstruction {
708     APValue::LValueBase Base;
709     ArrayRef<APValue::LValuePathEntry> Path;
operator ==(const ObjectUnderConstruction & LHS,const ObjectUnderConstruction & RHS)710     friend bool operator==(const ObjectUnderConstruction &LHS,
711                            const ObjectUnderConstruction &RHS) {
712       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
713     }
hash_value(const ObjectUnderConstruction & Obj)714     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
715       return llvm::hash_combine(Obj.Base, Obj.Path);
716     }
717   };
718   enum class ConstructionPhase {
719     None,
720     Bases,
721     AfterBases,
722     AfterFields,
723     Destroying,
724     DestroyingBases
725   };
726 }
727 
728 namespace llvm {
729 template<> struct DenseMapInfo<ObjectUnderConstruction> {
730   using Base = DenseMapInfo<APValue::LValueBase>;
getEmptyKeyllvm::DenseMapInfo731   static ObjectUnderConstruction getEmptyKey() {
732     return {Base::getEmptyKey(), {}}; }
getTombstoneKeyllvm::DenseMapInfo733   static ObjectUnderConstruction getTombstoneKey() {
734     return {Base::getTombstoneKey(), {}};
735   }
getHashValuellvm::DenseMapInfo736   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
737     return hash_value(Object);
738   }
isEqualllvm::DenseMapInfo739   static bool isEqual(const ObjectUnderConstruction &LHS,
740                       const ObjectUnderConstruction &RHS) {
741     return LHS == RHS;
742   }
743 };
744 }
745 
746 namespace {
747   /// A dynamically-allocated heap object.
748   struct DynAlloc {
749     /// The value of this heap-allocated object.
750     APValue Value;
751     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
752     /// or a CallExpr (the latter is for direct calls to operator new inside
753     /// std::allocator<T>::allocate).
754     const Expr *AllocExpr = nullptr;
755 
756     enum Kind {
757       New,
758       ArrayNew,
759       StdAllocator
760     };
761 
762     /// Get the kind of the allocation. This must match between allocation
763     /// and deallocation.
getKind__anon7a1fdcea0311::DynAlloc764     Kind getKind() const {
765       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
766         return NE->isArray() ? ArrayNew : New;
767       assert(isa<CallExpr>(AllocExpr));
768       return StdAllocator;
769     }
770   };
771 
772   struct DynAllocOrder {
operator ()__anon7a1fdcea0311::DynAllocOrder773     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
774       return L.getIndex() < R.getIndex();
775     }
776   };
777 
778   /// EvalInfo - This is a private struct used by the evaluator to capture
779   /// information about a subexpression as it is folded.  It retains information
780   /// about the AST context, but also maintains information about the folded
781   /// expression.
782   ///
783   /// If an expression could be evaluated, it is still possible it is not a C
784   /// "integer constant expression" or constant expression.  If not, this struct
785   /// captures information about how and why not.
786   ///
787   /// One bit of information passed *into* the request for constant folding
788   /// indicates whether the subexpression is "evaluated" or not according to C
789   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
790   /// evaluate the expression regardless of what the RHS is, but C only allows
791   /// certain things in certain situations.
792   class EvalInfo : public interp::State {
793   public:
794     ASTContext &Ctx;
795 
796     /// EvalStatus - Contains information about the evaluation.
797     Expr::EvalStatus &EvalStatus;
798 
799     /// CurrentCall - The top of the constexpr call stack.
800     CallStackFrame *CurrentCall;
801 
802     /// CallStackDepth - The number of calls in the call stack right now.
803     unsigned CallStackDepth;
804 
805     /// NextCallIndex - The next call index to assign.
806     unsigned NextCallIndex;
807 
808     /// StepsLeft - The remaining number of evaluation steps we're permitted
809     /// to perform. This is essentially a limit for the number of statements
810     /// we will evaluate.
811     unsigned StepsLeft;
812 
813     /// Enable the experimental new constant interpreter. If an expression is
814     /// not supported by the interpreter, an error is triggered.
815     bool EnableNewConstInterp;
816 
817     /// BottomFrame - The frame in which evaluation started. This must be
818     /// initialized after CurrentCall and CallStackDepth.
819     CallStackFrame BottomFrame;
820 
821     /// A stack of values whose lifetimes end at the end of some surrounding
822     /// evaluation frame.
823     llvm::SmallVector<Cleanup, 16> CleanupStack;
824 
825     /// EvaluatingDecl - This is the declaration whose initializer is being
826     /// evaluated, if any.
827     APValue::LValueBase EvaluatingDecl;
828 
829     enum class EvaluatingDeclKind {
830       None,
831       /// We're evaluating the construction of EvaluatingDecl.
832       Ctor,
833       /// We're evaluating the destruction of EvaluatingDecl.
834       Dtor,
835     };
836     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
837 
838     /// EvaluatingDeclValue - This is the value being constructed for the
839     /// declaration whose initializer is being evaluated, if any.
840     APValue *EvaluatingDeclValue;
841 
842     /// Set of objects that are currently being constructed.
843     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
844         ObjectsUnderConstruction;
845 
846     /// Current heap allocations, along with the location where each was
847     /// allocated. We use std::map here because we need stable addresses
848     /// for the stored APValues.
849     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
850 
851     /// The number of heap allocations performed so far in this evaluation.
852     unsigned NumHeapAllocs = 0;
853 
854     struct EvaluatingConstructorRAII {
855       EvalInfo &EI;
856       ObjectUnderConstruction Object;
857       bool DidInsert;
EvaluatingConstructorRAII__anon7a1fdcea0311::EvalInfo::EvaluatingConstructorRAII858       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
859                                 bool HasBases)
860           : EI(EI), Object(Object) {
861         DidInsert =
862             EI.ObjectsUnderConstruction
863                 .insert({Object, HasBases ? ConstructionPhase::Bases
864                                           : ConstructionPhase::AfterBases})
865                 .second;
866       }
finishedConstructingBases__anon7a1fdcea0311::EvalInfo::EvaluatingConstructorRAII867       void finishedConstructingBases() {
868         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
869       }
finishedConstructingFields__anon7a1fdcea0311::EvalInfo::EvaluatingConstructorRAII870       void finishedConstructingFields() {
871         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
872       }
~EvaluatingConstructorRAII__anon7a1fdcea0311::EvalInfo::EvaluatingConstructorRAII873       ~EvaluatingConstructorRAII() {
874         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
875       }
876     };
877 
878     struct EvaluatingDestructorRAII {
879       EvalInfo &EI;
880       ObjectUnderConstruction Object;
881       bool DidInsert;
EvaluatingDestructorRAII__anon7a1fdcea0311::EvalInfo::EvaluatingDestructorRAII882       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
883           : EI(EI), Object(Object) {
884         DidInsert = EI.ObjectsUnderConstruction
885                         .insert({Object, ConstructionPhase::Destroying})
886                         .second;
887       }
startedDestroyingBases__anon7a1fdcea0311::EvalInfo::EvaluatingDestructorRAII888       void startedDestroyingBases() {
889         EI.ObjectsUnderConstruction[Object] =
890             ConstructionPhase::DestroyingBases;
891       }
~EvaluatingDestructorRAII__anon7a1fdcea0311::EvalInfo::EvaluatingDestructorRAII892       ~EvaluatingDestructorRAII() {
893         if (DidInsert)
894           EI.ObjectsUnderConstruction.erase(Object);
895       }
896     };
897 
898     ConstructionPhase
isEvaluatingCtorDtor(APValue::LValueBase Base,ArrayRef<APValue::LValuePathEntry> Path)899     isEvaluatingCtorDtor(APValue::LValueBase Base,
900                          ArrayRef<APValue::LValuePathEntry> Path) {
901       return ObjectsUnderConstruction.lookup({Base, Path});
902     }
903 
904     /// If we're currently speculatively evaluating, the outermost call stack
905     /// depth at which we can mutate state, otherwise 0.
906     unsigned SpeculativeEvaluationDepth = 0;
907 
908     /// The current array initialization index, if we're performing array
909     /// initialization.
910     uint64_t ArrayInitIndex = -1;
911 
912     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
913     /// notes attached to it will also be stored, otherwise they will not be.
914     bool HasActiveDiagnostic;
915 
916     /// Have we emitted a diagnostic explaining why we couldn't constant
917     /// fold (not just why it's not strictly a constant expression)?
918     bool HasFoldFailureDiagnostic;
919 
920     /// Whether or not we're in a context where the front end requires a
921     /// constant value.
922     bool InConstantContext;
923 
924     /// Whether we're checking that an expression is a potential constant
925     /// expression. If so, do not fail on constructs that could become constant
926     /// later on (such as a use of an undefined global).
927     bool CheckingPotentialConstantExpression = false;
928 
929     /// Whether we're checking for an expression that has undefined behavior.
930     /// If so, we will produce warnings if we encounter an operation that is
931     /// always undefined.
932     ///
933     /// Note that we still need to evaluate the expression normally when this
934     /// is set; this is used when evaluating ICEs in C.
935     bool CheckingForUndefinedBehavior = false;
936 
937     enum EvaluationMode {
938       /// Evaluate as a constant expression. Stop if we find that the expression
939       /// is not a constant expression.
940       EM_ConstantExpression,
941 
942       /// Evaluate as a constant expression. Stop if we find that the expression
943       /// is not a constant expression. Some expressions can be retried in the
944       /// optimizer if we don't constant fold them here, but in an unevaluated
945       /// context we try to fold them immediately since the optimizer never
946       /// gets a chance to look at it.
947       EM_ConstantExpressionUnevaluated,
948 
949       /// Fold the expression to a constant. Stop if we hit a side-effect that
950       /// we can't model.
951       EM_ConstantFold,
952 
953       /// Evaluate in any way we know how. Don't worry about side-effects that
954       /// can't be modeled.
955       EM_IgnoreSideEffects,
956     } EvalMode;
957 
958     /// Are we checking whether the expression is a potential constant
959     /// expression?
checkingPotentialConstantExpression() const960     bool checkingPotentialConstantExpression() const override  {
961       return CheckingPotentialConstantExpression;
962     }
963 
964     /// Are we checking an expression for overflow?
965     // FIXME: We should check for any kind of undefined or suspicious behavior
966     // in such constructs, not just overflow.
checkingForUndefinedBehavior() const967     bool checkingForUndefinedBehavior() const override {
968       return CheckingForUndefinedBehavior;
969     }
970 
EvalInfo(const ASTContext & C,Expr::EvalStatus & S,EvaluationMode Mode)971     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
972         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
973           CallStackDepth(0), NextCallIndex(1),
974           StepsLeft(C.getLangOpts().ConstexprStepLimit),
975           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
976           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
977           EvaluatingDecl((const ValueDecl *)nullptr),
978           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
979           HasFoldFailureDiagnostic(false), InConstantContext(false),
980           EvalMode(Mode) {}
981 
~EvalInfo()982     ~EvalInfo() {
983       discardCleanups();
984     }
985 
getCtx() const986     ASTContext &getCtx() const override { return Ctx; }
987 
setEvaluatingDecl(APValue::LValueBase Base,APValue & Value,EvaluatingDeclKind EDK=EvaluatingDeclKind::Ctor)988     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
989                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
990       EvaluatingDecl = Base;
991       IsEvaluatingDecl = EDK;
992       EvaluatingDeclValue = &Value;
993     }
994 
CheckCallLimit(SourceLocation Loc)995     bool CheckCallLimit(SourceLocation Loc) {
996       // Don't perform any constexpr calls (other than the call we're checking)
997       // when checking a potential constant expression.
998       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
999         return false;
1000       if (NextCallIndex == 0) {
1001         // NextCallIndex has wrapped around.
1002         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1003         return false;
1004       }
1005       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1006         return true;
1007       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1008         << getLangOpts().ConstexprCallDepth;
1009       return false;
1010     }
1011 
1012     std::pair<CallStackFrame *, unsigned>
getCallFrameAndDepth(unsigned CallIndex)1013     getCallFrameAndDepth(unsigned CallIndex) {
1014       assert(CallIndex && "no call index in getCallFrameAndDepth");
1015       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1016       // be null in this loop.
1017       unsigned Depth = CallStackDepth;
1018       CallStackFrame *Frame = CurrentCall;
1019       while (Frame->Index > CallIndex) {
1020         Frame = Frame->Caller;
1021         --Depth;
1022       }
1023       if (Frame->Index == CallIndex)
1024         return {Frame, Depth};
1025       return {nullptr, 0};
1026     }
1027 
nextStep(const Stmt * S)1028     bool nextStep(const Stmt *S) {
1029       if (!StepsLeft) {
1030         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1031         return false;
1032       }
1033       --StepsLeft;
1034       return true;
1035     }
1036 
1037     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1038 
lookupDynamicAlloc(DynamicAllocLValue DA)1039     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1040       Optional<DynAlloc*> Result;
1041       auto It = HeapAllocs.find(DA);
1042       if (It != HeapAllocs.end())
1043         Result = &It->second;
1044       return Result;
1045     }
1046 
1047     /// Get the allocated storage for the given parameter of the given call.
getParamSlot(CallRef Call,const ParmVarDecl * PVD)1048     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1049       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1050       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1051                    : nullptr;
1052     }
1053 
1054     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1055     struct StdAllocatorCaller {
1056       unsigned FrameIndex;
1057       QualType ElemType;
operator bool__anon7a1fdcea0311::EvalInfo::StdAllocatorCaller1058       explicit operator bool() const { return FrameIndex != 0; };
1059     };
1060 
getStdAllocatorCaller(StringRef FnName) const1061     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1062       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1063            Call = Call->Caller) {
1064         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1065         if (!MD)
1066           continue;
1067         const IdentifierInfo *FnII = MD->getIdentifier();
1068         if (!FnII || !FnII->isStr(FnName))
1069           continue;
1070 
1071         const auto *CTSD =
1072             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1073         if (!CTSD)
1074           continue;
1075 
1076         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1077         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1078         if (CTSD->isInStdNamespace() && ClassII &&
1079             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1080             TAL[0].getKind() == TemplateArgument::Type)
1081           return {Call->Index, TAL[0].getAsType()};
1082       }
1083 
1084       return {};
1085     }
1086 
performLifetimeExtension()1087     void performLifetimeExtension() {
1088       // Disable the cleanups for lifetime-extended temporaries.
1089       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1090         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1091       });
1092     }
1093 
1094     /// Throw away any remaining cleanups at the end of evaluation. If any
1095     /// cleanups would have had a side-effect, note that as an unmodeled
1096     /// side-effect and return false. Otherwise, return true.
discardCleanups()1097     bool discardCleanups() {
1098       for (Cleanup &C : CleanupStack) {
1099         if (C.hasSideEffect() && !noteSideEffect()) {
1100           CleanupStack.clear();
1101           return false;
1102         }
1103       }
1104       CleanupStack.clear();
1105       return true;
1106     }
1107 
1108   private:
getCurrentFrame()1109     interp::Frame *getCurrentFrame() override { return CurrentCall; }
getBottomFrame() const1110     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1111 
hasActiveDiagnostic()1112     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
setActiveDiagnostic(bool Flag)1113     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1114 
setFoldFailureDiagnostic(bool Flag)1115     void setFoldFailureDiagnostic(bool Flag) override {
1116       HasFoldFailureDiagnostic = Flag;
1117     }
1118 
getEvalStatus() const1119     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1120 
1121     // If we have a prior diagnostic, it will be noting that the expression
1122     // isn't a constant expression. This diagnostic is more important,
1123     // unless we require this evaluation to produce a constant expression.
1124     //
1125     // FIXME: We might want to show both diagnostics to the user in
1126     // EM_ConstantFold mode.
hasPriorDiagnostic()1127     bool hasPriorDiagnostic() override {
1128       if (!EvalStatus.Diag->empty()) {
1129         switch (EvalMode) {
1130         case EM_ConstantFold:
1131         case EM_IgnoreSideEffects:
1132           if (!HasFoldFailureDiagnostic)
1133             break;
1134           // We've already failed to fold something. Keep that diagnostic.
1135           LLVM_FALLTHROUGH;
1136         case EM_ConstantExpression:
1137         case EM_ConstantExpressionUnevaluated:
1138           setActiveDiagnostic(false);
1139           return true;
1140         }
1141       }
1142       return false;
1143     }
1144 
getCallStackDepth()1145     unsigned getCallStackDepth() override { return CallStackDepth; }
1146 
1147   public:
1148     /// Should we continue evaluation after encountering a side-effect that we
1149     /// couldn't model?
keepEvaluatingAfterSideEffect()1150     bool keepEvaluatingAfterSideEffect() {
1151       switch (EvalMode) {
1152       case EM_IgnoreSideEffects:
1153         return true;
1154 
1155       case EM_ConstantExpression:
1156       case EM_ConstantExpressionUnevaluated:
1157       case EM_ConstantFold:
1158         // By default, assume any side effect might be valid in some other
1159         // evaluation of this expression from a different context.
1160         return checkingPotentialConstantExpression() ||
1161                checkingForUndefinedBehavior();
1162       }
1163       llvm_unreachable("Missed EvalMode case");
1164     }
1165 
1166     /// Note that we have had a side-effect, and determine whether we should
1167     /// keep evaluating.
noteSideEffect()1168     bool noteSideEffect() {
1169       EvalStatus.HasSideEffects = true;
1170       return keepEvaluatingAfterSideEffect();
1171     }
1172 
1173     /// Should we continue evaluation after encountering undefined behavior?
keepEvaluatingAfterUndefinedBehavior()1174     bool keepEvaluatingAfterUndefinedBehavior() {
1175       switch (EvalMode) {
1176       case EM_IgnoreSideEffects:
1177       case EM_ConstantFold:
1178         return true;
1179 
1180       case EM_ConstantExpression:
1181       case EM_ConstantExpressionUnevaluated:
1182         return checkingForUndefinedBehavior();
1183       }
1184       llvm_unreachable("Missed EvalMode case");
1185     }
1186 
1187     /// Note that we hit something that was technically undefined behavior, but
1188     /// that we can evaluate past it (such as signed overflow or floating-point
1189     /// division by zero.)
noteUndefinedBehavior()1190     bool noteUndefinedBehavior() override {
1191       EvalStatus.HasUndefinedBehavior = true;
1192       return keepEvaluatingAfterUndefinedBehavior();
1193     }
1194 
1195     /// Should we continue evaluation as much as possible after encountering a
1196     /// construct which can't be reduced to a value?
keepEvaluatingAfterFailure() const1197     bool keepEvaluatingAfterFailure() const override {
1198       if (!StepsLeft)
1199         return false;
1200 
1201       switch (EvalMode) {
1202       case EM_ConstantExpression:
1203       case EM_ConstantExpressionUnevaluated:
1204       case EM_ConstantFold:
1205       case EM_IgnoreSideEffects:
1206         return checkingPotentialConstantExpression() ||
1207                checkingForUndefinedBehavior();
1208       }
1209       llvm_unreachable("Missed EvalMode case");
1210     }
1211 
1212     /// Notes that we failed to evaluate an expression that other expressions
1213     /// directly depend on, and determine if we should keep evaluating. This
1214     /// should only be called if we actually intend to keep evaluating.
1215     ///
1216     /// Call noteSideEffect() instead if we may be able to ignore the value that
1217     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1218     ///
1219     /// (Foo(), 1)      // use noteSideEffect
1220     /// (Foo() || true) // use noteSideEffect
1221     /// Foo() + 1       // use noteFailure
noteFailure()1222     LLVM_NODISCARD bool noteFailure() {
1223       // Failure when evaluating some expression often means there is some
1224       // subexpression whose evaluation was skipped. Therefore, (because we
1225       // don't track whether we skipped an expression when unwinding after an
1226       // evaluation failure) every evaluation failure that bubbles up from a
1227       // subexpression implies that a side-effect has potentially happened. We
1228       // skip setting the HasSideEffects flag to true until we decide to
1229       // continue evaluating after that point, which happens here.
1230       bool KeepGoing = keepEvaluatingAfterFailure();
1231       EvalStatus.HasSideEffects |= KeepGoing;
1232       return KeepGoing;
1233     }
1234 
1235     class ArrayInitLoopIndex {
1236       EvalInfo &Info;
1237       uint64_t OuterIndex;
1238 
1239     public:
ArrayInitLoopIndex(EvalInfo & Info)1240       ArrayInitLoopIndex(EvalInfo &Info)
1241           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1242         Info.ArrayInitIndex = 0;
1243       }
~ArrayInitLoopIndex()1244       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1245 
operator uint64_t&()1246       operator uint64_t&() { return Info.ArrayInitIndex; }
1247     };
1248   };
1249 
1250   /// Object used to treat all foldable expressions as constant expressions.
1251   struct FoldConstant {
1252     EvalInfo &Info;
1253     bool Enabled;
1254     bool HadNoPriorDiags;
1255     EvalInfo::EvaluationMode OldMode;
1256 
FoldConstant__anon7a1fdcea0311::FoldConstant1257     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1258       : Info(Info),
1259         Enabled(Enabled),
1260         HadNoPriorDiags(Info.EvalStatus.Diag &&
1261                         Info.EvalStatus.Diag->empty() &&
1262                         !Info.EvalStatus.HasSideEffects),
1263         OldMode(Info.EvalMode) {
1264       if (Enabled)
1265         Info.EvalMode = EvalInfo::EM_ConstantFold;
1266     }
keepDiagnostics__anon7a1fdcea0311::FoldConstant1267     void keepDiagnostics() { Enabled = false; }
~FoldConstant__anon7a1fdcea0311::FoldConstant1268     ~FoldConstant() {
1269       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1270           !Info.EvalStatus.HasSideEffects)
1271         Info.EvalStatus.Diag->clear();
1272       Info.EvalMode = OldMode;
1273     }
1274   };
1275 
1276   /// RAII object used to set the current evaluation mode to ignore
1277   /// side-effects.
1278   struct IgnoreSideEffectsRAII {
1279     EvalInfo &Info;
1280     EvalInfo::EvaluationMode OldMode;
IgnoreSideEffectsRAII__anon7a1fdcea0311::IgnoreSideEffectsRAII1281     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1282         : Info(Info), OldMode(Info.EvalMode) {
1283       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1284     }
1285 
~IgnoreSideEffectsRAII__anon7a1fdcea0311::IgnoreSideEffectsRAII1286     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1287   };
1288 
1289   /// RAII object used to optionally suppress diagnostics and side-effects from
1290   /// a speculative evaluation.
1291   class SpeculativeEvaluationRAII {
1292     EvalInfo *Info = nullptr;
1293     Expr::EvalStatus OldStatus;
1294     unsigned OldSpeculativeEvaluationDepth;
1295 
moveFromAndCancel(SpeculativeEvaluationRAII && Other)1296     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1297       Info = Other.Info;
1298       OldStatus = Other.OldStatus;
1299       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1300       Other.Info = nullptr;
1301     }
1302 
maybeRestoreState()1303     void maybeRestoreState() {
1304       if (!Info)
1305         return;
1306 
1307       Info->EvalStatus = OldStatus;
1308       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1309     }
1310 
1311   public:
1312     SpeculativeEvaluationRAII() = default;
1313 
SpeculativeEvaluationRAII(EvalInfo & Info,SmallVectorImpl<PartialDiagnosticAt> * NewDiag=nullptr)1314     SpeculativeEvaluationRAII(
1315         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1316         : Info(&Info), OldStatus(Info.EvalStatus),
1317           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1318       Info.EvalStatus.Diag = NewDiag;
1319       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1320     }
1321 
1322     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
SpeculativeEvaluationRAII(SpeculativeEvaluationRAII && Other)1323     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1324       moveFromAndCancel(std::move(Other));
1325     }
1326 
operator =(SpeculativeEvaluationRAII && Other)1327     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1328       maybeRestoreState();
1329       moveFromAndCancel(std::move(Other));
1330       return *this;
1331     }
1332 
~SpeculativeEvaluationRAII()1333     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1334   };
1335 
1336   /// RAII object wrapping a full-expression or block scope, and handling
1337   /// the ending of the lifetime of temporaries created within it.
1338   template<ScopeKind Kind>
1339   class ScopeRAII {
1340     EvalInfo &Info;
1341     unsigned OldStackSize;
1342   public:
ScopeRAII(EvalInfo & Info)1343     ScopeRAII(EvalInfo &Info)
1344         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1345       // Push a new temporary version. This is needed to distinguish between
1346       // temporaries created in different iterations of a loop.
1347       Info.CurrentCall->pushTempVersion();
1348     }
destroy(bool RunDestructors=true)1349     bool destroy(bool RunDestructors = true) {
1350       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1351       OldStackSize = -1U;
1352       return OK;
1353     }
~ScopeRAII()1354     ~ScopeRAII() {
1355       if (OldStackSize != -1U)
1356         destroy(false);
1357       // Body moved to a static method to encourage the compiler to inline away
1358       // instances of this class.
1359       Info.CurrentCall->popTempVersion();
1360     }
1361   private:
cleanup(EvalInfo & Info,bool RunDestructors,unsigned OldStackSize)1362     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1363                         unsigned OldStackSize) {
1364       assert(OldStackSize <= Info.CleanupStack.size() &&
1365              "running cleanups out of order?");
1366 
1367       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1368       // for a full-expression scope.
1369       bool Success = true;
1370       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1371         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1372           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1373             Success = false;
1374             break;
1375           }
1376         }
1377       }
1378 
1379       // Compact any retained cleanups.
1380       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1381       if (Kind != ScopeKind::Block)
1382         NewEnd =
1383             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1384               return C.isDestroyedAtEndOf(Kind);
1385             });
1386       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1387       return Success;
1388     }
1389   };
1390   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1391   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1392   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1393 }
1394 
checkSubobject(EvalInfo & Info,const Expr * E,CheckSubobjectKind CSK)1395 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1396                                          CheckSubobjectKind CSK) {
1397   if (Invalid)
1398     return false;
1399   if (isOnePastTheEnd()) {
1400     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1401       << CSK;
1402     setInvalid();
1403     return false;
1404   }
1405   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1406   // must actually be at least one array element; even a VLA cannot have a
1407   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1408   return true;
1409 }
1410 
diagnoseUnsizedArrayPointerArithmetic(EvalInfo & Info,const Expr * E)1411 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1412                                                                 const Expr *E) {
1413   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1414   // Do not set the designator as invalid: we can represent this situation,
1415   // and correct handling of __builtin_object_size requires us to do so.
1416 }
1417 
diagnosePointerArithmetic(EvalInfo & Info,const Expr * E,const APSInt & N)1418 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1419                                                     const Expr *E,
1420                                                     const APSInt &N) {
1421   // If we're complaining, we must be able to statically determine the size of
1422   // the most derived array.
1423   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1424     Info.CCEDiag(E, diag::note_constexpr_array_index)
1425       << N << /*array*/ 0
1426       << static_cast<unsigned>(getMostDerivedArraySize());
1427   else
1428     Info.CCEDiag(E, diag::note_constexpr_array_index)
1429       << N << /*non-array*/ 1;
1430   setInvalid();
1431 }
1432 
CallStackFrame(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Callee,const LValue * This,CallRef Call)1433 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1434                                const FunctionDecl *Callee, const LValue *This,
1435                                CallRef Call)
1436     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1437       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1438   Info.CurrentCall = this;
1439   ++Info.CallStackDepth;
1440 }
1441 
~CallStackFrame()1442 CallStackFrame::~CallStackFrame() {
1443   assert(Info.CurrentCall == this && "calls retired out of order");
1444   --Info.CallStackDepth;
1445   Info.CurrentCall = Caller;
1446 }
1447 
isRead(AccessKinds AK)1448 static bool isRead(AccessKinds AK) {
1449   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1450 }
1451 
isModification(AccessKinds AK)1452 static bool isModification(AccessKinds AK) {
1453   switch (AK) {
1454   case AK_Read:
1455   case AK_ReadObjectRepresentation:
1456   case AK_MemberCall:
1457   case AK_DynamicCast:
1458   case AK_TypeId:
1459     return false;
1460   case AK_Assign:
1461   case AK_Increment:
1462   case AK_Decrement:
1463   case AK_Construct:
1464   case AK_Destroy:
1465     return true;
1466   }
1467   llvm_unreachable("unknown access kind");
1468 }
1469 
isAnyAccess(AccessKinds AK)1470 static bool isAnyAccess(AccessKinds AK) {
1471   return isRead(AK) || isModification(AK);
1472 }
1473 
1474 /// Is this an access per the C++ definition?
isFormalAccess(AccessKinds AK)1475 static bool isFormalAccess(AccessKinds AK) {
1476   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1477 }
1478 
1479 /// Is this kind of axcess valid on an indeterminate object value?
isValidIndeterminateAccess(AccessKinds AK)1480 static bool isValidIndeterminateAccess(AccessKinds AK) {
1481   switch (AK) {
1482   case AK_Read:
1483   case AK_Increment:
1484   case AK_Decrement:
1485     // These need the object's value.
1486     return false;
1487 
1488   case AK_ReadObjectRepresentation:
1489   case AK_Assign:
1490   case AK_Construct:
1491   case AK_Destroy:
1492     // Construction and destruction don't need the value.
1493     return true;
1494 
1495   case AK_MemberCall:
1496   case AK_DynamicCast:
1497   case AK_TypeId:
1498     // These aren't really meaningful on scalars.
1499     return true;
1500   }
1501   llvm_unreachable("unknown access kind");
1502 }
1503 
1504 namespace {
1505   struct ComplexValue {
1506   private:
1507     bool IsInt;
1508 
1509   public:
1510     APSInt IntReal, IntImag;
1511     APFloat FloatReal, FloatImag;
1512 
ComplexValue__anon7a1fdcea0611::ComplexValue1513     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1514 
makeComplexFloat__anon7a1fdcea0611::ComplexValue1515     void makeComplexFloat() { IsInt = false; }
isComplexFloat__anon7a1fdcea0611::ComplexValue1516     bool isComplexFloat() const { return !IsInt; }
getComplexFloatReal__anon7a1fdcea0611::ComplexValue1517     APFloat &getComplexFloatReal() { return FloatReal; }
getComplexFloatImag__anon7a1fdcea0611::ComplexValue1518     APFloat &getComplexFloatImag() { return FloatImag; }
1519 
makeComplexInt__anon7a1fdcea0611::ComplexValue1520     void makeComplexInt() { IsInt = true; }
isComplexInt__anon7a1fdcea0611::ComplexValue1521     bool isComplexInt() const { return IsInt; }
getComplexIntReal__anon7a1fdcea0611::ComplexValue1522     APSInt &getComplexIntReal() { return IntReal; }
getComplexIntImag__anon7a1fdcea0611::ComplexValue1523     APSInt &getComplexIntImag() { return IntImag; }
1524 
moveInto__anon7a1fdcea0611::ComplexValue1525     void moveInto(APValue &v) const {
1526       if (isComplexFloat())
1527         v = APValue(FloatReal, FloatImag);
1528       else
1529         v = APValue(IntReal, IntImag);
1530     }
setFrom__anon7a1fdcea0611::ComplexValue1531     void setFrom(const APValue &v) {
1532       assert(v.isComplexFloat() || v.isComplexInt());
1533       if (v.isComplexFloat()) {
1534         makeComplexFloat();
1535         FloatReal = v.getComplexFloatReal();
1536         FloatImag = v.getComplexFloatImag();
1537       } else {
1538         makeComplexInt();
1539         IntReal = v.getComplexIntReal();
1540         IntImag = v.getComplexIntImag();
1541       }
1542     }
1543   };
1544 
1545   struct LValue {
1546     APValue::LValueBase Base;
1547     CharUnits Offset;
1548     SubobjectDesignator Designator;
1549     bool IsNullPtr : 1;
1550     bool InvalidBase : 1;
1551 
getLValueBase__anon7a1fdcea0611::LValue1552     const APValue::LValueBase getLValueBase() const { return Base; }
getLValueOffset__anon7a1fdcea0611::LValue1553     CharUnits &getLValueOffset() { return Offset; }
getLValueOffset__anon7a1fdcea0611::LValue1554     const CharUnits &getLValueOffset() const { return Offset; }
getLValueDesignator__anon7a1fdcea0611::LValue1555     SubobjectDesignator &getLValueDesignator() { return Designator; }
getLValueDesignator__anon7a1fdcea0611::LValue1556     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
isNullPointer__anon7a1fdcea0611::LValue1557     bool isNullPointer() const { return IsNullPtr;}
1558 
getLValueCallIndex__anon7a1fdcea0611::LValue1559     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
getLValueVersion__anon7a1fdcea0611::LValue1560     unsigned getLValueVersion() const { return Base.getVersion(); }
1561 
moveInto__anon7a1fdcea0611::LValue1562     void moveInto(APValue &V) const {
1563       if (Designator.Invalid)
1564         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1565       else {
1566         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1567         V = APValue(Base, Offset, Designator.Entries,
1568                     Designator.IsOnePastTheEnd, IsNullPtr);
1569       }
1570     }
setFrom__anon7a1fdcea0611::LValue1571     void setFrom(ASTContext &Ctx, const APValue &V) {
1572       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1573       Base = V.getLValueBase();
1574       Offset = V.getLValueOffset();
1575       InvalidBase = false;
1576       Designator = SubobjectDesignator(Ctx, V);
1577       IsNullPtr = V.isNullPointer();
1578     }
1579 
set__anon7a1fdcea0611::LValue1580     void set(APValue::LValueBase B, bool BInvalid = false) {
1581 #ifndef NDEBUG
1582       // We only allow a few types of invalid bases. Enforce that here.
1583       if (BInvalid) {
1584         const auto *E = B.get<const Expr *>();
1585         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1586                "Unexpected type of invalid base");
1587       }
1588 #endif
1589 
1590       Base = B;
1591       Offset = CharUnits::fromQuantity(0);
1592       InvalidBase = BInvalid;
1593       Designator = SubobjectDesignator(getType(B));
1594       IsNullPtr = false;
1595     }
1596 
setNull__anon7a1fdcea0611::LValue1597     void setNull(ASTContext &Ctx, QualType PointerTy) {
1598       Base = (const ValueDecl *)nullptr;
1599       Offset =
1600           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1601       InvalidBase = false;
1602       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1603       IsNullPtr = true;
1604     }
1605 
setInvalid__anon7a1fdcea0611::LValue1606     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1607       set(B, true);
1608     }
1609 
toString__anon7a1fdcea0611::LValue1610     std::string toString(ASTContext &Ctx, QualType T) const {
1611       APValue Printable;
1612       moveInto(Printable);
1613       return Printable.getAsString(Ctx, T);
1614     }
1615 
1616   private:
1617     // Check that this LValue is not based on a null pointer. If it is, produce
1618     // a diagnostic and mark the designator as invalid.
1619     template <typename GenDiagType>
checkNullPointerDiagnosingWith__anon7a1fdcea0611::LValue1620     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1621       if (Designator.Invalid)
1622         return false;
1623       if (IsNullPtr) {
1624         GenDiag();
1625         Designator.setInvalid();
1626         return false;
1627       }
1628       return true;
1629     }
1630 
1631   public:
checkNullPointer__anon7a1fdcea0611::LValue1632     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1633                           CheckSubobjectKind CSK) {
1634       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1635         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1636       });
1637     }
1638 
checkNullPointerForFoldAccess__anon7a1fdcea0611::LValue1639     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1640                                        AccessKinds AK) {
1641       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1642         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1643       });
1644     }
1645 
1646     // Check this LValue refers to an object. If not, set the designator to be
1647     // invalid and emit a diagnostic.
checkSubobject__anon7a1fdcea0611::LValue1648     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1649       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1650              Designator.checkSubobject(Info, E, CSK);
1651     }
1652 
addDecl__anon7a1fdcea0611::LValue1653     void addDecl(EvalInfo &Info, const Expr *E,
1654                  const Decl *D, bool Virtual = false) {
1655       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1656         Designator.addDeclUnchecked(D, Virtual);
1657     }
addUnsizedArray__anon7a1fdcea0611::LValue1658     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1659       if (!Designator.Entries.empty()) {
1660         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1661         Designator.setInvalid();
1662         return;
1663       }
1664       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1665         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1666         Designator.FirstEntryIsAnUnsizedArray = true;
1667         Designator.addUnsizedArrayUnchecked(ElemTy);
1668       }
1669     }
addArray__anon7a1fdcea0611::LValue1670     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1671       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1672         Designator.addArrayUnchecked(CAT);
1673     }
addComplex__anon7a1fdcea0611::LValue1674     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1675       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1676         Designator.addComplexUnchecked(EltTy, Imag);
1677     }
clearIsNullPointer__anon7a1fdcea0611::LValue1678     void clearIsNullPointer() {
1679       IsNullPtr = false;
1680     }
adjustOffsetAndIndex__anon7a1fdcea0611::LValue1681     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1682                               const APSInt &Index, CharUnits ElementSize) {
1683       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1684       // but we're not required to diagnose it and it's valid in C++.)
1685       if (!Index)
1686         return;
1687 
1688       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1689       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1690       // offsets.
1691       uint64_t Offset64 = Offset.getQuantity();
1692       uint64_t ElemSize64 = ElementSize.getQuantity();
1693       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1694       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1695 
1696       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1697         Designator.adjustIndex(Info, E, Index);
1698       clearIsNullPointer();
1699     }
adjustOffset__anon7a1fdcea0611::LValue1700     void adjustOffset(CharUnits N) {
1701       Offset += N;
1702       if (N.getQuantity())
1703         clearIsNullPointer();
1704     }
1705   };
1706 
1707   struct MemberPtr {
MemberPtr__anon7a1fdcea0611::MemberPtr1708     MemberPtr() {}
MemberPtr__anon7a1fdcea0611::MemberPtr1709     explicit MemberPtr(const ValueDecl *Decl)
1710         : DeclAndIsDerivedMember(Decl, false) {}
1711 
1712     /// The member or (direct or indirect) field referred to by this member
1713     /// pointer, or 0 if this is a null member pointer.
getDecl__anon7a1fdcea0611::MemberPtr1714     const ValueDecl *getDecl() const {
1715       return DeclAndIsDerivedMember.getPointer();
1716     }
1717     /// Is this actually a member of some type derived from the relevant class?
isDerivedMember__anon7a1fdcea0611::MemberPtr1718     bool isDerivedMember() const {
1719       return DeclAndIsDerivedMember.getInt();
1720     }
1721     /// Get the class which the declaration actually lives in.
getContainingRecord__anon7a1fdcea0611::MemberPtr1722     const CXXRecordDecl *getContainingRecord() const {
1723       return cast<CXXRecordDecl>(
1724           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1725     }
1726 
moveInto__anon7a1fdcea0611::MemberPtr1727     void moveInto(APValue &V) const {
1728       V = APValue(getDecl(), isDerivedMember(), Path);
1729     }
setFrom__anon7a1fdcea0611::MemberPtr1730     void setFrom(const APValue &V) {
1731       assert(V.isMemberPointer());
1732       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1733       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1734       Path.clear();
1735       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1736       Path.insert(Path.end(), P.begin(), P.end());
1737     }
1738 
1739     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1740     /// whether the member is a member of some class derived from the class type
1741     /// of the member pointer.
1742     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1743     /// Path - The path of base/derived classes from the member declaration's
1744     /// class (exclusive) to the class type of the member pointer (inclusive).
1745     SmallVector<const CXXRecordDecl*, 4> Path;
1746 
1747     /// Perform a cast towards the class of the Decl (either up or down the
1748     /// hierarchy).
castBack__anon7a1fdcea0611::MemberPtr1749     bool castBack(const CXXRecordDecl *Class) {
1750       assert(!Path.empty());
1751       const CXXRecordDecl *Expected;
1752       if (Path.size() >= 2)
1753         Expected = Path[Path.size() - 2];
1754       else
1755         Expected = getContainingRecord();
1756       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1757         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1758         // if B does not contain the original member and is not a base or
1759         // derived class of the class containing the original member, the result
1760         // of the cast is undefined.
1761         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1762         // (D::*). We consider that to be a language defect.
1763         return false;
1764       }
1765       Path.pop_back();
1766       return true;
1767     }
1768     /// Perform a base-to-derived member pointer cast.
castToDerived__anon7a1fdcea0611::MemberPtr1769     bool castToDerived(const CXXRecordDecl *Derived) {
1770       if (!getDecl())
1771         return true;
1772       if (!isDerivedMember()) {
1773         Path.push_back(Derived);
1774         return true;
1775       }
1776       if (!castBack(Derived))
1777         return false;
1778       if (Path.empty())
1779         DeclAndIsDerivedMember.setInt(false);
1780       return true;
1781     }
1782     /// Perform a derived-to-base member pointer cast.
castToBase__anon7a1fdcea0611::MemberPtr1783     bool castToBase(const CXXRecordDecl *Base) {
1784       if (!getDecl())
1785         return true;
1786       if (Path.empty())
1787         DeclAndIsDerivedMember.setInt(true);
1788       if (isDerivedMember()) {
1789         Path.push_back(Base);
1790         return true;
1791       }
1792       return castBack(Base);
1793     }
1794   };
1795 
1796   /// Compare two member pointers, which are assumed to be of the same type.
operator ==(const MemberPtr & LHS,const MemberPtr & RHS)1797   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1798     if (!LHS.getDecl() || !RHS.getDecl())
1799       return !LHS.getDecl() && !RHS.getDecl();
1800     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1801       return false;
1802     return LHS.Path == RHS.Path;
1803   }
1804 }
1805 
1806 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1807 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1808                             const LValue &This, const Expr *E,
1809                             bool AllowNonLiteralTypes = false);
1810 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1811                            bool InvalidBaseOK = false);
1812 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1813                             bool InvalidBaseOK = false);
1814 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1815                                   EvalInfo &Info);
1816 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1817 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1818 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1819                                     EvalInfo &Info);
1820 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1821 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1822 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1823                            EvalInfo &Info);
1824 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1825 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1826                                   EvalInfo &Info);
1827 
1828 /// Evaluate an integer or fixed point expression into an APResult.
1829 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1830                                         EvalInfo &Info);
1831 
1832 /// Evaluate only a fixed point expression into an APResult.
1833 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1834                                EvalInfo &Info);
1835 
1836 //===----------------------------------------------------------------------===//
1837 // Misc utilities
1838 //===----------------------------------------------------------------------===//
1839 
1840 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1841 /// preserving its value (by extending by up to one bit as needed).
negateAsSigned(APSInt & Int)1842 static void negateAsSigned(APSInt &Int) {
1843   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1844     Int = Int.extend(Int.getBitWidth() + 1);
1845     Int.setIsSigned(true);
1846   }
1847   Int = -Int;
1848 }
1849 
1850 template<typename KeyT>
createTemporary(const KeyT * Key,QualType T,ScopeKind Scope,LValue & LV)1851 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1852                                          ScopeKind Scope, LValue &LV) {
1853   unsigned Version = getTempVersion();
1854   APValue::LValueBase Base(Key, Index, Version);
1855   LV.set(Base);
1856   return createLocal(Base, Key, T, Scope);
1857 }
1858 
1859 /// Allocate storage for a parameter of a function call made in this frame.
createParam(CallRef Args,const ParmVarDecl * PVD,LValue & LV)1860 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1861                                      LValue &LV) {
1862   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1863   APValue::LValueBase Base(PVD, Index, Args.Version);
1864   LV.set(Base);
1865   // We always destroy parameters at the end of the call, even if we'd allow
1866   // them to live to the end of the full-expression at runtime, in order to
1867   // give portable results and match other compilers.
1868   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1869 }
1870 
createLocal(APValue::LValueBase Base,const void * Key,QualType T,ScopeKind Scope)1871 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1872                                      QualType T, ScopeKind Scope) {
1873   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1874   unsigned Version = Base.getVersion();
1875   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1876   assert(Result.isAbsent() && "local created multiple times");
1877 
1878   // If we're creating a local immediately in the operand of a speculative
1879   // evaluation, don't register a cleanup to be run outside the speculative
1880   // evaluation context, since we won't actually be able to initialize this
1881   // object.
1882   if (Index <= Info.SpeculativeEvaluationDepth) {
1883     if (T.isDestructedType())
1884       Info.noteSideEffect();
1885   } else {
1886     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1887   }
1888   return Result;
1889 }
1890 
createHeapAlloc(const Expr * E,QualType T,LValue & LV)1891 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1892   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1893     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1894     return nullptr;
1895   }
1896 
1897   DynamicAllocLValue DA(NumHeapAllocs++);
1898   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1899   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1900                                    std::forward_as_tuple(DA), std::tuple<>());
1901   assert(Result.second && "reused a heap alloc index?");
1902   Result.first->second.AllocExpr = E;
1903   return &Result.first->second.Value;
1904 }
1905 
1906 /// Produce a string describing the given constexpr call.
describe(raw_ostream & Out)1907 void CallStackFrame::describe(raw_ostream &Out) {
1908   unsigned ArgIndex = 0;
1909   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1910                       !isa<CXXConstructorDecl>(Callee) &&
1911                       cast<CXXMethodDecl>(Callee)->isInstance();
1912 
1913   if (!IsMemberCall)
1914     Out << *Callee << '(';
1915 
1916   if (This && IsMemberCall) {
1917     APValue Val;
1918     This->moveInto(Val);
1919     Val.printPretty(Out, Info.Ctx,
1920                     This->Designator.MostDerivedType);
1921     // FIXME: Add parens around Val if needed.
1922     Out << "->" << *Callee << '(';
1923     IsMemberCall = false;
1924   }
1925 
1926   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1927        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1928     if (ArgIndex > (unsigned)IsMemberCall)
1929       Out << ", ";
1930 
1931     const ParmVarDecl *Param = *I;
1932     APValue *V = Info.getParamSlot(Arguments, Param);
1933     if (V)
1934       V->printPretty(Out, Info.Ctx, Param->getType());
1935     else
1936       Out << "<...>";
1937 
1938     if (ArgIndex == 0 && IsMemberCall)
1939       Out << "->" << *Callee << '(';
1940   }
1941 
1942   Out << ')';
1943 }
1944 
1945 /// Evaluate an expression to see if it had side-effects, and discard its
1946 /// result.
1947 /// \return \c true if the caller should keep evaluating.
EvaluateIgnoredValue(EvalInfo & Info,const Expr * E)1948 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1949   assert(!E->isValueDependent());
1950   APValue Scratch;
1951   if (!Evaluate(Scratch, Info, E))
1952     // We don't need the value, but we might have skipped a side effect here.
1953     return Info.noteSideEffect();
1954   return true;
1955 }
1956 
1957 /// Should this call expression be treated as a constant?
IsConstantCall(const CallExpr * E)1958 static bool IsConstantCall(const CallExpr *E) {
1959   unsigned Builtin = E->getBuiltinCallee();
1960   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1961           Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1962           Builtin == Builtin::BI__builtin_function_start);
1963 }
1964 
IsGlobalLValue(APValue::LValueBase B)1965 static bool IsGlobalLValue(APValue::LValueBase B) {
1966   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1967   // constant expression of pointer type that evaluates to...
1968 
1969   // ... a null pointer value, or a prvalue core constant expression of type
1970   // std::nullptr_t.
1971   if (!B) return true;
1972 
1973   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1974     // ... the address of an object with static storage duration,
1975     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1976       return VD->hasGlobalStorage();
1977     if (isa<TemplateParamObjectDecl>(D))
1978       return true;
1979     // ... the address of a function,
1980     // ... the address of a GUID [MS extension],
1981     // ... the address of an unnamed global constant
1982     return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
1983   }
1984 
1985   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1986     return true;
1987 
1988   const Expr *E = B.get<const Expr*>();
1989   switch (E->getStmtClass()) {
1990   default:
1991     return false;
1992   case Expr::CompoundLiteralExprClass: {
1993     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1994     return CLE->isFileScope() && CLE->isLValue();
1995   }
1996   case Expr::MaterializeTemporaryExprClass:
1997     // A materialized temporary might have been lifetime-extended to static
1998     // storage duration.
1999     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2000   // A string literal has static storage duration.
2001   case Expr::StringLiteralClass:
2002   case Expr::PredefinedExprClass:
2003   case Expr::ObjCStringLiteralClass:
2004   case Expr::ObjCEncodeExprClass:
2005     return true;
2006   case Expr::ObjCBoxedExprClass:
2007     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2008   case Expr::CallExprClass:
2009     return IsConstantCall(cast<CallExpr>(E));
2010   // For GCC compatibility, &&label has static storage duration.
2011   case Expr::AddrLabelExprClass:
2012     return true;
2013   // A Block literal expression may be used as the initialization value for
2014   // Block variables at global or local static scope.
2015   case Expr::BlockExprClass:
2016     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2017   // The APValue generated from a __builtin_source_location will be emitted as a
2018   // literal.
2019   case Expr::SourceLocExprClass:
2020     return true;
2021   case Expr::ImplicitValueInitExprClass:
2022     // FIXME:
2023     // We can never form an lvalue with an implicit value initialization as its
2024     // base through expression evaluation, so these only appear in one case: the
2025     // implicit variable declaration we invent when checking whether a constexpr
2026     // constructor can produce a constant expression. We must assume that such
2027     // an expression might be a global lvalue.
2028     return true;
2029   }
2030 }
2031 
GetLValueBaseDecl(const LValue & LVal)2032 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2033   return LVal.Base.dyn_cast<const ValueDecl*>();
2034 }
2035 
IsLiteralLValue(const LValue & Value)2036 static bool IsLiteralLValue(const LValue &Value) {
2037   if (Value.getLValueCallIndex())
2038     return false;
2039   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2040   return E && !isa<MaterializeTemporaryExpr>(E);
2041 }
2042 
IsWeakLValue(const LValue & Value)2043 static bool IsWeakLValue(const LValue &Value) {
2044   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2045   return Decl && Decl->isWeak();
2046 }
2047 
isZeroSized(const LValue & Value)2048 static bool isZeroSized(const LValue &Value) {
2049   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2050   if (Decl && isa<VarDecl>(Decl)) {
2051     QualType Ty = Decl->getType();
2052     if (Ty->isArrayType())
2053       return Ty->isIncompleteType() ||
2054              Decl->getASTContext().getTypeSize(Ty) == 0;
2055   }
2056   return false;
2057 }
2058 
HasSameBase(const LValue & A,const LValue & B)2059 static bool HasSameBase(const LValue &A, const LValue &B) {
2060   if (!A.getLValueBase())
2061     return !B.getLValueBase();
2062   if (!B.getLValueBase())
2063     return false;
2064 
2065   if (A.getLValueBase().getOpaqueValue() !=
2066       B.getLValueBase().getOpaqueValue())
2067     return false;
2068 
2069   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2070          A.getLValueVersion() == B.getLValueVersion();
2071 }
2072 
NoteLValueLocation(EvalInfo & Info,APValue::LValueBase Base)2073 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2074   assert(Base && "no location for a null lvalue");
2075   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2076 
2077   // For a parameter, find the corresponding call stack frame (if it still
2078   // exists), and point at the parameter of the function definition we actually
2079   // invoked.
2080   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2081     unsigned Idx = PVD->getFunctionScopeIndex();
2082     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2083       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2084           F->Arguments.Version == Base.getVersion() && F->Callee &&
2085           Idx < F->Callee->getNumParams()) {
2086         VD = F->Callee->getParamDecl(Idx);
2087         break;
2088       }
2089     }
2090   }
2091 
2092   if (VD)
2093     Info.Note(VD->getLocation(), diag::note_declared_at);
2094   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2095     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2096   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2097     // FIXME: Produce a note for dangling pointers too.
2098     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2099       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2100                 diag::note_constexpr_dynamic_alloc_here);
2101   }
2102   // We have no information to show for a typeid(T) object.
2103 }
2104 
2105 enum class CheckEvaluationResultKind {
2106   ConstantExpression,
2107   FullyInitialized,
2108 };
2109 
2110 /// Materialized temporaries that we've already checked to determine if they're
2111 /// initializsed by a constant expression.
2112 using CheckedTemporaries =
2113     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2114 
2115 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2116                                   EvalInfo &Info, SourceLocation DiagLoc,
2117                                   QualType Type, const APValue &Value,
2118                                   ConstantExprKind Kind,
2119                                   SourceLocation SubobjectLoc,
2120                                   CheckedTemporaries &CheckedTemps);
2121 
2122 /// Check that this reference or pointer core constant expression is a valid
2123 /// value for an address or reference constant expression. Return true if we
2124 /// 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)2125 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2126                                           QualType Type, const LValue &LVal,
2127                                           ConstantExprKind Kind,
2128                                           CheckedTemporaries &CheckedTemps) {
2129   bool IsReferenceType = Type->isReferenceType();
2130 
2131   APValue::LValueBase Base = LVal.getLValueBase();
2132   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2133 
2134   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2135   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2136 
2137   // Additional restrictions apply in a template argument. We only enforce the
2138   // C++20 restrictions here; additional syntactic and semantic restrictions
2139   // are applied elsewhere.
2140   if (isTemplateArgument(Kind)) {
2141     int InvalidBaseKind = -1;
2142     StringRef Ident;
2143     if (Base.is<TypeInfoLValue>())
2144       InvalidBaseKind = 0;
2145     else if (isa_and_nonnull<StringLiteral>(BaseE))
2146       InvalidBaseKind = 1;
2147     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2148              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2149       InvalidBaseKind = 2;
2150     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2151       InvalidBaseKind = 3;
2152       Ident = PE->getIdentKindName();
2153     }
2154 
2155     if (InvalidBaseKind != -1) {
2156       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2157           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2158           << Ident;
2159       return false;
2160     }
2161   }
2162 
2163   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2164     if (FD->isConsteval()) {
2165       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2166           << !Type->isAnyPointerType();
2167       Info.Note(FD->getLocation(), diag::note_declared_at);
2168       return false;
2169     }
2170   }
2171 
2172   // Check that the object is a global. Note that the fake 'this' object we
2173   // manufacture when checking potential constant expressions is conservatively
2174   // assumed to be global here.
2175   if (!IsGlobalLValue(Base)) {
2176     if (Info.getLangOpts().CPlusPlus11) {
2177       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2178       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2179         << IsReferenceType << !Designator.Entries.empty()
2180         << !!VD << VD;
2181 
2182       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2183       if (VarD && VarD->isConstexpr()) {
2184         // Non-static local constexpr variables have unintuitive semantics:
2185         //   constexpr int a = 1;
2186         //   constexpr const int *p = &a;
2187         // ... is invalid because the address of 'a' is not constant. Suggest
2188         // adding a 'static' in this case.
2189         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2190             << VarD
2191             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2192       } else {
2193         NoteLValueLocation(Info, Base);
2194       }
2195     } else {
2196       Info.FFDiag(Loc);
2197     }
2198     // Don't allow references to temporaries to escape.
2199     return false;
2200   }
2201   assert((Info.checkingPotentialConstantExpression() ||
2202           LVal.getLValueCallIndex() == 0) &&
2203          "have call index for global lvalue");
2204 
2205   if (Base.is<DynamicAllocLValue>()) {
2206     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2207         << IsReferenceType << !Designator.Entries.empty();
2208     NoteLValueLocation(Info, Base);
2209     return false;
2210   }
2211 
2212   if (BaseVD) {
2213     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2214       // Check if this is a thread-local variable.
2215       if (Var->getTLSKind())
2216         // FIXME: Diagnostic!
2217         return false;
2218 
2219       // A dllimport variable never acts like a constant, unless we're
2220       // evaluating a value for use only in name mangling.
2221       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2222         // FIXME: Diagnostic!
2223         return false;
2224 
2225       // In CUDA/HIP device compilation, only device side variables have
2226       // constant addresses.
2227       if (Info.getCtx().getLangOpts().CUDA &&
2228           Info.getCtx().getLangOpts().CUDAIsDevice &&
2229           Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2230         if ((!Var->hasAttr<CUDADeviceAttr>() &&
2231              !Var->hasAttr<CUDAConstantAttr>() &&
2232              !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2233              !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2234             Var->hasAttr<HIPManagedAttr>())
2235           return false;
2236       }
2237     }
2238     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2239       // __declspec(dllimport) must be handled very carefully:
2240       // We must never initialize an expression with the thunk in C++.
2241       // Doing otherwise would allow the same id-expression to yield
2242       // different addresses for the same function in different translation
2243       // units.  However, this means that we must dynamically initialize the
2244       // expression with the contents of the import address table at runtime.
2245       //
2246       // The C language has no notion of ODR; furthermore, it has no notion of
2247       // dynamic initialization.  This means that we are permitted to
2248       // perform initialization with the address of the thunk.
2249       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2250           FD->hasAttr<DLLImportAttr>())
2251         // FIXME: Diagnostic!
2252         return false;
2253     }
2254   } else if (const auto *MTE =
2255                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2256     if (CheckedTemps.insert(MTE).second) {
2257       QualType TempType = getType(Base);
2258       if (TempType.isDestructedType()) {
2259         Info.FFDiag(MTE->getExprLoc(),
2260                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2261             << TempType;
2262         return false;
2263       }
2264 
2265       APValue *V = MTE->getOrCreateValue(false);
2266       assert(V && "evasluation result refers to uninitialised temporary");
2267       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2268                                  Info, MTE->getExprLoc(), TempType, *V,
2269                                  Kind, SourceLocation(), CheckedTemps))
2270         return false;
2271     }
2272   }
2273 
2274   // Allow address constant expressions to be past-the-end pointers. This is
2275   // an extension: the standard requires them to point to an object.
2276   if (!IsReferenceType)
2277     return true;
2278 
2279   // A reference constant expression must refer to an object.
2280   if (!Base) {
2281     // FIXME: diagnostic
2282     Info.CCEDiag(Loc);
2283     return true;
2284   }
2285 
2286   // Does this refer one past the end of some object?
2287   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2288     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2289       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2290     NoteLValueLocation(Info, Base);
2291   }
2292 
2293   return true;
2294 }
2295 
2296 /// Member pointers are constant expressions unless they point to a
2297 /// non-virtual dllimport member function.
CheckMemberPointerConstantExpression(EvalInfo & Info,SourceLocation Loc,QualType Type,const APValue & Value,ConstantExprKind Kind)2298 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2299                                                  SourceLocation Loc,
2300                                                  QualType Type,
2301                                                  const APValue &Value,
2302                                                  ConstantExprKind Kind) {
2303   const ValueDecl *Member = Value.getMemberPointerDecl();
2304   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2305   if (!FD)
2306     return true;
2307   if (FD->isConsteval()) {
2308     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2309     Info.Note(FD->getLocation(), diag::note_declared_at);
2310     return false;
2311   }
2312   return isForManglingOnly(Kind) || FD->isVirtual() ||
2313          !FD->hasAttr<DLLImportAttr>();
2314 }
2315 
2316 /// Check that this core constant expression is of literal type, and if not,
2317 /// produce an appropriate diagnostic.
CheckLiteralType(EvalInfo & Info,const Expr * E,const LValue * This=nullptr)2318 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2319                              const LValue *This = nullptr) {
2320   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2321     return true;
2322 
2323   // C++1y: A constant initializer for an object o [...] may also invoke
2324   // constexpr constructors for o and its subobjects even if those objects
2325   // are of non-literal class types.
2326   //
2327   // C++11 missed this detail for aggregates, so classes like this:
2328   //   struct foo_t { union { int i; volatile int j; } u; };
2329   // are not (obviously) initializable like so:
2330   //   __attribute__((__require_constant_initialization__))
2331   //   static const foo_t x = {{0}};
2332   // because "i" is a subobject with non-literal initialization (due to the
2333   // volatile member of the union). See:
2334   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2335   // Therefore, we use the C++1y behavior.
2336   if (This && Info.EvaluatingDecl == This->getLValueBase())
2337     return true;
2338 
2339   // Prvalue constant expressions must be of literal types.
2340   if (Info.getLangOpts().CPlusPlus11)
2341     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2342       << E->getType();
2343   else
2344     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2345   return false;
2346 }
2347 
CheckEvaluationResult(CheckEvaluationResultKind CERK,EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value,ConstantExprKind Kind,SourceLocation SubobjectLoc,CheckedTemporaries & CheckedTemps)2348 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2349                                   EvalInfo &Info, SourceLocation DiagLoc,
2350                                   QualType Type, const APValue &Value,
2351                                   ConstantExprKind Kind,
2352                                   SourceLocation SubobjectLoc,
2353                                   CheckedTemporaries &CheckedTemps) {
2354   if (!Value.hasValue()) {
2355     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2356       << true << Type;
2357     if (SubobjectLoc.isValid())
2358       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2359     return false;
2360   }
2361 
2362   // We allow _Atomic(T) to be initialized from anything that T can be
2363   // initialized from.
2364   if (const AtomicType *AT = Type->getAs<AtomicType>())
2365     Type = AT->getValueType();
2366 
2367   // Core issue 1454: For a literal constant expression of array or class type,
2368   // each subobject of its value shall have been initialized by a constant
2369   // expression.
2370   if (Value.isArray()) {
2371     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2372     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2373       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2374                                  Value.getArrayInitializedElt(I), Kind,
2375                                  SubobjectLoc, CheckedTemps))
2376         return false;
2377     }
2378     if (!Value.hasArrayFiller())
2379       return true;
2380     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2381                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2382                                  CheckedTemps);
2383   }
2384   if (Value.isUnion() && Value.getUnionField()) {
2385     return CheckEvaluationResult(
2386         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2387         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2388         CheckedTemps);
2389   }
2390   if (Value.isStruct()) {
2391     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2392     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2393       unsigned BaseIndex = 0;
2394       for (const CXXBaseSpecifier &BS : CD->bases()) {
2395         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2396                                    Value.getStructBase(BaseIndex), Kind,
2397                                    BS.getBeginLoc(), CheckedTemps))
2398           return false;
2399         ++BaseIndex;
2400       }
2401     }
2402     for (const auto *I : RD->fields()) {
2403       if (I->isUnnamedBitfield())
2404         continue;
2405 
2406       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2407                                  Value.getStructField(I->getFieldIndex()),
2408                                  Kind, I->getLocation(), CheckedTemps))
2409         return false;
2410     }
2411   }
2412 
2413   if (Value.isLValue() &&
2414       CERK == CheckEvaluationResultKind::ConstantExpression) {
2415     LValue LVal;
2416     LVal.setFrom(Info.Ctx, Value);
2417     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2418                                          CheckedTemps);
2419   }
2420 
2421   if (Value.isMemberPointer() &&
2422       CERK == CheckEvaluationResultKind::ConstantExpression)
2423     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2424 
2425   // Everything else is fine.
2426   return true;
2427 }
2428 
2429 /// Check that this core constant expression value is a valid value for a
2430 /// constant expression. If not, report an appropriate diagnostic. Does not
2431 /// check that the expression is of literal type.
CheckConstantExpression(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value,ConstantExprKind Kind)2432 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2433                                     QualType Type, const APValue &Value,
2434                                     ConstantExprKind Kind) {
2435   // Nothing to check for a constant expression of type 'cv void'.
2436   if (Type->isVoidType())
2437     return true;
2438 
2439   CheckedTemporaries CheckedTemps;
2440   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2441                                Info, DiagLoc, Type, Value, Kind,
2442                                SourceLocation(), CheckedTemps);
2443 }
2444 
2445 /// Check that this evaluated value is fully-initialized and can be loaded by
2446 /// an lvalue-to-rvalue conversion.
CheckFullyInitialized(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value)2447 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2448                                   QualType Type, const APValue &Value) {
2449   CheckedTemporaries CheckedTemps;
2450   return CheckEvaluationResult(
2451       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2452       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2453 }
2454 
2455 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2456 /// "the allocated storage is deallocated within the evaluation".
CheckMemoryLeaks(EvalInfo & Info)2457 static bool CheckMemoryLeaks(EvalInfo &Info) {
2458   if (!Info.HeapAllocs.empty()) {
2459     // We can still fold to a constant despite a compile-time memory leak,
2460     // so long as the heap allocation isn't referenced in the result (we check
2461     // that in CheckConstantExpression).
2462     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2463                  diag::note_constexpr_memory_leak)
2464         << unsigned(Info.HeapAllocs.size() - 1);
2465   }
2466   return true;
2467 }
2468 
EvalPointerValueAsBool(const APValue & Value,bool & Result)2469 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2470   // A null base expression indicates a null pointer.  These are always
2471   // evaluatable, and they are false unless the offset is zero.
2472   if (!Value.getLValueBase()) {
2473     Result = !Value.getLValueOffset().isZero();
2474     return true;
2475   }
2476 
2477   // We have a non-null base.  These are generally known to be true, but if it's
2478   // a weak declaration it can be null at runtime.
2479   Result = true;
2480   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2481   return !Decl || !Decl->isWeak();
2482 }
2483 
HandleConversionToBool(const APValue & Val,bool & Result)2484 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2485   switch (Val.getKind()) {
2486   case APValue::None:
2487   case APValue::Indeterminate:
2488     return false;
2489   case APValue::Int:
2490     Result = Val.getInt().getBoolValue();
2491     return true;
2492   case APValue::FixedPoint:
2493     Result = Val.getFixedPoint().getBoolValue();
2494     return true;
2495   case APValue::Float:
2496     Result = !Val.getFloat().isZero();
2497     return true;
2498   case APValue::ComplexInt:
2499     Result = Val.getComplexIntReal().getBoolValue() ||
2500              Val.getComplexIntImag().getBoolValue();
2501     return true;
2502   case APValue::ComplexFloat:
2503     Result = !Val.getComplexFloatReal().isZero() ||
2504              !Val.getComplexFloatImag().isZero();
2505     return true;
2506   case APValue::LValue:
2507     return EvalPointerValueAsBool(Val, Result);
2508   case APValue::MemberPointer:
2509     Result = Val.getMemberPointerDecl();
2510     return true;
2511   case APValue::Vector:
2512   case APValue::Array:
2513   case APValue::Struct:
2514   case APValue::Union:
2515   case APValue::AddrLabelDiff:
2516     return false;
2517   }
2518 
2519   llvm_unreachable("unknown APValue kind");
2520 }
2521 
EvaluateAsBooleanCondition(const Expr * E,bool & Result,EvalInfo & Info)2522 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2523                                        EvalInfo &Info) {
2524   assert(!E->isValueDependent());
2525   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2526   APValue Val;
2527   if (!Evaluate(Val, Info, E))
2528     return false;
2529   return HandleConversionToBool(Val, Result);
2530 }
2531 
2532 template<typename T>
HandleOverflow(EvalInfo & Info,const Expr * E,const T & SrcValue,QualType DestType)2533 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2534                            const T &SrcValue, QualType DestType) {
2535   Info.CCEDiag(E, diag::note_constexpr_overflow)
2536     << SrcValue << DestType;
2537   return Info.noteUndefinedBehavior();
2538 }
2539 
HandleFloatToIntCast(EvalInfo & Info,const Expr * E,QualType SrcType,const APFloat & Value,QualType DestType,APSInt & Result)2540 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2541                                  QualType SrcType, const APFloat &Value,
2542                                  QualType DestType, APSInt &Result) {
2543   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2544   // Determine whether we are converting to unsigned or signed.
2545   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2546 
2547   Result = APSInt(DestWidth, !DestSigned);
2548   bool ignored;
2549   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2550       & APFloat::opInvalidOp)
2551     return HandleOverflow(Info, E, Value, DestType);
2552   return true;
2553 }
2554 
2555 /// Get rounding mode to use in evaluation of the specified expression.
2556 ///
2557 /// If rounding mode is unknown at compile time, still try to evaluate the
2558 /// expression. If the result is exact, it does not depend on rounding mode.
2559 /// So return "tonearest" mode instead of "dynamic".
getActiveRoundingMode(EvalInfo & Info,const Expr * E)2560 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2561   llvm::RoundingMode RM =
2562       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2563   if (RM == llvm::RoundingMode::Dynamic)
2564     RM = llvm::RoundingMode::NearestTiesToEven;
2565   return RM;
2566 }
2567 
2568 /// Check if the given evaluation result is allowed for constant evaluation.
checkFloatingPointResult(EvalInfo & Info,const Expr * E,APFloat::opStatus St)2569 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2570                                      APFloat::opStatus St) {
2571   // In a constant context, assume that any dynamic rounding mode or FP
2572   // exception state matches the default floating-point environment.
2573   if (Info.InConstantContext)
2574     return true;
2575 
2576   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2577   if ((St & APFloat::opInexact) &&
2578       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2579     // Inexact result means that it depends on rounding mode. If the requested
2580     // mode is dynamic, the evaluation cannot be made in compile time.
2581     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2582     return false;
2583   }
2584 
2585   if ((St != APFloat::opOK) &&
2586       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2587        FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2588        FPO.getAllowFEnvAccess())) {
2589     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2590     return false;
2591   }
2592 
2593   if ((St & APFloat::opStatus::opInvalidOp) &&
2594       FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2595     // There is no usefully definable result.
2596     Info.FFDiag(E);
2597     return false;
2598   }
2599 
2600   // FIXME: if:
2601   // - evaluation triggered other FP exception, and
2602   // - exception mode is not "ignore", and
2603   // - the expression being evaluated is not a part of global variable
2604   //   initializer,
2605   // the evaluation probably need to be rejected.
2606   return true;
2607 }
2608 
HandleFloatToFloatCast(EvalInfo & Info,const Expr * E,QualType SrcType,QualType DestType,APFloat & Result)2609 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2610                                    QualType SrcType, QualType DestType,
2611                                    APFloat &Result) {
2612   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2613   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2614   APFloat::opStatus St;
2615   APFloat Value = Result;
2616   bool ignored;
2617   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2618   return checkFloatingPointResult(Info, E, St);
2619 }
2620 
HandleIntToIntCast(EvalInfo & Info,const Expr * E,QualType DestType,QualType SrcType,const APSInt & Value)2621 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2622                                  QualType DestType, QualType SrcType,
2623                                  const APSInt &Value) {
2624   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2625   // Figure out if this is a truncate, extend or noop cast.
2626   // If the input is signed, do a sign extend, noop, or truncate.
2627   APSInt Result = Value.extOrTrunc(DestWidth);
2628   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2629   if (DestType->isBooleanType())
2630     Result = Value.getBoolValue();
2631   return Result;
2632 }
2633 
HandleIntToFloatCast(EvalInfo & Info,const Expr * E,const FPOptions FPO,QualType SrcType,const APSInt & Value,QualType DestType,APFloat & Result)2634 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2635                                  const FPOptions FPO,
2636                                  QualType SrcType, const APSInt &Value,
2637                                  QualType DestType, APFloat &Result) {
2638   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2639   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2640        APFloat::rmNearestTiesToEven);
2641   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2642       FPO.isFPConstrained()) {
2643     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2644     return false;
2645   }
2646   return true;
2647 }
2648 
truncateBitfieldValue(EvalInfo & Info,const Expr * E,APValue & Value,const FieldDecl * FD)2649 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2650                                   APValue &Value, const FieldDecl *FD) {
2651   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2652 
2653   if (!Value.isInt()) {
2654     // Trying to store a pointer-cast-to-integer into a bitfield.
2655     // FIXME: In this case, we should provide the diagnostic for casting
2656     // a pointer to an integer.
2657     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2658     Info.FFDiag(E);
2659     return false;
2660   }
2661 
2662   APSInt &Int = Value.getInt();
2663   unsigned OldBitWidth = Int.getBitWidth();
2664   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2665   if (NewBitWidth < OldBitWidth)
2666     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2667   return true;
2668 }
2669 
EvalAndBitcastToAPInt(EvalInfo & Info,const Expr * E,llvm::APInt & Res)2670 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2671                                   llvm::APInt &Res) {
2672   APValue SVal;
2673   if (!Evaluate(SVal, Info, E))
2674     return false;
2675   if (SVal.isInt()) {
2676     Res = SVal.getInt();
2677     return true;
2678   }
2679   if (SVal.isFloat()) {
2680     Res = SVal.getFloat().bitcastToAPInt();
2681     return true;
2682   }
2683   if (SVal.isVector()) {
2684     QualType VecTy = E->getType();
2685     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2686     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2687     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2688     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2689     Res = llvm::APInt::getZero(VecSize);
2690     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2691       APValue &Elt = SVal.getVectorElt(i);
2692       llvm::APInt EltAsInt;
2693       if (Elt.isInt()) {
2694         EltAsInt = Elt.getInt();
2695       } else if (Elt.isFloat()) {
2696         EltAsInt = Elt.getFloat().bitcastToAPInt();
2697       } else {
2698         // Don't try to handle vectors of anything other than int or float
2699         // (not sure if it's possible to hit this case).
2700         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2701         return false;
2702       }
2703       unsigned BaseEltSize = EltAsInt.getBitWidth();
2704       if (BigEndian)
2705         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2706       else
2707         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2708     }
2709     return true;
2710   }
2711   // Give up if the input isn't an int, float, or vector.  For example, we
2712   // reject "(v4i16)(intptr_t)&a".
2713   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2714   return false;
2715 }
2716 
2717 /// Perform the given integer operation, which is known to need at most BitWidth
2718 /// bits, and check for overflow in the original type (if that type was not an
2719 /// unsigned type).
2720 template<typename Operation>
CheckedIntArithmetic(EvalInfo & Info,const Expr * E,const APSInt & LHS,const APSInt & RHS,unsigned BitWidth,Operation Op,APSInt & Result)2721 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2722                                  const APSInt &LHS, const APSInt &RHS,
2723                                  unsigned BitWidth, Operation Op,
2724                                  APSInt &Result) {
2725   if (LHS.isUnsigned()) {
2726     Result = Op(LHS, RHS);
2727     return true;
2728   }
2729 
2730   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2731   Result = Value.trunc(LHS.getBitWidth());
2732   if (Result.extend(BitWidth) != Value) {
2733     if (Info.checkingForUndefinedBehavior())
2734       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2735                                        diag::warn_integer_constant_overflow)
2736           << toString(Result, 10) << E->getType();
2737     return HandleOverflow(Info, E, Value, E->getType());
2738   }
2739   return true;
2740 }
2741 
2742 /// Perform the given binary integer operation.
handleIntIntBinOp(EvalInfo & Info,const Expr * E,const APSInt & LHS,BinaryOperatorKind Opcode,APSInt RHS,APSInt & Result)2743 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2744                               BinaryOperatorKind Opcode, APSInt RHS,
2745                               APSInt &Result) {
2746   switch (Opcode) {
2747   default:
2748     Info.FFDiag(E);
2749     return false;
2750   case BO_Mul:
2751     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2752                                 std::multiplies<APSInt>(), Result);
2753   case BO_Add:
2754     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2755                                 std::plus<APSInt>(), Result);
2756   case BO_Sub:
2757     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2758                                 std::minus<APSInt>(), Result);
2759   case BO_And: Result = LHS & RHS; return true;
2760   case BO_Xor: Result = LHS ^ RHS; return true;
2761   case BO_Or:  Result = LHS | RHS; return true;
2762   case BO_Div:
2763   case BO_Rem:
2764     if (RHS == 0) {
2765       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2766       return false;
2767     }
2768     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2769     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2770     // this operation and gives the two's complement result.
2771     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2772         LHS.isMinSignedValue())
2773       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2774                             E->getType());
2775     return true;
2776   case BO_Shl: {
2777     if (Info.getLangOpts().OpenCL)
2778       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2779       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2780                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2781                     RHS.isUnsigned());
2782     else if (RHS.isSigned() && RHS.isNegative()) {
2783       // During constant-folding, a negative shift is an opposite shift. Such
2784       // a shift is not a constant expression.
2785       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2786       RHS = -RHS;
2787       goto shift_right;
2788     }
2789   shift_left:
2790     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2791     // the shifted type.
2792     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2793     if (SA != RHS) {
2794       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2795         << RHS << E->getType() << LHS.getBitWidth();
2796     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2797       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2798       // operand, and must not overflow the corresponding unsigned type.
2799       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2800       // E1 x 2^E2 module 2^N.
2801       if (LHS.isNegative())
2802         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2803       else if (LHS.countLeadingZeros() < SA)
2804         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2805     }
2806     Result = LHS << SA;
2807     return true;
2808   }
2809   case BO_Shr: {
2810     if (Info.getLangOpts().OpenCL)
2811       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2812       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2813                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2814                     RHS.isUnsigned());
2815     else if (RHS.isSigned() && RHS.isNegative()) {
2816       // During constant-folding, a negative shift is an opposite shift. Such a
2817       // shift is not a constant expression.
2818       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2819       RHS = -RHS;
2820       goto shift_left;
2821     }
2822   shift_right:
2823     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2824     // shifted type.
2825     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2826     if (SA != RHS)
2827       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2828         << RHS << E->getType() << LHS.getBitWidth();
2829     Result = LHS >> SA;
2830     return true;
2831   }
2832 
2833   case BO_LT: Result = LHS < RHS; return true;
2834   case BO_GT: Result = LHS > RHS; return true;
2835   case BO_LE: Result = LHS <= RHS; return true;
2836   case BO_GE: Result = LHS >= RHS; return true;
2837   case BO_EQ: Result = LHS == RHS; return true;
2838   case BO_NE: Result = LHS != RHS; return true;
2839   case BO_Cmp:
2840     llvm_unreachable("BO_Cmp should be handled elsewhere");
2841   }
2842 }
2843 
2844 /// Perform the given binary floating-point operation, in-place, on LHS.
handleFloatFloatBinOp(EvalInfo & Info,const BinaryOperator * E,APFloat & LHS,BinaryOperatorKind Opcode,const APFloat & RHS)2845 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2846                                   APFloat &LHS, BinaryOperatorKind Opcode,
2847                                   const APFloat &RHS) {
2848   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2849   APFloat::opStatus St;
2850   switch (Opcode) {
2851   default:
2852     Info.FFDiag(E);
2853     return false;
2854   case BO_Mul:
2855     St = LHS.multiply(RHS, RM);
2856     break;
2857   case BO_Add:
2858     St = LHS.add(RHS, RM);
2859     break;
2860   case BO_Sub:
2861     St = LHS.subtract(RHS, RM);
2862     break;
2863   case BO_Div:
2864     // [expr.mul]p4:
2865     //   If the second operand of / or % is zero the behavior is undefined.
2866     if (RHS.isZero())
2867       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2868     St = LHS.divide(RHS, RM);
2869     break;
2870   }
2871 
2872   // [expr.pre]p4:
2873   //   If during the evaluation of an expression, the result is not
2874   //   mathematically defined [...], the behavior is undefined.
2875   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2876   if (LHS.isNaN()) {
2877     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2878     return Info.noteUndefinedBehavior();
2879   }
2880 
2881   return checkFloatingPointResult(Info, E, St);
2882 }
2883 
handleLogicalOpForVector(const APInt & LHSValue,BinaryOperatorKind Opcode,const APInt & RHSValue,APInt & Result)2884 static bool handleLogicalOpForVector(const APInt &LHSValue,
2885                                      BinaryOperatorKind Opcode,
2886                                      const APInt &RHSValue, APInt &Result) {
2887   bool LHS = (LHSValue != 0);
2888   bool RHS = (RHSValue != 0);
2889 
2890   if (Opcode == BO_LAnd)
2891     Result = LHS && RHS;
2892   else
2893     Result = LHS || RHS;
2894   return true;
2895 }
handleLogicalOpForVector(const APFloat & LHSValue,BinaryOperatorKind Opcode,const APFloat & RHSValue,APInt & Result)2896 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2897                                      BinaryOperatorKind Opcode,
2898                                      const APFloat &RHSValue, APInt &Result) {
2899   bool LHS = !LHSValue.isZero();
2900   bool RHS = !RHSValue.isZero();
2901 
2902   if (Opcode == BO_LAnd)
2903     Result = LHS && RHS;
2904   else
2905     Result = LHS || RHS;
2906   return true;
2907 }
2908 
handleLogicalOpForVector(const APValue & LHSValue,BinaryOperatorKind Opcode,const APValue & RHSValue,APInt & Result)2909 static bool handleLogicalOpForVector(const APValue &LHSValue,
2910                                      BinaryOperatorKind Opcode,
2911                                      const APValue &RHSValue, APInt &Result) {
2912   // The result is always an int type, however operands match the first.
2913   if (LHSValue.getKind() == APValue::Int)
2914     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2915                                     RHSValue.getInt(), Result);
2916   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2917   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2918                                   RHSValue.getFloat(), Result);
2919 }
2920 
2921 template <typename APTy>
2922 static bool
handleCompareOpForVectorHelper(const APTy & LHSValue,BinaryOperatorKind Opcode,const APTy & RHSValue,APInt & Result)2923 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2924                                const APTy &RHSValue, APInt &Result) {
2925   switch (Opcode) {
2926   default:
2927     llvm_unreachable("unsupported binary operator");
2928   case BO_EQ:
2929     Result = (LHSValue == RHSValue);
2930     break;
2931   case BO_NE:
2932     Result = (LHSValue != RHSValue);
2933     break;
2934   case BO_LT:
2935     Result = (LHSValue < RHSValue);
2936     break;
2937   case BO_GT:
2938     Result = (LHSValue > RHSValue);
2939     break;
2940   case BO_LE:
2941     Result = (LHSValue <= RHSValue);
2942     break;
2943   case BO_GE:
2944     Result = (LHSValue >= RHSValue);
2945     break;
2946   }
2947 
2948   // The boolean operations on these vector types use an instruction that
2949   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2950   // to -1 to make sure that we produce the correct value.
2951   Result.negate();
2952 
2953   return true;
2954 }
2955 
handleCompareOpForVector(const APValue & LHSValue,BinaryOperatorKind Opcode,const APValue & RHSValue,APInt & Result)2956 static bool handleCompareOpForVector(const APValue &LHSValue,
2957                                      BinaryOperatorKind Opcode,
2958                                      const APValue &RHSValue, APInt &Result) {
2959   // The result is always an int type, however operands match the first.
2960   if (LHSValue.getKind() == APValue::Int)
2961     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2962                                           RHSValue.getInt(), Result);
2963   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2964   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2965                                         RHSValue.getFloat(), Result);
2966 }
2967 
2968 // Perform binary operations for vector types, in place on the LHS.
handleVectorVectorBinOp(EvalInfo & Info,const BinaryOperator * E,BinaryOperatorKind Opcode,APValue & LHSValue,const APValue & RHSValue)2969 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2970                                     BinaryOperatorKind Opcode,
2971                                     APValue &LHSValue,
2972                                     const APValue &RHSValue) {
2973   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2974          "Operation not supported on vector types");
2975 
2976   const auto *VT = E->getType()->castAs<VectorType>();
2977   unsigned NumElements = VT->getNumElements();
2978   QualType EltTy = VT->getElementType();
2979 
2980   // In the cases (typically C as I've observed) where we aren't evaluating
2981   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2982   // just give up.
2983   if (!LHSValue.isVector()) {
2984     assert(LHSValue.isLValue() &&
2985            "A vector result that isn't a vector OR uncalculated LValue");
2986     Info.FFDiag(E);
2987     return false;
2988   }
2989 
2990   assert(LHSValue.getVectorLength() == NumElements &&
2991          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2992 
2993   SmallVector<APValue, 4> ResultElements;
2994 
2995   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2996     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2997     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2998 
2999     if (EltTy->isIntegerType()) {
3000       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3001                        EltTy->isUnsignedIntegerType()};
3002       bool Success = true;
3003 
3004       if (BinaryOperator::isLogicalOp(Opcode))
3005         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3006       else if (BinaryOperator::isComparisonOp(Opcode))
3007         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3008       else
3009         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3010                                     RHSElt.getInt(), EltResult);
3011 
3012       if (!Success) {
3013         Info.FFDiag(E);
3014         return false;
3015       }
3016       ResultElements.emplace_back(EltResult);
3017 
3018     } else if (EltTy->isFloatingType()) {
3019       assert(LHSElt.getKind() == APValue::Float &&
3020              RHSElt.getKind() == APValue::Float &&
3021              "Mismatched LHS/RHS/Result Type");
3022       APFloat LHSFloat = LHSElt.getFloat();
3023 
3024       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3025                                  RHSElt.getFloat())) {
3026         Info.FFDiag(E);
3027         return false;
3028       }
3029 
3030       ResultElements.emplace_back(LHSFloat);
3031     }
3032   }
3033 
3034   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3035   return true;
3036 }
3037 
3038 /// Cast an lvalue referring to a base subobject to a derived class, by
3039 /// truncating the lvalue's path to the given length.
CastToDerivedClass(EvalInfo & Info,const Expr * E,LValue & Result,const RecordDecl * TruncatedType,unsigned TruncatedElements)3040 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3041                                const RecordDecl *TruncatedType,
3042                                unsigned TruncatedElements) {
3043   SubobjectDesignator &D = Result.Designator;
3044 
3045   // Check we actually point to a derived class object.
3046   if (TruncatedElements == D.Entries.size())
3047     return true;
3048   assert(TruncatedElements >= D.MostDerivedPathLength &&
3049          "not casting to a derived class");
3050   if (!Result.checkSubobject(Info, E, CSK_Derived))
3051     return false;
3052 
3053   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3054   const RecordDecl *RD = TruncatedType;
3055   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3056     if (RD->isInvalidDecl()) return false;
3057     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3058     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3059     if (isVirtualBaseClass(D.Entries[I]))
3060       Result.Offset -= Layout.getVBaseClassOffset(Base);
3061     else
3062       Result.Offset -= Layout.getBaseClassOffset(Base);
3063     RD = Base;
3064   }
3065   D.Entries.resize(TruncatedElements);
3066   return true;
3067 }
3068 
HandleLValueDirectBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * Derived,const CXXRecordDecl * Base,const ASTRecordLayout * RL=nullptr)3069 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3070                                    const CXXRecordDecl *Derived,
3071                                    const CXXRecordDecl *Base,
3072                                    const ASTRecordLayout *RL = nullptr) {
3073   if (!RL) {
3074     if (Derived->isInvalidDecl()) return false;
3075     RL = &Info.Ctx.getASTRecordLayout(Derived);
3076   }
3077 
3078   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3079   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3080   return true;
3081 }
3082 
HandleLValueBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * DerivedDecl,const CXXBaseSpecifier * Base)3083 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3084                              const CXXRecordDecl *DerivedDecl,
3085                              const CXXBaseSpecifier *Base) {
3086   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3087 
3088   if (!Base->isVirtual())
3089     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3090 
3091   SubobjectDesignator &D = Obj.Designator;
3092   if (D.Invalid)
3093     return false;
3094 
3095   // Extract most-derived object and corresponding type.
3096   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3097   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3098     return false;
3099 
3100   // Find the virtual base class.
3101   if (DerivedDecl->isInvalidDecl()) return false;
3102   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3103   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3104   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3105   return true;
3106 }
3107 
HandleLValueBasePath(EvalInfo & Info,const CastExpr * E,QualType Type,LValue & Result)3108 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3109                                  QualType Type, LValue &Result) {
3110   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3111                                      PathE = E->path_end();
3112        PathI != PathE; ++PathI) {
3113     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3114                           *PathI))
3115       return false;
3116     Type = (*PathI)->getType();
3117   }
3118   return true;
3119 }
3120 
3121 /// 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)3122 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3123                             const CXXRecordDecl *DerivedRD,
3124                             const CXXRecordDecl *BaseRD) {
3125   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3126                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3127   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3128     llvm_unreachable("Class must be derived from the passed in base class!");
3129 
3130   for (CXXBasePathElement &Elem : Paths.front())
3131     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3132       return false;
3133   return true;
3134 }
3135 
3136 /// Update LVal to refer to the given field, which must be a member of the type
3137 /// currently described by LVal.
HandleLValueMember(EvalInfo & Info,const Expr * E,LValue & LVal,const FieldDecl * FD,const ASTRecordLayout * RL=nullptr)3138 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3139                                const FieldDecl *FD,
3140                                const ASTRecordLayout *RL = nullptr) {
3141   if (!RL) {
3142     if (FD->getParent()->isInvalidDecl()) return false;
3143     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3144   }
3145 
3146   unsigned I = FD->getFieldIndex();
3147   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3148   LVal.addDecl(Info, E, FD);
3149   return true;
3150 }
3151 
3152 /// Update LVal to refer to the given indirect field.
HandleLValueIndirectMember(EvalInfo & Info,const Expr * E,LValue & LVal,const IndirectFieldDecl * IFD)3153 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3154                                        LValue &LVal,
3155                                        const IndirectFieldDecl *IFD) {
3156   for (const auto *C : IFD->chain())
3157     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3158       return false;
3159   return true;
3160 }
3161 
3162 /// Get the size of the given type in char units.
HandleSizeof(EvalInfo & Info,SourceLocation Loc,QualType Type,CharUnits & Size)3163 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3164                          QualType Type, CharUnits &Size) {
3165   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3166   // extension.
3167   if (Type->isVoidType() || Type->isFunctionType()) {
3168     Size = CharUnits::One();
3169     return true;
3170   }
3171 
3172   if (Type->isDependentType()) {
3173     Info.FFDiag(Loc);
3174     return false;
3175   }
3176 
3177   if (!Type->isConstantSizeType()) {
3178     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3179     // FIXME: Better diagnostic.
3180     Info.FFDiag(Loc);
3181     return false;
3182   }
3183 
3184   Size = Info.Ctx.getTypeSizeInChars(Type);
3185   return true;
3186 }
3187 
3188 /// Update a pointer value to model pointer arithmetic.
3189 /// \param Info - Information about the ongoing evaluation.
3190 /// \param E - The expression being evaluated, for diagnostic purposes.
3191 /// \param LVal - The pointer value to be updated.
3192 /// \param EltTy - The pointee type represented by LVal.
3193 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,APSInt Adjustment)3194 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3195                                         LValue &LVal, QualType EltTy,
3196                                         APSInt Adjustment) {
3197   CharUnits SizeOfPointee;
3198   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3199     return false;
3200 
3201   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3202   return true;
3203 }
3204 
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,int64_t Adjustment)3205 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3206                                         LValue &LVal, QualType EltTy,
3207                                         int64_t Adjustment) {
3208   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3209                                      APSInt::get(Adjustment));
3210 }
3211 
3212 /// Update an lvalue to refer to a component of a complex number.
3213 /// \param Info - Information about the ongoing evaluation.
3214 /// \param LVal - The lvalue to be updated.
3215 /// \param EltTy - The complex number's component type.
3216 /// \param Imag - False for the real component, true for the imaginary.
HandleLValueComplexElement(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,bool Imag)3217 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3218                                        LValue &LVal, QualType EltTy,
3219                                        bool Imag) {
3220   if (Imag) {
3221     CharUnits SizeOfComponent;
3222     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3223       return false;
3224     LVal.Offset += SizeOfComponent;
3225   }
3226   LVal.addComplex(Info, E, EltTy, Imag);
3227   return true;
3228 }
3229 
3230 /// Try to evaluate the initializer for a variable declaration.
3231 ///
3232 /// \param Info   Information about the ongoing evaluation.
3233 /// \param E      An expression to be used when printing diagnostics.
3234 /// \param VD     The variable whose initializer should be obtained.
3235 /// \param Version The version of the variable within the frame.
3236 /// \param Frame  The frame in which the variable was created. Must be null
3237 ///               if this variable is not local to the evaluation.
3238 /// \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)3239 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3240                                 const VarDecl *VD, CallStackFrame *Frame,
3241                                 unsigned Version, APValue *&Result) {
3242   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3243 
3244   // If this is a local variable, dig out its value.
3245   if (Frame) {
3246     Result = Frame->getTemporary(VD, Version);
3247     if (Result)
3248       return true;
3249 
3250     if (!isa<ParmVarDecl>(VD)) {
3251       // Assume variables referenced within a lambda's call operator that were
3252       // not declared within the call operator are captures and during checking
3253       // of a potential constant expression, assume they are unknown constant
3254       // expressions.
3255       assert(isLambdaCallOperator(Frame->Callee) &&
3256              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3257              "missing value for local variable");
3258       if (Info.checkingPotentialConstantExpression())
3259         return false;
3260       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3261       // still reachable at all?
3262       Info.FFDiag(E->getBeginLoc(),
3263                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3264           << "captures not currently allowed";
3265       return false;
3266     }
3267   }
3268 
3269   // If we're currently evaluating the initializer of this declaration, use that
3270   // in-flight value.
3271   if (Info.EvaluatingDecl == Base) {
3272     Result = Info.EvaluatingDeclValue;
3273     return true;
3274   }
3275 
3276   if (isa<ParmVarDecl>(VD)) {
3277     // Assume parameters of a potential constant expression are usable in
3278     // constant expressions.
3279     if (!Info.checkingPotentialConstantExpression() ||
3280         !Info.CurrentCall->Callee ||
3281         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3282       if (Info.getLangOpts().CPlusPlus11) {
3283         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3284             << VD;
3285         NoteLValueLocation(Info, Base);
3286       } else {
3287         Info.FFDiag(E);
3288       }
3289     }
3290     return false;
3291   }
3292 
3293   // Dig out the initializer, and use the declaration which it's attached to.
3294   // FIXME: We should eventually check whether the variable has a reachable
3295   // initializing declaration.
3296   const Expr *Init = VD->getAnyInitializer(VD);
3297   if (!Init) {
3298     // Don't diagnose during potential constant expression checking; an
3299     // initializer might be added later.
3300     if (!Info.checkingPotentialConstantExpression()) {
3301       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3302         << VD;
3303       NoteLValueLocation(Info, Base);
3304     }
3305     return false;
3306   }
3307 
3308   if (Init->isValueDependent()) {
3309     // The DeclRefExpr is not value-dependent, but the variable it refers to
3310     // has a value-dependent initializer. This should only happen in
3311     // constant-folding cases, where the variable is not actually of a suitable
3312     // type for use in a constant expression (otherwise the DeclRefExpr would
3313     // have been value-dependent too), so diagnose that.
3314     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3315     if (!Info.checkingPotentialConstantExpression()) {
3316       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3317                          ? diag::note_constexpr_ltor_non_constexpr
3318                          : diag::note_constexpr_ltor_non_integral, 1)
3319           << VD << VD->getType();
3320       NoteLValueLocation(Info, Base);
3321     }
3322     return false;
3323   }
3324 
3325   // Check that we can fold the initializer. In C++, we will have already done
3326   // this in the cases where it matters for conformance.
3327   if (!VD->evaluateValue()) {
3328     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3329     NoteLValueLocation(Info, Base);
3330     return false;
3331   }
3332 
3333   // Check that the variable is actually usable in constant expressions. For a
3334   // const integral variable or a reference, we might have a non-constant
3335   // initializer that we can nonetheless evaluate the initializer for. Such
3336   // variables are not usable in constant expressions. In C++98, the
3337   // initializer also syntactically needs to be an ICE.
3338   //
3339   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3340   // expressions here; doing so would regress diagnostics for things like
3341   // reading from a volatile constexpr variable.
3342   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3343        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3344       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3345        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3346     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3347     NoteLValueLocation(Info, Base);
3348   }
3349 
3350   // Never use the initializer of a weak variable, not even for constant
3351   // folding. We can't be sure that this is the definition that will be used.
3352   if (VD->isWeak()) {
3353     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3354     NoteLValueLocation(Info, Base);
3355     return false;
3356   }
3357 
3358   Result = VD->getEvaluatedValue();
3359   return true;
3360 }
3361 
3362 /// Get the base index of the given base class within an APValue representing
3363 /// the given derived class.
getBaseIndex(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)3364 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3365                              const CXXRecordDecl *Base) {
3366   Base = Base->getCanonicalDecl();
3367   unsigned Index = 0;
3368   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3369          E = Derived->bases_end(); I != E; ++I, ++Index) {
3370     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3371       return Index;
3372   }
3373 
3374   llvm_unreachable("base class missing from derived class's bases list");
3375 }
3376 
3377 /// Extract the value of a character from a string literal.
extractStringLiteralCharacter(EvalInfo & Info,const Expr * Lit,uint64_t Index)3378 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3379                                             uint64_t Index) {
3380   assert(!isa<SourceLocExpr>(Lit) &&
3381          "SourceLocExpr should have already been converted to a StringLiteral");
3382 
3383   // FIXME: Support MakeStringConstant
3384   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3385     std::string Str;
3386     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3387     assert(Index <= Str.size() && "Index too large");
3388     return APSInt::getUnsigned(Str.c_str()[Index]);
3389   }
3390 
3391   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3392     Lit = PE->getFunctionName();
3393   const StringLiteral *S = cast<StringLiteral>(Lit);
3394   const ConstantArrayType *CAT =
3395       Info.Ctx.getAsConstantArrayType(S->getType());
3396   assert(CAT && "string literal isn't an array");
3397   QualType CharType = CAT->getElementType();
3398   assert(CharType->isIntegerType() && "unexpected character type");
3399 
3400   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3401                CharType->isUnsignedIntegerType());
3402   if (Index < S->getLength())
3403     Value = S->getCodeUnit(Index);
3404   return Value;
3405 }
3406 
3407 // Expand a string literal into an array of characters.
3408 //
3409 // FIXME: This is inefficient; we should probably introduce something similar
3410 // to the LLVM ConstantDataArray to make this cheaper.
expandStringLiteral(EvalInfo & Info,const StringLiteral * S,APValue & Result,QualType AllocType=QualType ())3411 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3412                                 APValue &Result,
3413                                 QualType AllocType = QualType()) {
3414   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3415       AllocType.isNull() ? S->getType() : AllocType);
3416   assert(CAT && "string literal isn't an array");
3417   QualType CharType = CAT->getElementType();
3418   assert(CharType->isIntegerType() && "unexpected character type");
3419 
3420   unsigned Elts = CAT->getSize().getZExtValue();
3421   Result = APValue(APValue::UninitArray(),
3422                    std::min(S->getLength(), Elts), Elts);
3423   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3424                CharType->isUnsignedIntegerType());
3425   if (Result.hasArrayFiller())
3426     Result.getArrayFiller() = APValue(Value);
3427   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3428     Value = S->getCodeUnit(I);
3429     Result.getArrayInitializedElt(I) = APValue(Value);
3430   }
3431 }
3432 
3433 // Expand an array so that it has more than Index filled elements.
expandArray(APValue & Array,unsigned Index)3434 static void expandArray(APValue &Array, unsigned Index) {
3435   unsigned Size = Array.getArraySize();
3436   assert(Index < Size);
3437 
3438   // Always at least double the number of elements for which we store a value.
3439   unsigned OldElts = Array.getArrayInitializedElts();
3440   unsigned NewElts = std::max(Index+1, OldElts * 2);
3441   NewElts = std::min(Size, std::max(NewElts, 8u));
3442 
3443   // Copy the data across.
3444   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3445   for (unsigned I = 0; I != OldElts; ++I)
3446     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3447   for (unsigned I = OldElts; I != NewElts; ++I)
3448     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3449   if (NewValue.hasArrayFiller())
3450     NewValue.getArrayFiller() = Array.getArrayFiller();
3451   Array.swap(NewValue);
3452 }
3453 
3454 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3455 /// conversion. If it's of class type, we may assume that the copy operation
3456 /// is trivial. Note that this is never true for a union type with fields
3457 /// (because the copy always "reads" the active member) and always true for
3458 /// a non-class type.
3459 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
isReadByLvalueToRvalueConversion(QualType T)3460 static bool isReadByLvalueToRvalueConversion(QualType T) {
3461   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3462   return !RD || isReadByLvalueToRvalueConversion(RD);
3463 }
isReadByLvalueToRvalueConversion(const CXXRecordDecl * RD)3464 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3465   // FIXME: A trivial copy of a union copies the object representation, even if
3466   // the union is empty.
3467   if (RD->isUnion())
3468     return !RD->field_empty();
3469   if (RD->isEmpty())
3470     return false;
3471 
3472   for (auto *Field : RD->fields())
3473     if (!Field->isUnnamedBitfield() &&
3474         isReadByLvalueToRvalueConversion(Field->getType()))
3475       return true;
3476 
3477   for (auto &BaseSpec : RD->bases())
3478     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3479       return true;
3480 
3481   return false;
3482 }
3483 
3484 /// Diagnose an attempt to read from any unreadable field within the specified
3485 /// type, which might be a class type.
diagnoseMutableFields(EvalInfo & Info,const Expr * E,AccessKinds AK,QualType T)3486 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3487                                   QualType T) {
3488   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3489   if (!RD)
3490     return false;
3491 
3492   if (!RD->hasMutableFields())
3493     return false;
3494 
3495   for (auto *Field : RD->fields()) {
3496     // If we're actually going to read this field in some way, then it can't
3497     // be mutable. If we're in a union, then assigning to a mutable field
3498     // (even an empty one) can change the active member, so that's not OK.
3499     // FIXME: Add core issue number for the union case.
3500     if (Field->isMutable() &&
3501         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3502       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3503       Info.Note(Field->getLocation(), diag::note_declared_at);
3504       return true;
3505     }
3506 
3507     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3508       return true;
3509   }
3510 
3511   for (auto &BaseSpec : RD->bases())
3512     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3513       return true;
3514 
3515   // All mutable fields were empty, and thus not actually read.
3516   return false;
3517 }
3518 
lifetimeStartedInEvaluation(EvalInfo & Info,APValue::LValueBase Base,bool MutableSubobject=false)3519 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3520                                         APValue::LValueBase Base,
3521                                         bool MutableSubobject = false) {
3522   // A temporary or transient heap allocation we created.
3523   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3524     return true;
3525 
3526   switch (Info.IsEvaluatingDecl) {
3527   case EvalInfo::EvaluatingDeclKind::None:
3528     return false;
3529 
3530   case EvalInfo::EvaluatingDeclKind::Ctor:
3531     // The variable whose initializer we're evaluating.
3532     if (Info.EvaluatingDecl == Base)
3533       return true;
3534 
3535     // A temporary lifetime-extended by the variable whose initializer we're
3536     // evaluating.
3537     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3538       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3539         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3540     return false;
3541 
3542   case EvalInfo::EvaluatingDeclKind::Dtor:
3543     // C++2a [expr.const]p6:
3544     //   [during constant destruction] the lifetime of a and its non-mutable
3545     //   subobjects (but not its mutable subobjects) [are] considered to start
3546     //   within e.
3547     if (MutableSubobject || Base != Info.EvaluatingDecl)
3548       return false;
3549     // FIXME: We can meaningfully extend this to cover non-const objects, but
3550     // we will need special handling: we should be able to access only
3551     // subobjects of such objects that are themselves declared const.
3552     QualType T = getType(Base);
3553     return T.isConstQualified() || T->isReferenceType();
3554   }
3555 
3556   llvm_unreachable("unknown evaluating decl kind");
3557 }
3558 
3559 namespace {
3560 /// A handle to a complete object (an object that is not a subobject of
3561 /// another object).
3562 struct CompleteObject {
3563   /// The identity of the object.
3564   APValue::LValueBase Base;
3565   /// The value of the complete object.
3566   APValue *Value;
3567   /// The type of the complete object.
3568   QualType Type;
3569 
CompleteObject__anon7a1fdcea0911::CompleteObject3570   CompleteObject() : Value(nullptr) {}
CompleteObject__anon7a1fdcea0911::CompleteObject3571   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3572       : Base(Base), Value(Value), Type(Type) {}
3573 
mayAccessMutableMembers__anon7a1fdcea0911::CompleteObject3574   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3575     // If this isn't a "real" access (eg, if it's just accessing the type
3576     // info), allow it. We assume the type doesn't change dynamically for
3577     // subobjects of constexpr objects (even though we'd hit UB here if it
3578     // did). FIXME: Is this right?
3579     if (!isAnyAccess(AK))
3580       return true;
3581 
3582     // In C++14 onwards, it is permitted to read a mutable member whose
3583     // lifetime began within the evaluation.
3584     // FIXME: Should we also allow this in C++11?
3585     if (!Info.getLangOpts().CPlusPlus14)
3586       return false;
3587     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3588   }
3589 
operator bool__anon7a1fdcea0911::CompleteObject3590   explicit operator bool() const { return !Type.isNull(); }
3591 };
3592 } // end anonymous namespace
3593 
getSubobjectType(QualType ObjType,QualType SubobjType,bool IsMutable=false)3594 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3595                                  bool IsMutable = false) {
3596   // C++ [basic.type.qualifier]p1:
3597   // - A const object is an object of type const T or a non-mutable subobject
3598   //   of a const object.
3599   if (ObjType.isConstQualified() && !IsMutable)
3600     SubobjType.addConst();
3601   // - A volatile object is an object of type const T or a subobject of a
3602   //   volatile object.
3603   if (ObjType.isVolatileQualified())
3604     SubobjType.addVolatile();
3605   return SubobjType;
3606 }
3607 
3608 /// Find the designated sub-object of an rvalue.
3609 template<typename SubobjectHandler>
3610 typename SubobjectHandler::result_type
findSubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,SubobjectHandler & handler)3611 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3612               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3613   if (Sub.Invalid)
3614     // A diagnostic will have already been produced.
3615     return handler.failed();
3616   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3617     if (Info.getLangOpts().CPlusPlus11)
3618       Info.FFDiag(E, Sub.isOnePastTheEnd()
3619                          ? diag::note_constexpr_access_past_end
3620                          : diag::note_constexpr_access_unsized_array)
3621           << handler.AccessKind;
3622     else
3623       Info.FFDiag(E);
3624     return handler.failed();
3625   }
3626 
3627   APValue *O = Obj.Value;
3628   QualType ObjType = Obj.Type;
3629   const FieldDecl *LastField = nullptr;
3630   const FieldDecl *VolatileField = nullptr;
3631 
3632   // Walk the designator's path to find the subobject.
3633   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3634     // Reading an indeterminate value is undefined, but assigning over one is OK.
3635     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3636         (O->isIndeterminate() &&
3637          !isValidIndeterminateAccess(handler.AccessKind))) {
3638       if (!Info.checkingPotentialConstantExpression())
3639         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3640             << handler.AccessKind << O->isIndeterminate();
3641       return handler.failed();
3642     }
3643 
3644     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3645     //    const and volatile semantics are not applied on an object under
3646     //    {con,de}struction.
3647     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3648         ObjType->isRecordType() &&
3649         Info.isEvaluatingCtorDtor(
3650             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3651                                          Sub.Entries.begin() + I)) !=
3652                           ConstructionPhase::None) {
3653       ObjType = Info.Ctx.getCanonicalType(ObjType);
3654       ObjType.removeLocalConst();
3655       ObjType.removeLocalVolatile();
3656     }
3657 
3658     // If this is our last pass, check that the final object type is OK.
3659     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3660       // Accesses to volatile objects are prohibited.
3661       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3662         if (Info.getLangOpts().CPlusPlus) {
3663           int DiagKind;
3664           SourceLocation Loc;
3665           const NamedDecl *Decl = nullptr;
3666           if (VolatileField) {
3667             DiagKind = 2;
3668             Loc = VolatileField->getLocation();
3669             Decl = VolatileField;
3670           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3671             DiagKind = 1;
3672             Loc = VD->getLocation();
3673             Decl = VD;
3674           } else {
3675             DiagKind = 0;
3676             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3677               Loc = E->getExprLoc();
3678           }
3679           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3680               << handler.AccessKind << DiagKind << Decl;
3681           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3682         } else {
3683           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3684         }
3685         return handler.failed();
3686       }
3687 
3688       // If we are reading an object of class type, there may still be more
3689       // things we need to check: if there are any mutable subobjects, we
3690       // cannot perform this read. (This only happens when performing a trivial
3691       // copy or assignment.)
3692       if (ObjType->isRecordType() &&
3693           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3694           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3695         return handler.failed();
3696     }
3697 
3698     if (I == N) {
3699       if (!handler.found(*O, ObjType))
3700         return false;
3701 
3702       // If we modified a bit-field, truncate it to the right width.
3703       if (isModification(handler.AccessKind) &&
3704           LastField && LastField->isBitField() &&
3705           !truncateBitfieldValue(Info, E, *O, LastField))
3706         return false;
3707 
3708       return true;
3709     }
3710 
3711     LastField = nullptr;
3712     if (ObjType->isArrayType()) {
3713       // Next subobject is an array element.
3714       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3715       assert(CAT && "vla in literal type?");
3716       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3717       if (CAT->getSize().ule(Index)) {
3718         // Note, it should not be possible to form a pointer with a valid
3719         // designator which points more than one past the end of the array.
3720         if (Info.getLangOpts().CPlusPlus11)
3721           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3722             << handler.AccessKind;
3723         else
3724           Info.FFDiag(E);
3725         return handler.failed();
3726       }
3727 
3728       ObjType = CAT->getElementType();
3729 
3730       if (O->getArrayInitializedElts() > Index)
3731         O = &O->getArrayInitializedElt(Index);
3732       else if (!isRead(handler.AccessKind)) {
3733         expandArray(*O, Index);
3734         O = &O->getArrayInitializedElt(Index);
3735       } else
3736         O = &O->getArrayFiller();
3737     } else if (ObjType->isAnyComplexType()) {
3738       // Next subobject is a complex number.
3739       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3740       if (Index > 1) {
3741         if (Info.getLangOpts().CPlusPlus11)
3742           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3743             << handler.AccessKind;
3744         else
3745           Info.FFDiag(E);
3746         return handler.failed();
3747       }
3748 
3749       ObjType = getSubobjectType(
3750           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3751 
3752       assert(I == N - 1 && "extracting subobject of scalar?");
3753       if (O->isComplexInt()) {
3754         return handler.found(Index ? O->getComplexIntImag()
3755                                    : O->getComplexIntReal(), ObjType);
3756       } else {
3757         assert(O->isComplexFloat());
3758         return handler.found(Index ? O->getComplexFloatImag()
3759                                    : O->getComplexFloatReal(), ObjType);
3760       }
3761     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3762       if (Field->isMutable() &&
3763           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3764         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3765           << handler.AccessKind << Field;
3766         Info.Note(Field->getLocation(), diag::note_declared_at);
3767         return handler.failed();
3768       }
3769 
3770       // Next subobject is a class, struct or union field.
3771       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3772       if (RD->isUnion()) {
3773         const FieldDecl *UnionField = O->getUnionField();
3774         if (!UnionField ||
3775             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3776           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3777             // Placement new onto an inactive union member makes it active.
3778             O->setUnion(Field, APValue());
3779           } else {
3780             // FIXME: If O->getUnionValue() is absent, report that there's no
3781             // active union member rather than reporting the prior active union
3782             // member. We'll need to fix nullptr_t to not use APValue() as its
3783             // representation first.
3784             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3785                 << handler.AccessKind << Field << !UnionField << UnionField;
3786             return handler.failed();
3787           }
3788         }
3789         O = &O->getUnionValue();
3790       } else
3791         O = &O->getStructField(Field->getFieldIndex());
3792 
3793       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3794       LastField = Field;
3795       if (Field->getType().isVolatileQualified())
3796         VolatileField = Field;
3797     } else {
3798       // Next subobject is a base class.
3799       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3800       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3801       O = &O->getStructBase(getBaseIndex(Derived, Base));
3802 
3803       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3804     }
3805   }
3806 }
3807 
3808 namespace {
3809 struct ExtractSubobjectHandler {
3810   EvalInfo &Info;
3811   const Expr *E;
3812   APValue &Result;
3813   const AccessKinds AccessKind;
3814 
3815   typedef bool result_type;
failed__anon7a1fdcea0a11::ExtractSubobjectHandler3816   bool failed() { return false; }
found__anon7a1fdcea0a11::ExtractSubobjectHandler3817   bool found(APValue &Subobj, QualType SubobjType) {
3818     Result = Subobj;
3819     if (AccessKind == AK_ReadObjectRepresentation)
3820       return true;
3821     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3822   }
found__anon7a1fdcea0a11::ExtractSubobjectHandler3823   bool found(APSInt &Value, QualType SubobjType) {
3824     Result = APValue(Value);
3825     return true;
3826   }
found__anon7a1fdcea0a11::ExtractSubobjectHandler3827   bool found(APFloat &Value, QualType SubobjType) {
3828     Result = APValue(Value);
3829     return true;
3830   }
3831 };
3832 } // end anonymous namespace
3833 
3834 /// 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)3835 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3836                              const CompleteObject &Obj,
3837                              const SubobjectDesignator &Sub, APValue &Result,
3838                              AccessKinds AK = AK_Read) {
3839   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3840   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3841   return findSubobject(Info, E, Obj, Sub, Handler);
3842 }
3843 
3844 namespace {
3845 struct ModifySubobjectHandler {
3846   EvalInfo &Info;
3847   APValue &NewVal;
3848   const Expr *E;
3849 
3850   typedef bool result_type;
3851   static const AccessKinds AccessKind = AK_Assign;
3852 
checkConst__anon7a1fdcea0b11::ModifySubobjectHandler3853   bool checkConst(QualType QT) {
3854     // Assigning to a const object has undefined behavior.
3855     if (QT.isConstQualified()) {
3856       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3857       return false;
3858     }
3859     return true;
3860   }
3861 
failed__anon7a1fdcea0b11::ModifySubobjectHandler3862   bool failed() { return false; }
found__anon7a1fdcea0b11::ModifySubobjectHandler3863   bool found(APValue &Subobj, QualType SubobjType) {
3864     if (!checkConst(SubobjType))
3865       return false;
3866     // We've been given ownership of NewVal, so just swap it in.
3867     Subobj.swap(NewVal);
3868     return true;
3869   }
found__anon7a1fdcea0b11::ModifySubobjectHandler3870   bool found(APSInt &Value, QualType SubobjType) {
3871     if (!checkConst(SubobjType))
3872       return false;
3873     if (!NewVal.isInt()) {
3874       // Maybe trying to write a cast pointer value into a complex?
3875       Info.FFDiag(E);
3876       return false;
3877     }
3878     Value = NewVal.getInt();
3879     return true;
3880   }
found__anon7a1fdcea0b11::ModifySubobjectHandler3881   bool found(APFloat &Value, QualType SubobjType) {
3882     if (!checkConst(SubobjType))
3883       return false;
3884     Value = NewVal.getFloat();
3885     return true;
3886   }
3887 };
3888 } // end anonymous namespace
3889 
3890 const AccessKinds ModifySubobjectHandler::AccessKind;
3891 
3892 /// 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)3893 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3894                             const CompleteObject &Obj,
3895                             const SubobjectDesignator &Sub,
3896                             APValue &NewVal) {
3897   ModifySubobjectHandler Handler = { Info, NewVal, E };
3898   return findSubobject(Info, E, Obj, Sub, Handler);
3899 }
3900 
3901 /// Find the position where two subobject designators diverge, or equivalently
3902 /// the length of the common initial subsequence.
FindDesignatorMismatch(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B,bool & WasArrayIndex)3903 static unsigned FindDesignatorMismatch(QualType ObjType,
3904                                        const SubobjectDesignator &A,
3905                                        const SubobjectDesignator &B,
3906                                        bool &WasArrayIndex) {
3907   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3908   for (/**/; I != N; ++I) {
3909     if (!ObjType.isNull() &&
3910         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3911       // Next subobject is an array element.
3912       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3913         WasArrayIndex = true;
3914         return I;
3915       }
3916       if (ObjType->isAnyComplexType())
3917         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3918       else
3919         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3920     } else {
3921       if (A.Entries[I].getAsBaseOrMember() !=
3922           B.Entries[I].getAsBaseOrMember()) {
3923         WasArrayIndex = false;
3924         return I;
3925       }
3926       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3927         // Next subobject is a field.
3928         ObjType = FD->getType();
3929       else
3930         // Next subobject is a base class.
3931         ObjType = QualType();
3932     }
3933   }
3934   WasArrayIndex = false;
3935   return I;
3936 }
3937 
3938 /// Determine whether the given subobject designators refer to elements of the
3939 /// same array object.
AreElementsOfSameArray(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B)3940 static bool AreElementsOfSameArray(QualType ObjType,
3941                                    const SubobjectDesignator &A,
3942                                    const SubobjectDesignator &B) {
3943   if (A.Entries.size() != B.Entries.size())
3944     return false;
3945 
3946   bool IsArray = A.MostDerivedIsArrayElement;
3947   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3948     // A is a subobject of the array element.
3949     return false;
3950 
3951   // If A (and B) designates an array element, the last entry will be the array
3952   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3953   // of length 1' case, and the entire path must match.
3954   bool WasArrayIndex;
3955   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3956   return CommonLength >= A.Entries.size() - IsArray;
3957 }
3958 
3959 /// Find the complete object to which an LValue refers.
findCompleteObject(EvalInfo & Info,const Expr * E,AccessKinds AK,const LValue & LVal,QualType LValType)3960 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3961                                          AccessKinds AK, const LValue &LVal,
3962                                          QualType LValType) {
3963   if (LVal.InvalidBase) {
3964     Info.FFDiag(E);
3965     return CompleteObject();
3966   }
3967 
3968   if (!LVal.Base) {
3969     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3970     return CompleteObject();
3971   }
3972 
3973   CallStackFrame *Frame = nullptr;
3974   unsigned Depth = 0;
3975   if (LVal.getLValueCallIndex()) {
3976     std::tie(Frame, Depth) =
3977         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3978     if (!Frame) {
3979       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3980         << AK << LVal.Base.is<const ValueDecl*>();
3981       NoteLValueLocation(Info, LVal.Base);
3982       return CompleteObject();
3983     }
3984   }
3985 
3986   bool IsAccess = isAnyAccess(AK);
3987 
3988   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3989   // is not a constant expression (even if the object is non-volatile). We also
3990   // apply this rule to C++98, in order to conform to the expected 'volatile'
3991   // semantics.
3992   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3993     if (Info.getLangOpts().CPlusPlus)
3994       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3995         << AK << LValType;
3996     else
3997       Info.FFDiag(E);
3998     return CompleteObject();
3999   }
4000 
4001   // Compute value storage location and type of base object.
4002   APValue *BaseVal = nullptr;
4003   QualType BaseType = getType(LVal.Base);
4004 
4005   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4006       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4007     // This is the object whose initializer we're evaluating, so its lifetime
4008     // started in the current evaluation.
4009     BaseVal = Info.EvaluatingDeclValue;
4010   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4011     // Allow reading from a GUID declaration.
4012     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4013       if (isModification(AK)) {
4014         // All the remaining cases do not permit modification of the object.
4015         Info.FFDiag(E, diag::note_constexpr_modify_global);
4016         return CompleteObject();
4017       }
4018       APValue &V = GD->getAsAPValue();
4019       if (V.isAbsent()) {
4020         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4021             << GD->getType();
4022         return CompleteObject();
4023       }
4024       return CompleteObject(LVal.Base, &V, GD->getType());
4025     }
4026 
4027     // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4028     if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4029       if (isModification(AK)) {
4030         Info.FFDiag(E, diag::note_constexpr_modify_global);
4031         return CompleteObject();
4032       }
4033       return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4034                             GCD->getType());
4035     }
4036 
4037     // Allow reading from template parameter objects.
4038     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4039       if (isModification(AK)) {
4040         Info.FFDiag(E, diag::note_constexpr_modify_global);
4041         return CompleteObject();
4042       }
4043       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4044                             TPO->getType());
4045     }
4046 
4047     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4048     // In C++11, constexpr, non-volatile variables initialized with constant
4049     // expressions are constant expressions too. Inside constexpr functions,
4050     // parameters are constant expressions even if they're non-const.
4051     // In C++1y, objects local to a constant expression (those with a Frame) are
4052     // both readable and writable inside constant expressions.
4053     // In C, such things can also be folded, although they are not ICEs.
4054     const VarDecl *VD = dyn_cast<VarDecl>(D);
4055     if (VD) {
4056       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4057         VD = VDef;
4058     }
4059     if (!VD || VD->isInvalidDecl()) {
4060       Info.FFDiag(E);
4061       return CompleteObject();
4062     }
4063 
4064     bool IsConstant = BaseType.isConstant(Info.Ctx);
4065 
4066     // Unless we're looking at a local variable or argument in a constexpr call,
4067     // the variable we're reading must be const.
4068     if (!Frame) {
4069       if (IsAccess && isa<ParmVarDecl>(VD)) {
4070         // Access of a parameter that's not associated with a frame isn't going
4071         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4072         // suitable diagnostic.
4073       } else if (Info.getLangOpts().CPlusPlus14 &&
4074                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4075         // OK, we can read and modify an object if we're in the process of
4076         // evaluating its initializer, because its lifetime began in this
4077         // evaluation.
4078       } else 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       } else if (VD->isConstexpr()) {
4083         // OK, we can read this variable.
4084       } else if (BaseType->isIntegralOrEnumerationType()) {
4085         if (!IsConstant) {
4086           if (!IsAccess)
4087             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4088           if (Info.getLangOpts().CPlusPlus) {
4089             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4090             Info.Note(VD->getLocation(), diag::note_declared_at);
4091           } else {
4092             Info.FFDiag(E);
4093           }
4094           return CompleteObject();
4095         }
4096       } else if (!IsAccess) {
4097         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4098       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4099                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4100         // This variable might end up being constexpr. Don't diagnose it yet.
4101       } else if (IsConstant) {
4102         // Keep evaluating to see what we can do. In particular, we support
4103         // folding of const floating-point types, in order to make static const
4104         // data members of such types (supported as an extension) more useful.
4105         if (Info.getLangOpts().CPlusPlus) {
4106           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4107                               ? diag::note_constexpr_ltor_non_constexpr
4108                               : diag::note_constexpr_ltor_non_integral, 1)
4109               << VD << BaseType;
4110           Info.Note(VD->getLocation(), diag::note_declared_at);
4111         } else {
4112           Info.CCEDiag(E);
4113         }
4114       } else {
4115         // Never allow reading a non-const value.
4116         if (Info.getLangOpts().CPlusPlus) {
4117           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4118                              ? diag::note_constexpr_ltor_non_constexpr
4119                              : diag::note_constexpr_ltor_non_integral, 1)
4120               << VD << BaseType;
4121           Info.Note(VD->getLocation(), diag::note_declared_at);
4122         } else {
4123           Info.FFDiag(E);
4124         }
4125         return CompleteObject();
4126       }
4127     }
4128 
4129     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4130       return CompleteObject();
4131   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4132     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4133     if (!Alloc) {
4134       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4135       return CompleteObject();
4136     }
4137     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4138                           LVal.Base.getDynamicAllocType());
4139   } else {
4140     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4141 
4142     if (!Frame) {
4143       if (const MaterializeTemporaryExpr *MTE =
4144               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4145         assert(MTE->getStorageDuration() == SD_Static &&
4146                "should have a frame for a non-global materialized temporary");
4147 
4148         // C++20 [expr.const]p4: [DR2126]
4149         //   An object or reference is usable in constant expressions if it is
4150         //   - a temporary object of non-volatile const-qualified literal type
4151         //     whose lifetime is extended to that of a variable that is usable
4152         //     in constant expressions
4153         //
4154         // C++20 [expr.const]p5:
4155         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4156         //   - a non-volatile glvalue that refers to an object that is usable
4157         //     in constant expressions, or
4158         //   - a non-volatile glvalue of literal type that refers to a
4159         //     non-volatile object whose lifetime began within the evaluation
4160         //     of E;
4161         //
4162         // C++11 misses the 'began within the evaluation of e' check and
4163         // instead allows all temporaries, including things like:
4164         //   int &&r = 1;
4165         //   int x = ++r;
4166         //   constexpr int k = r;
4167         // Therefore we use the C++14-onwards rules in C++11 too.
4168         //
4169         // Note that temporaries whose lifetimes began while evaluating a
4170         // variable's constructor are not usable while evaluating the
4171         // corresponding destructor, not even if they're of const-qualified
4172         // types.
4173         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4174             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4175           if (!IsAccess)
4176             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4177           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4178           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4179           return CompleteObject();
4180         }
4181 
4182         BaseVal = MTE->getOrCreateValue(false);
4183         assert(BaseVal && "got reference to unevaluated temporary");
4184       } else {
4185         if (!IsAccess)
4186           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4187         APValue Val;
4188         LVal.moveInto(Val);
4189         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4190             << AK
4191             << Val.getAsString(Info.Ctx,
4192                                Info.Ctx.getLValueReferenceType(LValType));
4193         NoteLValueLocation(Info, LVal.Base);
4194         return CompleteObject();
4195       }
4196     } else {
4197       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4198       assert(BaseVal && "missing value for temporary");
4199     }
4200   }
4201 
4202   // In C++14, we can't safely access any mutable state when we might be
4203   // evaluating after an unmodeled side effect. Parameters are modeled as state
4204   // in the caller, but aren't visible once the call returns, so they can be
4205   // modified in a speculatively-evaluated call.
4206   //
4207   // FIXME: Not all local state is mutable. Allow local constant subobjects
4208   // to be read here (but take care with 'mutable' fields).
4209   unsigned VisibleDepth = Depth;
4210   if (llvm::isa_and_nonnull<ParmVarDecl>(
4211           LVal.Base.dyn_cast<const ValueDecl *>()))
4212     ++VisibleDepth;
4213   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4214        Info.EvalStatus.HasSideEffects) ||
4215       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4216     return CompleteObject();
4217 
4218   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4219 }
4220 
4221 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4222 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4223 /// glvalue referred to by an entity of reference type.
4224 ///
4225 /// \param Info - Information about the ongoing evaluation.
4226 /// \param Conv - The expression for which we are performing the conversion.
4227 ///               Used for diagnostics.
4228 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4229 ///               case of a non-class type).
4230 /// \param LVal - The glvalue on which we are attempting to perform this action.
4231 /// \param RVal - The produced value will be placed here.
4232 /// \param WantObjectRepresentation - If true, we're looking for the object
4233 ///               representation rather than the value, and in particular,
4234 ///               there is no requirement that the result be fully initialized.
4235 static bool
handleLValueToRValueConversion(EvalInfo & Info,const Expr * Conv,QualType Type,const LValue & LVal,APValue & RVal,bool WantObjectRepresentation=false)4236 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4237                                const LValue &LVal, APValue &RVal,
4238                                bool WantObjectRepresentation = false) {
4239   if (LVal.Designator.Invalid)
4240     return false;
4241 
4242   // Check for special cases where there is no existing APValue to look at.
4243   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4244 
4245   AccessKinds AK =
4246       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4247 
4248   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4249     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4250       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4251       // initializer until now for such expressions. Such an expression can't be
4252       // an ICE in C, so this only matters for fold.
4253       if (Type.isVolatileQualified()) {
4254         Info.FFDiag(Conv);
4255         return false;
4256       }
4257 
4258       APValue Lit;
4259       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4260         return false;
4261 
4262       // According to GCC info page:
4263       //
4264       // 6.28 Compound Literals
4265       //
4266       // As an optimization, G++ sometimes gives array compound literals longer
4267       // lifetimes: when the array either appears outside a function or has a
4268       // const-qualified type. If foo and its initializer had elements of type
4269       // char *const rather than char *, or if foo were a global variable, the
4270       // array would have static storage duration. But it is probably safest
4271       // just to avoid the use of array compound literals in C++ code.
4272       //
4273       // Obey that rule by checking constness for converted array types.
4274 
4275       QualType CLETy = CLE->getType();
4276       if (CLETy->isArrayType() && !Type->isArrayType()) {
4277         if (!CLETy.isConstant(Info.Ctx)) {
4278           Info.FFDiag(Conv);
4279           Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4280           return false;
4281         }
4282       }
4283 
4284       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4285       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4286     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4287       // Special-case character extraction so we don't have to construct an
4288       // APValue for the whole string.
4289       assert(LVal.Designator.Entries.size() <= 1 &&
4290              "Can only read characters from string literals");
4291       if (LVal.Designator.Entries.empty()) {
4292         // Fail for now for LValue to RValue conversion of an array.
4293         // (This shouldn't show up in C/C++, but it could be triggered by a
4294         // weird EvaluateAsRValue call from a tool.)
4295         Info.FFDiag(Conv);
4296         return false;
4297       }
4298       if (LVal.Designator.isOnePastTheEnd()) {
4299         if (Info.getLangOpts().CPlusPlus11)
4300           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4301         else
4302           Info.FFDiag(Conv);
4303         return false;
4304       }
4305       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4306       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4307       return true;
4308     }
4309   }
4310 
4311   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4312   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4313 }
4314 
4315 /// Perform an assignment of Val to LVal. Takes ownership of Val.
handleAssignment(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,APValue & Val)4316 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4317                              QualType LValType, APValue &Val) {
4318   if (LVal.Designator.Invalid)
4319     return false;
4320 
4321   if (!Info.getLangOpts().CPlusPlus14) {
4322     Info.FFDiag(E);
4323     return false;
4324   }
4325 
4326   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4327   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4328 }
4329 
4330 namespace {
4331 struct CompoundAssignSubobjectHandler {
4332   EvalInfo &Info;
4333   const CompoundAssignOperator *E;
4334   QualType PromotedLHSType;
4335   BinaryOperatorKind Opcode;
4336   const APValue &RHS;
4337 
4338   static const AccessKinds AccessKind = AK_Assign;
4339 
4340   typedef bool result_type;
4341 
checkConst__anon7a1fdcea0c11::CompoundAssignSubobjectHandler4342   bool checkConst(QualType QT) {
4343     // Assigning to a const object has undefined behavior.
4344     if (QT.isConstQualified()) {
4345       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4346       return false;
4347     }
4348     return true;
4349   }
4350 
failed__anon7a1fdcea0c11::CompoundAssignSubobjectHandler4351   bool failed() { return false; }
found__anon7a1fdcea0c11::CompoundAssignSubobjectHandler4352   bool found(APValue &Subobj, QualType SubobjType) {
4353     switch (Subobj.getKind()) {
4354     case APValue::Int:
4355       return found(Subobj.getInt(), SubobjType);
4356     case APValue::Float:
4357       return found(Subobj.getFloat(), SubobjType);
4358     case APValue::ComplexInt:
4359     case APValue::ComplexFloat:
4360       // FIXME: Implement complex compound assignment.
4361       Info.FFDiag(E);
4362       return false;
4363     case APValue::LValue:
4364       return foundPointer(Subobj, SubobjType);
4365     case APValue::Vector:
4366       return foundVector(Subobj, SubobjType);
4367     default:
4368       // FIXME: can this happen?
4369       Info.FFDiag(E);
4370       return false;
4371     }
4372   }
4373 
foundVector__anon7a1fdcea0c11::CompoundAssignSubobjectHandler4374   bool foundVector(APValue &Value, QualType SubobjType) {
4375     if (!checkConst(SubobjType))
4376       return false;
4377 
4378     if (!SubobjType->isVectorType()) {
4379       Info.FFDiag(E);
4380       return false;
4381     }
4382     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4383   }
4384 
found__anon7a1fdcea0c11::CompoundAssignSubobjectHandler4385   bool found(APSInt &Value, QualType SubobjType) {
4386     if (!checkConst(SubobjType))
4387       return false;
4388 
4389     if (!SubobjType->isIntegerType()) {
4390       // We don't support compound assignment on integer-cast-to-pointer
4391       // values.
4392       Info.FFDiag(E);
4393       return false;
4394     }
4395 
4396     if (RHS.isInt()) {
4397       APSInt LHS =
4398           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4399       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4400         return false;
4401       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4402       return true;
4403     } else if (RHS.isFloat()) {
4404       const FPOptions FPO = E->getFPFeaturesInEffect(
4405                                     Info.Ctx.getLangOpts());
4406       APFloat FValue(0.0);
4407       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4408                                   PromotedLHSType, FValue) &&
4409              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4410              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4411                                   Value);
4412     }
4413 
4414     Info.FFDiag(E);
4415     return false;
4416   }
found__anon7a1fdcea0c11::CompoundAssignSubobjectHandler4417   bool found(APFloat &Value, QualType SubobjType) {
4418     return checkConst(SubobjType) &&
4419            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4420                                   Value) &&
4421            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4422            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4423   }
foundPointer__anon7a1fdcea0c11::CompoundAssignSubobjectHandler4424   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4425     if (!checkConst(SubobjType))
4426       return false;
4427 
4428     QualType PointeeType;
4429     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4430       PointeeType = PT->getPointeeType();
4431 
4432     if (PointeeType.isNull() || !RHS.isInt() ||
4433         (Opcode != BO_Add && Opcode != BO_Sub)) {
4434       Info.FFDiag(E);
4435       return false;
4436     }
4437 
4438     APSInt Offset = RHS.getInt();
4439     if (Opcode == BO_Sub)
4440       negateAsSigned(Offset);
4441 
4442     LValue LVal;
4443     LVal.setFrom(Info.Ctx, Subobj);
4444     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4445       return false;
4446     LVal.moveInto(Subobj);
4447     return true;
4448   }
4449 };
4450 } // end anonymous namespace
4451 
4452 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4453 
4454 /// 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)4455 static bool handleCompoundAssignment(EvalInfo &Info,
4456                                      const CompoundAssignOperator *E,
4457                                      const LValue &LVal, QualType LValType,
4458                                      QualType PromotedLValType,
4459                                      BinaryOperatorKind Opcode,
4460                                      const APValue &RVal) {
4461   if (LVal.Designator.Invalid)
4462     return false;
4463 
4464   if (!Info.getLangOpts().CPlusPlus14) {
4465     Info.FFDiag(E);
4466     return false;
4467   }
4468 
4469   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4470   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4471                                              RVal };
4472   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4473 }
4474 
4475 namespace {
4476 struct IncDecSubobjectHandler {
4477   EvalInfo &Info;
4478   const UnaryOperator *E;
4479   AccessKinds AccessKind;
4480   APValue *Old;
4481 
4482   typedef bool result_type;
4483 
checkConst__anon7a1fdcea0d11::IncDecSubobjectHandler4484   bool checkConst(QualType QT) {
4485     // Assigning to a const object has undefined behavior.
4486     if (QT.isConstQualified()) {
4487       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4488       return false;
4489     }
4490     return true;
4491   }
4492 
failed__anon7a1fdcea0d11::IncDecSubobjectHandler4493   bool failed() { return false; }
found__anon7a1fdcea0d11::IncDecSubobjectHandler4494   bool found(APValue &Subobj, QualType SubobjType) {
4495     // Stash the old value. Also clear Old, so we don't clobber it later
4496     // if we're post-incrementing a complex.
4497     if (Old) {
4498       *Old = Subobj;
4499       Old = nullptr;
4500     }
4501 
4502     switch (Subobj.getKind()) {
4503     case APValue::Int:
4504       return found(Subobj.getInt(), SubobjType);
4505     case APValue::Float:
4506       return found(Subobj.getFloat(), SubobjType);
4507     case APValue::ComplexInt:
4508       return found(Subobj.getComplexIntReal(),
4509                    SubobjType->castAs<ComplexType>()->getElementType()
4510                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4511     case APValue::ComplexFloat:
4512       return found(Subobj.getComplexFloatReal(),
4513                    SubobjType->castAs<ComplexType>()->getElementType()
4514                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4515     case APValue::LValue:
4516       return foundPointer(Subobj, SubobjType);
4517     default:
4518       // FIXME: can this happen?
4519       Info.FFDiag(E);
4520       return false;
4521     }
4522   }
found__anon7a1fdcea0d11::IncDecSubobjectHandler4523   bool found(APSInt &Value, QualType SubobjType) {
4524     if (!checkConst(SubobjType))
4525       return false;
4526 
4527     if (!SubobjType->isIntegerType()) {
4528       // We don't support increment / decrement on integer-cast-to-pointer
4529       // values.
4530       Info.FFDiag(E);
4531       return false;
4532     }
4533 
4534     if (Old) *Old = APValue(Value);
4535 
4536     // bool arithmetic promotes to int, and the conversion back to bool
4537     // doesn't reduce mod 2^n, so special-case it.
4538     if (SubobjType->isBooleanType()) {
4539       if (AccessKind == AK_Increment)
4540         Value = 1;
4541       else
4542         Value = !Value;
4543       return true;
4544     }
4545 
4546     bool WasNegative = Value.isNegative();
4547     if (AccessKind == AK_Increment) {
4548       ++Value;
4549 
4550       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4551         APSInt ActualValue(Value, /*IsUnsigned*/true);
4552         return HandleOverflow(Info, E, ActualValue, SubobjType);
4553       }
4554     } else {
4555       --Value;
4556 
4557       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4558         unsigned BitWidth = Value.getBitWidth();
4559         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4560         ActualValue.setBit(BitWidth);
4561         return HandleOverflow(Info, E, ActualValue, SubobjType);
4562       }
4563     }
4564     return true;
4565   }
found__anon7a1fdcea0d11::IncDecSubobjectHandler4566   bool found(APFloat &Value, QualType SubobjType) {
4567     if (!checkConst(SubobjType))
4568       return false;
4569 
4570     if (Old) *Old = APValue(Value);
4571 
4572     APFloat One(Value.getSemantics(), 1);
4573     if (AccessKind == AK_Increment)
4574       Value.add(One, APFloat::rmNearestTiesToEven);
4575     else
4576       Value.subtract(One, APFloat::rmNearestTiesToEven);
4577     return true;
4578   }
foundPointer__anon7a1fdcea0d11::IncDecSubobjectHandler4579   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4580     if (!checkConst(SubobjType))
4581       return false;
4582 
4583     QualType PointeeType;
4584     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4585       PointeeType = PT->getPointeeType();
4586     else {
4587       Info.FFDiag(E);
4588       return false;
4589     }
4590 
4591     LValue LVal;
4592     LVal.setFrom(Info.Ctx, Subobj);
4593     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4594                                      AccessKind == AK_Increment ? 1 : -1))
4595       return false;
4596     LVal.moveInto(Subobj);
4597     return true;
4598   }
4599 };
4600 } // end anonymous namespace
4601 
4602 /// Perform an increment or decrement on LVal.
handleIncDec(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,bool IsIncrement,APValue * Old)4603 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4604                          QualType LValType, bool IsIncrement, APValue *Old) {
4605   if (LVal.Designator.Invalid)
4606     return false;
4607 
4608   if (!Info.getLangOpts().CPlusPlus14) {
4609     Info.FFDiag(E);
4610     return false;
4611   }
4612 
4613   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4614   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4615   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4616   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4617 }
4618 
4619 /// Build an lvalue for the object argument of a member function call.
EvaluateObjectArgument(EvalInfo & Info,const Expr * Object,LValue & This)4620 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4621                                    LValue &This) {
4622   if (Object->getType()->isPointerType() && Object->isPRValue())
4623     return EvaluatePointer(Object, This, Info);
4624 
4625   if (Object->isGLValue())
4626     return EvaluateLValue(Object, This, Info);
4627 
4628   if (Object->getType()->isLiteralType(Info.Ctx))
4629     return EvaluateTemporary(Object, This, Info);
4630 
4631   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4632   return false;
4633 }
4634 
4635 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4636 /// lvalue referring to the result.
4637 ///
4638 /// \param Info - Information about the ongoing evaluation.
4639 /// \param LV - An lvalue referring to the base of the member pointer.
4640 /// \param RHS - The member pointer expression.
4641 /// \param IncludeMember - Specifies whether the member itself is included in
4642 ///        the resulting LValue subobject designator. This is not possible when
4643 ///        creating a bound member function.
4644 /// \return The field or method declaration to which the member pointer refers,
4645 ///         or 0 if evaluation fails.
HandleMemberPointerAccess(EvalInfo & Info,QualType LVType,LValue & LV,const Expr * RHS,bool IncludeMember=true)4646 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4647                                                   QualType LVType,
4648                                                   LValue &LV,
4649                                                   const Expr *RHS,
4650                                                   bool IncludeMember = true) {
4651   MemberPtr MemPtr;
4652   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4653     return nullptr;
4654 
4655   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4656   // member value, the behavior is undefined.
4657   if (!MemPtr.getDecl()) {
4658     // FIXME: Specific diagnostic.
4659     Info.FFDiag(RHS);
4660     return nullptr;
4661   }
4662 
4663   if (MemPtr.isDerivedMember()) {
4664     // This is a member of some derived class. Truncate LV appropriately.
4665     // The end of the derived-to-base path for the base object must match the
4666     // derived-to-base path for the member pointer.
4667     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4668         LV.Designator.Entries.size()) {
4669       Info.FFDiag(RHS);
4670       return nullptr;
4671     }
4672     unsigned PathLengthToMember =
4673         LV.Designator.Entries.size() - MemPtr.Path.size();
4674     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4675       const CXXRecordDecl *LVDecl = getAsBaseClass(
4676           LV.Designator.Entries[PathLengthToMember + I]);
4677       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4678       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4679         Info.FFDiag(RHS);
4680         return nullptr;
4681       }
4682     }
4683 
4684     // Truncate the lvalue to the appropriate derived class.
4685     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4686                             PathLengthToMember))
4687       return nullptr;
4688   } else if (!MemPtr.Path.empty()) {
4689     // Extend the LValue path with the member pointer's path.
4690     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4691                                   MemPtr.Path.size() + IncludeMember);
4692 
4693     // Walk down to the appropriate base class.
4694     if (const PointerType *PT = LVType->getAs<PointerType>())
4695       LVType = PT->getPointeeType();
4696     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4697     assert(RD && "member pointer access on non-class-type expression");
4698     // The first class in the path is that of the lvalue.
4699     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4700       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4701       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4702         return nullptr;
4703       RD = Base;
4704     }
4705     // Finally cast to the class containing the member.
4706     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4707                                 MemPtr.getContainingRecord()))
4708       return nullptr;
4709   }
4710 
4711   // Add the member. Note that we cannot build bound member functions here.
4712   if (IncludeMember) {
4713     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4714       if (!HandleLValueMember(Info, RHS, LV, FD))
4715         return nullptr;
4716     } else if (const IndirectFieldDecl *IFD =
4717                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4718       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4719         return nullptr;
4720     } else {
4721       llvm_unreachable("can't construct reference to bound member function");
4722     }
4723   }
4724 
4725   return MemPtr.getDecl();
4726 }
4727 
HandleMemberPointerAccess(EvalInfo & Info,const BinaryOperator * BO,LValue & LV,bool IncludeMember=true)4728 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4729                                                   const BinaryOperator *BO,
4730                                                   LValue &LV,
4731                                                   bool IncludeMember = true) {
4732   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4733 
4734   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4735     if (Info.noteFailure()) {
4736       MemberPtr MemPtr;
4737       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4738     }
4739     return nullptr;
4740   }
4741 
4742   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4743                                    BO->getRHS(), IncludeMember);
4744 }
4745 
4746 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4747 /// the provided lvalue, which currently refers to the base object.
HandleBaseToDerivedCast(EvalInfo & Info,const CastExpr * E,LValue & Result)4748 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4749                                     LValue &Result) {
4750   SubobjectDesignator &D = Result.Designator;
4751   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4752     return false;
4753 
4754   QualType TargetQT = E->getType();
4755   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4756     TargetQT = PT->getPointeeType();
4757 
4758   // Check this cast lands within the final derived-to-base subobject path.
4759   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4760     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4761       << D.MostDerivedType << TargetQT;
4762     return false;
4763   }
4764 
4765   // Check the type of the final cast. We don't need to check the path,
4766   // since a cast can only be formed if the path is unique.
4767   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4768   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4769   const CXXRecordDecl *FinalType;
4770   if (NewEntriesSize == D.MostDerivedPathLength)
4771     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4772   else
4773     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4774   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4775     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4776       << D.MostDerivedType << TargetQT;
4777     return false;
4778   }
4779 
4780   // Truncate the lvalue to the appropriate derived class.
4781   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4782 }
4783 
4784 /// Get the value to use for a default-initialized object of type T.
4785 /// Return false if it encounters something invalid.
getDefaultInitValue(QualType T,APValue & Result)4786 static bool getDefaultInitValue(QualType T, APValue &Result) {
4787   bool Success = true;
4788   if (auto *RD = T->getAsCXXRecordDecl()) {
4789     if (RD->isInvalidDecl()) {
4790       Result = APValue();
4791       return false;
4792     }
4793     if (RD->isUnion()) {
4794       Result = APValue((const FieldDecl *)nullptr);
4795       return true;
4796     }
4797     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4798                      std::distance(RD->field_begin(), RD->field_end()));
4799 
4800     unsigned Index = 0;
4801     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4802                                                   End = RD->bases_end();
4803          I != End; ++I, ++Index)
4804       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4805 
4806     for (const auto *I : RD->fields()) {
4807       if (I->isUnnamedBitfield())
4808         continue;
4809       Success &= getDefaultInitValue(I->getType(),
4810                                      Result.getStructField(I->getFieldIndex()));
4811     }
4812     return Success;
4813   }
4814 
4815   if (auto *AT =
4816           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4817     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4818     if (Result.hasArrayFiller())
4819       Success &=
4820           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4821 
4822     return Success;
4823   }
4824 
4825   Result = APValue::IndeterminateValue();
4826   return true;
4827 }
4828 
4829 namespace {
4830 enum EvalStmtResult {
4831   /// Evaluation failed.
4832   ESR_Failed,
4833   /// Hit a 'return' statement.
4834   ESR_Returned,
4835   /// Evaluation succeeded.
4836   ESR_Succeeded,
4837   /// Hit a 'continue' statement.
4838   ESR_Continue,
4839   /// Hit a 'break' statement.
4840   ESR_Break,
4841   /// Still scanning for 'case' or 'default' statement.
4842   ESR_CaseNotFound
4843 };
4844 }
4845 
EvaluateVarDecl(EvalInfo & Info,const VarDecl * VD)4846 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4847   // We don't need to evaluate the initializer for a static local.
4848   if (!VD->hasLocalStorage())
4849     return true;
4850 
4851   LValue Result;
4852   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4853                                                    ScopeKind::Block, Result);
4854 
4855   const Expr *InitE = VD->getInit();
4856   if (!InitE) {
4857     if (VD->getType()->isDependentType())
4858       return Info.noteSideEffect();
4859     return getDefaultInitValue(VD->getType(), Val);
4860   }
4861   if (InitE->isValueDependent())
4862     return false;
4863 
4864   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4865     // Wipe out any partially-computed value, to allow tracking that this
4866     // evaluation failed.
4867     Val = APValue();
4868     return false;
4869   }
4870 
4871   return true;
4872 }
4873 
EvaluateDecl(EvalInfo & Info,const Decl * D)4874 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4875   bool OK = true;
4876 
4877   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4878     OK &= EvaluateVarDecl(Info, VD);
4879 
4880   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4881     for (auto *BD : DD->bindings())
4882       if (auto *VD = BD->getHoldingVar())
4883         OK &= EvaluateDecl(Info, VD);
4884 
4885   return OK;
4886 }
4887 
EvaluateDependentExpr(const Expr * E,EvalInfo & Info)4888 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4889   assert(E->isValueDependent());
4890   if (Info.noteSideEffect())
4891     return true;
4892   assert(E->containsErrors() && "valid value-dependent expression should never "
4893                                 "reach invalid code path.");
4894   return false;
4895 }
4896 
4897 /// Evaluate a condition (either a variable declaration or an expression).
EvaluateCond(EvalInfo & Info,const VarDecl * CondDecl,const Expr * Cond,bool & Result)4898 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4899                          const Expr *Cond, bool &Result) {
4900   if (Cond->isValueDependent())
4901     return false;
4902   FullExpressionRAII Scope(Info);
4903   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4904     return false;
4905   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4906     return false;
4907   return Scope.destroy();
4908 }
4909 
4910 namespace {
4911 /// A location where the result (returned value) of evaluating a
4912 /// statement should be stored.
4913 struct StmtResult {
4914   /// The APValue that should be filled in with the returned value.
4915   APValue &Value;
4916   /// The location containing the result, if any (used to support RVO).
4917   const LValue *Slot;
4918 };
4919 
4920 struct TempVersionRAII {
4921   CallStackFrame &Frame;
4922 
TempVersionRAII__anon7a1fdcea0f11::TempVersionRAII4923   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4924     Frame.pushTempVersion();
4925   }
4926 
~TempVersionRAII__anon7a1fdcea0f11::TempVersionRAII4927   ~TempVersionRAII() {
4928     Frame.popTempVersion();
4929   }
4930 };
4931 
4932 }
4933 
4934 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4935                                    const Stmt *S,
4936                                    const SwitchCase *SC = nullptr);
4937 
4938 /// Evaluate the body of a loop, and translate the result as appropriate.
EvaluateLoopBody(StmtResult & Result,EvalInfo & Info,const Stmt * Body,const SwitchCase * Case=nullptr)4939 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4940                                        const Stmt *Body,
4941                                        const SwitchCase *Case = nullptr) {
4942   BlockScopeRAII Scope(Info);
4943 
4944   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4945   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4946     ESR = ESR_Failed;
4947 
4948   switch (ESR) {
4949   case ESR_Break:
4950     return ESR_Succeeded;
4951   case ESR_Succeeded:
4952   case ESR_Continue:
4953     return ESR_Continue;
4954   case ESR_Failed:
4955   case ESR_Returned:
4956   case ESR_CaseNotFound:
4957     return ESR;
4958   }
4959   llvm_unreachable("Invalid EvalStmtResult!");
4960 }
4961 
4962 /// Evaluate a switch statement.
EvaluateSwitch(StmtResult & Result,EvalInfo & Info,const SwitchStmt * SS)4963 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4964                                      const SwitchStmt *SS) {
4965   BlockScopeRAII Scope(Info);
4966 
4967   // Evaluate the switch condition.
4968   APSInt Value;
4969   {
4970     if (const Stmt *Init = SS->getInit()) {
4971       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4972       if (ESR != ESR_Succeeded) {
4973         if (ESR != ESR_Failed && !Scope.destroy())
4974           ESR = ESR_Failed;
4975         return ESR;
4976       }
4977     }
4978 
4979     FullExpressionRAII CondScope(Info);
4980     if (SS->getConditionVariable() &&
4981         !EvaluateDecl(Info, SS->getConditionVariable()))
4982       return ESR_Failed;
4983     if (SS->getCond()->isValueDependent()) {
4984       if (!EvaluateDependentExpr(SS->getCond(), Info))
4985         return ESR_Failed;
4986     } else {
4987       if (!EvaluateInteger(SS->getCond(), Value, Info))
4988         return ESR_Failed;
4989     }
4990     if (!CondScope.destroy())
4991       return ESR_Failed;
4992   }
4993 
4994   // Find the switch case corresponding to the value of the condition.
4995   // FIXME: Cache this lookup.
4996   const SwitchCase *Found = nullptr;
4997   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4998        SC = SC->getNextSwitchCase()) {
4999     if (isa<DefaultStmt>(SC)) {
5000       Found = SC;
5001       continue;
5002     }
5003 
5004     const CaseStmt *CS = cast<CaseStmt>(SC);
5005     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5006     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5007                               : LHS;
5008     if (LHS <= Value && Value <= RHS) {
5009       Found = SC;
5010       break;
5011     }
5012   }
5013 
5014   if (!Found)
5015     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5016 
5017   // Search the switch body for the switch case and evaluate it from there.
5018   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5019   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5020     return ESR_Failed;
5021 
5022   switch (ESR) {
5023   case ESR_Break:
5024     return ESR_Succeeded;
5025   case ESR_Succeeded:
5026   case ESR_Continue:
5027   case ESR_Failed:
5028   case ESR_Returned:
5029     return ESR;
5030   case ESR_CaseNotFound:
5031     // This can only happen if the switch case is nested within a statement
5032     // expression. We have no intention of supporting that.
5033     Info.FFDiag(Found->getBeginLoc(),
5034                 diag::note_constexpr_stmt_expr_unsupported);
5035     return ESR_Failed;
5036   }
5037   llvm_unreachable("Invalid EvalStmtResult!");
5038 }
5039 
CheckLocalVariableDeclaration(EvalInfo & Info,const VarDecl * VD)5040 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5041   // An expression E is a core constant expression unless the evaluation of E
5042   // would evaluate one of the following: [C++2b] - a control flow that passes
5043   // through a declaration of a variable with static or thread storage duration.
5044   if (VD->isLocalVarDecl() && VD->isStaticLocal()) {
5045     Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5046         << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5047     return false;
5048   }
5049   return true;
5050 }
5051 
5052 // Evaluate a statement.
EvaluateStmt(StmtResult & Result,EvalInfo & Info,const Stmt * S,const SwitchCase * Case)5053 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5054                                    const Stmt *S, const SwitchCase *Case) {
5055   if (!Info.nextStep(S))
5056     return ESR_Failed;
5057 
5058   // If we're hunting down a 'case' or 'default' label, recurse through
5059   // substatements until we hit the label.
5060   if (Case) {
5061     switch (S->getStmtClass()) {
5062     case Stmt::CompoundStmtClass:
5063       // FIXME: Precompute which substatement of a compound statement we
5064       // would jump to, and go straight there rather than performing a
5065       // linear scan each time.
5066     case Stmt::LabelStmtClass:
5067     case Stmt::AttributedStmtClass:
5068     case Stmt::DoStmtClass:
5069       break;
5070 
5071     case Stmt::CaseStmtClass:
5072     case Stmt::DefaultStmtClass:
5073       if (Case == S)
5074         Case = nullptr;
5075       break;
5076 
5077     case Stmt::IfStmtClass: {
5078       // FIXME: Precompute which side of an 'if' we would jump to, and go
5079       // straight there rather than scanning both sides.
5080       const IfStmt *IS = cast<IfStmt>(S);
5081 
5082       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5083       // preceded by our switch label.
5084       BlockScopeRAII Scope(Info);
5085 
5086       // Step into the init statement in case it brings an (uninitialized)
5087       // variable into scope.
5088       if (const Stmt *Init = IS->getInit()) {
5089         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5090         if (ESR != ESR_CaseNotFound) {
5091           assert(ESR != ESR_Succeeded);
5092           return ESR;
5093         }
5094       }
5095 
5096       // Condition variable must be initialized if it exists.
5097       // FIXME: We can skip evaluating the body if there's a condition
5098       // variable, as there can't be any case labels within it.
5099       // (The same is true for 'for' statements.)
5100 
5101       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5102       if (ESR == ESR_Failed)
5103         return ESR;
5104       if (ESR != ESR_CaseNotFound)
5105         return Scope.destroy() ? ESR : ESR_Failed;
5106       if (!IS->getElse())
5107         return ESR_CaseNotFound;
5108 
5109       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5110       if (ESR == ESR_Failed)
5111         return ESR;
5112       if (ESR != ESR_CaseNotFound)
5113         return Scope.destroy() ? ESR : ESR_Failed;
5114       return ESR_CaseNotFound;
5115     }
5116 
5117     case Stmt::WhileStmtClass: {
5118       EvalStmtResult ESR =
5119           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5120       if (ESR != ESR_Continue)
5121         return ESR;
5122       break;
5123     }
5124 
5125     case Stmt::ForStmtClass: {
5126       const ForStmt *FS = cast<ForStmt>(S);
5127       BlockScopeRAII Scope(Info);
5128 
5129       // Step into the init statement in case it brings an (uninitialized)
5130       // variable into scope.
5131       if (const Stmt *Init = FS->getInit()) {
5132         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5133         if (ESR != ESR_CaseNotFound) {
5134           assert(ESR != ESR_Succeeded);
5135           return ESR;
5136         }
5137       }
5138 
5139       EvalStmtResult ESR =
5140           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5141       if (ESR != ESR_Continue)
5142         return ESR;
5143       if (const auto *Inc = FS->getInc()) {
5144         if (Inc->isValueDependent()) {
5145           if (!EvaluateDependentExpr(Inc, Info))
5146             return ESR_Failed;
5147         } else {
5148           FullExpressionRAII IncScope(Info);
5149           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5150             return ESR_Failed;
5151         }
5152       }
5153       break;
5154     }
5155 
5156     case Stmt::DeclStmtClass: {
5157       // Start the lifetime of any uninitialized variables we encounter. They
5158       // might be used by the selected branch of the switch.
5159       const DeclStmt *DS = cast<DeclStmt>(S);
5160       for (const auto *D : DS->decls()) {
5161         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5162           if (!CheckLocalVariableDeclaration(Info, VD))
5163             return ESR_Failed;
5164           if (VD->hasLocalStorage() && !VD->getInit())
5165             if (!EvaluateVarDecl(Info, VD))
5166               return ESR_Failed;
5167           // FIXME: If the variable has initialization that can't be jumped
5168           // over, bail out of any immediately-surrounding compound-statement
5169           // too. There can't be any case labels here.
5170         }
5171       }
5172       return ESR_CaseNotFound;
5173     }
5174 
5175     default:
5176       return ESR_CaseNotFound;
5177     }
5178   }
5179 
5180   switch (S->getStmtClass()) {
5181   default:
5182     if (const Expr *E = dyn_cast<Expr>(S)) {
5183       if (E->isValueDependent()) {
5184         if (!EvaluateDependentExpr(E, Info))
5185           return ESR_Failed;
5186       } else {
5187         // Don't bother evaluating beyond an expression-statement which couldn't
5188         // be evaluated.
5189         // FIXME: Do we need the FullExpressionRAII object here?
5190         // VisitExprWithCleanups should create one when necessary.
5191         FullExpressionRAII Scope(Info);
5192         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5193           return ESR_Failed;
5194       }
5195       return ESR_Succeeded;
5196     }
5197 
5198     Info.FFDiag(S->getBeginLoc());
5199     return ESR_Failed;
5200 
5201   case Stmt::NullStmtClass:
5202     return ESR_Succeeded;
5203 
5204   case Stmt::DeclStmtClass: {
5205     const DeclStmt *DS = cast<DeclStmt>(S);
5206     for (const auto *D : DS->decls()) {
5207       const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5208       if (VD && !CheckLocalVariableDeclaration(Info, VD))
5209         return ESR_Failed;
5210       // Each declaration initialization is its own full-expression.
5211       FullExpressionRAII Scope(Info);
5212       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5213         return ESR_Failed;
5214       if (!Scope.destroy())
5215         return ESR_Failed;
5216     }
5217     return ESR_Succeeded;
5218   }
5219 
5220   case Stmt::ReturnStmtClass: {
5221     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5222     FullExpressionRAII Scope(Info);
5223     if (RetExpr && RetExpr->isValueDependent()) {
5224       EvaluateDependentExpr(RetExpr, Info);
5225       // We know we returned, but we don't know what the value is.
5226       return ESR_Failed;
5227     }
5228     if (RetExpr &&
5229         !(Result.Slot
5230               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5231               : Evaluate(Result.Value, Info, RetExpr)))
5232       return ESR_Failed;
5233     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5234   }
5235 
5236   case Stmt::CompoundStmtClass: {
5237     BlockScopeRAII Scope(Info);
5238 
5239     const CompoundStmt *CS = cast<CompoundStmt>(S);
5240     for (const auto *BI : CS->body()) {
5241       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5242       if (ESR == ESR_Succeeded)
5243         Case = nullptr;
5244       else if (ESR != ESR_CaseNotFound) {
5245         if (ESR != ESR_Failed && !Scope.destroy())
5246           return ESR_Failed;
5247         return ESR;
5248       }
5249     }
5250     if (Case)
5251       return ESR_CaseNotFound;
5252     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5253   }
5254 
5255   case Stmt::IfStmtClass: {
5256     const IfStmt *IS = cast<IfStmt>(S);
5257 
5258     // Evaluate the condition, as either a var decl or as an expression.
5259     BlockScopeRAII Scope(Info);
5260     if (const Stmt *Init = IS->getInit()) {
5261       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5262       if (ESR != ESR_Succeeded) {
5263         if (ESR != ESR_Failed && !Scope.destroy())
5264           return ESR_Failed;
5265         return ESR;
5266       }
5267     }
5268     bool Cond;
5269     if (IS->isConsteval()) {
5270       Cond = IS->isNonNegatedConsteval();
5271       // If we are not in a constant context, if consteval should not evaluate
5272       // to true.
5273       if (!Info.InConstantContext)
5274         Cond = !Cond;
5275     } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5276                              Cond))
5277       return ESR_Failed;
5278 
5279     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5280       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5281       if (ESR != ESR_Succeeded) {
5282         if (ESR != ESR_Failed && !Scope.destroy())
5283           return ESR_Failed;
5284         return ESR;
5285       }
5286     }
5287     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5288   }
5289 
5290   case Stmt::WhileStmtClass: {
5291     const WhileStmt *WS = cast<WhileStmt>(S);
5292     while (true) {
5293       BlockScopeRAII Scope(Info);
5294       bool Continue;
5295       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5296                         Continue))
5297         return ESR_Failed;
5298       if (!Continue)
5299         break;
5300 
5301       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5302       if (ESR != ESR_Continue) {
5303         if (ESR != ESR_Failed && !Scope.destroy())
5304           return ESR_Failed;
5305         return ESR;
5306       }
5307       if (!Scope.destroy())
5308         return ESR_Failed;
5309     }
5310     return ESR_Succeeded;
5311   }
5312 
5313   case Stmt::DoStmtClass: {
5314     const DoStmt *DS = cast<DoStmt>(S);
5315     bool Continue;
5316     do {
5317       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5318       if (ESR != ESR_Continue)
5319         return ESR;
5320       Case = nullptr;
5321 
5322       if (DS->getCond()->isValueDependent()) {
5323         EvaluateDependentExpr(DS->getCond(), Info);
5324         // Bailout as we don't know whether to keep going or terminate the loop.
5325         return ESR_Failed;
5326       }
5327       FullExpressionRAII CondScope(Info);
5328       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5329           !CondScope.destroy())
5330         return ESR_Failed;
5331     } while (Continue);
5332     return ESR_Succeeded;
5333   }
5334 
5335   case Stmt::ForStmtClass: {
5336     const ForStmt *FS = cast<ForStmt>(S);
5337     BlockScopeRAII ForScope(Info);
5338     if (FS->getInit()) {
5339       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5340       if (ESR != ESR_Succeeded) {
5341         if (ESR != ESR_Failed && !ForScope.destroy())
5342           return ESR_Failed;
5343         return ESR;
5344       }
5345     }
5346     while (true) {
5347       BlockScopeRAII IterScope(Info);
5348       bool Continue = true;
5349       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5350                                          FS->getCond(), Continue))
5351         return ESR_Failed;
5352       if (!Continue)
5353         break;
5354 
5355       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5356       if (ESR != ESR_Continue) {
5357         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5358           return ESR_Failed;
5359         return ESR;
5360       }
5361 
5362       if (const auto *Inc = FS->getInc()) {
5363         if (Inc->isValueDependent()) {
5364           if (!EvaluateDependentExpr(Inc, Info))
5365             return ESR_Failed;
5366         } else {
5367           FullExpressionRAII IncScope(Info);
5368           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5369             return ESR_Failed;
5370         }
5371       }
5372 
5373       if (!IterScope.destroy())
5374         return ESR_Failed;
5375     }
5376     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5377   }
5378 
5379   case Stmt::CXXForRangeStmtClass: {
5380     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5381     BlockScopeRAII Scope(Info);
5382 
5383     // Evaluate the init-statement if present.
5384     if (FS->getInit()) {
5385       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5386       if (ESR != ESR_Succeeded) {
5387         if (ESR != ESR_Failed && !Scope.destroy())
5388           return ESR_Failed;
5389         return ESR;
5390       }
5391     }
5392 
5393     // Initialize the __range variable.
5394     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5395     if (ESR != ESR_Succeeded) {
5396       if (ESR != ESR_Failed && !Scope.destroy())
5397         return ESR_Failed;
5398       return ESR;
5399     }
5400 
5401     // In error-recovery cases it's possible to get here even if we failed to
5402     // synthesize the __begin and __end variables.
5403     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5404       return ESR_Failed;
5405 
5406     // Create the __begin and __end iterators.
5407     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5408     if (ESR != ESR_Succeeded) {
5409       if (ESR != ESR_Failed && !Scope.destroy())
5410         return ESR_Failed;
5411       return ESR;
5412     }
5413     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5414     if (ESR != ESR_Succeeded) {
5415       if (ESR != ESR_Failed && !Scope.destroy())
5416         return ESR_Failed;
5417       return ESR;
5418     }
5419 
5420     while (true) {
5421       // Condition: __begin != __end.
5422       {
5423         if (FS->getCond()->isValueDependent()) {
5424           EvaluateDependentExpr(FS->getCond(), Info);
5425           // We don't know whether to keep going or terminate the loop.
5426           return ESR_Failed;
5427         }
5428         bool Continue = true;
5429         FullExpressionRAII CondExpr(Info);
5430         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5431           return ESR_Failed;
5432         if (!Continue)
5433           break;
5434       }
5435 
5436       // User's variable declaration, initialized by *__begin.
5437       BlockScopeRAII InnerScope(Info);
5438       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5439       if (ESR != ESR_Succeeded) {
5440         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5441           return ESR_Failed;
5442         return ESR;
5443       }
5444 
5445       // Loop body.
5446       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5447       if (ESR != ESR_Continue) {
5448         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5449           return ESR_Failed;
5450         return ESR;
5451       }
5452       if (FS->getInc()->isValueDependent()) {
5453         if (!EvaluateDependentExpr(FS->getInc(), Info))
5454           return ESR_Failed;
5455       } else {
5456         // Increment: ++__begin
5457         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5458           return ESR_Failed;
5459       }
5460 
5461       if (!InnerScope.destroy())
5462         return ESR_Failed;
5463     }
5464 
5465     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5466   }
5467 
5468   case Stmt::SwitchStmtClass:
5469     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5470 
5471   case Stmt::ContinueStmtClass:
5472     return ESR_Continue;
5473 
5474   case Stmt::BreakStmtClass:
5475     return ESR_Break;
5476 
5477   case Stmt::LabelStmtClass:
5478     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5479 
5480   case Stmt::AttributedStmtClass:
5481     // As a general principle, C++11 attributes can be ignored without
5482     // any semantic impact.
5483     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5484                         Case);
5485 
5486   case Stmt::CaseStmtClass:
5487   case Stmt::DefaultStmtClass:
5488     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5489   case Stmt::CXXTryStmtClass:
5490     // Evaluate try blocks by evaluating all sub statements.
5491     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5492   }
5493 }
5494 
5495 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5496 /// default constructor. If so, we'll fold it whether or not it's marked as
5497 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5498 /// so we need special handling.
CheckTrivialDefaultConstructor(EvalInfo & Info,SourceLocation Loc,const CXXConstructorDecl * CD,bool IsValueInitialization)5499 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5500                                            const CXXConstructorDecl *CD,
5501                                            bool IsValueInitialization) {
5502   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5503     return false;
5504 
5505   // Value-initialization does not call a trivial default constructor, so such a
5506   // call is a core constant expression whether or not the constructor is
5507   // constexpr.
5508   if (!CD->isConstexpr() && !IsValueInitialization) {
5509     if (Info.getLangOpts().CPlusPlus11) {
5510       // FIXME: If DiagDecl is an implicitly-declared special member function,
5511       // we should be much more explicit about why it's not constexpr.
5512       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5513         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5514       Info.Note(CD->getLocation(), diag::note_declared_at);
5515     } else {
5516       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5517     }
5518   }
5519   return true;
5520 }
5521 
5522 /// CheckConstexprFunction - Check that a function can be called in a constant
5523 /// expression.
CheckConstexprFunction(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Declaration,const FunctionDecl * Definition,const Stmt * Body)5524 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5525                                    const FunctionDecl *Declaration,
5526                                    const FunctionDecl *Definition,
5527                                    const Stmt *Body) {
5528   // Potential constant expressions can contain calls to declared, but not yet
5529   // defined, constexpr functions.
5530   if (Info.checkingPotentialConstantExpression() && !Definition &&
5531       Declaration->isConstexpr())
5532     return false;
5533 
5534   // Bail out if the function declaration itself is invalid.  We will
5535   // have produced a relevant diagnostic while parsing it, so just
5536   // note the problematic sub-expression.
5537   if (Declaration->isInvalidDecl()) {
5538     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5539     return false;
5540   }
5541 
5542   // DR1872: An instantiated virtual constexpr function can't be called in a
5543   // constant expression (prior to C++20). We can still constant-fold such a
5544   // call.
5545   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5546       cast<CXXMethodDecl>(Declaration)->isVirtual())
5547     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5548 
5549   if (Definition && Definition->isInvalidDecl()) {
5550     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5551     return false;
5552   }
5553 
5554   // Can we evaluate this function call?
5555   if (Definition && Definition->isConstexpr() && Body)
5556     return true;
5557 
5558   if (Info.getLangOpts().CPlusPlus11) {
5559     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5560 
5561     // If this function is not constexpr because it is an inherited
5562     // non-constexpr constructor, diagnose that directly.
5563     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5564     if (CD && CD->isInheritingConstructor()) {
5565       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5566       if (!Inherited->isConstexpr())
5567         DiagDecl = CD = Inherited;
5568     }
5569 
5570     // FIXME: If DiagDecl is an implicitly-declared special member function
5571     // or an inheriting constructor, we should be much more explicit about why
5572     // it's not constexpr.
5573     if (CD && CD->isInheritingConstructor())
5574       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5575         << CD->getInheritedConstructor().getConstructor()->getParent();
5576     else
5577       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5578         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5579     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5580   } else {
5581     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5582   }
5583   return false;
5584 }
5585 
5586 namespace {
5587 struct CheckDynamicTypeHandler {
5588   AccessKinds AccessKind;
5589   typedef bool result_type;
failed__anon7a1fdcea1011::CheckDynamicTypeHandler5590   bool failed() { return false; }
found__anon7a1fdcea1011::CheckDynamicTypeHandler5591   bool found(APValue &Subobj, QualType SubobjType) { return true; }
found__anon7a1fdcea1011::CheckDynamicTypeHandler5592   bool found(APSInt &Value, QualType SubobjType) { return true; }
found__anon7a1fdcea1011::CheckDynamicTypeHandler5593   bool found(APFloat &Value, QualType SubobjType) { return true; }
5594 };
5595 } // end anonymous namespace
5596 
5597 /// Check that we can access the notional vptr of an object / determine its
5598 /// dynamic type.
checkDynamicType(EvalInfo & Info,const Expr * E,const LValue & This,AccessKinds AK,bool Polymorphic)5599 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5600                              AccessKinds AK, bool Polymorphic) {
5601   if (This.Designator.Invalid)
5602     return false;
5603 
5604   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5605 
5606   if (!Obj)
5607     return false;
5608 
5609   if (!Obj.Value) {
5610     // The object is not usable in constant expressions, so we can't inspect
5611     // its value to see if it's in-lifetime or what the active union members
5612     // are. We can still check for a one-past-the-end lvalue.
5613     if (This.Designator.isOnePastTheEnd() ||
5614         This.Designator.isMostDerivedAnUnsizedArray()) {
5615       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5616                          ? diag::note_constexpr_access_past_end
5617                          : diag::note_constexpr_access_unsized_array)
5618           << AK;
5619       return false;
5620     } else if (Polymorphic) {
5621       // Conservatively refuse to perform a polymorphic operation if we would
5622       // not be able to read a notional 'vptr' value.
5623       APValue Val;
5624       This.moveInto(Val);
5625       QualType StarThisType =
5626           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5627       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5628           << AK << Val.getAsString(Info.Ctx, StarThisType);
5629       return false;
5630     }
5631     return true;
5632   }
5633 
5634   CheckDynamicTypeHandler Handler{AK};
5635   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5636 }
5637 
5638 /// Check that the pointee of the 'this' pointer in a member function call is
5639 /// either within its lifetime or in its period of construction or destruction.
5640 static bool
checkNonVirtualMemberCallThisPointer(EvalInfo & Info,const Expr * E,const LValue & This,const CXXMethodDecl * NamedMember)5641 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5642                                      const LValue &This,
5643                                      const CXXMethodDecl *NamedMember) {
5644   return checkDynamicType(
5645       Info, E, This,
5646       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5647 }
5648 
5649 struct DynamicType {
5650   /// The dynamic class type of the object.
5651   const CXXRecordDecl *Type;
5652   /// The corresponding path length in the lvalue.
5653   unsigned PathLength;
5654 };
5655 
getBaseClassType(SubobjectDesignator & Designator,unsigned PathLength)5656 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5657                                              unsigned PathLength) {
5658   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5659       Designator.Entries.size() && "invalid path length");
5660   return (PathLength == Designator.MostDerivedPathLength)
5661              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5662              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5663 }
5664 
5665 /// Determine the dynamic type of an object.
ComputeDynamicType(EvalInfo & Info,const Expr * E,LValue & This,AccessKinds AK)5666 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5667                                                 LValue &This, AccessKinds AK) {
5668   // If we don't have an lvalue denoting an object of class type, there is no
5669   // meaningful dynamic type. (We consider objects of non-class type to have no
5670   // dynamic type.)
5671   if (!checkDynamicType(Info, E, This, AK, true))
5672     return None;
5673 
5674   // Refuse to compute a dynamic type in the presence of virtual bases. This
5675   // shouldn't happen other than in constant-folding situations, since literal
5676   // types can't have virtual bases.
5677   //
5678   // Note that consumers of DynamicType assume that the type has no virtual
5679   // bases, and will need modifications if this restriction is relaxed.
5680   const CXXRecordDecl *Class =
5681       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5682   if (!Class || Class->getNumVBases()) {
5683     Info.FFDiag(E);
5684     return None;
5685   }
5686 
5687   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5688   // binary search here instead. But the overwhelmingly common case is that
5689   // we're not in the middle of a constructor, so it probably doesn't matter
5690   // in practice.
5691   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5692   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5693        PathLength <= Path.size(); ++PathLength) {
5694     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5695                                       Path.slice(0, PathLength))) {
5696     case ConstructionPhase::Bases:
5697     case ConstructionPhase::DestroyingBases:
5698       // We're constructing or destroying a base class. This is not the dynamic
5699       // type.
5700       break;
5701 
5702     case ConstructionPhase::None:
5703     case ConstructionPhase::AfterBases:
5704     case ConstructionPhase::AfterFields:
5705     case ConstructionPhase::Destroying:
5706       // We've finished constructing the base classes and not yet started
5707       // destroying them again, so this is the dynamic type.
5708       return DynamicType{getBaseClassType(This.Designator, PathLength),
5709                          PathLength};
5710     }
5711   }
5712 
5713   // CWG issue 1517: we're constructing a base class of the object described by
5714   // 'This', so that object has not yet begun its period of construction and
5715   // any polymorphic operation on it results in undefined behavior.
5716   Info.FFDiag(E);
5717   return None;
5718 }
5719 
5720 /// Perform virtual dispatch.
HandleVirtualDispatch(EvalInfo & Info,const Expr * E,LValue & This,const CXXMethodDecl * Found,llvm::SmallVectorImpl<QualType> & CovariantAdjustmentPath)5721 static const CXXMethodDecl *HandleVirtualDispatch(
5722     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5723     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5724   Optional<DynamicType> DynType = ComputeDynamicType(
5725       Info, E, This,
5726       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5727   if (!DynType)
5728     return nullptr;
5729 
5730   // Find the final overrider. It must be declared in one of the classes on the
5731   // path from the dynamic type to the static type.
5732   // FIXME: If we ever allow literal types to have virtual base classes, that
5733   // won't be true.
5734   const CXXMethodDecl *Callee = Found;
5735   unsigned PathLength = DynType->PathLength;
5736   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5737     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5738     const CXXMethodDecl *Overrider =
5739         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5740     if (Overrider) {
5741       Callee = Overrider;
5742       break;
5743     }
5744   }
5745 
5746   // C++2a [class.abstract]p6:
5747   //   the effect of making a virtual call to a pure virtual function [...] is
5748   //   undefined
5749   if (Callee->isPure()) {
5750     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5751     Info.Note(Callee->getLocation(), diag::note_declared_at);
5752     return nullptr;
5753   }
5754 
5755   // If necessary, walk the rest of the path to determine the sequence of
5756   // covariant adjustment steps to apply.
5757   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5758                                        Found->getReturnType())) {
5759     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5760     for (unsigned CovariantPathLength = PathLength + 1;
5761          CovariantPathLength != This.Designator.Entries.size();
5762          ++CovariantPathLength) {
5763       const CXXRecordDecl *NextClass =
5764           getBaseClassType(This.Designator, CovariantPathLength);
5765       const CXXMethodDecl *Next =
5766           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5767       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5768                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5769         CovariantAdjustmentPath.push_back(Next->getReturnType());
5770     }
5771     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5772                                          CovariantAdjustmentPath.back()))
5773       CovariantAdjustmentPath.push_back(Found->getReturnType());
5774   }
5775 
5776   // Perform 'this' adjustment.
5777   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5778     return nullptr;
5779 
5780   return Callee;
5781 }
5782 
5783 /// Perform the adjustment from a value returned by a virtual function to
5784 /// a value of the statically expected type, which may be a pointer or
5785 /// reference to a base class of the returned type.
HandleCovariantReturnAdjustment(EvalInfo & Info,const Expr * E,APValue & Result,ArrayRef<QualType> Path)5786 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5787                                             APValue &Result,
5788                                             ArrayRef<QualType> Path) {
5789   assert(Result.isLValue() &&
5790          "unexpected kind of APValue for covariant return");
5791   if (Result.isNullPointer())
5792     return true;
5793 
5794   LValue LVal;
5795   LVal.setFrom(Info.Ctx, Result);
5796 
5797   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5798   for (unsigned I = 1; I != Path.size(); ++I) {
5799     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5800     assert(OldClass && NewClass && "unexpected kind of covariant return");
5801     if (OldClass != NewClass &&
5802         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5803       return false;
5804     OldClass = NewClass;
5805   }
5806 
5807   LVal.moveInto(Result);
5808   return true;
5809 }
5810 
5811 /// Determine whether \p Base, which is known to be a direct base class of
5812 /// \p Derived, is a public base class.
isBaseClassPublic(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)5813 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5814                               const CXXRecordDecl *Base) {
5815   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5816     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5817     if (BaseClass && declaresSameEntity(BaseClass, Base))
5818       return BaseSpec.getAccessSpecifier() == AS_public;
5819   }
5820   llvm_unreachable("Base is not a direct base of Derived");
5821 }
5822 
5823 /// Apply the given dynamic cast operation on the provided lvalue.
5824 ///
5825 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5826 /// to find a suitable target subobject.
HandleDynamicCast(EvalInfo & Info,const ExplicitCastExpr * E,LValue & Ptr)5827 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5828                               LValue &Ptr) {
5829   // We can't do anything with a non-symbolic pointer value.
5830   SubobjectDesignator &D = Ptr.Designator;
5831   if (D.Invalid)
5832     return false;
5833 
5834   // C++ [expr.dynamic.cast]p6:
5835   //   If v is a null pointer value, the result is a null pointer value.
5836   if (Ptr.isNullPointer() && !E->isGLValue())
5837     return true;
5838 
5839   // For all the other cases, we need the pointer to point to an object within
5840   // its lifetime / period of construction / destruction, and we need to know
5841   // its dynamic type.
5842   Optional<DynamicType> DynType =
5843       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5844   if (!DynType)
5845     return false;
5846 
5847   // C++ [expr.dynamic.cast]p7:
5848   //   If T is "pointer to cv void", then the result is a pointer to the most
5849   //   derived object
5850   if (E->getType()->isVoidPointerType())
5851     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5852 
5853   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5854   assert(C && "dynamic_cast target is not void pointer nor class");
5855   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5856 
5857   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5858     // C++ [expr.dynamic.cast]p9:
5859     if (!E->isGLValue()) {
5860       //   The value of a failed cast to pointer type is the null pointer value
5861       //   of the required result type.
5862       Ptr.setNull(Info.Ctx, E->getType());
5863       return true;
5864     }
5865 
5866     //   A failed cast to reference type throws [...] std::bad_cast.
5867     unsigned DiagKind;
5868     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5869                    DynType->Type->isDerivedFrom(C)))
5870       DiagKind = 0;
5871     else if (!Paths || Paths->begin() == Paths->end())
5872       DiagKind = 1;
5873     else if (Paths->isAmbiguous(CQT))
5874       DiagKind = 2;
5875     else {
5876       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5877       DiagKind = 3;
5878     }
5879     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5880         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5881         << Info.Ctx.getRecordType(DynType->Type)
5882         << E->getType().getUnqualifiedType();
5883     return false;
5884   };
5885 
5886   // Runtime check, phase 1:
5887   //   Walk from the base subobject towards the derived object looking for the
5888   //   target type.
5889   for (int PathLength = Ptr.Designator.Entries.size();
5890        PathLength >= (int)DynType->PathLength; --PathLength) {
5891     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5892     if (declaresSameEntity(Class, C))
5893       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5894     // We can only walk across public inheritance edges.
5895     if (PathLength > (int)DynType->PathLength &&
5896         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5897                            Class))
5898       return RuntimeCheckFailed(nullptr);
5899   }
5900 
5901   // Runtime check, phase 2:
5902   //   Search the dynamic type for an unambiguous public base of type C.
5903   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5904                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5905   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5906       Paths.front().Access == AS_public) {
5907     // Downcast to the dynamic type...
5908     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5909       return false;
5910     // ... then upcast to the chosen base class subobject.
5911     for (CXXBasePathElement &Elem : Paths.front())
5912       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5913         return false;
5914     return true;
5915   }
5916 
5917   // Otherwise, the runtime check fails.
5918   return RuntimeCheckFailed(&Paths);
5919 }
5920 
5921 namespace {
5922 struct StartLifetimeOfUnionMemberHandler {
5923   EvalInfo &Info;
5924   const Expr *LHSExpr;
5925   const FieldDecl *Field;
5926   bool DuringInit;
5927   bool Failed = false;
5928   static const AccessKinds AccessKind = AK_Assign;
5929 
5930   typedef bool result_type;
failed__anon7a1fdcea1211::StartLifetimeOfUnionMemberHandler5931   bool failed() { return Failed; }
found__anon7a1fdcea1211::StartLifetimeOfUnionMemberHandler5932   bool found(APValue &Subobj, QualType SubobjType) {
5933     // We are supposed to perform no initialization but begin the lifetime of
5934     // the object. We interpret that as meaning to do what default
5935     // initialization of the object would do if all constructors involved were
5936     // trivial:
5937     //  * All base, non-variant member, and array element subobjects' lifetimes
5938     //    begin
5939     //  * No variant members' lifetimes begin
5940     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5941     assert(SubobjType->isUnionType());
5942     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5943       // This union member is already active. If it's also in-lifetime, there's
5944       // nothing to do.
5945       if (Subobj.getUnionValue().hasValue())
5946         return true;
5947     } else if (DuringInit) {
5948       // We're currently in the process of initializing a different union
5949       // member.  If we carried on, that initialization would attempt to
5950       // store to an inactive union member, resulting in undefined behavior.
5951       Info.FFDiag(LHSExpr,
5952                   diag::note_constexpr_union_member_change_during_init);
5953       return false;
5954     }
5955     APValue Result;
5956     Failed = !getDefaultInitValue(Field->getType(), Result);
5957     Subobj.setUnion(Field, Result);
5958     return true;
5959   }
found__anon7a1fdcea1211::StartLifetimeOfUnionMemberHandler5960   bool found(APSInt &Value, QualType SubobjType) {
5961     llvm_unreachable("wrong value kind for union object");
5962   }
found__anon7a1fdcea1211::StartLifetimeOfUnionMemberHandler5963   bool found(APFloat &Value, QualType SubobjType) {
5964     llvm_unreachable("wrong value kind for union object");
5965   }
5966 };
5967 } // end anonymous namespace
5968 
5969 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5970 
5971 /// Handle a builtin simple-assignment or a call to a trivial assignment
5972 /// operator whose left-hand side might involve a union member access. If it
5973 /// does, implicitly start the lifetime of any accessed union elements per
5974 /// C++20 [class.union]5.
HandleUnionActiveMemberChange(EvalInfo & Info,const Expr * LHSExpr,const LValue & LHS)5975 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5976                                           const LValue &LHS) {
5977   if (LHS.InvalidBase || LHS.Designator.Invalid)
5978     return false;
5979 
5980   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5981   // C++ [class.union]p5:
5982   //   define the set S(E) of subexpressions of E as follows:
5983   unsigned PathLength = LHS.Designator.Entries.size();
5984   for (const Expr *E = LHSExpr; E != nullptr;) {
5985     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5986     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5987       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5988       // Note that we can't implicitly start the lifetime of a reference,
5989       // so we don't need to proceed any further if we reach one.
5990       if (!FD || FD->getType()->isReferenceType())
5991         break;
5992 
5993       //    ... and also contains A.B if B names a union member ...
5994       if (FD->getParent()->isUnion()) {
5995         //    ... of a non-class, non-array type, or of a class type with a
5996         //    trivial default constructor that is not deleted, or an array of
5997         //    such types.
5998         auto *RD =
5999             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6000         if (!RD || RD->hasTrivialDefaultConstructor())
6001           UnionPathLengths.push_back({PathLength - 1, FD});
6002       }
6003 
6004       E = ME->getBase();
6005       --PathLength;
6006       assert(declaresSameEntity(FD,
6007                                 LHS.Designator.Entries[PathLength]
6008                                     .getAsBaseOrMember().getPointer()));
6009 
6010       //   -- If E is of the form A[B] and is interpreted as a built-in array
6011       //      subscripting operator, S(E) is [S(the array operand, if any)].
6012     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6013       // Step over an ArrayToPointerDecay implicit cast.
6014       auto *Base = ASE->getBase()->IgnoreImplicit();
6015       if (!Base->getType()->isArrayType())
6016         break;
6017 
6018       E = Base;
6019       --PathLength;
6020 
6021     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6022       // Step over a derived-to-base conversion.
6023       E = ICE->getSubExpr();
6024       if (ICE->getCastKind() == CK_NoOp)
6025         continue;
6026       if (ICE->getCastKind() != CK_DerivedToBase &&
6027           ICE->getCastKind() != CK_UncheckedDerivedToBase)
6028         break;
6029       // Walk path backwards as we walk up from the base to the derived class.
6030       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6031         --PathLength;
6032         (void)Elt;
6033         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6034                                   LHS.Designator.Entries[PathLength]
6035                                       .getAsBaseOrMember().getPointer()));
6036       }
6037 
6038     //   -- Otherwise, S(E) is empty.
6039     } else {
6040       break;
6041     }
6042   }
6043 
6044   // Common case: no unions' lifetimes are started.
6045   if (UnionPathLengths.empty())
6046     return true;
6047 
6048   //   if modification of X [would access an inactive union member], an object
6049   //   of the type of X is implicitly created
6050   CompleteObject Obj =
6051       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6052   if (!Obj)
6053     return false;
6054   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6055            llvm::reverse(UnionPathLengths)) {
6056     // Form a designator for the union object.
6057     SubobjectDesignator D = LHS.Designator;
6058     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6059 
6060     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6061                       ConstructionPhase::AfterBases;
6062     StartLifetimeOfUnionMemberHandler StartLifetime{
6063         Info, LHSExpr, LengthAndField.second, DuringInit};
6064     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6065       return false;
6066   }
6067 
6068   return true;
6069 }
6070 
EvaluateCallArg(const ParmVarDecl * PVD,const Expr * Arg,CallRef Call,EvalInfo & Info,bool NonNull=false)6071 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6072                             CallRef Call, EvalInfo &Info,
6073                             bool NonNull = false) {
6074   LValue LV;
6075   // Create the parameter slot and register its destruction. For a vararg
6076   // argument, create a temporary.
6077   // FIXME: For calling conventions that destroy parameters in the callee,
6078   // should we consider performing destruction when the function returns
6079   // instead?
6080   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6081                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6082                                                        ScopeKind::Call, LV);
6083   if (!EvaluateInPlace(V, Info, LV, Arg))
6084     return false;
6085 
6086   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6087   // undefined behavior, so is non-constant.
6088   if (NonNull && V.isLValue() && V.isNullPointer()) {
6089     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6090     return false;
6091   }
6092 
6093   return true;
6094 }
6095 
6096 /// Evaluate the arguments to a function call.
EvaluateArgs(ArrayRef<const Expr * > Args,CallRef Call,EvalInfo & Info,const FunctionDecl * Callee,bool RightToLeft=false)6097 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6098                          EvalInfo &Info, const FunctionDecl *Callee,
6099                          bool RightToLeft = false) {
6100   bool Success = true;
6101   llvm::SmallBitVector ForbiddenNullArgs;
6102   if (Callee->hasAttr<NonNullAttr>()) {
6103     ForbiddenNullArgs.resize(Args.size());
6104     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6105       if (!Attr->args_size()) {
6106         ForbiddenNullArgs.set();
6107         break;
6108       } else
6109         for (auto Idx : Attr->args()) {
6110           unsigned ASTIdx = Idx.getASTIndex();
6111           if (ASTIdx >= Args.size())
6112             continue;
6113           ForbiddenNullArgs[ASTIdx] = true;
6114         }
6115     }
6116   }
6117   for (unsigned I = 0; I < Args.size(); I++) {
6118     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6119     const ParmVarDecl *PVD =
6120         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6121     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6122     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6123       // If we're checking for a potential constant expression, evaluate all
6124       // initializers even if some of them fail.
6125       if (!Info.noteFailure())
6126         return false;
6127       Success = false;
6128     }
6129   }
6130   return Success;
6131 }
6132 
6133 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6134 /// constructor or assignment operator.
handleTrivialCopy(EvalInfo & Info,const ParmVarDecl * Param,const Expr * E,APValue & Result,bool CopyObjectRepresentation)6135 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6136                               const Expr *E, APValue &Result,
6137                               bool CopyObjectRepresentation) {
6138   // Find the reference argument.
6139   CallStackFrame *Frame = Info.CurrentCall;
6140   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6141   if (!RefValue) {
6142     Info.FFDiag(E);
6143     return false;
6144   }
6145 
6146   // Copy out the contents of the RHS object.
6147   LValue RefLValue;
6148   RefLValue.setFrom(Info.Ctx, *RefValue);
6149   return handleLValueToRValueConversion(
6150       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6151       CopyObjectRepresentation);
6152 }
6153 
6154 /// Evaluate a function call.
HandleFunctionCall(SourceLocation CallLoc,const FunctionDecl * Callee,const LValue * This,ArrayRef<const Expr * > Args,CallRef Call,const Stmt * Body,EvalInfo & Info,APValue & Result,const LValue * ResultSlot)6155 static bool HandleFunctionCall(SourceLocation CallLoc,
6156                                const FunctionDecl *Callee, const LValue *This,
6157                                ArrayRef<const Expr *> Args, CallRef Call,
6158                                const Stmt *Body, EvalInfo &Info,
6159                                APValue &Result, const LValue *ResultSlot) {
6160   if (!Info.CheckCallLimit(CallLoc))
6161     return false;
6162 
6163   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6164 
6165   // For a trivial copy or move assignment, perform an APValue copy. This is
6166   // essential for unions, where the operations performed by the assignment
6167   // operator cannot be represented as statements.
6168   //
6169   // Skip this for non-union classes with no fields; in that case, the defaulted
6170   // copy/move does not actually read the object.
6171   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6172   if (MD && MD->isDefaulted() &&
6173       (MD->getParent()->isUnion() ||
6174        (MD->isTrivial() &&
6175         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6176     assert(This &&
6177            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6178     APValue RHSValue;
6179     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6180                            MD->getParent()->isUnion()))
6181       return false;
6182     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6183                           RHSValue))
6184       return false;
6185     This->moveInto(Result);
6186     return true;
6187   } else if (MD && isLambdaCallOperator(MD)) {
6188     // We're in a lambda; determine the lambda capture field maps unless we're
6189     // just constexpr checking a lambda's call operator. constexpr checking is
6190     // done before the captures have been added to the closure object (unless
6191     // we're inferring constexpr-ness), so we don't have access to them in this
6192     // case. But since we don't need the captures to constexpr check, we can
6193     // just ignore them.
6194     if (!Info.checkingPotentialConstantExpression())
6195       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6196                                         Frame.LambdaThisCaptureField);
6197   }
6198 
6199   StmtResult Ret = {Result, ResultSlot};
6200   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6201   if (ESR == ESR_Succeeded) {
6202     if (Callee->getReturnType()->isVoidType())
6203       return true;
6204     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6205   }
6206   return ESR == ESR_Returned;
6207 }
6208 
6209 /// Evaluate a constructor call.
HandleConstructorCall(const Expr * E,const LValue & This,CallRef Call,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6210 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6211                                   CallRef Call,
6212                                   const CXXConstructorDecl *Definition,
6213                                   EvalInfo &Info, APValue &Result) {
6214   SourceLocation CallLoc = E->getExprLoc();
6215   if (!Info.CheckCallLimit(CallLoc))
6216     return false;
6217 
6218   const CXXRecordDecl *RD = Definition->getParent();
6219   if (RD->getNumVBases()) {
6220     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6221     return false;
6222   }
6223 
6224   EvalInfo::EvaluatingConstructorRAII EvalObj(
6225       Info,
6226       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6227       RD->getNumBases());
6228   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6229 
6230   // FIXME: Creating an APValue just to hold a nonexistent return value is
6231   // wasteful.
6232   APValue RetVal;
6233   StmtResult Ret = {RetVal, nullptr};
6234 
6235   // If it's a delegating constructor, delegate.
6236   if (Definition->isDelegatingConstructor()) {
6237     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6238     if ((*I)->getInit()->isValueDependent()) {
6239       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6240         return false;
6241     } else {
6242       FullExpressionRAII InitScope(Info);
6243       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6244           !InitScope.destroy())
6245         return false;
6246     }
6247     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6248   }
6249 
6250   // For a trivial copy or move constructor, perform an APValue copy. This is
6251   // essential for unions (or classes with anonymous union members), where the
6252   // operations performed by the constructor cannot be represented by
6253   // ctor-initializers.
6254   //
6255   // Skip this for empty non-union classes; we should not perform an
6256   // lvalue-to-rvalue conversion on them because their copy constructor does not
6257   // actually read them.
6258   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6259       (Definition->getParent()->isUnion() ||
6260        (Definition->isTrivial() &&
6261         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6262     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6263                              Definition->getParent()->isUnion());
6264   }
6265 
6266   // Reserve space for the struct members.
6267   if (!Result.hasValue()) {
6268     if (!RD->isUnion())
6269       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6270                        std::distance(RD->field_begin(), RD->field_end()));
6271     else
6272       // A union starts with no active member.
6273       Result = APValue((const FieldDecl*)nullptr);
6274   }
6275 
6276   if (RD->isInvalidDecl()) return false;
6277   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6278 
6279   // A scope for temporaries lifetime-extended by reference members.
6280   BlockScopeRAII LifetimeExtendedScope(Info);
6281 
6282   bool Success = true;
6283   unsigned BasesSeen = 0;
6284 #ifndef NDEBUG
6285   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6286 #endif
6287   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6288   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6289     // We might be initializing the same field again if this is an indirect
6290     // field initialization.
6291     if (FieldIt == RD->field_end() ||
6292         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6293       assert(Indirect && "fields out of order?");
6294       return;
6295     }
6296 
6297     // Default-initialize any fields with no explicit initializer.
6298     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6299       assert(FieldIt != RD->field_end() && "missing field?");
6300       if (!FieldIt->isUnnamedBitfield())
6301         Success &= getDefaultInitValue(
6302             FieldIt->getType(),
6303             Result.getStructField(FieldIt->getFieldIndex()));
6304     }
6305     ++FieldIt;
6306   };
6307   for (const auto *I : Definition->inits()) {
6308     LValue Subobject = This;
6309     LValue SubobjectParent = This;
6310     APValue *Value = &Result;
6311 
6312     // Determine the subobject to initialize.
6313     FieldDecl *FD = nullptr;
6314     if (I->isBaseInitializer()) {
6315       QualType BaseType(I->getBaseClass(), 0);
6316 #ifndef NDEBUG
6317       // Non-virtual base classes are initialized in the order in the class
6318       // definition. We have already checked for virtual base classes.
6319       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6320       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6321              "base class initializers not in expected order");
6322       ++BaseIt;
6323 #endif
6324       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6325                                   BaseType->getAsCXXRecordDecl(), &Layout))
6326         return false;
6327       Value = &Result.getStructBase(BasesSeen++);
6328     } else if ((FD = I->getMember())) {
6329       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6330         return false;
6331       if (RD->isUnion()) {
6332         Result = APValue(FD);
6333         Value = &Result.getUnionValue();
6334       } else {
6335         SkipToField(FD, false);
6336         Value = &Result.getStructField(FD->getFieldIndex());
6337       }
6338     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6339       // Walk the indirect field decl's chain to find the object to initialize,
6340       // and make sure we've initialized every step along it.
6341       auto IndirectFieldChain = IFD->chain();
6342       for (auto *C : IndirectFieldChain) {
6343         FD = cast<FieldDecl>(C);
6344         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6345         // Switch the union field if it differs. This happens if we had
6346         // preceding zero-initialization, and we're now initializing a union
6347         // subobject other than the first.
6348         // FIXME: In this case, the values of the other subobjects are
6349         // specified, since zero-initialization sets all padding bits to zero.
6350         if (!Value->hasValue() ||
6351             (Value->isUnion() && Value->getUnionField() != FD)) {
6352           if (CD->isUnion())
6353             *Value = APValue(FD);
6354           else
6355             // FIXME: This immediately starts the lifetime of all members of
6356             // an anonymous struct. It would be preferable to strictly start
6357             // member lifetime in initialization order.
6358             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6359         }
6360         // Store Subobject as its parent before updating it for the last element
6361         // in the chain.
6362         if (C == IndirectFieldChain.back())
6363           SubobjectParent = Subobject;
6364         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6365           return false;
6366         if (CD->isUnion())
6367           Value = &Value->getUnionValue();
6368         else {
6369           if (C == IndirectFieldChain.front() && !RD->isUnion())
6370             SkipToField(FD, true);
6371           Value = &Value->getStructField(FD->getFieldIndex());
6372         }
6373       }
6374     } else {
6375       llvm_unreachable("unknown base initializer kind");
6376     }
6377 
6378     // Need to override This for implicit field initializers as in this case
6379     // This refers to innermost anonymous struct/union containing initializer,
6380     // not to currently constructed class.
6381     const Expr *Init = I->getInit();
6382     if (Init->isValueDependent()) {
6383       if (!EvaluateDependentExpr(Init, Info))
6384         return false;
6385     } else {
6386       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6387                                     isa<CXXDefaultInitExpr>(Init));
6388       FullExpressionRAII InitScope(Info);
6389       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6390           (FD && FD->isBitField() &&
6391            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6392         // If we're checking for a potential constant expression, evaluate all
6393         // initializers even if some of them fail.
6394         if (!Info.noteFailure())
6395           return false;
6396         Success = false;
6397       }
6398     }
6399 
6400     // This is the point at which the dynamic type of the object becomes this
6401     // class type.
6402     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6403       EvalObj.finishedConstructingBases();
6404   }
6405 
6406   // Default-initialize any remaining fields.
6407   if (!RD->isUnion()) {
6408     for (; FieldIt != RD->field_end(); ++FieldIt) {
6409       if (!FieldIt->isUnnamedBitfield())
6410         Success &= getDefaultInitValue(
6411             FieldIt->getType(),
6412             Result.getStructField(FieldIt->getFieldIndex()));
6413     }
6414   }
6415 
6416   EvalObj.finishedConstructingFields();
6417 
6418   return Success &&
6419          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6420          LifetimeExtendedScope.destroy();
6421 }
6422 
HandleConstructorCall(const Expr * E,const LValue & This,ArrayRef<const Expr * > Args,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6423 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6424                                   ArrayRef<const Expr*> Args,
6425                                   const CXXConstructorDecl *Definition,
6426                                   EvalInfo &Info, APValue &Result) {
6427   CallScopeRAII CallScope(Info);
6428   CallRef Call = Info.CurrentCall->createCall(Definition);
6429   if (!EvaluateArgs(Args, Call, Info, Definition))
6430     return false;
6431 
6432   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6433          CallScope.destroy();
6434 }
6435 
HandleDestructionImpl(EvalInfo & Info,SourceLocation CallLoc,const LValue & This,APValue & Value,QualType T)6436 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6437                                   const LValue &This, APValue &Value,
6438                                   QualType T) {
6439   // Objects can only be destroyed while they're within their lifetimes.
6440   // FIXME: We have no representation for whether an object of type nullptr_t
6441   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6442   // as indeterminate instead?
6443   if (Value.isAbsent() && !T->isNullPtrType()) {
6444     APValue Printable;
6445     This.moveInto(Printable);
6446     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6447       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6448     return false;
6449   }
6450 
6451   // Invent an expression for location purposes.
6452   // FIXME: We shouldn't need to do this.
6453   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6454 
6455   // For arrays, destroy elements right-to-left.
6456   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6457     uint64_t Size = CAT->getSize().getZExtValue();
6458     QualType ElemT = CAT->getElementType();
6459 
6460     LValue ElemLV = This;
6461     ElemLV.addArray(Info, &LocE, CAT);
6462     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6463       return false;
6464 
6465     // Ensure that we have actual array elements available to destroy; the
6466     // destructors might mutate the value, so we can't run them on the array
6467     // filler.
6468     if (Size && Size > Value.getArrayInitializedElts())
6469       expandArray(Value, Value.getArraySize() - 1);
6470 
6471     for (; Size != 0; --Size) {
6472       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6473       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6474           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6475         return false;
6476     }
6477 
6478     // End the lifetime of this array now.
6479     Value = APValue();
6480     return true;
6481   }
6482 
6483   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6484   if (!RD) {
6485     if (T.isDestructedType()) {
6486       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6487       return false;
6488     }
6489 
6490     Value = APValue();
6491     return true;
6492   }
6493 
6494   if (RD->getNumVBases()) {
6495     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6496     return false;
6497   }
6498 
6499   const CXXDestructorDecl *DD = RD->getDestructor();
6500   if (!DD && !RD->hasTrivialDestructor()) {
6501     Info.FFDiag(CallLoc);
6502     return false;
6503   }
6504 
6505   if (!DD || DD->isTrivial() ||
6506       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6507     // A trivial destructor just ends the lifetime of the object. Check for
6508     // this case before checking for a body, because we might not bother
6509     // building a body for a trivial destructor. Note that it doesn't matter
6510     // whether the destructor is constexpr in this case; all trivial
6511     // destructors are constexpr.
6512     //
6513     // If an anonymous union would be destroyed, some enclosing destructor must
6514     // have been explicitly defined, and the anonymous union destruction should
6515     // have no effect.
6516     Value = APValue();
6517     return true;
6518   }
6519 
6520   if (!Info.CheckCallLimit(CallLoc))
6521     return false;
6522 
6523   const FunctionDecl *Definition = nullptr;
6524   const Stmt *Body = DD->getBody(Definition);
6525 
6526   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6527     return false;
6528 
6529   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6530 
6531   // We're now in the period of destruction of this object.
6532   unsigned BasesLeft = RD->getNumBases();
6533   EvalInfo::EvaluatingDestructorRAII EvalObj(
6534       Info,
6535       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6536   if (!EvalObj.DidInsert) {
6537     // C++2a [class.dtor]p19:
6538     //   the behavior is undefined if the destructor is invoked for an object
6539     //   whose lifetime has ended
6540     // (Note that formally the lifetime ends when the period of destruction
6541     // begins, even though certain uses of the object remain valid until the
6542     // period of destruction ends.)
6543     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6544     return false;
6545   }
6546 
6547   // FIXME: Creating an APValue just to hold a nonexistent return value is
6548   // wasteful.
6549   APValue RetVal;
6550   StmtResult Ret = {RetVal, nullptr};
6551   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6552     return false;
6553 
6554   // A union destructor does not implicitly destroy its members.
6555   if (RD->isUnion())
6556     return true;
6557 
6558   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6559 
6560   // We don't have a good way to iterate fields in reverse, so collect all the
6561   // fields first and then walk them backwards.
6562   SmallVector<FieldDecl*, 16> Fields(RD->fields());
6563   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6564     if (FD->isUnnamedBitfield())
6565       continue;
6566 
6567     LValue Subobject = This;
6568     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6569       return false;
6570 
6571     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6572     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6573                                FD->getType()))
6574       return false;
6575   }
6576 
6577   if (BasesLeft != 0)
6578     EvalObj.startedDestroyingBases();
6579 
6580   // Destroy base classes in reverse order.
6581   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6582     --BasesLeft;
6583 
6584     QualType BaseType = Base.getType();
6585     LValue Subobject = This;
6586     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6587                                 BaseType->getAsCXXRecordDecl(), &Layout))
6588       return false;
6589 
6590     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6591     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6592                                BaseType))
6593       return false;
6594   }
6595   assert(BasesLeft == 0 && "NumBases was wrong?");
6596 
6597   // The period of destruction ends now. The object is gone.
6598   Value = APValue();
6599   return true;
6600 }
6601 
6602 namespace {
6603 struct DestroyObjectHandler {
6604   EvalInfo &Info;
6605   const Expr *E;
6606   const LValue &This;
6607   const AccessKinds AccessKind;
6608 
6609   typedef bool result_type;
failed__anon7a1fdcea1411::DestroyObjectHandler6610   bool failed() { return false; }
found__anon7a1fdcea1411::DestroyObjectHandler6611   bool found(APValue &Subobj, QualType SubobjType) {
6612     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6613                                  SubobjType);
6614   }
found__anon7a1fdcea1411::DestroyObjectHandler6615   bool found(APSInt &Value, QualType SubobjType) {
6616     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6617     return false;
6618   }
found__anon7a1fdcea1411::DestroyObjectHandler6619   bool found(APFloat &Value, QualType SubobjType) {
6620     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6621     return false;
6622   }
6623 };
6624 }
6625 
6626 /// Perform a destructor or pseudo-destructor call on the given object, which
6627 /// might in general not be a complete object.
HandleDestruction(EvalInfo & Info,const Expr * E,const LValue & This,QualType ThisType)6628 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6629                               const LValue &This, QualType ThisType) {
6630   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6631   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6632   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6633 }
6634 
6635 /// Destroy and end the lifetime of the given complete object.
HandleDestruction(EvalInfo & Info,SourceLocation Loc,APValue::LValueBase LVBase,APValue & Value,QualType T)6636 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6637                               APValue::LValueBase LVBase, APValue &Value,
6638                               QualType T) {
6639   // If we've had an unmodeled side-effect, we can't rely on mutable state
6640   // (such as the object we're about to destroy) being correct.
6641   if (Info.EvalStatus.HasSideEffects)
6642     return false;
6643 
6644   LValue LV;
6645   LV.set({LVBase});
6646   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6647 }
6648 
6649 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
HandleOperatorNewCall(EvalInfo & Info,const CallExpr * E,LValue & Result)6650 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6651                                   LValue &Result) {
6652   if (Info.checkingPotentialConstantExpression() ||
6653       Info.SpeculativeEvaluationDepth)
6654     return false;
6655 
6656   // This is permitted only within a call to std::allocator<T>::allocate.
6657   auto Caller = Info.getStdAllocatorCaller("allocate");
6658   if (!Caller) {
6659     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6660                                      ? diag::note_constexpr_new_untyped
6661                                      : diag::note_constexpr_new);
6662     return false;
6663   }
6664 
6665   QualType ElemType = Caller.ElemType;
6666   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6667     Info.FFDiag(E->getExprLoc(),
6668                 diag::note_constexpr_new_not_complete_object_type)
6669         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6670     return false;
6671   }
6672 
6673   APSInt ByteSize;
6674   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6675     return false;
6676   bool IsNothrow = false;
6677   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6678     EvaluateIgnoredValue(Info, E->getArg(I));
6679     IsNothrow |= E->getType()->isNothrowT();
6680   }
6681 
6682   CharUnits ElemSize;
6683   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6684     return false;
6685   APInt Size, Remainder;
6686   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6687   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6688   if (Remainder != 0) {
6689     // This likely indicates a bug in the implementation of 'std::allocator'.
6690     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6691         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6692     return false;
6693   }
6694 
6695   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6696     if (IsNothrow) {
6697       Result.setNull(Info.Ctx, E->getType());
6698       return true;
6699     }
6700 
6701     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6702     return false;
6703   }
6704 
6705   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6706                                                      ArrayType::Normal, 0);
6707   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6708   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6709   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6710   return true;
6711 }
6712 
hasVirtualDestructor(QualType T)6713 static bool hasVirtualDestructor(QualType T) {
6714   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6715     if (CXXDestructorDecl *DD = RD->getDestructor())
6716       return DD->isVirtual();
6717   return false;
6718 }
6719 
getVirtualOperatorDelete(QualType T)6720 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6721   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6722     if (CXXDestructorDecl *DD = RD->getDestructor())
6723       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6724   return nullptr;
6725 }
6726 
6727 /// Check that the given object is a suitable pointer to a heap allocation that
6728 /// still exists and is of the right kind for the purpose of a deletion.
6729 ///
6730 /// On success, returns the heap allocation to deallocate. On failure, produces
6731 /// a diagnostic and returns None.
CheckDeleteKind(EvalInfo & Info,const Expr * E,const LValue & Pointer,DynAlloc::Kind DeallocKind)6732 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6733                                             const LValue &Pointer,
6734                                             DynAlloc::Kind DeallocKind) {
6735   auto PointerAsString = [&] {
6736     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6737   };
6738 
6739   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6740   if (!DA) {
6741     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6742         << PointerAsString();
6743     if (Pointer.Base)
6744       NoteLValueLocation(Info, Pointer.Base);
6745     return None;
6746   }
6747 
6748   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6749   if (!Alloc) {
6750     Info.FFDiag(E, diag::note_constexpr_double_delete);
6751     return None;
6752   }
6753 
6754   QualType AllocType = Pointer.Base.getDynamicAllocType();
6755   if (DeallocKind != (*Alloc)->getKind()) {
6756     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6757         << DeallocKind << (*Alloc)->getKind() << AllocType;
6758     NoteLValueLocation(Info, Pointer.Base);
6759     return None;
6760   }
6761 
6762   bool Subobject = false;
6763   if (DeallocKind == DynAlloc::New) {
6764     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6765                 Pointer.Designator.isOnePastTheEnd();
6766   } else {
6767     Subobject = Pointer.Designator.Entries.size() != 1 ||
6768                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6769   }
6770   if (Subobject) {
6771     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6772         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6773     return None;
6774   }
6775 
6776   return Alloc;
6777 }
6778 
6779 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
HandleOperatorDeleteCall(EvalInfo & Info,const CallExpr * E)6780 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6781   if (Info.checkingPotentialConstantExpression() ||
6782       Info.SpeculativeEvaluationDepth)
6783     return false;
6784 
6785   // This is permitted only within a call to std::allocator<T>::deallocate.
6786   if (!Info.getStdAllocatorCaller("deallocate")) {
6787     Info.FFDiag(E->getExprLoc());
6788     return true;
6789   }
6790 
6791   LValue Pointer;
6792   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6793     return false;
6794   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6795     EvaluateIgnoredValue(Info, E->getArg(I));
6796 
6797   if (Pointer.Designator.Invalid)
6798     return false;
6799 
6800   // Deleting a null pointer would have no effect, but it's not permitted by
6801   // std::allocator<T>::deallocate's contract.
6802   if (Pointer.isNullPointer()) {
6803     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6804     return true;
6805   }
6806 
6807   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6808     return false;
6809 
6810   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6811   return true;
6812 }
6813 
6814 //===----------------------------------------------------------------------===//
6815 // Generic Evaluation
6816 //===----------------------------------------------------------------------===//
6817 namespace {
6818 
6819 class BitCastBuffer {
6820   // FIXME: We're going to need bit-level granularity when we support
6821   // bit-fields.
6822   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6823   // we don't support a host or target where that is the case. Still, we should
6824   // use a more generic type in case we ever do.
6825   SmallVector<Optional<unsigned char>, 32> Bytes;
6826 
6827   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6828                 "Need at least 8 bit unsigned char");
6829 
6830   bool TargetIsLittleEndian;
6831 
6832 public:
BitCastBuffer(CharUnits Width,bool TargetIsLittleEndian)6833   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6834       : Bytes(Width.getQuantity()),
6835         TargetIsLittleEndian(TargetIsLittleEndian) {}
6836 
6837   LLVM_NODISCARD
readObject(CharUnits Offset,CharUnits Width,SmallVectorImpl<unsigned char> & Output) const6838   bool readObject(CharUnits Offset, CharUnits Width,
6839                   SmallVectorImpl<unsigned char> &Output) const {
6840     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6841       // If a byte of an integer is uninitialized, then the whole integer is
6842       // uninitialized.
6843       if (!Bytes[I.getQuantity()])
6844         return false;
6845       Output.push_back(*Bytes[I.getQuantity()]);
6846     }
6847     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6848       std::reverse(Output.begin(), Output.end());
6849     return true;
6850   }
6851 
writeObject(CharUnits Offset,SmallVectorImpl<unsigned char> & Input)6852   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6853     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6854       std::reverse(Input.begin(), Input.end());
6855 
6856     size_t Index = 0;
6857     for (unsigned char Byte : Input) {
6858       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6859       Bytes[Offset.getQuantity() + Index] = Byte;
6860       ++Index;
6861     }
6862   }
6863 
size()6864   size_t size() { return Bytes.size(); }
6865 };
6866 
6867 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6868 /// target would represent the value at runtime.
6869 class APValueToBufferConverter {
6870   EvalInfo &Info;
6871   BitCastBuffer Buffer;
6872   const CastExpr *BCE;
6873 
APValueToBufferConverter(EvalInfo & Info,CharUnits ObjectWidth,const CastExpr * BCE)6874   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6875                            const CastExpr *BCE)
6876       : Info(Info),
6877         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6878         BCE(BCE) {}
6879 
visit(const APValue & Val,QualType Ty)6880   bool visit(const APValue &Val, QualType Ty) {
6881     return visit(Val, Ty, CharUnits::fromQuantity(0));
6882   }
6883 
6884   // Write out Val with type Ty into Buffer starting at Offset.
visit(const APValue & Val,QualType Ty,CharUnits Offset)6885   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6886     assert((size_t)Offset.getQuantity() <= Buffer.size());
6887 
6888     // As a special case, nullptr_t has an indeterminate value.
6889     if (Ty->isNullPtrType())
6890       return true;
6891 
6892     // Dig through Src to find the byte at SrcOffset.
6893     switch (Val.getKind()) {
6894     case APValue::Indeterminate:
6895     case APValue::None:
6896       return true;
6897 
6898     case APValue::Int:
6899       return visitInt(Val.getInt(), Ty, Offset);
6900     case APValue::Float:
6901       return visitFloat(Val.getFloat(), Ty, Offset);
6902     case APValue::Array:
6903       return visitArray(Val, Ty, Offset);
6904     case APValue::Struct:
6905       return visitRecord(Val, Ty, Offset);
6906 
6907     case APValue::ComplexInt:
6908     case APValue::ComplexFloat:
6909     case APValue::Vector:
6910     case APValue::FixedPoint:
6911       // FIXME: We should support these.
6912 
6913     case APValue::Union:
6914     case APValue::MemberPointer:
6915     case APValue::AddrLabelDiff: {
6916       Info.FFDiag(BCE->getBeginLoc(),
6917                   diag::note_constexpr_bit_cast_unsupported_type)
6918           << Ty;
6919       return false;
6920     }
6921 
6922     case APValue::LValue:
6923       llvm_unreachable("LValue subobject in bit_cast?");
6924     }
6925     llvm_unreachable("Unhandled APValue::ValueKind");
6926   }
6927 
visitRecord(const APValue & Val,QualType Ty,CharUnits Offset)6928   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6929     const RecordDecl *RD = Ty->getAsRecordDecl();
6930     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6931 
6932     // Visit the base classes.
6933     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6934       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6935         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6936         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6937 
6938         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6939                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6940           return false;
6941       }
6942     }
6943 
6944     // Visit the fields.
6945     unsigned FieldIdx = 0;
6946     for (FieldDecl *FD : RD->fields()) {
6947       if (FD->isBitField()) {
6948         Info.FFDiag(BCE->getBeginLoc(),
6949                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6950         return false;
6951       }
6952 
6953       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6954 
6955       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6956              "only bit-fields can have sub-char alignment");
6957       CharUnits FieldOffset =
6958           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6959       QualType FieldTy = FD->getType();
6960       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6961         return false;
6962       ++FieldIdx;
6963     }
6964 
6965     return true;
6966   }
6967 
visitArray(const APValue & Val,QualType Ty,CharUnits Offset)6968   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6969     const auto *CAT =
6970         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6971     if (!CAT)
6972       return false;
6973 
6974     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6975     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6976     unsigned ArraySize = Val.getArraySize();
6977     // First, initialize the initialized elements.
6978     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6979       const APValue &SubObj = Val.getArrayInitializedElt(I);
6980       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6981         return false;
6982     }
6983 
6984     // Next, initialize the rest of the array using the filler.
6985     if (Val.hasArrayFiller()) {
6986       const APValue &Filler = Val.getArrayFiller();
6987       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6988         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6989           return false;
6990       }
6991     }
6992 
6993     return true;
6994   }
6995 
visitInt(const APSInt & Val,QualType Ty,CharUnits Offset)6996   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6997     APSInt AdjustedVal = Val;
6998     unsigned Width = AdjustedVal.getBitWidth();
6999     if (Ty->isBooleanType()) {
7000       Width = Info.Ctx.getTypeSize(Ty);
7001       AdjustedVal = AdjustedVal.extend(Width);
7002     }
7003 
7004     SmallVector<unsigned char, 8> Bytes(Width / 8);
7005     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7006     Buffer.writeObject(Offset, Bytes);
7007     return true;
7008   }
7009 
visitFloat(const APFloat & Val,QualType Ty,CharUnits Offset)7010   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7011     APSInt AsInt(Val.bitcastToAPInt());
7012     return visitInt(AsInt, Ty, Offset);
7013   }
7014 
7015 public:
convert(EvalInfo & Info,const APValue & Src,const CastExpr * BCE)7016   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
7017                                          const CastExpr *BCE) {
7018     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7019     APValueToBufferConverter Converter(Info, DstSize, BCE);
7020     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7021       return None;
7022     return Converter.Buffer;
7023   }
7024 };
7025 
7026 /// Write an BitCastBuffer into an APValue.
7027 class BufferToAPValueConverter {
7028   EvalInfo &Info;
7029   const BitCastBuffer &Buffer;
7030   const CastExpr *BCE;
7031 
BufferToAPValueConverter(EvalInfo & Info,const BitCastBuffer & Buffer,const CastExpr * BCE)7032   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7033                            const CastExpr *BCE)
7034       : Info(Info), Buffer(Buffer), BCE(BCE) {}
7035 
7036   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7037   // with an invalid type, so anything left is a deficiency on our part (FIXME).
7038   // Ideally this will be unreachable.
unsupportedType(QualType Ty)7039   llvm::NoneType unsupportedType(QualType Ty) {
7040     Info.FFDiag(BCE->getBeginLoc(),
7041                 diag::note_constexpr_bit_cast_unsupported_type)
7042         << Ty;
7043     return None;
7044   }
7045 
unrepresentableValue(QualType Ty,const APSInt & Val)7046   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
7047     Info.FFDiag(BCE->getBeginLoc(),
7048                 diag::note_constexpr_bit_cast_unrepresentable_value)
7049         << Ty << toString(Val, /*Radix=*/10);
7050     return None;
7051   }
7052 
visit(const BuiltinType * T,CharUnits Offset,const EnumType * EnumSugar=nullptr)7053   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7054                           const EnumType *EnumSugar = nullptr) {
7055     if (T->isNullPtrType()) {
7056       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7057       return APValue((Expr *)nullptr,
7058                      /*Offset=*/CharUnits::fromQuantity(NullValue),
7059                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7060     }
7061 
7062     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7063 
7064     // Work around floating point types that contain unused padding bytes. This
7065     // is really just `long double` on x86, which is the only fundamental type
7066     // with padding bytes.
7067     if (T->isRealFloatingType()) {
7068       const llvm::fltSemantics &Semantics =
7069           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7070       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7071       assert(NumBits % 8 == 0);
7072       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7073       if (NumBytes != SizeOf)
7074         SizeOf = NumBytes;
7075     }
7076 
7077     SmallVector<uint8_t, 8> Bytes;
7078     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7079       // If this is std::byte or unsigned char, then its okay to store an
7080       // indeterminate value.
7081       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7082       bool IsUChar =
7083           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7084                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7085       if (!IsStdByte && !IsUChar) {
7086         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7087         Info.FFDiag(BCE->getExprLoc(),
7088                     diag::note_constexpr_bit_cast_indet_dest)
7089             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7090         return None;
7091       }
7092 
7093       return APValue::IndeterminateValue();
7094     }
7095 
7096     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7097     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7098 
7099     if (T->isIntegralOrEnumerationType()) {
7100       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7101 
7102       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7103       if (IntWidth != Val.getBitWidth()) {
7104         APSInt Truncated = Val.trunc(IntWidth);
7105         if (Truncated.extend(Val.getBitWidth()) != Val)
7106           return unrepresentableValue(QualType(T, 0), Val);
7107         Val = Truncated;
7108       }
7109 
7110       return APValue(Val);
7111     }
7112 
7113     if (T->isRealFloatingType()) {
7114       const llvm::fltSemantics &Semantics =
7115           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7116       return APValue(APFloat(Semantics, Val));
7117     }
7118 
7119     return unsupportedType(QualType(T, 0));
7120   }
7121 
visit(const RecordType * RTy,CharUnits Offset)7122   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7123     const RecordDecl *RD = RTy->getAsRecordDecl();
7124     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7125 
7126     unsigned NumBases = 0;
7127     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7128       NumBases = CXXRD->getNumBases();
7129 
7130     APValue ResultVal(APValue::UninitStruct(), NumBases,
7131                       std::distance(RD->field_begin(), RD->field_end()));
7132 
7133     // Visit the base classes.
7134     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7135       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7136         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7137         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7138         if (BaseDecl->isEmpty() ||
7139             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7140           continue;
7141 
7142         Optional<APValue> SubObj = visitType(
7143             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7144         if (!SubObj)
7145           return None;
7146         ResultVal.getStructBase(I) = *SubObj;
7147       }
7148     }
7149 
7150     // Visit the fields.
7151     unsigned FieldIdx = 0;
7152     for (FieldDecl *FD : RD->fields()) {
7153       // FIXME: We don't currently support bit-fields. A lot of the logic for
7154       // this is in CodeGen, so we need to factor it around.
7155       if (FD->isBitField()) {
7156         Info.FFDiag(BCE->getBeginLoc(),
7157                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7158         return None;
7159       }
7160 
7161       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7162       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7163 
7164       CharUnits FieldOffset =
7165           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7166           Offset;
7167       QualType FieldTy = FD->getType();
7168       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7169       if (!SubObj)
7170         return None;
7171       ResultVal.getStructField(FieldIdx) = *SubObj;
7172       ++FieldIdx;
7173     }
7174 
7175     return ResultVal;
7176   }
7177 
visit(const EnumType * Ty,CharUnits Offset)7178   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7179     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7180     assert(!RepresentationType.isNull() &&
7181            "enum forward decl should be caught by Sema");
7182     const auto *AsBuiltin =
7183         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7184     // Recurse into the underlying type. Treat std::byte transparently as
7185     // unsigned char.
7186     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7187   }
7188 
visit(const ConstantArrayType * Ty,CharUnits Offset)7189   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7190     size_t Size = Ty->getSize().getLimitedValue();
7191     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7192 
7193     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7194     for (size_t I = 0; I != Size; ++I) {
7195       Optional<APValue> ElementValue =
7196           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7197       if (!ElementValue)
7198         return None;
7199       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7200     }
7201 
7202     return ArrayValue;
7203   }
7204 
visit(const Type * Ty,CharUnits Offset)7205   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7206     return unsupportedType(QualType(Ty, 0));
7207   }
7208 
visitType(QualType Ty,CharUnits Offset)7209   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7210     QualType Can = Ty.getCanonicalType();
7211 
7212     switch (Can->getTypeClass()) {
7213 #define TYPE(Class, Base)                                                      \
7214   case Type::Class:                                                            \
7215     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7216 #define ABSTRACT_TYPE(Class, Base)
7217 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7218   case Type::Class:                                                            \
7219     llvm_unreachable("non-canonical type should be impossible!");
7220 #define DEPENDENT_TYPE(Class, Base)                                            \
7221   case Type::Class:                                                            \
7222     llvm_unreachable(                                                          \
7223         "dependent types aren't supported in the constant evaluator!");
7224 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7225   case Type::Class:                                                            \
7226     llvm_unreachable("either dependent or not canonical!");
7227 #include "clang/AST/TypeNodes.inc"
7228     }
7229     llvm_unreachable("Unhandled Type::TypeClass");
7230   }
7231 
7232 public:
7233   // Pull out a full value of type DstType.
convert(EvalInfo & Info,BitCastBuffer & Buffer,const CastExpr * BCE)7234   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7235                                    const CastExpr *BCE) {
7236     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7237     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7238   }
7239 };
7240 
checkBitCastConstexprEligibilityType(SourceLocation Loc,QualType Ty,EvalInfo * Info,const ASTContext & Ctx,bool CheckingDest)7241 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7242                                                  QualType Ty, EvalInfo *Info,
7243                                                  const ASTContext &Ctx,
7244                                                  bool CheckingDest) {
7245   Ty = Ty.getCanonicalType();
7246 
7247   auto diag = [&](int Reason) {
7248     if (Info)
7249       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7250           << CheckingDest << (Reason == 4) << Reason;
7251     return false;
7252   };
7253   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7254     if (Info)
7255       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7256           << NoteTy << Construct << Ty;
7257     return false;
7258   };
7259 
7260   if (Ty->isUnionType())
7261     return diag(0);
7262   if (Ty->isPointerType())
7263     return diag(1);
7264   if (Ty->isMemberPointerType())
7265     return diag(2);
7266   if (Ty.isVolatileQualified())
7267     return diag(3);
7268 
7269   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7270     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7271       for (CXXBaseSpecifier &BS : CXXRD->bases())
7272         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7273                                                   CheckingDest))
7274           return note(1, BS.getType(), BS.getBeginLoc());
7275     }
7276     for (FieldDecl *FD : Record->fields()) {
7277       if (FD->getType()->isReferenceType())
7278         return diag(4);
7279       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7280                                                 CheckingDest))
7281         return note(0, FD->getType(), FD->getBeginLoc());
7282     }
7283   }
7284 
7285   if (Ty->isArrayType() &&
7286       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7287                                             Info, Ctx, CheckingDest))
7288     return false;
7289 
7290   return true;
7291 }
7292 
checkBitCastConstexprEligibility(EvalInfo * Info,const ASTContext & Ctx,const CastExpr * BCE)7293 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7294                                              const ASTContext &Ctx,
7295                                              const CastExpr *BCE) {
7296   bool DestOK = checkBitCastConstexprEligibilityType(
7297       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7298   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7299                                 BCE->getBeginLoc(),
7300                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7301   return SourceOK;
7302 }
7303 
handleLValueToRValueBitCast(EvalInfo & Info,APValue & DestValue,APValue & SourceValue,const CastExpr * BCE)7304 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7305                                         APValue &SourceValue,
7306                                         const CastExpr *BCE) {
7307   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7308          "no host or target supports non 8-bit chars");
7309   assert(SourceValue.isLValue() &&
7310          "LValueToRValueBitcast requires an lvalue operand!");
7311 
7312   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7313     return false;
7314 
7315   LValue SourceLValue;
7316   APValue SourceRValue;
7317   SourceLValue.setFrom(Info.Ctx, SourceValue);
7318   if (!handleLValueToRValueConversion(
7319           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7320           SourceRValue, /*WantObjectRepresentation=*/true))
7321     return false;
7322 
7323   // Read out SourceValue into a char buffer.
7324   Optional<BitCastBuffer> Buffer =
7325       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7326   if (!Buffer)
7327     return false;
7328 
7329   // Write out the buffer into a new APValue.
7330   Optional<APValue> MaybeDestValue =
7331       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7332   if (!MaybeDestValue)
7333     return false;
7334 
7335   DestValue = std::move(*MaybeDestValue);
7336   return true;
7337 }
7338 
7339 template <class Derived>
7340 class ExprEvaluatorBase
7341   : public ConstStmtVisitor<Derived, bool> {
7342 private:
getDerived()7343   Derived &getDerived() { return static_cast<Derived&>(*this); }
DerivedSuccess(const APValue & V,const Expr * E)7344   bool DerivedSuccess(const APValue &V, const Expr *E) {
7345     return getDerived().Success(V, E);
7346   }
DerivedZeroInitialization(const Expr * E)7347   bool DerivedZeroInitialization(const Expr *E) {
7348     return getDerived().ZeroInitialization(E);
7349   }
7350 
7351   // Check whether a conditional operator with a non-constant condition is a
7352   // potential constant expression. If neither arm is a potential constant
7353   // expression, then the conditional operator is not either.
7354   template<typename ConditionalOperator>
CheckPotentialConstantConditional(const ConditionalOperator * E)7355   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7356     assert(Info.checkingPotentialConstantExpression());
7357 
7358     // Speculatively evaluate both arms.
7359     SmallVector<PartialDiagnosticAt, 8> Diag;
7360     {
7361       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7362       StmtVisitorTy::Visit(E->getFalseExpr());
7363       if (Diag.empty())
7364         return;
7365     }
7366 
7367     {
7368       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7369       Diag.clear();
7370       StmtVisitorTy::Visit(E->getTrueExpr());
7371       if (Diag.empty())
7372         return;
7373     }
7374 
7375     Error(E, diag::note_constexpr_conditional_never_const);
7376   }
7377 
7378 
7379   template<typename ConditionalOperator>
HandleConditionalOperator(const ConditionalOperator * E)7380   bool HandleConditionalOperator(const ConditionalOperator *E) {
7381     bool BoolResult;
7382     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7383       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7384         CheckPotentialConstantConditional(E);
7385         return false;
7386       }
7387       if (Info.noteFailure()) {
7388         StmtVisitorTy::Visit(E->getTrueExpr());
7389         StmtVisitorTy::Visit(E->getFalseExpr());
7390       }
7391       return false;
7392     }
7393 
7394     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7395     return StmtVisitorTy::Visit(EvalExpr);
7396   }
7397 
7398 protected:
7399   EvalInfo &Info;
7400   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7401   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7402 
CCEDiag(const Expr * E,diag::kind D)7403   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7404     return Info.CCEDiag(E, D);
7405   }
7406 
ZeroInitialization(const Expr * E)7407   bool ZeroInitialization(const Expr *E) { return Error(E); }
7408 
7409 public:
ExprEvaluatorBase(EvalInfo & Info)7410   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7411 
getEvalInfo()7412   EvalInfo &getEvalInfo() { return Info; }
7413 
7414   /// Report an evaluation error. This should only be called when an error is
7415   /// first discovered. When propagating an error, just return false.
Error(const Expr * E,diag::kind D)7416   bool Error(const Expr *E, diag::kind D) {
7417     Info.FFDiag(E, D);
7418     return false;
7419   }
Error(const Expr * E)7420   bool Error(const Expr *E) {
7421     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7422   }
7423 
VisitStmt(const Stmt *)7424   bool VisitStmt(const Stmt *) {
7425     llvm_unreachable("Expression evaluator should not be called on stmts");
7426   }
VisitExpr(const Expr * E)7427   bool VisitExpr(const Expr *E) {
7428     return Error(E);
7429   }
7430 
VisitConstantExpr(const ConstantExpr * E)7431   bool VisitConstantExpr(const ConstantExpr *E) {
7432     if (E->hasAPValueResult())
7433       return DerivedSuccess(E->getAPValueResult(), E);
7434 
7435     return StmtVisitorTy::Visit(E->getSubExpr());
7436   }
7437 
VisitParenExpr(const ParenExpr * E)7438   bool VisitParenExpr(const ParenExpr *E)
7439     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryExtension(const UnaryOperator * E)7440   bool VisitUnaryExtension(const UnaryOperator *E)
7441     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryPlus(const UnaryOperator * E)7442   bool VisitUnaryPlus(const UnaryOperator *E)
7443     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitChooseExpr(const ChooseExpr * E)7444   bool VisitChooseExpr(const ChooseExpr *E)
7445     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
VisitGenericSelectionExpr(const GenericSelectionExpr * E)7446   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7447     { return StmtVisitorTy::Visit(E->getResultExpr()); }
VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr * E)7448   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7449     { return StmtVisitorTy::Visit(E->getReplacement()); }
VisitCXXDefaultArgExpr(const CXXDefaultArgExpr * E)7450   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7451     TempVersionRAII RAII(*Info.CurrentCall);
7452     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7453     return StmtVisitorTy::Visit(E->getExpr());
7454   }
VisitCXXDefaultInitExpr(const CXXDefaultInitExpr * E)7455   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7456     TempVersionRAII RAII(*Info.CurrentCall);
7457     // The initializer may not have been parsed yet, or might be erroneous.
7458     if (!E->getExpr())
7459       return Error(E);
7460     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7461     return StmtVisitorTy::Visit(E->getExpr());
7462   }
7463 
VisitExprWithCleanups(const ExprWithCleanups * E)7464   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7465     FullExpressionRAII Scope(Info);
7466     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7467   }
7468 
7469   // Temporaries are registered when created, so we don't care about
7470   // CXXBindTemporaryExpr.
VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr * E)7471   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7472     return StmtVisitorTy::Visit(E->getSubExpr());
7473   }
7474 
VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr * E)7475   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7476     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7477     return static_cast<Derived*>(this)->VisitCastExpr(E);
7478   }
VisitCXXDynamicCastExpr(const CXXDynamicCastExpr * E)7479   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7480     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7481       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7482     return static_cast<Derived*>(this)->VisitCastExpr(E);
7483   }
VisitBuiltinBitCastExpr(const BuiltinBitCastExpr * E)7484   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7485     return static_cast<Derived*>(this)->VisitCastExpr(E);
7486   }
7487 
VisitBinaryOperator(const BinaryOperator * E)7488   bool VisitBinaryOperator(const BinaryOperator *E) {
7489     switch (E->getOpcode()) {
7490     default:
7491       return Error(E);
7492 
7493     case BO_Comma:
7494       VisitIgnoredValue(E->getLHS());
7495       return StmtVisitorTy::Visit(E->getRHS());
7496 
7497     case BO_PtrMemD:
7498     case BO_PtrMemI: {
7499       LValue Obj;
7500       if (!HandleMemberPointerAccess(Info, E, Obj))
7501         return false;
7502       APValue Result;
7503       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7504         return false;
7505       return DerivedSuccess(Result, E);
7506     }
7507     }
7508   }
7509 
VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator * E)7510   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7511     return StmtVisitorTy::Visit(E->getSemanticForm());
7512   }
7513 
VisitBinaryConditionalOperator(const BinaryConditionalOperator * E)7514   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7515     // Evaluate and cache the common expression. We treat it as a temporary,
7516     // even though it's not quite the same thing.
7517     LValue CommonLV;
7518     if (!Evaluate(Info.CurrentCall->createTemporary(
7519                       E->getOpaqueValue(),
7520                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7521                       ScopeKind::FullExpression, CommonLV),
7522                   Info, E->getCommon()))
7523       return false;
7524 
7525     return HandleConditionalOperator(E);
7526   }
7527 
VisitConditionalOperator(const ConditionalOperator * E)7528   bool VisitConditionalOperator(const ConditionalOperator *E) {
7529     bool IsBcpCall = false;
7530     // If the condition (ignoring parens) is a __builtin_constant_p call,
7531     // the result is a constant expression if it can be folded without
7532     // side-effects. This is an important GNU extension. See GCC PR38377
7533     // for discussion.
7534     if (const CallExpr *CallCE =
7535           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7536       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7537         IsBcpCall = true;
7538 
7539     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7540     // constant expression; we can't check whether it's potentially foldable.
7541     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7542     // it would return 'false' in this mode.
7543     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7544       return false;
7545 
7546     FoldConstant Fold(Info, IsBcpCall);
7547     if (!HandleConditionalOperator(E)) {
7548       Fold.keepDiagnostics();
7549       return false;
7550     }
7551 
7552     return true;
7553   }
7554 
VisitOpaqueValueExpr(const OpaqueValueExpr * E)7555   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7556     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7557       return DerivedSuccess(*Value, E);
7558 
7559     const Expr *Source = E->getSourceExpr();
7560     if (!Source)
7561       return Error(E);
7562     if (Source == E) {
7563       assert(0 && "OpaqueValueExpr recursively refers to itself");
7564       return Error(E);
7565     }
7566     return StmtVisitorTy::Visit(Source);
7567   }
7568 
VisitPseudoObjectExpr(const PseudoObjectExpr * E)7569   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7570     for (const Expr *SemE : E->semantics()) {
7571       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7572         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7573         // result expression: there could be two different LValues that would
7574         // refer to the same object in that case, and we can't model that.
7575         if (SemE == E->getResultExpr())
7576           return Error(E);
7577 
7578         // Unique OVEs get evaluated if and when we encounter them when
7579         // emitting the rest of the semantic form, rather than eagerly.
7580         if (OVE->isUnique())
7581           continue;
7582 
7583         LValue LV;
7584         if (!Evaluate(Info.CurrentCall->createTemporary(
7585                           OVE, getStorageType(Info.Ctx, OVE),
7586                           ScopeKind::FullExpression, LV),
7587                       Info, OVE->getSourceExpr()))
7588           return false;
7589       } else if (SemE == E->getResultExpr()) {
7590         if (!StmtVisitorTy::Visit(SemE))
7591           return false;
7592       } else {
7593         if (!EvaluateIgnoredValue(Info, SemE))
7594           return false;
7595       }
7596     }
7597     return true;
7598   }
7599 
VisitCallExpr(const CallExpr * E)7600   bool VisitCallExpr(const CallExpr *E) {
7601     APValue Result;
7602     if (!handleCallExpr(E, Result, nullptr))
7603       return false;
7604     return DerivedSuccess(Result, E);
7605   }
7606 
handleCallExpr(const CallExpr * E,APValue & Result,const LValue * ResultSlot)7607   bool handleCallExpr(const CallExpr *E, APValue &Result,
7608                      const LValue *ResultSlot) {
7609     CallScopeRAII CallScope(Info);
7610 
7611     const Expr *Callee = E->getCallee()->IgnoreParens();
7612     QualType CalleeType = Callee->getType();
7613 
7614     const FunctionDecl *FD = nullptr;
7615     LValue *This = nullptr, ThisVal;
7616     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7617     bool HasQualifier = false;
7618 
7619     CallRef Call;
7620 
7621     // Extract function decl and 'this' pointer from the callee.
7622     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7623       const CXXMethodDecl *Member = nullptr;
7624       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7625         // Explicit bound member calls, such as x.f() or p->g();
7626         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7627           return false;
7628         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7629         if (!Member)
7630           return Error(Callee);
7631         This = &ThisVal;
7632         HasQualifier = ME->hasQualifier();
7633       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7634         // Indirect bound member calls ('.*' or '->*').
7635         const ValueDecl *D =
7636             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7637         if (!D)
7638           return false;
7639         Member = dyn_cast<CXXMethodDecl>(D);
7640         if (!Member)
7641           return Error(Callee);
7642         This = &ThisVal;
7643       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7644         if (!Info.getLangOpts().CPlusPlus20)
7645           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7646         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7647                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7648       } else
7649         return Error(Callee);
7650       FD = Member;
7651     } else if (CalleeType->isFunctionPointerType()) {
7652       LValue CalleeLV;
7653       if (!EvaluatePointer(Callee, CalleeLV, Info))
7654         return false;
7655 
7656       if (!CalleeLV.getLValueOffset().isZero())
7657         return Error(Callee);
7658       FD = dyn_cast_or_null<FunctionDecl>(
7659           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7660       if (!FD)
7661         return Error(Callee);
7662       // Don't call function pointers which have been cast to some other type.
7663       // Per DR (no number yet), the caller and callee can differ in noexcept.
7664       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7665         CalleeType->getPointeeType(), FD->getType())) {
7666         return Error(E);
7667       }
7668 
7669       // For an (overloaded) assignment expression, evaluate the RHS before the
7670       // LHS.
7671       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7672       if (OCE && OCE->isAssignmentOp()) {
7673         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7674         Call = Info.CurrentCall->createCall(FD);
7675         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7676                           Info, FD, /*RightToLeft=*/true))
7677           return false;
7678       }
7679 
7680       // Overloaded operator calls to member functions are represented as normal
7681       // calls with '*this' as the first argument.
7682       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7683       if (MD && !MD->isStatic()) {
7684         // FIXME: When selecting an implicit conversion for an overloaded
7685         // operator delete, we sometimes try to evaluate calls to conversion
7686         // operators without a 'this' parameter!
7687         if (Args.empty())
7688           return Error(E);
7689 
7690         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7691           return false;
7692         This = &ThisVal;
7693 
7694         // If this is syntactically a simple assignment using a trivial
7695         // assignment operator, start the lifetimes of union members as needed,
7696         // per C++20 [class.union]5.
7697         if (Info.getLangOpts().CPlusPlus20 && OCE &&
7698             OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7699             !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7700           return false;
7701 
7702         Args = Args.slice(1);
7703       } else if (MD && MD->isLambdaStaticInvoker()) {
7704         // Map the static invoker for the lambda back to the call operator.
7705         // Conveniently, we don't have to slice out the 'this' argument (as is
7706         // being done for the non-static case), since a static member function
7707         // doesn't have an implicit argument passed in.
7708         const CXXRecordDecl *ClosureClass = MD->getParent();
7709         assert(
7710             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7711             "Number of captures must be zero for conversion to function-ptr");
7712 
7713         const CXXMethodDecl *LambdaCallOp =
7714             ClosureClass->getLambdaCallOperator();
7715 
7716         // Set 'FD', the function that will be called below, to the call
7717         // operator.  If the closure object represents a generic lambda, find
7718         // the corresponding specialization of the call operator.
7719 
7720         if (ClosureClass->isGenericLambda()) {
7721           assert(MD->isFunctionTemplateSpecialization() &&
7722                  "A generic lambda's static-invoker function must be a "
7723                  "template specialization");
7724           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7725           FunctionTemplateDecl *CallOpTemplate =
7726               LambdaCallOp->getDescribedFunctionTemplate();
7727           void *InsertPos = nullptr;
7728           FunctionDecl *CorrespondingCallOpSpecialization =
7729               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7730           assert(CorrespondingCallOpSpecialization &&
7731                  "We must always have a function call operator specialization "
7732                  "that corresponds to our static invoker specialization");
7733           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7734         } else
7735           FD = LambdaCallOp;
7736       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7737         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7738             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7739           LValue Ptr;
7740           if (!HandleOperatorNewCall(Info, E, Ptr))
7741             return false;
7742           Ptr.moveInto(Result);
7743           return CallScope.destroy();
7744         } else {
7745           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7746         }
7747       }
7748     } else
7749       return Error(E);
7750 
7751     // Evaluate the arguments now if we've not already done so.
7752     if (!Call) {
7753       Call = Info.CurrentCall->createCall(FD);
7754       if (!EvaluateArgs(Args, Call, Info, FD))
7755         return false;
7756     }
7757 
7758     SmallVector<QualType, 4> CovariantAdjustmentPath;
7759     if (This) {
7760       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7761       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7762         // Perform virtual dispatch, if necessary.
7763         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7764                                    CovariantAdjustmentPath);
7765         if (!FD)
7766           return false;
7767       } else {
7768         // Check that the 'this' pointer points to an object of the right type.
7769         // FIXME: If this is an assignment operator call, we may need to change
7770         // the active union member before we check this.
7771         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7772           return false;
7773       }
7774     }
7775 
7776     // Destructor calls are different enough that they have their own codepath.
7777     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7778       assert(This && "no 'this' pointer for destructor call");
7779       return HandleDestruction(Info, E, *This,
7780                                Info.Ctx.getRecordType(DD->getParent())) &&
7781              CallScope.destroy();
7782     }
7783 
7784     const FunctionDecl *Definition = nullptr;
7785     Stmt *Body = FD->getBody(Definition);
7786 
7787     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7788         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7789                             Body, Info, Result, ResultSlot))
7790       return false;
7791 
7792     if (!CovariantAdjustmentPath.empty() &&
7793         !HandleCovariantReturnAdjustment(Info, E, Result,
7794                                          CovariantAdjustmentPath))
7795       return false;
7796 
7797     return CallScope.destroy();
7798   }
7799 
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)7800   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7801     return StmtVisitorTy::Visit(E->getInitializer());
7802   }
VisitInitListExpr(const InitListExpr * E)7803   bool VisitInitListExpr(const InitListExpr *E) {
7804     if (E->getNumInits() == 0)
7805       return DerivedZeroInitialization(E);
7806     if (E->getNumInits() == 1)
7807       return StmtVisitorTy::Visit(E->getInit(0));
7808     return Error(E);
7809   }
VisitImplicitValueInitExpr(const ImplicitValueInitExpr * E)7810   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7811     return DerivedZeroInitialization(E);
7812   }
VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr * E)7813   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7814     return DerivedZeroInitialization(E);
7815   }
VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr * E)7816   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7817     return DerivedZeroInitialization(E);
7818   }
7819 
7820   /// A member expression where the object is a prvalue is itself a prvalue.
VisitMemberExpr(const MemberExpr * E)7821   bool VisitMemberExpr(const MemberExpr *E) {
7822     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7823            "missing temporary materialization conversion");
7824     assert(!E->isArrow() && "missing call to bound member function?");
7825 
7826     APValue Val;
7827     if (!Evaluate(Val, Info, E->getBase()))
7828       return false;
7829 
7830     QualType BaseTy = E->getBase()->getType();
7831 
7832     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7833     if (!FD) return Error(E);
7834     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7835     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7836            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7837 
7838     // Note: there is no lvalue base here. But this case should only ever
7839     // happen in C or in C++98, where we cannot be evaluating a constexpr
7840     // constructor, which is the only case the base matters.
7841     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7842     SubobjectDesignator Designator(BaseTy);
7843     Designator.addDeclUnchecked(FD);
7844 
7845     APValue Result;
7846     return extractSubobject(Info, E, Obj, Designator, Result) &&
7847            DerivedSuccess(Result, E);
7848   }
7849 
VisitExtVectorElementExpr(const ExtVectorElementExpr * E)7850   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7851     APValue Val;
7852     if (!Evaluate(Val, Info, E->getBase()))
7853       return false;
7854 
7855     if (Val.isVector()) {
7856       SmallVector<uint32_t, 4> Indices;
7857       E->getEncodedElementAccess(Indices);
7858       if (Indices.size() == 1) {
7859         // Return scalar.
7860         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7861       } else {
7862         // Construct new APValue vector.
7863         SmallVector<APValue, 4> Elts;
7864         for (unsigned I = 0; I < Indices.size(); ++I) {
7865           Elts.push_back(Val.getVectorElt(Indices[I]));
7866         }
7867         APValue VecResult(Elts.data(), Indices.size());
7868         return DerivedSuccess(VecResult, E);
7869       }
7870     }
7871 
7872     return false;
7873   }
7874 
VisitCastExpr(const CastExpr * E)7875   bool VisitCastExpr(const CastExpr *E) {
7876     switch (E->getCastKind()) {
7877     default:
7878       break;
7879 
7880     case CK_AtomicToNonAtomic: {
7881       APValue AtomicVal;
7882       // This does not need to be done in place even for class/array types:
7883       // atomic-to-non-atomic conversion implies copying the object
7884       // representation.
7885       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7886         return false;
7887       return DerivedSuccess(AtomicVal, E);
7888     }
7889 
7890     case CK_NoOp:
7891     case CK_UserDefinedConversion:
7892       return StmtVisitorTy::Visit(E->getSubExpr());
7893 
7894     case CK_LValueToRValue: {
7895       LValue LVal;
7896       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7897         return false;
7898       APValue RVal;
7899       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7900       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7901                                           LVal, RVal))
7902         return false;
7903       return DerivedSuccess(RVal, E);
7904     }
7905     case CK_LValueToRValueBitCast: {
7906       APValue DestValue, SourceValue;
7907       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7908         return false;
7909       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7910         return false;
7911       return DerivedSuccess(DestValue, E);
7912     }
7913 
7914     case CK_AddressSpaceConversion: {
7915       APValue Value;
7916       if (!Evaluate(Value, Info, E->getSubExpr()))
7917         return false;
7918       return DerivedSuccess(Value, E);
7919     }
7920     }
7921 
7922     return Error(E);
7923   }
7924 
VisitUnaryPostInc(const UnaryOperator * UO)7925   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7926     return VisitUnaryPostIncDec(UO);
7927   }
VisitUnaryPostDec(const UnaryOperator * UO)7928   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7929     return VisitUnaryPostIncDec(UO);
7930   }
VisitUnaryPostIncDec(const UnaryOperator * UO)7931   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7932     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7933       return Error(UO);
7934 
7935     LValue LVal;
7936     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7937       return false;
7938     APValue RVal;
7939     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7940                       UO->isIncrementOp(), &RVal))
7941       return false;
7942     return DerivedSuccess(RVal, UO);
7943   }
7944 
VisitStmtExpr(const StmtExpr * E)7945   bool VisitStmtExpr(const StmtExpr *E) {
7946     // We will have checked the full-expressions inside the statement expression
7947     // when they were completed, and don't need to check them again now.
7948     llvm::SaveAndRestore<bool> NotCheckingForUB(
7949         Info.CheckingForUndefinedBehavior, false);
7950 
7951     const CompoundStmt *CS = E->getSubStmt();
7952     if (CS->body_empty())
7953       return true;
7954 
7955     BlockScopeRAII Scope(Info);
7956     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7957                                            BE = CS->body_end();
7958          /**/; ++BI) {
7959       if (BI + 1 == BE) {
7960         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7961         if (!FinalExpr) {
7962           Info.FFDiag((*BI)->getBeginLoc(),
7963                       diag::note_constexpr_stmt_expr_unsupported);
7964           return false;
7965         }
7966         return this->Visit(FinalExpr) && Scope.destroy();
7967       }
7968 
7969       APValue ReturnValue;
7970       StmtResult Result = { ReturnValue, nullptr };
7971       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7972       if (ESR != ESR_Succeeded) {
7973         // FIXME: If the statement-expression terminated due to 'return',
7974         // 'break', or 'continue', it would be nice to propagate that to
7975         // the outer statement evaluation rather than bailing out.
7976         if (ESR != ESR_Failed)
7977           Info.FFDiag((*BI)->getBeginLoc(),
7978                       diag::note_constexpr_stmt_expr_unsupported);
7979         return false;
7980       }
7981     }
7982 
7983     llvm_unreachable("Return from function from the loop above.");
7984   }
7985 
7986   /// Visit a value which is evaluated, but whose value is ignored.
VisitIgnoredValue(const Expr * E)7987   void VisitIgnoredValue(const Expr *E) {
7988     EvaluateIgnoredValue(Info, E);
7989   }
7990 
7991   /// Potentially visit a MemberExpr's base expression.
VisitIgnoredBaseExpression(const Expr * E)7992   void VisitIgnoredBaseExpression(const Expr *E) {
7993     // While MSVC doesn't evaluate the base expression, it does diagnose the
7994     // presence of side-effecting behavior.
7995     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7996       return;
7997     VisitIgnoredValue(E);
7998   }
7999 };
8000 
8001 } // namespace
8002 
8003 //===----------------------------------------------------------------------===//
8004 // Common base class for lvalue and temporary evaluation.
8005 //===----------------------------------------------------------------------===//
8006 namespace {
8007 template<class Derived>
8008 class LValueExprEvaluatorBase
8009   : public ExprEvaluatorBase<Derived> {
8010 protected:
8011   LValue &Result;
8012   bool InvalidBaseOK;
8013   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8014   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8015 
Success(APValue::LValueBase B)8016   bool Success(APValue::LValueBase B) {
8017     Result.set(B);
8018     return true;
8019   }
8020 
evaluatePointer(const Expr * E,LValue & Result)8021   bool evaluatePointer(const Expr *E, LValue &Result) {
8022     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8023   }
8024 
8025 public:
LValueExprEvaluatorBase(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)8026   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8027       : ExprEvaluatorBaseTy(Info), Result(Result),
8028         InvalidBaseOK(InvalidBaseOK) {}
8029 
Success(const APValue & V,const Expr * E)8030   bool Success(const APValue &V, const Expr *E) {
8031     Result.setFrom(this->Info.Ctx, V);
8032     return true;
8033   }
8034 
VisitMemberExpr(const MemberExpr * E)8035   bool VisitMemberExpr(const MemberExpr *E) {
8036     // Handle non-static data members.
8037     QualType BaseTy;
8038     bool EvalOK;
8039     if (E->isArrow()) {
8040       EvalOK = evaluatePointer(E->getBase(), Result);
8041       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8042     } else if (E->getBase()->isPRValue()) {
8043       assert(E->getBase()->getType()->isRecordType());
8044       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8045       BaseTy = E->getBase()->getType();
8046     } else {
8047       EvalOK = this->Visit(E->getBase());
8048       BaseTy = E->getBase()->getType();
8049     }
8050     if (!EvalOK) {
8051       if (!InvalidBaseOK)
8052         return false;
8053       Result.setInvalid(E);
8054       return true;
8055     }
8056 
8057     const ValueDecl *MD = E->getMemberDecl();
8058     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8059       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8060              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8061       (void)BaseTy;
8062       if (!HandleLValueMember(this->Info, E, Result, FD))
8063         return false;
8064     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8065       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8066         return false;
8067     } else
8068       return this->Error(E);
8069 
8070     if (MD->getType()->isReferenceType()) {
8071       APValue RefValue;
8072       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8073                                           RefValue))
8074         return false;
8075       return Success(RefValue, E);
8076     }
8077     return true;
8078   }
8079 
VisitBinaryOperator(const BinaryOperator * E)8080   bool VisitBinaryOperator(const BinaryOperator *E) {
8081     switch (E->getOpcode()) {
8082     default:
8083       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8084 
8085     case BO_PtrMemD:
8086     case BO_PtrMemI:
8087       return HandleMemberPointerAccess(this->Info, E, Result);
8088     }
8089   }
8090 
VisitCastExpr(const CastExpr * E)8091   bool VisitCastExpr(const CastExpr *E) {
8092     switch (E->getCastKind()) {
8093     default:
8094       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8095 
8096     case CK_DerivedToBase:
8097     case CK_UncheckedDerivedToBase:
8098       if (!this->Visit(E->getSubExpr()))
8099         return false;
8100 
8101       // Now figure out the necessary offset to add to the base LV to get from
8102       // the derived class to the base class.
8103       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8104                                   Result);
8105     }
8106   }
8107 };
8108 }
8109 
8110 //===----------------------------------------------------------------------===//
8111 // LValue Evaluation
8112 //
8113 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8114 // function designators (in C), decl references to void objects (in C), and
8115 // temporaries (if building with -Wno-address-of-temporary).
8116 //
8117 // LValue evaluation produces values comprising a base expression of one of the
8118 // following types:
8119 // - Declarations
8120 //  * VarDecl
8121 //  * FunctionDecl
8122 // - Literals
8123 //  * CompoundLiteralExpr in C (and in global scope in C++)
8124 //  * StringLiteral
8125 //  * PredefinedExpr
8126 //  * ObjCStringLiteralExpr
8127 //  * ObjCEncodeExpr
8128 //  * AddrLabelExpr
8129 //  * BlockExpr
8130 //  * CallExpr for a MakeStringConstant builtin
8131 // - typeid(T) expressions, as TypeInfoLValues
8132 // - Locals and temporaries
8133 //  * MaterializeTemporaryExpr
8134 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8135 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8136 //    from the AST (FIXME).
8137 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8138 //    CallIndex, for a lifetime-extended temporary.
8139 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8140 //    immediate invocation.
8141 // plus an offset in bytes.
8142 //===----------------------------------------------------------------------===//
8143 namespace {
8144 class LValueExprEvaluator
8145   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8146 public:
LValueExprEvaluator(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)8147   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8148     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8149 
8150   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8151   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8152 
8153   bool VisitCallExpr(const CallExpr *E);
8154   bool VisitDeclRefExpr(const DeclRefExpr *E);
VisitPredefinedExpr(const PredefinedExpr * E)8155   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8156   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8157   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8158   bool VisitMemberExpr(const MemberExpr *E);
VisitStringLiteral(const StringLiteral * E)8159   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
VisitObjCEncodeExpr(const ObjCEncodeExpr * E)8160   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8161   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8162   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8163   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8164   bool VisitUnaryDeref(const UnaryOperator *E);
8165   bool VisitUnaryReal(const UnaryOperator *E);
8166   bool VisitUnaryImag(const UnaryOperator *E);
VisitUnaryPreInc(const UnaryOperator * UO)8167   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8168     return VisitUnaryPreIncDec(UO);
8169   }
VisitUnaryPreDec(const UnaryOperator * UO)8170   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8171     return VisitUnaryPreIncDec(UO);
8172   }
8173   bool VisitBinAssign(const BinaryOperator *BO);
8174   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8175 
VisitCastExpr(const CastExpr * E)8176   bool VisitCastExpr(const CastExpr *E) {
8177     switch (E->getCastKind()) {
8178     default:
8179       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8180 
8181     case CK_LValueBitCast:
8182       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8183       if (!Visit(E->getSubExpr()))
8184         return false;
8185       Result.Designator.setInvalid();
8186       return true;
8187 
8188     case CK_BaseToDerived:
8189       if (!Visit(E->getSubExpr()))
8190         return false;
8191       return HandleBaseToDerivedCast(Info, E, Result);
8192 
8193     case CK_Dynamic:
8194       if (!Visit(E->getSubExpr()))
8195         return false;
8196       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8197     }
8198   }
8199 };
8200 } // end anonymous namespace
8201 
8202 /// Evaluate an expression as an lvalue. This can be legitimately called on
8203 /// expressions which are not glvalues, in three cases:
8204 ///  * function designators in C, and
8205 ///  * "extern void" objects
8206 ///  * @selector() expressions in Objective-C
EvaluateLValue(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)8207 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8208                            bool InvalidBaseOK) {
8209   assert(!E->isValueDependent());
8210   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8211          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8212   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8213 }
8214 
VisitDeclRefExpr(const DeclRefExpr * E)8215 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8216   const NamedDecl *D = E->getDecl();
8217   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8218           UnnamedGlobalConstantDecl>(D))
8219     return Success(cast<ValueDecl>(D));
8220   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8221     return VisitVarDecl(E, VD);
8222   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8223     return Visit(BD->getBinding());
8224   return Error(E);
8225 }
8226 
8227 
VisitVarDecl(const Expr * E,const VarDecl * VD)8228 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8229 
8230   // If we are within a lambda's call operator, check whether the 'VD' referred
8231   // to within 'E' actually represents a lambda-capture that maps to a
8232   // data-member/field within the closure object, and if so, evaluate to the
8233   // field or what the field refers to.
8234   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8235       isa<DeclRefExpr>(E) &&
8236       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8237     // We don't always have a complete capture-map when checking or inferring if
8238     // the function call operator meets the requirements of a constexpr function
8239     // - but we don't need to evaluate the captures to determine constexprness
8240     // (dcl.constexpr C++17).
8241     if (Info.checkingPotentialConstantExpression())
8242       return false;
8243 
8244     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8245       // Start with 'Result' referring to the complete closure object...
8246       Result = *Info.CurrentCall->This;
8247       // ... then update it to refer to the field of the closure object
8248       // that represents the capture.
8249       if (!HandleLValueMember(Info, E, Result, FD))
8250         return false;
8251       // And if the field is of reference type, update 'Result' to refer to what
8252       // the field refers to.
8253       if (FD->getType()->isReferenceType()) {
8254         APValue RVal;
8255         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8256                                             RVal))
8257           return false;
8258         Result.setFrom(Info.Ctx, RVal);
8259       }
8260       return true;
8261     }
8262   }
8263 
8264   CallStackFrame *Frame = nullptr;
8265   unsigned Version = 0;
8266   if (VD->hasLocalStorage()) {
8267     // Only if a local variable was declared in the function currently being
8268     // evaluated, do we expect to be able to find its value in the current
8269     // frame. (Otherwise it was likely declared in an enclosing context and
8270     // could either have a valid evaluatable value (for e.g. a constexpr
8271     // variable) or be ill-formed (and trigger an appropriate evaluation
8272     // diagnostic)).
8273     CallStackFrame *CurrFrame = Info.CurrentCall;
8274     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8275       // Function parameters are stored in some caller's frame. (Usually the
8276       // immediate caller, but for an inherited constructor they may be more
8277       // distant.)
8278       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8279         if (CurrFrame->Arguments) {
8280           VD = CurrFrame->Arguments.getOrigParam(PVD);
8281           Frame =
8282               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8283           Version = CurrFrame->Arguments.Version;
8284         }
8285       } else {
8286         Frame = CurrFrame;
8287         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8288       }
8289     }
8290   }
8291 
8292   if (!VD->getType()->isReferenceType()) {
8293     if (Frame) {
8294       Result.set({VD, Frame->Index, Version});
8295       return true;
8296     }
8297     return Success(VD);
8298   }
8299 
8300   if (!Info.getLangOpts().CPlusPlus11) {
8301     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8302         << VD << VD->getType();
8303     Info.Note(VD->getLocation(), diag::note_declared_at);
8304   }
8305 
8306   APValue *V;
8307   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8308     return false;
8309   if (!V->hasValue()) {
8310     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8311     // adjust the diagnostic to say that.
8312     if (!Info.checkingPotentialConstantExpression())
8313       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8314     return false;
8315   }
8316   return Success(*V, E);
8317 }
8318 
VisitCallExpr(const CallExpr * E)8319 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8320   switch (E->getBuiltinCallee()) {
8321   case Builtin::BIas_const:
8322   case Builtin::BIforward:
8323   case Builtin::BImove:
8324   case Builtin::BImove_if_noexcept:
8325     if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8326       return Visit(E->getArg(0));
8327     break;
8328   }
8329 
8330   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8331 }
8332 
VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * E)8333 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8334     const MaterializeTemporaryExpr *E) {
8335   // Walk through the expression to find the materialized temporary itself.
8336   SmallVector<const Expr *, 2> CommaLHSs;
8337   SmallVector<SubobjectAdjustment, 2> Adjustments;
8338   const Expr *Inner =
8339       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8340 
8341   // If we passed any comma operators, evaluate their LHSs.
8342   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8343     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8344       return false;
8345 
8346   // A materialized temporary with static storage duration can appear within the
8347   // result of a constant expression evaluation, so we need to preserve its
8348   // value for use outside this evaluation.
8349   APValue *Value;
8350   if (E->getStorageDuration() == SD_Static) {
8351     // FIXME: What about SD_Thread?
8352     Value = E->getOrCreateValue(true);
8353     *Value = APValue();
8354     Result.set(E);
8355   } else {
8356     Value = &Info.CurrentCall->createTemporary(
8357         E, E->getType(),
8358         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8359                                                      : ScopeKind::Block,
8360         Result);
8361   }
8362 
8363   QualType Type = Inner->getType();
8364 
8365   // Materialize the temporary itself.
8366   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8367     *Value = APValue();
8368     return false;
8369   }
8370 
8371   // Adjust our lvalue to refer to the desired subobject.
8372   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8373     --I;
8374     switch (Adjustments[I].Kind) {
8375     case SubobjectAdjustment::DerivedToBaseAdjustment:
8376       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8377                                 Type, Result))
8378         return false;
8379       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8380       break;
8381 
8382     case SubobjectAdjustment::FieldAdjustment:
8383       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8384         return false;
8385       Type = Adjustments[I].Field->getType();
8386       break;
8387 
8388     case SubobjectAdjustment::MemberPointerAdjustment:
8389       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8390                                      Adjustments[I].Ptr.RHS))
8391         return false;
8392       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8393       break;
8394     }
8395   }
8396 
8397   return true;
8398 }
8399 
8400 bool
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)8401 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8402   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8403          "lvalue compound literal in c++?");
8404   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8405   // only see this when folding in C, so there's no standard to follow here.
8406   return Success(E);
8407 }
8408 
VisitCXXTypeidExpr(const CXXTypeidExpr * E)8409 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8410   TypeInfoLValue TypeInfo;
8411 
8412   if (!E->isPotentiallyEvaluated()) {
8413     if (E->isTypeOperand())
8414       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8415     else
8416       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8417   } else {
8418     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8419       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8420         << E->getExprOperand()->getType()
8421         << E->getExprOperand()->getSourceRange();
8422     }
8423 
8424     if (!Visit(E->getExprOperand()))
8425       return false;
8426 
8427     Optional<DynamicType> DynType =
8428         ComputeDynamicType(Info, E, Result, AK_TypeId);
8429     if (!DynType)
8430       return false;
8431 
8432     TypeInfo =
8433         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8434   }
8435 
8436   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8437 }
8438 
VisitCXXUuidofExpr(const CXXUuidofExpr * E)8439 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8440   return Success(E->getGuidDecl());
8441 }
8442 
VisitMemberExpr(const MemberExpr * E)8443 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8444   // Handle static data members.
8445   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8446     VisitIgnoredBaseExpression(E->getBase());
8447     return VisitVarDecl(E, VD);
8448   }
8449 
8450   // Handle static member functions.
8451   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8452     if (MD->isStatic()) {
8453       VisitIgnoredBaseExpression(E->getBase());
8454       return Success(MD);
8455     }
8456   }
8457 
8458   // Handle non-static data members.
8459   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8460 }
8461 
VisitArraySubscriptExpr(const ArraySubscriptExpr * E)8462 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8463   // FIXME: Deal with vectors as array subscript bases.
8464   if (E->getBase()->getType()->isVectorType() ||
8465       E->getBase()->getType()->isVLSTBuiltinType())
8466     return Error(E);
8467 
8468   APSInt Index;
8469   bool Success = true;
8470 
8471   // C++17's rules require us to evaluate the LHS first, regardless of which
8472   // side is the base.
8473   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8474     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8475                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8476       if (!Info.noteFailure())
8477         return false;
8478       Success = false;
8479     }
8480   }
8481 
8482   return Success &&
8483          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8484 }
8485 
VisitUnaryDeref(const UnaryOperator * E)8486 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8487   return evaluatePointer(E->getSubExpr(), Result);
8488 }
8489 
VisitUnaryReal(const UnaryOperator * E)8490 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8491   if (!Visit(E->getSubExpr()))
8492     return false;
8493   // __real is a no-op on scalar lvalues.
8494   if (E->getSubExpr()->getType()->isAnyComplexType())
8495     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8496   return true;
8497 }
8498 
VisitUnaryImag(const UnaryOperator * E)8499 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8500   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8501          "lvalue __imag__ on scalar?");
8502   if (!Visit(E->getSubExpr()))
8503     return false;
8504   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8505   return true;
8506 }
8507 
VisitUnaryPreIncDec(const UnaryOperator * UO)8508 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8509   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8510     return Error(UO);
8511 
8512   if (!this->Visit(UO->getSubExpr()))
8513     return false;
8514 
8515   return handleIncDec(
8516       this->Info, UO, Result, UO->getSubExpr()->getType(),
8517       UO->isIncrementOp(), nullptr);
8518 }
8519 
VisitCompoundAssignOperator(const CompoundAssignOperator * CAO)8520 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8521     const CompoundAssignOperator *CAO) {
8522   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8523     return Error(CAO);
8524 
8525   bool Success = true;
8526 
8527   // C++17 onwards require that we evaluate the RHS first.
8528   APValue RHS;
8529   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8530     if (!Info.noteFailure())
8531       return false;
8532     Success = false;
8533   }
8534 
8535   // The overall lvalue result is the result of evaluating the LHS.
8536   if (!this->Visit(CAO->getLHS()) || !Success)
8537     return false;
8538 
8539   return handleCompoundAssignment(
8540       this->Info, CAO,
8541       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8542       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8543 }
8544 
VisitBinAssign(const BinaryOperator * E)8545 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8546   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8547     return Error(E);
8548 
8549   bool Success = true;
8550 
8551   // C++17 onwards require that we evaluate the RHS first.
8552   APValue NewVal;
8553   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8554     if (!Info.noteFailure())
8555       return false;
8556     Success = false;
8557   }
8558 
8559   if (!this->Visit(E->getLHS()) || !Success)
8560     return false;
8561 
8562   if (Info.getLangOpts().CPlusPlus20 &&
8563       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8564     return false;
8565 
8566   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8567                           NewVal);
8568 }
8569 
8570 //===----------------------------------------------------------------------===//
8571 // Pointer Evaluation
8572 //===----------------------------------------------------------------------===//
8573 
8574 /// Attempts to compute the number of bytes available at the pointer
8575 /// returned by a function with the alloc_size attribute. Returns true if we
8576 /// were successful. Places an unsigned number into `Result`.
8577 ///
8578 /// This expects the given CallExpr to be a call to a function with an
8579 /// alloc_size attribute.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const CallExpr * Call,llvm::APInt & Result)8580 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8581                                             const CallExpr *Call,
8582                                             llvm::APInt &Result) {
8583   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8584 
8585   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8586   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8587   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8588   if (Call->getNumArgs() <= SizeArgNo)
8589     return false;
8590 
8591   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8592     Expr::EvalResult ExprResult;
8593     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8594       return false;
8595     Into = ExprResult.Val.getInt();
8596     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8597       return false;
8598     Into = Into.zext(BitsInSizeT);
8599     return true;
8600   };
8601 
8602   APSInt SizeOfElem;
8603   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8604     return false;
8605 
8606   if (!AllocSize->getNumElemsParam().isValid()) {
8607     Result = std::move(SizeOfElem);
8608     return true;
8609   }
8610 
8611   APSInt NumberOfElems;
8612   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8613   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8614     return false;
8615 
8616   bool Overflow;
8617   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8618   if (Overflow)
8619     return false;
8620 
8621   Result = std::move(BytesAvailable);
8622   return true;
8623 }
8624 
8625 /// Convenience function. LVal's base must be a call to an alloc_size
8626 /// function.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const LValue & LVal,llvm::APInt & Result)8627 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8628                                             const LValue &LVal,
8629                                             llvm::APInt &Result) {
8630   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8631          "Can't get the size of a non alloc_size function");
8632   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8633   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8634   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8635 }
8636 
8637 /// Attempts to evaluate the given LValueBase as the result of a call to
8638 /// a function with the alloc_size attribute. If it was possible to do so, this
8639 /// function will return true, make Result's Base point to said function call,
8640 /// and mark Result's Base as invalid.
evaluateLValueAsAllocSize(EvalInfo & Info,APValue::LValueBase Base,LValue & Result)8641 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8642                                       LValue &Result) {
8643   if (Base.isNull())
8644     return false;
8645 
8646   // Because we do no form of static analysis, we only support const variables.
8647   //
8648   // Additionally, we can't support parameters, nor can we support static
8649   // variables (in the latter case, use-before-assign isn't UB; in the former,
8650   // we have no clue what they'll be assigned to).
8651   const auto *VD =
8652       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8653   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8654     return false;
8655 
8656   const Expr *Init = VD->getAnyInitializer();
8657   if (!Init || Init->getType().isNull())
8658     return false;
8659 
8660   const Expr *E = Init->IgnoreParens();
8661   if (!tryUnwrapAllocSizeCall(E))
8662     return false;
8663 
8664   // Store E instead of E unwrapped so that the type of the LValue's base is
8665   // what the user wanted.
8666   Result.setInvalid(E);
8667 
8668   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8669   Result.addUnsizedArray(Info, E, Pointee);
8670   return true;
8671 }
8672 
8673 namespace {
8674 class PointerExprEvaluator
8675   : public ExprEvaluatorBase<PointerExprEvaluator> {
8676   LValue &Result;
8677   bool InvalidBaseOK;
8678 
Success(const Expr * E)8679   bool Success(const Expr *E) {
8680     Result.set(E);
8681     return true;
8682   }
8683 
evaluateLValue(const Expr * E,LValue & Result)8684   bool evaluateLValue(const Expr *E, LValue &Result) {
8685     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8686   }
8687 
evaluatePointer(const Expr * E,LValue & Result)8688   bool evaluatePointer(const Expr *E, LValue &Result) {
8689     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8690   }
8691 
8692   bool visitNonBuiltinCallExpr(const CallExpr *E);
8693 public:
8694 
PointerExprEvaluator(EvalInfo & info,LValue & Result,bool InvalidBaseOK)8695   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8696       : ExprEvaluatorBaseTy(info), Result(Result),
8697         InvalidBaseOK(InvalidBaseOK) {}
8698 
Success(const APValue & V,const Expr * E)8699   bool Success(const APValue &V, const Expr *E) {
8700     Result.setFrom(Info.Ctx, V);
8701     return true;
8702   }
ZeroInitialization(const Expr * E)8703   bool ZeroInitialization(const Expr *E) {
8704     Result.setNull(Info.Ctx, E->getType());
8705     return true;
8706   }
8707 
8708   bool VisitBinaryOperator(const BinaryOperator *E);
8709   bool VisitCastExpr(const CastExpr* E);
8710   bool VisitUnaryAddrOf(const UnaryOperator *E);
VisitObjCStringLiteral(const ObjCStringLiteral * E)8711   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8712       { return Success(E); }
VisitObjCBoxedExpr(const ObjCBoxedExpr * E)8713   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8714     if (E->isExpressibleAsConstantInitializer())
8715       return Success(E);
8716     if (Info.noteFailure())
8717       EvaluateIgnoredValue(Info, E->getSubExpr());
8718     return Error(E);
8719   }
VisitAddrLabelExpr(const AddrLabelExpr * E)8720   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8721       { return Success(E); }
8722   bool VisitCallExpr(const CallExpr *E);
8723   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
VisitBlockExpr(const BlockExpr * E)8724   bool VisitBlockExpr(const BlockExpr *E) {
8725     if (!E->getBlockDecl()->hasCaptures())
8726       return Success(E);
8727     return Error(E);
8728   }
VisitCXXThisExpr(const CXXThisExpr * E)8729   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8730     // Can't look at 'this' when checking a potential constant expression.
8731     if (Info.checkingPotentialConstantExpression())
8732       return false;
8733     if (!Info.CurrentCall->This) {
8734       if (Info.getLangOpts().CPlusPlus11)
8735         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8736       else
8737         Info.FFDiag(E);
8738       return false;
8739     }
8740     Result = *Info.CurrentCall->This;
8741     // If we are inside a lambda's call operator, the 'this' expression refers
8742     // to the enclosing '*this' object (either by value or reference) which is
8743     // either copied into the closure object's field that represents the '*this'
8744     // or refers to '*this'.
8745     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8746       // Ensure we actually have captured 'this'. (an error will have
8747       // been previously reported if not).
8748       if (!Info.CurrentCall->LambdaThisCaptureField)
8749         return false;
8750 
8751       // Update 'Result' to refer to the data member/field of the closure object
8752       // that represents the '*this' capture.
8753       if (!HandleLValueMember(Info, E, Result,
8754                              Info.CurrentCall->LambdaThisCaptureField))
8755         return false;
8756       // If we captured '*this' by reference, replace the field with its referent.
8757       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8758               ->isPointerType()) {
8759         APValue RVal;
8760         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8761                                             RVal))
8762           return false;
8763 
8764         Result.setFrom(Info.Ctx, RVal);
8765       }
8766     }
8767     return true;
8768   }
8769 
8770   bool VisitCXXNewExpr(const CXXNewExpr *E);
8771 
VisitSourceLocExpr(const SourceLocExpr * E)8772   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8773     assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
8774     APValue LValResult = E->EvaluateInContext(
8775         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8776     Result.setFrom(Info.Ctx, LValResult);
8777     return true;
8778   }
8779 
VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr * E)8780   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8781     std::string ResultStr = E->ComputeName(Info.Ctx);
8782 
8783     QualType CharTy = Info.Ctx.CharTy.withConst();
8784     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8785                ResultStr.size() + 1);
8786     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8787                                                      ArrayType::Normal, 0);
8788 
8789     StringLiteral *SL =
8790         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ordinary,
8791                               /*Pascal*/ false, ArrayTy, E->getLocation());
8792 
8793     evaluateLValue(SL, Result);
8794     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8795     return true;
8796   }
8797 
8798   // FIXME: Missing: @protocol, @selector
8799 };
8800 } // end anonymous namespace
8801 
EvaluatePointer(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)8802 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8803                             bool InvalidBaseOK) {
8804   assert(!E->isValueDependent());
8805   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8806   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8807 }
8808 
VisitBinaryOperator(const BinaryOperator * E)8809 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8810   if (E->getOpcode() != BO_Add &&
8811       E->getOpcode() != BO_Sub)
8812     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8813 
8814   const Expr *PExp = E->getLHS();
8815   const Expr *IExp = E->getRHS();
8816   if (IExp->getType()->isPointerType())
8817     std::swap(PExp, IExp);
8818 
8819   bool EvalPtrOK = evaluatePointer(PExp, Result);
8820   if (!EvalPtrOK && !Info.noteFailure())
8821     return false;
8822 
8823   llvm::APSInt Offset;
8824   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8825     return false;
8826 
8827   if (E->getOpcode() == BO_Sub)
8828     negateAsSigned(Offset);
8829 
8830   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8831   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8832 }
8833 
VisitUnaryAddrOf(const UnaryOperator * E)8834 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8835   return evaluateLValue(E->getSubExpr(), Result);
8836 }
8837 
8838 // Is the provided decl 'std::source_location::current'?
IsDeclSourceLocationCurrent(const FunctionDecl * FD)8839 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
8840   if (!FD)
8841     return false;
8842   const IdentifierInfo *FnII = FD->getIdentifier();
8843   if (!FnII || !FnII->isStr("current"))
8844     return false;
8845 
8846   const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
8847   if (!RD)
8848     return false;
8849 
8850   const IdentifierInfo *ClassII = RD->getIdentifier();
8851   return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
8852 }
8853 
VisitCastExpr(const CastExpr * E)8854 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8855   const Expr *SubExpr = E->getSubExpr();
8856 
8857   switch (E->getCastKind()) {
8858   default:
8859     break;
8860   case CK_BitCast:
8861   case CK_CPointerToObjCPointerCast:
8862   case CK_BlockPointerToObjCPointerCast:
8863   case CK_AnyPointerToBlockPointerCast:
8864   case CK_AddressSpaceConversion:
8865     if (!Visit(SubExpr))
8866       return false;
8867     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8868     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8869     // also static_casts, but we disallow them as a resolution to DR1312.
8870     if (!E->getType()->isVoidPointerType()) {
8871       // In some circumstances, we permit casting from void* to cv1 T*, when the
8872       // actual pointee object is actually a cv2 T.
8873       bool VoidPtrCastMaybeOK =
8874           !Result.InvalidBase && !Result.Designator.Invalid &&
8875           !Result.IsNullPtr &&
8876           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8877                                           E->getType()->getPointeeType());
8878       // 1. We'll allow it in std::allocator::allocate, and anything which that
8879       //    calls.
8880       // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
8881       //    <source_location> header. Fixed in GCC 12 and later (2022-04-??).
8882       //    We'll allow it in the body of std::source_location::current.  GCC's
8883       //    implementation had a parameter of type `void*`, and casts from
8884       //    that back to `const __impl*` in its body.
8885       if (VoidPtrCastMaybeOK &&
8886           (Info.getStdAllocatorCaller("allocate") ||
8887            IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) {
8888         // Permitted.
8889       } else {
8890         Result.Designator.setInvalid();
8891         if (SubExpr->getType()->isVoidPointerType())
8892           CCEDiag(E, diag::note_constexpr_invalid_cast)
8893             << 3 << SubExpr->getType();
8894         else
8895           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8896       }
8897     }
8898     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8899       ZeroInitialization(E);
8900     return true;
8901 
8902   case CK_DerivedToBase:
8903   case CK_UncheckedDerivedToBase:
8904     if (!evaluatePointer(E->getSubExpr(), Result))
8905       return false;
8906     if (!Result.Base && Result.Offset.isZero())
8907       return true;
8908 
8909     // Now figure out the necessary offset to add to the base LV to get from
8910     // the derived class to the base class.
8911     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8912                                   castAs<PointerType>()->getPointeeType(),
8913                                 Result);
8914 
8915   case CK_BaseToDerived:
8916     if (!Visit(E->getSubExpr()))
8917       return false;
8918     if (!Result.Base && Result.Offset.isZero())
8919       return true;
8920     return HandleBaseToDerivedCast(Info, E, Result);
8921 
8922   case CK_Dynamic:
8923     if (!Visit(E->getSubExpr()))
8924       return false;
8925     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8926 
8927   case CK_NullToPointer:
8928     VisitIgnoredValue(E->getSubExpr());
8929     return ZeroInitialization(E);
8930 
8931   case CK_IntegralToPointer: {
8932     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8933 
8934     APValue Value;
8935     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8936       break;
8937 
8938     if (Value.isInt()) {
8939       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8940       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8941       Result.Base = (Expr*)nullptr;
8942       Result.InvalidBase = false;
8943       Result.Offset = CharUnits::fromQuantity(N);
8944       Result.Designator.setInvalid();
8945       Result.IsNullPtr = false;
8946       return true;
8947     } else {
8948       // Cast is of an lvalue, no need to change value.
8949       Result.setFrom(Info.Ctx, Value);
8950       return true;
8951     }
8952   }
8953 
8954   case CK_ArrayToPointerDecay: {
8955     if (SubExpr->isGLValue()) {
8956       if (!evaluateLValue(SubExpr, Result))
8957         return false;
8958     } else {
8959       APValue &Value = Info.CurrentCall->createTemporary(
8960           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8961       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8962         return false;
8963     }
8964     // The result is a pointer to the first element of the array.
8965     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8966     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8967       Result.addArray(Info, E, CAT);
8968     else
8969       Result.addUnsizedArray(Info, E, AT->getElementType());
8970     return true;
8971   }
8972 
8973   case CK_FunctionToPointerDecay:
8974     return evaluateLValue(SubExpr, Result);
8975 
8976   case CK_LValueToRValue: {
8977     LValue LVal;
8978     if (!evaluateLValue(E->getSubExpr(), LVal))
8979       return false;
8980 
8981     APValue RVal;
8982     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8983     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8984                                         LVal, RVal))
8985       return InvalidBaseOK &&
8986              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8987     return Success(RVal, E);
8988   }
8989   }
8990 
8991   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8992 }
8993 
GetAlignOfType(EvalInfo & Info,QualType T,UnaryExprOrTypeTrait ExprKind)8994 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8995                                 UnaryExprOrTypeTrait ExprKind) {
8996   // C++ [expr.alignof]p3:
8997   //     When alignof is applied to a reference type, the result is the
8998   //     alignment of the referenced type.
8999   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
9000     T = Ref->getPointeeType();
9001 
9002   if (T.getQualifiers().hasUnaligned())
9003     return CharUnits::One();
9004 
9005   const bool AlignOfReturnsPreferred =
9006       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9007 
9008   // __alignof is defined to return the preferred alignment.
9009   // Before 8, clang returned the preferred alignment for alignof and _Alignof
9010   // as well.
9011   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9012     return Info.Ctx.toCharUnitsFromBits(
9013       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9014   // alignof and _Alignof are defined to return the ABI alignment.
9015   else if (ExprKind == UETT_AlignOf)
9016     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9017   else
9018     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9019 }
9020 
GetAlignOfExpr(EvalInfo & Info,const Expr * E,UnaryExprOrTypeTrait ExprKind)9021 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9022                                 UnaryExprOrTypeTrait ExprKind) {
9023   E = E->IgnoreParens();
9024 
9025   // The kinds of expressions that we have special-case logic here for
9026   // should be kept up to date with the special checks for those
9027   // expressions in Sema.
9028 
9029   // alignof decl is always accepted, even if it doesn't make sense: we default
9030   // to 1 in those cases.
9031   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9032     return Info.Ctx.getDeclAlign(DRE->getDecl(),
9033                                  /*RefAsPointee*/true);
9034 
9035   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9036     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9037                                  /*RefAsPointee*/true);
9038 
9039   return GetAlignOfType(Info, E->getType(), ExprKind);
9040 }
9041 
getBaseAlignment(EvalInfo & Info,const LValue & Value)9042 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9043   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9044     return Info.Ctx.getDeclAlign(VD);
9045   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9046     return GetAlignOfExpr(Info, E, UETT_AlignOf);
9047   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9048 }
9049 
9050 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9051 /// __builtin_is_aligned and __builtin_assume_aligned.
getAlignmentArgument(const Expr * E,QualType ForType,EvalInfo & Info,APSInt & Alignment)9052 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9053                                  EvalInfo &Info, APSInt &Alignment) {
9054   if (!EvaluateInteger(E, Alignment, Info))
9055     return false;
9056   if (Alignment < 0 || !Alignment.isPowerOf2()) {
9057     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9058     return false;
9059   }
9060   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9061   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9062   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9063     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9064         << MaxValue << ForType << Alignment;
9065     return false;
9066   }
9067   // Ensure both alignment and source value have the same bit width so that we
9068   // don't assert when computing the resulting value.
9069   APSInt ExtAlignment =
9070       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9071   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9072          "Alignment should not be changed by ext/trunc");
9073   Alignment = ExtAlignment;
9074   assert(Alignment.getBitWidth() == SrcWidth);
9075   return true;
9076 }
9077 
9078 // To be clear: this happily visits unsupported builtins. Better name welcomed.
visitNonBuiltinCallExpr(const CallExpr * E)9079 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9080   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9081     return true;
9082 
9083   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9084     return false;
9085 
9086   Result.setInvalid(E);
9087   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9088   Result.addUnsizedArray(Info, E, PointeeTy);
9089   return true;
9090 }
9091 
VisitCallExpr(const CallExpr * E)9092 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9093   if (IsConstantCall(E))
9094     return Success(E);
9095 
9096   if (unsigned BuiltinOp = E->getBuiltinCallee())
9097     return VisitBuiltinCallExpr(E, BuiltinOp);
9098 
9099   return visitNonBuiltinCallExpr(E);
9100 }
9101 
9102 // Determine if T is a character type for which we guarantee that
9103 // sizeof(T) == 1.
isOneByteCharacterType(QualType T)9104 static bool isOneByteCharacterType(QualType T) {
9105   return T->isCharType() || T->isChar8Type();
9106 }
9107 
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)9108 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9109                                                 unsigned BuiltinOp) {
9110   switch (BuiltinOp) {
9111   case Builtin::BIaddressof:
9112   case Builtin::BI__addressof:
9113   case Builtin::BI__builtin_addressof:
9114     return evaluateLValue(E->getArg(0), Result);
9115   case Builtin::BI__builtin_assume_aligned: {
9116     // We need to be very careful here because: if the pointer does not have the
9117     // asserted alignment, then the behavior is undefined, and undefined
9118     // behavior is non-constant.
9119     if (!evaluatePointer(E->getArg(0), Result))
9120       return false;
9121 
9122     LValue OffsetResult(Result);
9123     APSInt Alignment;
9124     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9125                               Alignment))
9126       return false;
9127     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9128 
9129     if (E->getNumArgs() > 2) {
9130       APSInt Offset;
9131       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9132         return false;
9133 
9134       int64_t AdditionalOffset = -Offset.getZExtValue();
9135       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9136     }
9137 
9138     // If there is a base object, then it must have the correct alignment.
9139     if (OffsetResult.Base) {
9140       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9141 
9142       if (BaseAlignment < Align) {
9143         Result.Designator.setInvalid();
9144         // FIXME: Add support to Diagnostic for long / long long.
9145         CCEDiag(E->getArg(0),
9146                 diag::note_constexpr_baa_insufficient_alignment) << 0
9147           << (unsigned)BaseAlignment.getQuantity()
9148           << (unsigned)Align.getQuantity();
9149         return false;
9150       }
9151     }
9152 
9153     // The offset must also have the correct alignment.
9154     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9155       Result.Designator.setInvalid();
9156 
9157       (OffsetResult.Base
9158            ? CCEDiag(E->getArg(0),
9159                      diag::note_constexpr_baa_insufficient_alignment) << 1
9160            : CCEDiag(E->getArg(0),
9161                      diag::note_constexpr_baa_value_insufficient_alignment))
9162         << (int)OffsetResult.Offset.getQuantity()
9163         << (unsigned)Align.getQuantity();
9164       return false;
9165     }
9166 
9167     return true;
9168   }
9169   case Builtin::BI__builtin_align_up:
9170   case Builtin::BI__builtin_align_down: {
9171     if (!evaluatePointer(E->getArg(0), Result))
9172       return false;
9173     APSInt Alignment;
9174     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9175                               Alignment))
9176       return false;
9177     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9178     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9179     // For align_up/align_down, we can return the same value if the alignment
9180     // is known to be greater or equal to the requested value.
9181     if (PtrAlign.getQuantity() >= Alignment)
9182       return true;
9183 
9184     // The alignment could be greater than the minimum at run-time, so we cannot
9185     // infer much about the resulting pointer value. One case is possible:
9186     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9187     // can infer the correct index if the requested alignment is smaller than
9188     // the base alignment so we can perform the computation on the offset.
9189     if (BaseAlignment.getQuantity() >= Alignment) {
9190       assert(Alignment.getBitWidth() <= 64 &&
9191              "Cannot handle > 64-bit address-space");
9192       uint64_t Alignment64 = Alignment.getZExtValue();
9193       CharUnits NewOffset = CharUnits::fromQuantity(
9194           BuiltinOp == Builtin::BI__builtin_align_down
9195               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9196               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9197       Result.adjustOffset(NewOffset - Result.Offset);
9198       // TODO: diagnose out-of-bounds values/only allow for arrays?
9199       return true;
9200     }
9201     // Otherwise, we cannot constant-evaluate the result.
9202     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9203         << Alignment;
9204     return false;
9205   }
9206   case Builtin::BI__builtin_operator_new:
9207     return HandleOperatorNewCall(Info, E, Result);
9208   case Builtin::BI__builtin_launder:
9209     return evaluatePointer(E->getArg(0), Result);
9210   case Builtin::BIstrchr:
9211   case Builtin::BIwcschr:
9212   case Builtin::BImemchr:
9213   case Builtin::BIwmemchr:
9214     if (Info.getLangOpts().CPlusPlus11)
9215       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9216         << /*isConstexpr*/0 << /*isConstructor*/0
9217         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9218     else
9219       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9220     LLVM_FALLTHROUGH;
9221   case Builtin::BI__builtin_strchr:
9222   case Builtin::BI__builtin_wcschr:
9223   case Builtin::BI__builtin_memchr:
9224   case Builtin::BI__builtin_char_memchr:
9225   case Builtin::BI__builtin_wmemchr: {
9226     if (!Visit(E->getArg(0)))
9227       return false;
9228     APSInt Desired;
9229     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9230       return false;
9231     uint64_t MaxLength = uint64_t(-1);
9232     if (BuiltinOp != Builtin::BIstrchr &&
9233         BuiltinOp != Builtin::BIwcschr &&
9234         BuiltinOp != Builtin::BI__builtin_strchr &&
9235         BuiltinOp != Builtin::BI__builtin_wcschr) {
9236       APSInt N;
9237       if (!EvaluateInteger(E->getArg(2), N, Info))
9238         return false;
9239       MaxLength = N.getExtValue();
9240     }
9241     // We cannot find the value if there are no candidates to match against.
9242     if (MaxLength == 0u)
9243       return ZeroInitialization(E);
9244     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9245         Result.Designator.Invalid)
9246       return false;
9247     QualType CharTy = Result.Designator.getType(Info.Ctx);
9248     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9249                      BuiltinOp == Builtin::BI__builtin_memchr;
9250     assert(IsRawByte ||
9251            Info.Ctx.hasSameUnqualifiedType(
9252                CharTy, E->getArg(0)->getType()->getPointeeType()));
9253     // Pointers to const void may point to objects of incomplete type.
9254     if (IsRawByte && CharTy->isIncompleteType()) {
9255       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9256       return false;
9257     }
9258     // Give up on byte-oriented matching against multibyte elements.
9259     // FIXME: We can compare the bytes in the correct order.
9260     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9261       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9262           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9263           << CharTy;
9264       return false;
9265     }
9266     // Figure out what value we're actually looking for (after converting to
9267     // the corresponding unsigned type if necessary).
9268     uint64_t DesiredVal;
9269     bool StopAtNull = false;
9270     switch (BuiltinOp) {
9271     case Builtin::BIstrchr:
9272     case Builtin::BI__builtin_strchr:
9273       // strchr compares directly to the passed integer, and therefore
9274       // always fails if given an int that is not a char.
9275       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9276                                                   E->getArg(1)->getType(),
9277                                                   Desired),
9278                                Desired))
9279         return ZeroInitialization(E);
9280       StopAtNull = true;
9281       LLVM_FALLTHROUGH;
9282     case Builtin::BImemchr:
9283     case Builtin::BI__builtin_memchr:
9284     case Builtin::BI__builtin_char_memchr:
9285       // memchr compares by converting both sides to unsigned char. That's also
9286       // correct for strchr if we get this far (to cope with plain char being
9287       // unsigned in the strchr case).
9288       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9289       break;
9290 
9291     case Builtin::BIwcschr:
9292     case Builtin::BI__builtin_wcschr:
9293       StopAtNull = true;
9294       LLVM_FALLTHROUGH;
9295     case Builtin::BIwmemchr:
9296     case Builtin::BI__builtin_wmemchr:
9297       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9298       DesiredVal = Desired.getZExtValue();
9299       break;
9300     }
9301 
9302     for (; MaxLength; --MaxLength) {
9303       APValue Char;
9304       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9305           !Char.isInt())
9306         return false;
9307       if (Char.getInt().getZExtValue() == DesiredVal)
9308         return true;
9309       if (StopAtNull && !Char.getInt())
9310         break;
9311       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9312         return false;
9313     }
9314     // Not found: return nullptr.
9315     return ZeroInitialization(E);
9316   }
9317 
9318   case Builtin::BImemcpy:
9319   case Builtin::BImemmove:
9320   case Builtin::BIwmemcpy:
9321   case Builtin::BIwmemmove:
9322     if (Info.getLangOpts().CPlusPlus11)
9323       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9324         << /*isConstexpr*/0 << /*isConstructor*/0
9325         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9326     else
9327       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9328     LLVM_FALLTHROUGH;
9329   case Builtin::BI__builtin_memcpy:
9330   case Builtin::BI__builtin_memmove:
9331   case Builtin::BI__builtin_wmemcpy:
9332   case Builtin::BI__builtin_wmemmove: {
9333     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9334                  BuiltinOp == Builtin::BIwmemmove ||
9335                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9336                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9337     bool Move = BuiltinOp == Builtin::BImemmove ||
9338                 BuiltinOp == Builtin::BIwmemmove ||
9339                 BuiltinOp == Builtin::BI__builtin_memmove ||
9340                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9341 
9342     // The result of mem* is the first argument.
9343     if (!Visit(E->getArg(0)))
9344       return false;
9345     LValue Dest = Result;
9346 
9347     LValue Src;
9348     if (!EvaluatePointer(E->getArg(1), Src, Info))
9349       return false;
9350 
9351     APSInt N;
9352     if (!EvaluateInteger(E->getArg(2), N, Info))
9353       return false;
9354     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9355 
9356     // If the size is zero, we treat this as always being a valid no-op.
9357     // (Even if one of the src and dest pointers is null.)
9358     if (!N)
9359       return true;
9360 
9361     // Otherwise, if either of the operands is null, we can't proceed. Don't
9362     // try to determine the type of the copied objects, because there aren't
9363     // any.
9364     if (!Src.Base || !Dest.Base) {
9365       APValue Val;
9366       (!Src.Base ? Src : Dest).moveInto(Val);
9367       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9368           << Move << WChar << !!Src.Base
9369           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9370       return false;
9371     }
9372     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9373       return false;
9374 
9375     // We require that Src and Dest are both pointers to arrays of
9376     // trivially-copyable type. (For the wide version, the designator will be
9377     // invalid if the designated object is not a wchar_t.)
9378     QualType T = Dest.Designator.getType(Info.Ctx);
9379     QualType SrcT = Src.Designator.getType(Info.Ctx);
9380     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9381       // FIXME: Consider using our bit_cast implementation to support this.
9382       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9383       return false;
9384     }
9385     if (T->isIncompleteType()) {
9386       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9387       return false;
9388     }
9389     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9390       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9391       return false;
9392     }
9393 
9394     // Figure out how many T's we're copying.
9395     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9396     if (!WChar) {
9397       uint64_t Remainder;
9398       llvm::APInt OrigN = N;
9399       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9400       if (Remainder) {
9401         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9402             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9403             << (unsigned)TSize;
9404         return false;
9405       }
9406     }
9407 
9408     // Check that the copying will remain within the arrays, just so that we
9409     // can give a more meaningful diagnostic. This implicitly also checks that
9410     // N fits into 64 bits.
9411     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9412     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9413     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9414       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9415           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9416           << toString(N, 10, /*Signed*/false);
9417       return false;
9418     }
9419     uint64_t NElems = N.getZExtValue();
9420     uint64_t NBytes = NElems * TSize;
9421 
9422     // Check for overlap.
9423     int Direction = 1;
9424     if (HasSameBase(Src, Dest)) {
9425       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9426       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9427       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9428         // Dest is inside the source region.
9429         if (!Move) {
9430           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9431           return false;
9432         }
9433         // For memmove and friends, copy backwards.
9434         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9435             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9436           return false;
9437         Direction = -1;
9438       } else if (!Move && SrcOffset >= DestOffset &&
9439                  SrcOffset - DestOffset < NBytes) {
9440         // Src is inside the destination region for memcpy: invalid.
9441         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9442         return false;
9443       }
9444     }
9445 
9446     while (true) {
9447       APValue Val;
9448       // FIXME: Set WantObjectRepresentation to true if we're copying a
9449       // char-like type?
9450       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9451           !handleAssignment(Info, E, Dest, T, Val))
9452         return false;
9453       // Do not iterate past the last element; if we're copying backwards, that
9454       // might take us off the start of the array.
9455       if (--NElems == 0)
9456         return true;
9457       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9458           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9459         return false;
9460     }
9461   }
9462 
9463   default:
9464     break;
9465   }
9466 
9467   return visitNonBuiltinCallExpr(E);
9468 }
9469 
9470 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9471                                      APValue &Result, const InitListExpr *ILE,
9472                                      QualType AllocType);
9473 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9474                                           APValue &Result,
9475                                           const CXXConstructExpr *CCE,
9476                                           QualType AllocType);
9477 
VisitCXXNewExpr(const CXXNewExpr * E)9478 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9479   if (!Info.getLangOpts().CPlusPlus20)
9480     Info.CCEDiag(E, diag::note_constexpr_new);
9481 
9482   // We cannot speculatively evaluate a delete expression.
9483   if (Info.SpeculativeEvaluationDepth)
9484     return false;
9485 
9486   FunctionDecl *OperatorNew = E->getOperatorNew();
9487 
9488   bool IsNothrow = false;
9489   bool IsPlacement = false;
9490   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9491       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9492     // FIXME Support array placement new.
9493     assert(E->getNumPlacementArgs() == 1);
9494     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9495       return false;
9496     if (Result.Designator.Invalid)
9497       return false;
9498     IsPlacement = true;
9499   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9500     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9501         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9502     return false;
9503   } else if (E->getNumPlacementArgs()) {
9504     // The only new-placement list we support is of the form (std::nothrow).
9505     //
9506     // FIXME: There is no restriction on this, but it's not clear that any
9507     // other form makes any sense. We get here for cases such as:
9508     //
9509     //   new (std::align_val_t{N}) X(int)
9510     //
9511     // (which should presumably be valid only if N is a multiple of
9512     // alignof(int), and in any case can't be deallocated unless N is
9513     // alignof(X) and X has new-extended alignment).
9514     if (E->getNumPlacementArgs() != 1 ||
9515         !E->getPlacementArg(0)->getType()->isNothrowT())
9516       return Error(E, diag::note_constexpr_new_placement);
9517 
9518     LValue Nothrow;
9519     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9520       return false;
9521     IsNothrow = true;
9522   }
9523 
9524   const Expr *Init = E->getInitializer();
9525   const InitListExpr *ResizedArrayILE = nullptr;
9526   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9527   bool ValueInit = false;
9528 
9529   QualType AllocType = E->getAllocatedType();
9530   if (Optional<const Expr *> ArraySize = E->getArraySize()) {
9531     const Expr *Stripped = *ArraySize;
9532     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9533          Stripped = ICE->getSubExpr())
9534       if (ICE->getCastKind() != CK_NoOp &&
9535           ICE->getCastKind() != CK_IntegralCast)
9536         break;
9537 
9538     llvm::APSInt ArrayBound;
9539     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9540       return false;
9541 
9542     // C++ [expr.new]p9:
9543     //   The expression is erroneous if:
9544     //   -- [...] its value before converting to size_t [or] applying the
9545     //      second standard conversion sequence is less than zero
9546     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9547       if (IsNothrow)
9548         return ZeroInitialization(E);
9549 
9550       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9551           << ArrayBound << (*ArraySize)->getSourceRange();
9552       return false;
9553     }
9554 
9555     //   -- its value is such that the size of the allocated object would
9556     //      exceed the implementation-defined limit
9557     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9558                                                 ArrayBound) >
9559         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9560       if (IsNothrow)
9561         return ZeroInitialization(E);
9562 
9563       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9564         << ArrayBound << (*ArraySize)->getSourceRange();
9565       return false;
9566     }
9567 
9568     //   -- the new-initializer is a braced-init-list and the number of
9569     //      array elements for which initializers are provided [...]
9570     //      exceeds the number of elements to initialize
9571     if (!Init) {
9572       // No initialization is performed.
9573     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9574                isa<ImplicitValueInitExpr>(Init)) {
9575       ValueInit = true;
9576     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9577       ResizedArrayCCE = CCE;
9578     } else {
9579       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9580       assert(CAT && "unexpected type for array initializer");
9581 
9582       unsigned Bits =
9583           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9584       llvm::APInt InitBound = CAT->getSize().zext(Bits);
9585       llvm::APInt AllocBound = ArrayBound.zext(Bits);
9586       if (InitBound.ugt(AllocBound)) {
9587         if (IsNothrow)
9588           return ZeroInitialization(E);
9589 
9590         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9591             << toString(AllocBound, 10, /*Signed=*/false)
9592             << toString(InitBound, 10, /*Signed=*/false)
9593             << (*ArraySize)->getSourceRange();
9594         return false;
9595       }
9596 
9597       // If the sizes differ, we must have an initializer list, and we need
9598       // special handling for this case when we initialize.
9599       if (InitBound != AllocBound)
9600         ResizedArrayILE = cast<InitListExpr>(Init);
9601     }
9602 
9603     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9604                                               ArrayType::Normal, 0);
9605   } else {
9606     assert(!AllocType->isArrayType() &&
9607            "array allocation with non-array new");
9608   }
9609 
9610   APValue *Val;
9611   if (IsPlacement) {
9612     AccessKinds AK = AK_Construct;
9613     struct FindObjectHandler {
9614       EvalInfo &Info;
9615       const Expr *E;
9616       QualType AllocType;
9617       const AccessKinds AccessKind;
9618       APValue *Value;
9619 
9620       typedef bool result_type;
9621       bool failed() { return false; }
9622       bool found(APValue &Subobj, QualType SubobjType) {
9623         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9624         // old name of the object to be used to name the new object.
9625         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9626           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9627             SubobjType << AllocType;
9628           return false;
9629         }
9630         Value = &Subobj;
9631         return true;
9632       }
9633       bool found(APSInt &Value, QualType SubobjType) {
9634         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9635         return false;
9636       }
9637       bool found(APFloat &Value, QualType SubobjType) {
9638         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9639         return false;
9640       }
9641     } Handler = {Info, E, AllocType, AK, nullptr};
9642 
9643     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9644     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9645       return false;
9646 
9647     Val = Handler.Value;
9648 
9649     // [basic.life]p1:
9650     //   The lifetime of an object o of type T ends when [...] the storage
9651     //   which the object occupies is [...] reused by an object that is not
9652     //   nested within o (6.6.2).
9653     *Val = APValue();
9654   } else {
9655     // Perform the allocation and obtain a pointer to the resulting object.
9656     Val = Info.createHeapAlloc(E, AllocType, Result);
9657     if (!Val)
9658       return false;
9659   }
9660 
9661   if (ValueInit) {
9662     ImplicitValueInitExpr VIE(AllocType);
9663     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9664       return false;
9665   } else if (ResizedArrayILE) {
9666     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9667                                   AllocType))
9668       return false;
9669   } else if (ResizedArrayCCE) {
9670     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9671                                        AllocType))
9672       return false;
9673   } else if (Init) {
9674     if (!EvaluateInPlace(*Val, Info, Result, Init))
9675       return false;
9676   } else if (!getDefaultInitValue(AllocType, *Val)) {
9677     return false;
9678   }
9679 
9680   // Array new returns a pointer to the first element, not a pointer to the
9681   // array.
9682   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9683     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9684 
9685   return true;
9686 }
9687 //===----------------------------------------------------------------------===//
9688 // Member Pointer Evaluation
9689 //===----------------------------------------------------------------------===//
9690 
9691 namespace {
9692 class MemberPointerExprEvaluator
9693   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9694   MemberPtr &Result;
9695 
Success(const ValueDecl * D)9696   bool Success(const ValueDecl *D) {
9697     Result = MemberPtr(D);
9698     return true;
9699   }
9700 public:
9701 
MemberPointerExprEvaluator(EvalInfo & Info,MemberPtr & Result)9702   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9703     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9704 
Success(const APValue & V,const Expr * E)9705   bool Success(const APValue &V, const Expr *E) {
9706     Result.setFrom(V);
9707     return true;
9708   }
ZeroInitialization(const Expr * E)9709   bool ZeroInitialization(const Expr *E) {
9710     return Success((const ValueDecl*)nullptr);
9711   }
9712 
9713   bool VisitCastExpr(const CastExpr *E);
9714   bool VisitUnaryAddrOf(const UnaryOperator *E);
9715 };
9716 } // end anonymous namespace
9717 
EvaluateMemberPointer(const Expr * E,MemberPtr & Result,EvalInfo & Info)9718 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9719                                   EvalInfo &Info) {
9720   assert(!E->isValueDependent());
9721   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9722   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9723 }
9724 
VisitCastExpr(const CastExpr * E)9725 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9726   switch (E->getCastKind()) {
9727   default:
9728     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9729 
9730   case CK_NullToMemberPointer:
9731     VisitIgnoredValue(E->getSubExpr());
9732     return ZeroInitialization(E);
9733 
9734   case CK_BaseToDerivedMemberPointer: {
9735     if (!Visit(E->getSubExpr()))
9736       return false;
9737     if (E->path_empty())
9738       return true;
9739     // Base-to-derived member pointer casts store the path in derived-to-base
9740     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9741     // the wrong end of the derived->base arc, so stagger the path by one class.
9742     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9743     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9744          PathI != PathE; ++PathI) {
9745       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9746       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9747       if (!Result.castToDerived(Derived))
9748         return Error(E);
9749     }
9750     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9751     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9752       return Error(E);
9753     return true;
9754   }
9755 
9756   case CK_DerivedToBaseMemberPointer:
9757     if (!Visit(E->getSubExpr()))
9758       return false;
9759     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9760          PathE = E->path_end(); PathI != PathE; ++PathI) {
9761       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9762       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9763       if (!Result.castToBase(Base))
9764         return Error(E);
9765     }
9766     return true;
9767   }
9768 }
9769 
VisitUnaryAddrOf(const UnaryOperator * E)9770 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9771   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9772   // member can be formed.
9773   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9774 }
9775 
9776 //===----------------------------------------------------------------------===//
9777 // Record Evaluation
9778 //===----------------------------------------------------------------------===//
9779 
9780 namespace {
9781   class RecordExprEvaluator
9782   : public ExprEvaluatorBase<RecordExprEvaluator> {
9783     const LValue &This;
9784     APValue &Result;
9785   public:
9786 
RecordExprEvaluator(EvalInfo & info,const LValue & This,APValue & Result)9787     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9788       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9789 
Success(const APValue & V,const Expr * E)9790     bool Success(const APValue &V, const Expr *E) {
9791       Result = V;
9792       return true;
9793     }
ZeroInitialization(const Expr * E)9794     bool ZeroInitialization(const Expr *E) {
9795       return ZeroInitialization(E, E->getType());
9796     }
9797     bool ZeroInitialization(const Expr *E, QualType T);
9798 
VisitCallExpr(const CallExpr * E)9799     bool VisitCallExpr(const CallExpr *E) {
9800       return handleCallExpr(E, Result, &This);
9801     }
9802     bool VisitCastExpr(const CastExpr *E);
9803     bool VisitInitListExpr(const InitListExpr *E);
VisitCXXConstructExpr(const CXXConstructExpr * E)9804     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9805       return VisitCXXConstructExpr(E, E->getType());
9806     }
9807     bool VisitLambdaExpr(const LambdaExpr *E);
9808     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9809     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9810     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9811     bool VisitBinCmp(const BinaryOperator *E);
9812   };
9813 }
9814 
9815 /// Perform zero-initialization on an object of non-union class type.
9816 /// C++11 [dcl.init]p5:
9817 ///  To zero-initialize an object or reference of type T means:
9818 ///    [...]
9819 ///    -- if T is a (possibly cv-qualified) non-union class type,
9820 ///       each non-static data member and each base-class subobject is
9821 ///       zero-initialized
HandleClassZeroInitialization(EvalInfo & Info,const Expr * E,const RecordDecl * RD,const LValue & This,APValue & Result)9822 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9823                                           const RecordDecl *RD,
9824                                           const LValue &This, APValue &Result) {
9825   assert(!RD->isUnion() && "Expected non-union class type");
9826   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9827   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9828                    std::distance(RD->field_begin(), RD->field_end()));
9829 
9830   if (RD->isInvalidDecl()) return false;
9831   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9832 
9833   if (CD) {
9834     unsigned Index = 0;
9835     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9836            End = CD->bases_end(); I != End; ++I, ++Index) {
9837       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9838       LValue Subobject = This;
9839       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9840         return false;
9841       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9842                                          Result.getStructBase(Index)))
9843         return false;
9844     }
9845   }
9846 
9847   for (const auto *I : RD->fields()) {
9848     // -- if T is a reference type, no initialization is performed.
9849     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9850       continue;
9851 
9852     LValue Subobject = This;
9853     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9854       return false;
9855 
9856     ImplicitValueInitExpr VIE(I->getType());
9857     if (!EvaluateInPlace(
9858           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9859       return false;
9860   }
9861 
9862   return true;
9863 }
9864 
ZeroInitialization(const Expr * E,QualType T)9865 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9866   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9867   if (RD->isInvalidDecl()) return false;
9868   if (RD->isUnion()) {
9869     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9870     // object's first non-static named data member is zero-initialized
9871     RecordDecl::field_iterator I = RD->field_begin();
9872     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9873       ++I;
9874     if (I == RD->field_end()) {
9875       Result = APValue((const FieldDecl*)nullptr);
9876       return true;
9877     }
9878 
9879     LValue Subobject = This;
9880     if (!HandleLValueMember(Info, E, Subobject, *I))
9881       return false;
9882     Result = APValue(*I);
9883     ImplicitValueInitExpr VIE(I->getType());
9884     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9885   }
9886 
9887   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9888     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9889     return false;
9890   }
9891 
9892   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9893 }
9894 
VisitCastExpr(const CastExpr * E)9895 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9896   switch (E->getCastKind()) {
9897   default:
9898     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9899 
9900   case CK_ConstructorConversion:
9901     return Visit(E->getSubExpr());
9902 
9903   case CK_DerivedToBase:
9904   case CK_UncheckedDerivedToBase: {
9905     APValue DerivedObject;
9906     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9907       return false;
9908     if (!DerivedObject.isStruct())
9909       return Error(E->getSubExpr());
9910 
9911     // Derived-to-base rvalue conversion: just slice off the derived part.
9912     APValue *Value = &DerivedObject;
9913     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9914     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9915          PathE = E->path_end(); PathI != PathE; ++PathI) {
9916       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9917       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9918       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9919       RD = Base;
9920     }
9921     Result = *Value;
9922     return true;
9923   }
9924   }
9925 }
9926 
VisitInitListExpr(const InitListExpr * E)9927 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9928   if (E->isTransparent())
9929     return Visit(E->getInit(0));
9930 
9931   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9932   if (RD->isInvalidDecl()) return false;
9933   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9934   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9935 
9936   EvalInfo::EvaluatingConstructorRAII EvalObj(
9937       Info,
9938       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9939       CXXRD && CXXRD->getNumBases());
9940 
9941   if (RD->isUnion()) {
9942     const FieldDecl *Field = E->getInitializedFieldInUnion();
9943     Result = APValue(Field);
9944     if (!Field)
9945       return true;
9946 
9947     // If the initializer list for a union does not contain any elements, the
9948     // first element of the union is value-initialized.
9949     // FIXME: The element should be initialized from an initializer list.
9950     //        Is this difference ever observable for initializer lists which
9951     //        we don't build?
9952     ImplicitValueInitExpr VIE(Field->getType());
9953     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9954 
9955     LValue Subobject = This;
9956     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9957       return false;
9958 
9959     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9960     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9961                                   isa<CXXDefaultInitExpr>(InitExpr));
9962 
9963     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9964       if (Field->isBitField())
9965         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9966                                      Field);
9967       return true;
9968     }
9969 
9970     return false;
9971   }
9972 
9973   if (!Result.hasValue())
9974     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9975                      std::distance(RD->field_begin(), RD->field_end()));
9976   unsigned ElementNo = 0;
9977   bool Success = true;
9978 
9979   // Initialize base classes.
9980   if (CXXRD && CXXRD->getNumBases()) {
9981     for (const auto &Base : CXXRD->bases()) {
9982       assert(ElementNo < E->getNumInits() && "missing init for base class");
9983       const Expr *Init = E->getInit(ElementNo);
9984 
9985       LValue Subobject = This;
9986       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9987         return false;
9988 
9989       APValue &FieldVal = Result.getStructBase(ElementNo);
9990       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9991         if (!Info.noteFailure())
9992           return false;
9993         Success = false;
9994       }
9995       ++ElementNo;
9996     }
9997 
9998     EvalObj.finishedConstructingBases();
9999   }
10000 
10001   // Initialize members.
10002   for (const auto *Field : RD->fields()) {
10003     // Anonymous bit-fields are not considered members of the class for
10004     // purposes of aggregate initialization.
10005     if (Field->isUnnamedBitfield())
10006       continue;
10007 
10008     LValue Subobject = This;
10009 
10010     bool HaveInit = ElementNo < E->getNumInits();
10011 
10012     // FIXME: Diagnostics here should point to the end of the initializer
10013     // list, not the start.
10014     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
10015                             Subobject, Field, &Layout))
10016       return false;
10017 
10018     // Perform an implicit value-initialization for members beyond the end of
10019     // the initializer list.
10020     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10021     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
10022 
10023     if (Field->getType()->isIncompleteArrayType()) {
10024       if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10025         if (!CAT->getSize().isZero()) {
10026           // Bail out for now. This might sort of "work", but the rest of the
10027           // code isn't really prepared to handle it.
10028           Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10029           return false;
10030         }
10031       }
10032     }
10033 
10034     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10035     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10036                                   isa<CXXDefaultInitExpr>(Init));
10037 
10038     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10039     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10040         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10041                                                        FieldVal, Field))) {
10042       if (!Info.noteFailure())
10043         return false;
10044       Success = false;
10045     }
10046   }
10047 
10048   EvalObj.finishedConstructingFields();
10049 
10050   return Success;
10051 }
10052 
VisitCXXConstructExpr(const CXXConstructExpr * E,QualType T)10053 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10054                                                 QualType T) {
10055   // Note that E's type is not necessarily the type of our class here; we might
10056   // be initializing an array element instead.
10057   const CXXConstructorDecl *FD = E->getConstructor();
10058   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10059 
10060   bool ZeroInit = E->requiresZeroInitialization();
10061   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10062     // If we've already performed zero-initialization, we're already done.
10063     if (Result.hasValue())
10064       return true;
10065 
10066     if (ZeroInit)
10067       return ZeroInitialization(E, T);
10068 
10069     return getDefaultInitValue(T, Result);
10070   }
10071 
10072   const FunctionDecl *Definition = nullptr;
10073   auto Body = FD->getBody(Definition);
10074 
10075   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10076     return false;
10077 
10078   // Avoid materializing a temporary for an elidable copy/move constructor.
10079   if (E->isElidable() && !ZeroInit) {
10080     // FIXME: This only handles the simplest case, where the source object
10081     //        is passed directly as the first argument to the constructor.
10082     //        This should also handle stepping though implicit casts and
10083     //        and conversion sequences which involve two steps, with a
10084     //        conversion operator followed by a converting constructor.
10085     const Expr *SrcObj = E->getArg(0);
10086     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10087     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10088     if (const MaterializeTemporaryExpr *ME =
10089             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10090       return Visit(ME->getSubExpr());
10091   }
10092 
10093   if (ZeroInit && !ZeroInitialization(E, T))
10094     return false;
10095 
10096   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
10097   return HandleConstructorCall(E, This, Args,
10098                                cast<CXXConstructorDecl>(Definition), Info,
10099                                Result);
10100 }
10101 
VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr * E)10102 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10103     const CXXInheritedCtorInitExpr *E) {
10104   if (!Info.CurrentCall) {
10105     assert(Info.checkingPotentialConstantExpression());
10106     return false;
10107   }
10108 
10109   const CXXConstructorDecl *FD = E->getConstructor();
10110   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10111     return false;
10112 
10113   const FunctionDecl *Definition = nullptr;
10114   auto Body = FD->getBody(Definition);
10115 
10116   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10117     return false;
10118 
10119   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10120                                cast<CXXConstructorDecl>(Definition), Info,
10121                                Result);
10122 }
10123 
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)10124 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10125     const CXXStdInitializerListExpr *E) {
10126   const ConstantArrayType *ArrayType =
10127       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10128 
10129   LValue Array;
10130   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10131     return false;
10132 
10133   // Get a pointer to the first element of the array.
10134   Array.addArray(Info, E, ArrayType);
10135 
10136   auto InvalidType = [&] {
10137     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10138       << E->getType();
10139     return false;
10140   };
10141 
10142   // FIXME: Perform the checks on the field types in SemaInit.
10143   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10144   RecordDecl::field_iterator Field = Record->field_begin();
10145   if (Field == Record->field_end())
10146     return InvalidType();
10147 
10148   // Start pointer.
10149   if (!Field->getType()->isPointerType() ||
10150       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10151                             ArrayType->getElementType()))
10152     return InvalidType();
10153 
10154   // FIXME: What if the initializer_list type has base classes, etc?
10155   Result = APValue(APValue::UninitStruct(), 0, 2);
10156   Array.moveInto(Result.getStructField(0));
10157 
10158   if (++Field == Record->field_end())
10159     return InvalidType();
10160 
10161   if (Field->getType()->isPointerType() &&
10162       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10163                            ArrayType->getElementType())) {
10164     // End pointer.
10165     if (!HandleLValueArrayAdjustment(Info, E, Array,
10166                                      ArrayType->getElementType(),
10167                                      ArrayType->getSize().getZExtValue()))
10168       return false;
10169     Array.moveInto(Result.getStructField(1));
10170   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10171     // Length.
10172     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10173   else
10174     return InvalidType();
10175 
10176   if (++Field != Record->field_end())
10177     return InvalidType();
10178 
10179   return true;
10180 }
10181 
VisitLambdaExpr(const LambdaExpr * E)10182 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10183   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10184   if (ClosureClass->isInvalidDecl())
10185     return false;
10186 
10187   const size_t NumFields =
10188       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10189 
10190   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10191                                             E->capture_init_end()) &&
10192          "The number of lambda capture initializers should equal the number of "
10193          "fields within the closure type");
10194 
10195   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10196   // Iterate through all the lambda's closure object's fields and initialize
10197   // them.
10198   auto *CaptureInitIt = E->capture_init_begin();
10199   bool Success = true;
10200   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10201   for (const auto *Field : ClosureClass->fields()) {
10202     assert(CaptureInitIt != E->capture_init_end());
10203     // Get the initializer for this field
10204     Expr *const CurFieldInit = *CaptureInitIt++;
10205 
10206     // If there is no initializer, either this is a VLA or an error has
10207     // occurred.
10208     if (!CurFieldInit)
10209       return Error(E);
10210 
10211     LValue Subobject = This;
10212 
10213     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10214       return false;
10215 
10216     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10217     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10218       if (!Info.keepEvaluatingAfterFailure())
10219         return false;
10220       Success = false;
10221     }
10222   }
10223   return Success;
10224 }
10225 
EvaluateRecord(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)10226 static bool EvaluateRecord(const Expr *E, const LValue &This,
10227                            APValue &Result, EvalInfo &Info) {
10228   assert(!E->isValueDependent());
10229   assert(E->isPRValue() && E->getType()->isRecordType() &&
10230          "can't evaluate expression as a record rvalue");
10231   return RecordExprEvaluator(Info, This, Result).Visit(E);
10232 }
10233 
10234 //===----------------------------------------------------------------------===//
10235 // Temporary Evaluation
10236 //
10237 // Temporaries are represented in the AST as rvalues, but generally behave like
10238 // lvalues. The full-object of which the temporary is a subobject is implicitly
10239 // materialized so that a reference can bind to it.
10240 //===----------------------------------------------------------------------===//
10241 namespace {
10242 class TemporaryExprEvaluator
10243   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10244 public:
TemporaryExprEvaluator(EvalInfo & Info,LValue & Result)10245   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10246     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10247 
10248   /// Visit an expression which constructs the value of this temporary.
VisitConstructExpr(const Expr * E)10249   bool VisitConstructExpr(const Expr *E) {
10250     APValue &Value = Info.CurrentCall->createTemporary(
10251         E, E->getType(), ScopeKind::FullExpression, Result);
10252     return EvaluateInPlace(Value, Info, Result, E);
10253   }
10254 
VisitCastExpr(const CastExpr * E)10255   bool VisitCastExpr(const CastExpr *E) {
10256     switch (E->getCastKind()) {
10257     default:
10258       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10259 
10260     case CK_ConstructorConversion:
10261       return VisitConstructExpr(E->getSubExpr());
10262     }
10263   }
VisitInitListExpr(const InitListExpr * E)10264   bool VisitInitListExpr(const InitListExpr *E) {
10265     return VisitConstructExpr(E);
10266   }
VisitCXXConstructExpr(const CXXConstructExpr * E)10267   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10268     return VisitConstructExpr(E);
10269   }
VisitCallExpr(const CallExpr * E)10270   bool VisitCallExpr(const CallExpr *E) {
10271     return VisitConstructExpr(E);
10272   }
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)10273   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10274     return VisitConstructExpr(E);
10275   }
VisitLambdaExpr(const LambdaExpr * E)10276   bool VisitLambdaExpr(const LambdaExpr *E) {
10277     return VisitConstructExpr(E);
10278   }
10279 };
10280 } // end anonymous namespace
10281 
10282 /// Evaluate an expression of record type as a temporary.
EvaluateTemporary(const Expr * E,LValue & Result,EvalInfo & Info)10283 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10284   assert(!E->isValueDependent());
10285   assert(E->isPRValue() && E->getType()->isRecordType());
10286   return TemporaryExprEvaluator(Info, Result).Visit(E);
10287 }
10288 
10289 //===----------------------------------------------------------------------===//
10290 // Vector Evaluation
10291 //===----------------------------------------------------------------------===//
10292 
10293 namespace {
10294   class VectorExprEvaluator
10295   : public ExprEvaluatorBase<VectorExprEvaluator> {
10296     APValue &Result;
10297   public:
10298 
VectorExprEvaluator(EvalInfo & info,APValue & Result)10299     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10300       : ExprEvaluatorBaseTy(info), Result(Result) {}
10301 
Success(ArrayRef<APValue> V,const Expr * E)10302     bool Success(ArrayRef<APValue> V, const Expr *E) {
10303       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10304       // FIXME: remove this APValue copy.
10305       Result = APValue(V.data(), V.size());
10306       return true;
10307     }
Success(const APValue & V,const Expr * E)10308     bool Success(const APValue &V, const Expr *E) {
10309       assert(V.isVector());
10310       Result = V;
10311       return true;
10312     }
10313     bool ZeroInitialization(const Expr *E);
10314 
VisitUnaryReal(const UnaryOperator * E)10315     bool VisitUnaryReal(const UnaryOperator *E)
10316       { return Visit(E->getSubExpr()); }
10317     bool VisitCastExpr(const CastExpr* E);
10318     bool VisitInitListExpr(const InitListExpr *E);
10319     bool VisitUnaryImag(const UnaryOperator *E);
10320     bool VisitBinaryOperator(const BinaryOperator *E);
10321     bool VisitUnaryOperator(const UnaryOperator *E);
10322     // FIXME: Missing: conditional operator (for GNU
10323     //                 conditional select), shufflevector, ExtVectorElementExpr
10324   };
10325 } // end anonymous namespace
10326 
EvaluateVector(const Expr * E,APValue & Result,EvalInfo & Info)10327 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10328   assert(E->isPRValue() && E->getType()->isVectorType() &&
10329          "not a vector prvalue");
10330   return VectorExprEvaluator(Info, Result).Visit(E);
10331 }
10332 
VisitCastExpr(const CastExpr * E)10333 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10334   const VectorType *VTy = E->getType()->castAs<VectorType>();
10335   unsigned NElts = VTy->getNumElements();
10336 
10337   const Expr *SE = E->getSubExpr();
10338   QualType SETy = SE->getType();
10339 
10340   switch (E->getCastKind()) {
10341   case CK_VectorSplat: {
10342     APValue Val = APValue();
10343     if (SETy->isIntegerType()) {
10344       APSInt IntResult;
10345       if (!EvaluateInteger(SE, IntResult, Info))
10346         return false;
10347       Val = APValue(std::move(IntResult));
10348     } else if (SETy->isRealFloatingType()) {
10349       APFloat FloatResult(0.0);
10350       if (!EvaluateFloat(SE, FloatResult, Info))
10351         return false;
10352       Val = APValue(std::move(FloatResult));
10353     } else {
10354       return Error(E);
10355     }
10356 
10357     // Splat and create vector APValue.
10358     SmallVector<APValue, 4> Elts(NElts, Val);
10359     return Success(Elts, E);
10360   }
10361   case CK_BitCast: {
10362     // Evaluate the operand into an APInt we can extract from.
10363     llvm::APInt SValInt;
10364     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10365       return false;
10366     // Extract the elements
10367     QualType EltTy = VTy->getElementType();
10368     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10369     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10370     SmallVector<APValue, 4> Elts;
10371     if (EltTy->isRealFloatingType()) {
10372       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10373       unsigned FloatEltSize = EltSize;
10374       if (&Sem == &APFloat::x87DoubleExtended())
10375         FloatEltSize = 80;
10376       for (unsigned i = 0; i < NElts; i++) {
10377         llvm::APInt Elt;
10378         if (BigEndian)
10379           Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize);
10380         else
10381           Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize);
10382         Elts.push_back(APValue(APFloat(Sem, Elt)));
10383       }
10384     } else if (EltTy->isIntegerType()) {
10385       for (unsigned i = 0; i < NElts; i++) {
10386         llvm::APInt Elt;
10387         if (BigEndian)
10388           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10389         else
10390           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10391         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10392       }
10393     } else {
10394       return Error(E);
10395     }
10396     return Success(Elts, E);
10397   }
10398   default:
10399     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10400   }
10401 }
10402 
10403 bool
VisitInitListExpr(const InitListExpr * E)10404 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10405   const VectorType *VT = E->getType()->castAs<VectorType>();
10406   unsigned NumInits = E->getNumInits();
10407   unsigned NumElements = VT->getNumElements();
10408 
10409   QualType EltTy = VT->getElementType();
10410   SmallVector<APValue, 4> Elements;
10411 
10412   // The number of initializers can be less than the number of
10413   // vector elements. For OpenCL, this can be due to nested vector
10414   // initialization. For GCC compatibility, missing trailing elements
10415   // should be initialized with zeroes.
10416   unsigned CountInits = 0, CountElts = 0;
10417   while (CountElts < NumElements) {
10418     // Handle nested vector initialization.
10419     if (CountInits < NumInits
10420         && E->getInit(CountInits)->getType()->isVectorType()) {
10421       APValue v;
10422       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10423         return Error(E);
10424       unsigned vlen = v.getVectorLength();
10425       for (unsigned j = 0; j < vlen; j++)
10426         Elements.push_back(v.getVectorElt(j));
10427       CountElts += vlen;
10428     } else if (EltTy->isIntegerType()) {
10429       llvm::APSInt sInt(32);
10430       if (CountInits < NumInits) {
10431         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10432           return false;
10433       } else // trailing integer zero.
10434         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10435       Elements.push_back(APValue(sInt));
10436       CountElts++;
10437     } else {
10438       llvm::APFloat f(0.0);
10439       if (CountInits < NumInits) {
10440         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10441           return false;
10442       } else // trailing float zero.
10443         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10444       Elements.push_back(APValue(f));
10445       CountElts++;
10446     }
10447     CountInits++;
10448   }
10449   return Success(Elements, E);
10450 }
10451 
10452 bool
ZeroInitialization(const Expr * E)10453 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10454   const auto *VT = E->getType()->castAs<VectorType>();
10455   QualType EltTy = VT->getElementType();
10456   APValue ZeroElement;
10457   if (EltTy->isIntegerType())
10458     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10459   else
10460     ZeroElement =
10461         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10462 
10463   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10464   return Success(Elements, E);
10465 }
10466 
VisitUnaryImag(const UnaryOperator * E)10467 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10468   VisitIgnoredValue(E->getSubExpr());
10469   return ZeroInitialization(E);
10470 }
10471 
VisitBinaryOperator(const BinaryOperator * E)10472 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10473   BinaryOperatorKind Op = E->getOpcode();
10474   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10475          "Operation not supported on vector types");
10476 
10477   if (Op == BO_Comma)
10478     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10479 
10480   Expr *LHS = E->getLHS();
10481   Expr *RHS = E->getRHS();
10482 
10483   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10484          "Must both be vector types");
10485   // Checking JUST the types are the same would be fine, except shifts don't
10486   // need to have their types be the same (since you always shift by an int).
10487   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10488              E->getType()->castAs<VectorType>()->getNumElements() &&
10489          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10490              E->getType()->castAs<VectorType>()->getNumElements() &&
10491          "All operands must be the same size.");
10492 
10493   APValue LHSValue;
10494   APValue RHSValue;
10495   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10496   if (!LHSOK && !Info.noteFailure())
10497     return false;
10498   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10499     return false;
10500 
10501   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10502     return false;
10503 
10504   return Success(LHSValue, E);
10505 }
10506 
handleVectorUnaryOperator(ASTContext & Ctx,QualType ResultTy,UnaryOperatorKind Op,APValue Elt)10507 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10508                                                          QualType ResultTy,
10509                                                          UnaryOperatorKind Op,
10510                                                          APValue Elt) {
10511   switch (Op) {
10512   case UO_Plus:
10513     // Nothing to do here.
10514     return Elt;
10515   case UO_Minus:
10516     if (Elt.getKind() == APValue::Int) {
10517       Elt.getInt().negate();
10518     } else {
10519       assert(Elt.getKind() == APValue::Float &&
10520              "Vector can only be int or float type");
10521       Elt.getFloat().changeSign();
10522     }
10523     return Elt;
10524   case UO_Not:
10525     // This is only valid for integral types anyway, so we don't have to handle
10526     // float here.
10527     assert(Elt.getKind() == APValue::Int &&
10528            "Vector operator ~ can only be int");
10529     Elt.getInt().flipAllBits();
10530     return Elt;
10531   case UO_LNot: {
10532     if (Elt.getKind() == APValue::Int) {
10533       Elt.getInt() = !Elt.getInt();
10534       // operator ! on vectors returns -1 for 'truth', so negate it.
10535       Elt.getInt().negate();
10536       return Elt;
10537     }
10538     assert(Elt.getKind() == APValue::Float &&
10539            "Vector can only be int or float type");
10540     // Float types result in an int of the same size, but -1 for true, or 0 for
10541     // false.
10542     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10543                      ResultTy->isUnsignedIntegerType()};
10544     if (Elt.getFloat().isZero())
10545       EltResult.setAllBits();
10546     else
10547       EltResult.clearAllBits();
10548 
10549     return APValue{EltResult};
10550   }
10551   default:
10552     // FIXME: Implement the rest of the unary operators.
10553     return llvm::None;
10554   }
10555 }
10556 
VisitUnaryOperator(const UnaryOperator * E)10557 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10558   Expr *SubExpr = E->getSubExpr();
10559   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10560   // This result element type differs in the case of negating a floating point
10561   // vector, since the result type is the a vector of the equivilant sized
10562   // integer.
10563   const QualType ResultEltTy = VD->getElementType();
10564   UnaryOperatorKind Op = E->getOpcode();
10565 
10566   APValue SubExprValue;
10567   if (!Evaluate(SubExprValue, Info, SubExpr))
10568     return false;
10569 
10570   // FIXME: This vector evaluator someday needs to be changed to be LValue
10571   // aware/keep LValue information around, rather than dealing with just vector
10572   // types directly. Until then, we cannot handle cases where the operand to
10573   // these unary operators is an LValue. The only case I've been able to see
10574   // cause this is operator++ assigning to a member expression (only valid in
10575   // altivec compilations) in C mode, so this shouldn't limit us too much.
10576   if (SubExprValue.isLValue())
10577     return false;
10578 
10579   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10580          "Vector length doesn't match type?");
10581 
10582   SmallVector<APValue, 4> ResultElements;
10583   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10584     llvm::Optional<APValue> Elt = handleVectorUnaryOperator(
10585         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10586     if (!Elt)
10587       return false;
10588     ResultElements.push_back(*Elt);
10589   }
10590   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10591 }
10592 
10593 //===----------------------------------------------------------------------===//
10594 // Array Evaluation
10595 //===----------------------------------------------------------------------===//
10596 
10597 namespace {
10598   class ArrayExprEvaluator
10599   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10600     const LValue &This;
10601     APValue &Result;
10602   public:
10603 
ArrayExprEvaluator(EvalInfo & Info,const LValue & This,APValue & Result)10604     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10605       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10606 
Success(const APValue & V,const Expr * E)10607     bool Success(const APValue &V, const Expr *E) {
10608       assert(V.isArray() && "expected array");
10609       Result = V;
10610       return true;
10611     }
10612 
ZeroInitialization(const Expr * E)10613     bool ZeroInitialization(const Expr *E) {
10614       const ConstantArrayType *CAT =
10615           Info.Ctx.getAsConstantArrayType(E->getType());
10616       if (!CAT) {
10617         if (E->getType()->isIncompleteArrayType()) {
10618           // We can be asked to zero-initialize a flexible array member; this
10619           // is represented as an ImplicitValueInitExpr of incomplete array
10620           // type. In this case, the array has zero elements.
10621           Result = APValue(APValue::UninitArray(), 0, 0);
10622           return true;
10623         }
10624         // FIXME: We could handle VLAs here.
10625         return Error(E);
10626       }
10627 
10628       Result = APValue(APValue::UninitArray(), 0,
10629                        CAT->getSize().getZExtValue());
10630       if (!Result.hasArrayFiller())
10631         return true;
10632 
10633       // Zero-initialize all elements.
10634       LValue Subobject = This;
10635       Subobject.addArray(Info, E, CAT);
10636       ImplicitValueInitExpr VIE(CAT->getElementType());
10637       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10638     }
10639 
VisitCallExpr(const CallExpr * E)10640     bool VisitCallExpr(const CallExpr *E) {
10641       return handleCallExpr(E, Result, &This);
10642     }
10643     bool VisitInitListExpr(const InitListExpr *E,
10644                            QualType AllocType = QualType());
10645     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10646     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10647     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10648                                const LValue &Subobject,
10649                                APValue *Value, QualType Type);
VisitStringLiteral(const StringLiteral * E,QualType AllocType=QualType ())10650     bool VisitStringLiteral(const StringLiteral *E,
10651                             QualType AllocType = QualType()) {
10652       expandStringLiteral(Info, E, Result, AllocType);
10653       return true;
10654     }
10655   };
10656 } // end anonymous namespace
10657 
EvaluateArray(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)10658 static bool EvaluateArray(const Expr *E, const LValue &This,
10659                           APValue &Result, EvalInfo &Info) {
10660   assert(!E->isValueDependent());
10661   assert(E->isPRValue() && E->getType()->isArrayType() &&
10662          "not an array prvalue");
10663   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10664 }
10665 
EvaluateArrayNewInitList(EvalInfo & Info,LValue & This,APValue & Result,const InitListExpr * ILE,QualType AllocType)10666 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10667                                      APValue &Result, const InitListExpr *ILE,
10668                                      QualType AllocType) {
10669   assert(!ILE->isValueDependent());
10670   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10671          "not an array prvalue");
10672   return ArrayExprEvaluator(Info, This, Result)
10673       .VisitInitListExpr(ILE, AllocType);
10674 }
10675 
EvaluateArrayNewConstructExpr(EvalInfo & Info,LValue & This,APValue & Result,const CXXConstructExpr * CCE,QualType AllocType)10676 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10677                                           APValue &Result,
10678                                           const CXXConstructExpr *CCE,
10679                                           QualType AllocType) {
10680   assert(!CCE->isValueDependent());
10681   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10682          "not an array prvalue");
10683   return ArrayExprEvaluator(Info, This, Result)
10684       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10685 }
10686 
10687 // Return true iff the given array filler may depend on the element index.
MaybeElementDependentArrayFiller(const Expr * FillerExpr)10688 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10689   // For now, just allow non-class value-initialization and initialization
10690   // lists comprised of them.
10691   if (isa<ImplicitValueInitExpr>(FillerExpr))
10692     return false;
10693   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10694     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10695       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10696         return true;
10697     }
10698     return false;
10699   }
10700   return true;
10701 }
10702 
VisitInitListExpr(const InitListExpr * E,QualType AllocType)10703 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10704                                            QualType AllocType) {
10705   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10706       AllocType.isNull() ? E->getType() : AllocType);
10707   if (!CAT)
10708     return Error(E);
10709 
10710   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10711   // an appropriately-typed string literal enclosed in braces.
10712   if (E->isStringLiteralInit()) {
10713     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10714     // FIXME: Support ObjCEncodeExpr here once we support it in
10715     // ArrayExprEvaluator generally.
10716     if (!SL)
10717       return Error(E);
10718     return VisitStringLiteral(SL, AllocType);
10719   }
10720   // Any other transparent list init will need proper handling of the
10721   // AllocType; we can't just recurse to the inner initializer.
10722   assert(!E->isTransparent() &&
10723          "transparent array list initialization is not string literal init?");
10724 
10725   bool Success = true;
10726 
10727   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10728          "zero-initialized array shouldn't have any initialized elts");
10729   APValue Filler;
10730   if (Result.isArray() && Result.hasArrayFiller())
10731     Filler = Result.getArrayFiller();
10732 
10733   unsigned NumEltsToInit = E->getNumInits();
10734   unsigned NumElts = CAT->getSize().getZExtValue();
10735   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10736 
10737   // If the initializer might depend on the array index, run it for each
10738   // array element.
10739   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10740     NumEltsToInit = NumElts;
10741 
10742   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10743                           << NumEltsToInit << ".\n");
10744 
10745   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10746 
10747   // If the array was previously zero-initialized, preserve the
10748   // zero-initialized values.
10749   if (Filler.hasValue()) {
10750     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10751       Result.getArrayInitializedElt(I) = Filler;
10752     if (Result.hasArrayFiller())
10753       Result.getArrayFiller() = Filler;
10754   }
10755 
10756   LValue Subobject = This;
10757   Subobject.addArray(Info, E, CAT);
10758   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10759     const Expr *Init =
10760         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10761     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10762                          Info, Subobject, Init) ||
10763         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10764                                      CAT->getElementType(), 1)) {
10765       if (!Info.noteFailure())
10766         return false;
10767       Success = false;
10768     }
10769   }
10770 
10771   if (!Result.hasArrayFiller())
10772     return Success;
10773 
10774   // If we get here, we have a trivial filler, which we can just evaluate
10775   // once and splat over the rest of the array elements.
10776   assert(FillerExpr && "no array filler for incomplete init list");
10777   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10778                          FillerExpr) && Success;
10779 }
10780 
VisitArrayInitLoopExpr(const ArrayInitLoopExpr * E)10781 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10782   LValue CommonLV;
10783   if (E->getCommonExpr() &&
10784       !Evaluate(Info.CurrentCall->createTemporary(
10785                     E->getCommonExpr(),
10786                     getStorageType(Info.Ctx, E->getCommonExpr()),
10787                     ScopeKind::FullExpression, CommonLV),
10788                 Info, E->getCommonExpr()->getSourceExpr()))
10789     return false;
10790 
10791   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10792 
10793   uint64_t Elements = CAT->getSize().getZExtValue();
10794   Result = APValue(APValue::UninitArray(), Elements, Elements);
10795 
10796   LValue Subobject = This;
10797   Subobject.addArray(Info, E, CAT);
10798 
10799   bool Success = true;
10800   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10801     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10802                          Info, Subobject, E->getSubExpr()) ||
10803         !HandleLValueArrayAdjustment(Info, E, Subobject,
10804                                      CAT->getElementType(), 1)) {
10805       if (!Info.noteFailure())
10806         return false;
10807       Success = false;
10808     }
10809   }
10810 
10811   return Success;
10812 }
10813 
VisitCXXConstructExpr(const CXXConstructExpr * E)10814 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10815   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10816 }
10817 
VisitCXXConstructExpr(const CXXConstructExpr * E,const LValue & Subobject,APValue * Value,QualType Type)10818 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10819                                                const LValue &Subobject,
10820                                                APValue *Value,
10821                                                QualType Type) {
10822   bool HadZeroInit = Value->hasValue();
10823 
10824   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10825     unsigned FinalSize = CAT->getSize().getZExtValue();
10826 
10827     // Preserve the array filler if we had prior zero-initialization.
10828     APValue Filler =
10829       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10830                                              : APValue();
10831 
10832     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10833     if (FinalSize == 0)
10834       return true;
10835 
10836     LValue ArrayElt = Subobject;
10837     ArrayElt.addArray(Info, E, CAT);
10838     // We do the whole initialization in two passes, first for just one element,
10839     // then for the whole array. It's possible we may find out we can't do const
10840     // init in the first pass, in which case we avoid allocating a potentially
10841     // large array. We don't do more passes because expanding array requires
10842     // copying the data, which is wasteful.
10843     for (const unsigned N : {1u, FinalSize}) {
10844       unsigned OldElts = Value->getArrayInitializedElts();
10845       if (OldElts == N)
10846         break;
10847 
10848       // Expand the array to appropriate size.
10849       APValue NewValue(APValue::UninitArray(), N, FinalSize);
10850       for (unsigned I = 0; I < OldElts; ++I)
10851         NewValue.getArrayInitializedElt(I).swap(
10852             Value->getArrayInitializedElt(I));
10853       Value->swap(NewValue);
10854 
10855       if (HadZeroInit)
10856         for (unsigned I = OldElts; I < N; ++I)
10857           Value->getArrayInitializedElt(I) = Filler;
10858 
10859       // Initialize the elements.
10860       for (unsigned I = OldElts; I < N; ++I) {
10861         if (!VisitCXXConstructExpr(E, ArrayElt,
10862                                    &Value->getArrayInitializedElt(I),
10863                                    CAT->getElementType()) ||
10864             !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10865                                          CAT->getElementType(), 1))
10866           return false;
10867         // When checking for const initilization any diagnostic is considered
10868         // an error.
10869         if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10870             !Info.keepEvaluatingAfterFailure())
10871           return false;
10872       }
10873     }
10874 
10875     return true;
10876   }
10877 
10878   if (!Type->isRecordType())
10879     return Error(E);
10880 
10881   return RecordExprEvaluator(Info, Subobject, *Value)
10882              .VisitCXXConstructExpr(E, Type);
10883 }
10884 
10885 //===----------------------------------------------------------------------===//
10886 // Integer Evaluation
10887 //
10888 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10889 // types and back in constant folding. Integer values are thus represented
10890 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10891 //===----------------------------------------------------------------------===//
10892 
10893 namespace {
10894 class IntExprEvaluator
10895         : public ExprEvaluatorBase<IntExprEvaluator> {
10896   APValue &Result;
10897 public:
IntExprEvaluator(EvalInfo & info,APValue & result)10898   IntExprEvaluator(EvalInfo &info, APValue &result)
10899       : ExprEvaluatorBaseTy(info), Result(result) {}
10900 
Success(const llvm::APSInt & SI,const Expr * E,APValue & Result)10901   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10902     assert(E->getType()->isIntegralOrEnumerationType() &&
10903            "Invalid evaluation result.");
10904     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10905            "Invalid evaluation result.");
10906     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10907            "Invalid evaluation result.");
10908     Result = APValue(SI);
10909     return true;
10910   }
Success(const llvm::APSInt & SI,const Expr * E)10911   bool Success(const llvm::APSInt &SI, const Expr *E) {
10912     return Success(SI, E, Result);
10913   }
10914 
Success(const llvm::APInt & I,const Expr * E,APValue & Result)10915   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10916     assert(E->getType()->isIntegralOrEnumerationType() &&
10917            "Invalid evaluation result.");
10918     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10919            "Invalid evaluation result.");
10920     Result = APValue(APSInt(I));
10921     Result.getInt().setIsUnsigned(
10922                             E->getType()->isUnsignedIntegerOrEnumerationType());
10923     return true;
10924   }
Success(const llvm::APInt & I,const Expr * E)10925   bool Success(const llvm::APInt &I, const Expr *E) {
10926     return Success(I, E, Result);
10927   }
10928 
Success(uint64_t Value,const Expr * E,APValue & Result)10929   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10930     assert(E->getType()->isIntegralOrEnumerationType() &&
10931            "Invalid evaluation result.");
10932     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10933     return true;
10934   }
Success(uint64_t Value,const Expr * E)10935   bool Success(uint64_t Value, const Expr *E) {
10936     return Success(Value, E, Result);
10937   }
10938 
Success(CharUnits Size,const Expr * E)10939   bool Success(CharUnits Size, const Expr *E) {
10940     return Success(Size.getQuantity(), E);
10941   }
10942 
Success(const APValue & V,const Expr * E)10943   bool Success(const APValue &V, const Expr *E) {
10944     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10945       Result = V;
10946       return true;
10947     }
10948     return Success(V.getInt(), E);
10949   }
10950 
ZeroInitialization(const Expr * E)10951   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10952 
10953   //===--------------------------------------------------------------------===//
10954   //                            Visitor Methods
10955   //===--------------------------------------------------------------------===//
10956 
VisitIntegerLiteral(const IntegerLiteral * E)10957   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10958     return Success(E->getValue(), E);
10959   }
VisitCharacterLiteral(const CharacterLiteral * E)10960   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10961     return Success(E->getValue(), E);
10962   }
10963 
10964   bool CheckReferencedDecl(const Expr *E, const Decl *D);
VisitDeclRefExpr(const DeclRefExpr * E)10965   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10966     if (CheckReferencedDecl(E, E->getDecl()))
10967       return true;
10968 
10969     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10970   }
VisitMemberExpr(const MemberExpr * E)10971   bool VisitMemberExpr(const MemberExpr *E) {
10972     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10973       VisitIgnoredBaseExpression(E->getBase());
10974       return true;
10975     }
10976 
10977     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10978   }
10979 
10980   bool VisitCallExpr(const CallExpr *E);
10981   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10982   bool VisitBinaryOperator(const BinaryOperator *E);
10983   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10984   bool VisitUnaryOperator(const UnaryOperator *E);
10985 
10986   bool VisitCastExpr(const CastExpr* E);
10987   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10988 
VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr * E)10989   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10990     return Success(E->getValue(), E);
10991   }
10992 
VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr * E)10993   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10994     return Success(E->getValue(), E);
10995   }
10996 
VisitArrayInitIndexExpr(const ArrayInitIndexExpr * E)10997   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10998     if (Info.ArrayInitIndex == uint64_t(-1)) {
10999       // We were asked to evaluate this subexpression independent of the
11000       // enclosing ArrayInitLoopExpr. We can't do that.
11001       Info.FFDiag(E);
11002       return false;
11003     }
11004     return Success(Info.ArrayInitIndex, E);
11005   }
11006 
11007   // Note, GNU defines __null as an integer, not a pointer.
VisitGNUNullExpr(const GNUNullExpr * E)11008   bool VisitGNUNullExpr(const GNUNullExpr *E) {
11009     return ZeroInitialization(E);
11010   }
11011 
VisitTypeTraitExpr(const TypeTraitExpr * E)11012   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11013     return Success(E->getValue(), E);
11014   }
11015 
VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr * E)11016   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11017     return Success(E->getValue(), E);
11018   }
11019 
VisitExpressionTraitExpr(const ExpressionTraitExpr * E)11020   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11021     return Success(E->getValue(), E);
11022   }
11023 
11024   bool VisitUnaryReal(const UnaryOperator *E);
11025   bool VisitUnaryImag(const UnaryOperator *E);
11026 
11027   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11028   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11029   bool VisitSourceLocExpr(const SourceLocExpr *E);
11030   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11031   bool VisitRequiresExpr(const RequiresExpr *E);
11032   // FIXME: Missing: array subscript of vector, member of vector
11033 };
11034 
11035 class FixedPointExprEvaluator
11036     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11037   APValue &Result;
11038 
11039  public:
FixedPointExprEvaluator(EvalInfo & info,APValue & result)11040   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11041       : ExprEvaluatorBaseTy(info), Result(result) {}
11042 
Success(const llvm::APInt & I,const Expr * E)11043   bool Success(const llvm::APInt &I, const Expr *E) {
11044     return Success(
11045         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11046   }
11047 
Success(uint64_t Value,const Expr * E)11048   bool Success(uint64_t Value, const Expr *E) {
11049     return Success(
11050         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11051   }
11052 
Success(const APValue & V,const Expr * E)11053   bool Success(const APValue &V, const Expr *E) {
11054     return Success(V.getFixedPoint(), E);
11055   }
11056 
Success(const APFixedPoint & V,const Expr * E)11057   bool Success(const APFixedPoint &V, const Expr *E) {
11058     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11059     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11060            "Invalid evaluation result.");
11061     Result = APValue(V);
11062     return true;
11063   }
11064 
11065   //===--------------------------------------------------------------------===//
11066   //                            Visitor Methods
11067   //===--------------------------------------------------------------------===//
11068 
VisitFixedPointLiteral(const FixedPointLiteral * E)11069   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11070     return Success(E->getValue(), E);
11071   }
11072 
11073   bool VisitCastExpr(const CastExpr *E);
11074   bool VisitUnaryOperator(const UnaryOperator *E);
11075   bool VisitBinaryOperator(const BinaryOperator *E);
11076 };
11077 } // end anonymous namespace
11078 
11079 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11080 /// produce either the integer value or a pointer.
11081 ///
11082 /// GCC has a heinous extension which folds casts between pointer types and
11083 /// pointer-sized integral types. We support this by allowing the evaluation of
11084 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11085 /// Some simple arithmetic on such values is supported (they are treated much
11086 /// like char*).
EvaluateIntegerOrLValue(const Expr * E,APValue & Result,EvalInfo & Info)11087 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11088                                     EvalInfo &Info) {
11089   assert(!E->isValueDependent());
11090   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11091   return IntExprEvaluator(Info, Result).Visit(E);
11092 }
11093 
EvaluateInteger(const Expr * E,APSInt & Result,EvalInfo & Info)11094 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11095   assert(!E->isValueDependent());
11096   APValue Val;
11097   if (!EvaluateIntegerOrLValue(E, Val, Info))
11098     return false;
11099   if (!Val.isInt()) {
11100     // FIXME: It would be better to produce the diagnostic for casting
11101     //        a pointer to an integer.
11102     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11103     return false;
11104   }
11105   Result = Val.getInt();
11106   return true;
11107 }
11108 
VisitSourceLocExpr(const SourceLocExpr * E)11109 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11110   APValue Evaluated = E->EvaluateInContext(
11111       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11112   return Success(Evaluated, E);
11113 }
11114 
EvaluateFixedPoint(const Expr * E,APFixedPoint & Result,EvalInfo & Info)11115 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11116                                EvalInfo &Info) {
11117   assert(!E->isValueDependent());
11118   if (E->getType()->isFixedPointType()) {
11119     APValue Val;
11120     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11121       return false;
11122     if (!Val.isFixedPoint())
11123       return false;
11124 
11125     Result = Val.getFixedPoint();
11126     return true;
11127   }
11128   return false;
11129 }
11130 
EvaluateFixedPointOrInteger(const Expr * E,APFixedPoint & Result,EvalInfo & Info)11131 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11132                                         EvalInfo &Info) {
11133   assert(!E->isValueDependent());
11134   if (E->getType()->isIntegerType()) {
11135     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11136     APSInt Val;
11137     if (!EvaluateInteger(E, Val, Info))
11138       return false;
11139     Result = APFixedPoint(Val, FXSema);
11140     return true;
11141   } else if (E->getType()->isFixedPointType()) {
11142     return EvaluateFixedPoint(E, Result, Info);
11143   }
11144   return false;
11145 }
11146 
11147 /// Check whether the given declaration can be directly converted to an integral
11148 /// rvalue. If not, no diagnostic is produced; there are other things we can
11149 /// try.
CheckReferencedDecl(const Expr * E,const Decl * D)11150 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11151   // Enums are integer constant exprs.
11152   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11153     // Check for signedness/width mismatches between E type and ECD value.
11154     bool SameSign = (ECD->getInitVal().isSigned()
11155                      == E->getType()->isSignedIntegerOrEnumerationType());
11156     bool SameWidth = (ECD->getInitVal().getBitWidth()
11157                       == Info.Ctx.getIntWidth(E->getType()));
11158     if (SameSign && SameWidth)
11159       return Success(ECD->getInitVal(), E);
11160     else {
11161       // Get rid of mismatch (otherwise Success assertions will fail)
11162       // by computing a new value matching the type of E.
11163       llvm::APSInt Val = ECD->getInitVal();
11164       if (!SameSign)
11165         Val.setIsSigned(!ECD->getInitVal().isSigned());
11166       if (!SameWidth)
11167         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11168       return Success(Val, E);
11169     }
11170   }
11171   return false;
11172 }
11173 
11174 /// Values returned by __builtin_classify_type, chosen to match the values
11175 /// produced by GCC's builtin.
11176 enum class GCCTypeClass {
11177   None = -1,
11178   Void = 0,
11179   Integer = 1,
11180   // GCC reserves 2 for character types, but instead classifies them as
11181   // integers.
11182   Enum = 3,
11183   Bool = 4,
11184   Pointer = 5,
11185   // GCC reserves 6 for references, but appears to never use it (because
11186   // expressions never have reference type, presumably).
11187   PointerToDataMember = 7,
11188   RealFloat = 8,
11189   Complex = 9,
11190   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11191   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11192   // GCC claims to reserve 11 for pointers to member functions, but *actually*
11193   // uses 12 for that purpose, same as for a class or struct. Maybe it
11194   // internally implements a pointer to member as a struct?  Who knows.
11195   PointerToMemberFunction = 12, // Not a bug, see above.
11196   ClassOrStruct = 12,
11197   Union = 13,
11198   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11199   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11200   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11201   // literals.
11202 };
11203 
11204 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11205 /// as GCC.
11206 static GCCTypeClass
EvaluateBuiltinClassifyType(QualType T,const LangOptions & LangOpts)11207 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11208   assert(!T->isDependentType() && "unexpected dependent type");
11209 
11210   QualType CanTy = T.getCanonicalType();
11211   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11212 
11213   switch (CanTy->getTypeClass()) {
11214 #define TYPE(ID, BASE)
11215 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11216 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11217 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11218 #include "clang/AST/TypeNodes.inc"
11219   case Type::Auto:
11220   case Type::DeducedTemplateSpecialization:
11221       llvm_unreachable("unexpected non-canonical or dependent type");
11222 
11223   case Type::Builtin:
11224     switch (BT->getKind()) {
11225 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11226 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11227     case BuiltinType::ID: return GCCTypeClass::Integer;
11228 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11229     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11230 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11231     case BuiltinType::ID: break;
11232 #include "clang/AST/BuiltinTypes.def"
11233     case BuiltinType::Void:
11234       return GCCTypeClass::Void;
11235 
11236     case BuiltinType::Bool:
11237       return GCCTypeClass::Bool;
11238 
11239     case BuiltinType::Char_U:
11240     case BuiltinType::UChar:
11241     case BuiltinType::WChar_U:
11242     case BuiltinType::Char8:
11243     case BuiltinType::Char16:
11244     case BuiltinType::Char32:
11245     case BuiltinType::UShort:
11246     case BuiltinType::UInt:
11247     case BuiltinType::ULong:
11248     case BuiltinType::ULongLong:
11249     case BuiltinType::UInt128:
11250       return GCCTypeClass::Integer;
11251 
11252     case BuiltinType::UShortAccum:
11253     case BuiltinType::UAccum:
11254     case BuiltinType::ULongAccum:
11255     case BuiltinType::UShortFract:
11256     case BuiltinType::UFract:
11257     case BuiltinType::ULongFract:
11258     case BuiltinType::SatUShortAccum:
11259     case BuiltinType::SatUAccum:
11260     case BuiltinType::SatULongAccum:
11261     case BuiltinType::SatUShortFract:
11262     case BuiltinType::SatUFract:
11263     case BuiltinType::SatULongFract:
11264       return GCCTypeClass::None;
11265 
11266     case BuiltinType::NullPtr:
11267 
11268     case BuiltinType::ObjCId:
11269     case BuiltinType::ObjCClass:
11270     case BuiltinType::ObjCSel:
11271 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11272     case BuiltinType::Id:
11273 #include "clang/Basic/OpenCLImageTypes.def"
11274 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11275     case BuiltinType::Id:
11276 #include "clang/Basic/OpenCLExtensionTypes.def"
11277     case BuiltinType::OCLSampler:
11278     case BuiltinType::OCLEvent:
11279     case BuiltinType::OCLClkEvent:
11280     case BuiltinType::OCLQueue:
11281     case BuiltinType::OCLReserveID:
11282 #define SVE_TYPE(Name, Id, SingletonId) \
11283     case BuiltinType::Id:
11284 #include "clang/Basic/AArch64SVEACLETypes.def"
11285 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11286     case BuiltinType::Id:
11287 #include "clang/Basic/PPCTypes.def"
11288 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11289 #include "clang/Basic/RISCVVTypes.def"
11290       return GCCTypeClass::None;
11291 
11292     case BuiltinType::Dependent:
11293       llvm_unreachable("unexpected dependent type");
11294     };
11295     llvm_unreachable("unexpected placeholder type");
11296 
11297   case Type::Enum:
11298     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11299 
11300   case Type::Pointer:
11301   case Type::ConstantArray:
11302   case Type::VariableArray:
11303   case Type::IncompleteArray:
11304   case Type::FunctionNoProto:
11305   case Type::FunctionProto:
11306     return GCCTypeClass::Pointer;
11307 
11308   case Type::MemberPointer:
11309     return CanTy->isMemberDataPointerType()
11310                ? GCCTypeClass::PointerToDataMember
11311                : GCCTypeClass::PointerToMemberFunction;
11312 
11313   case Type::Complex:
11314     return GCCTypeClass::Complex;
11315 
11316   case Type::Record:
11317     return CanTy->isUnionType() ? GCCTypeClass::Union
11318                                 : GCCTypeClass::ClassOrStruct;
11319 
11320   case Type::Atomic:
11321     // GCC classifies _Atomic T the same as T.
11322     return EvaluateBuiltinClassifyType(
11323         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11324 
11325   case Type::BlockPointer:
11326   case Type::Vector:
11327   case Type::ExtVector:
11328   case Type::ConstantMatrix:
11329   case Type::ObjCObject:
11330   case Type::ObjCInterface:
11331   case Type::ObjCObjectPointer:
11332   case Type::Pipe:
11333   case Type::BitInt:
11334     // GCC classifies vectors as None. We follow its lead and classify all
11335     // other types that don't fit into the regular classification the same way.
11336     return GCCTypeClass::None;
11337 
11338   case Type::LValueReference:
11339   case Type::RValueReference:
11340     llvm_unreachable("invalid type for expression");
11341   }
11342 
11343   llvm_unreachable("unexpected type class");
11344 }
11345 
11346 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11347 /// as GCC.
11348 static GCCTypeClass
EvaluateBuiltinClassifyType(const CallExpr * E,const LangOptions & LangOpts)11349 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11350   // If no argument was supplied, default to None. This isn't
11351   // ideal, however it is what gcc does.
11352   if (E->getNumArgs() == 0)
11353     return GCCTypeClass::None;
11354 
11355   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11356   // being an ICE, but still folds it to a constant using the type of the first
11357   // argument.
11358   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11359 }
11360 
11361 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11362 /// __builtin_constant_p when applied to the given pointer.
11363 ///
11364 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11365 /// or it points to the first character of a string literal.
EvaluateBuiltinConstantPForLValue(const APValue & LV)11366 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11367   APValue::LValueBase Base = LV.getLValueBase();
11368   if (Base.isNull()) {
11369     // A null base is acceptable.
11370     return true;
11371   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11372     if (!isa<StringLiteral>(E))
11373       return false;
11374     return LV.getLValueOffset().isZero();
11375   } else if (Base.is<TypeInfoLValue>()) {
11376     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11377     // evaluate to true.
11378     return true;
11379   } else {
11380     // Any other base is not constant enough for GCC.
11381     return false;
11382   }
11383 }
11384 
11385 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11386 /// GCC as we can manage.
EvaluateBuiltinConstantP(EvalInfo & Info,const Expr * Arg)11387 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11388   // This evaluation is not permitted to have side-effects, so evaluate it in
11389   // a speculative evaluation context.
11390   SpeculativeEvaluationRAII SpeculativeEval(Info);
11391 
11392   // Constant-folding is always enabled for the operand of __builtin_constant_p
11393   // (even when the enclosing evaluation context otherwise requires a strict
11394   // language-specific constant expression).
11395   FoldConstant Fold(Info, true);
11396 
11397   QualType ArgType = Arg->getType();
11398 
11399   // __builtin_constant_p always has one operand. The rules which gcc follows
11400   // are not precisely documented, but are as follows:
11401   //
11402   //  - If the operand is of integral, floating, complex or enumeration type,
11403   //    and can be folded to a known value of that type, it returns 1.
11404   //  - If the operand can be folded to a pointer to the first character
11405   //    of a string literal (or such a pointer cast to an integral type)
11406   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11407   //
11408   // Otherwise, it returns 0.
11409   //
11410   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11411   // its support for this did not work prior to GCC 9 and is not yet well
11412   // understood.
11413   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11414       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11415       ArgType->isNullPtrType()) {
11416     APValue V;
11417     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11418       Fold.keepDiagnostics();
11419       return false;
11420     }
11421 
11422     // For a pointer (possibly cast to integer), there are special rules.
11423     if (V.getKind() == APValue::LValue)
11424       return EvaluateBuiltinConstantPForLValue(V);
11425 
11426     // Otherwise, any constant value is good enough.
11427     return V.hasValue();
11428   }
11429 
11430   // Anything else isn't considered to be sufficiently constant.
11431   return false;
11432 }
11433 
11434 /// Retrieves the "underlying object type" of the given expression,
11435 /// as used by __builtin_object_size.
getObjectType(APValue::LValueBase B)11436 static QualType getObjectType(APValue::LValueBase B) {
11437   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11438     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11439       return VD->getType();
11440   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11441     if (isa<CompoundLiteralExpr>(E))
11442       return E->getType();
11443   } else if (B.is<TypeInfoLValue>()) {
11444     return B.getTypeInfoType();
11445   } else if (B.is<DynamicAllocLValue>()) {
11446     return B.getDynamicAllocType();
11447   }
11448 
11449   return QualType();
11450 }
11451 
11452 /// A more selective version of E->IgnoreParenCasts for
11453 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11454 /// to change the type of E.
11455 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11456 ///
11457 /// Always returns an RValue with a pointer representation.
ignorePointerCastsAndParens(const Expr * E)11458 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11459   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11460 
11461   auto *NoParens = E->IgnoreParens();
11462   auto *Cast = dyn_cast<CastExpr>(NoParens);
11463   if (Cast == nullptr)
11464     return NoParens;
11465 
11466   // We only conservatively allow a few kinds of casts, because this code is
11467   // inherently a simple solution that seeks to support the common case.
11468   auto CastKind = Cast->getCastKind();
11469   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11470       CastKind != CK_AddressSpaceConversion)
11471     return NoParens;
11472 
11473   auto *SubExpr = Cast->getSubExpr();
11474   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11475     return NoParens;
11476   return ignorePointerCastsAndParens(SubExpr);
11477 }
11478 
11479 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11480 /// record layout. e.g.
11481 ///   struct { struct { int a, b; } fst, snd; } obj;
11482 ///   obj.fst   // no
11483 ///   obj.snd   // yes
11484 ///   obj.fst.a // no
11485 ///   obj.fst.b // no
11486 ///   obj.snd.a // no
11487 ///   obj.snd.b // yes
11488 ///
11489 /// Please note: this function is specialized for how __builtin_object_size
11490 /// views "objects".
11491 ///
11492 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11493 /// correct result, it will always return true.
isDesignatorAtObjectEnd(const ASTContext & Ctx,const LValue & LVal)11494 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11495   assert(!LVal.Designator.Invalid);
11496 
11497   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11498     const RecordDecl *Parent = FD->getParent();
11499     Invalid = Parent->isInvalidDecl();
11500     if (Invalid || Parent->isUnion())
11501       return true;
11502     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11503     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11504   };
11505 
11506   auto &Base = LVal.getLValueBase();
11507   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11508     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11509       bool Invalid;
11510       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11511         return Invalid;
11512     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11513       for (auto *FD : IFD->chain()) {
11514         bool Invalid;
11515         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11516           return Invalid;
11517       }
11518     }
11519   }
11520 
11521   unsigned I = 0;
11522   QualType BaseType = getType(Base);
11523   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11524     // If we don't know the array bound, conservatively assume we're looking at
11525     // the final array element.
11526     ++I;
11527     if (BaseType->isIncompleteArrayType())
11528       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11529     else
11530       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11531   }
11532 
11533   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11534     const auto &Entry = LVal.Designator.Entries[I];
11535     if (BaseType->isArrayType()) {
11536       // Because __builtin_object_size treats arrays as objects, we can ignore
11537       // the index iff this is the last array in the Designator.
11538       if (I + 1 == E)
11539         return true;
11540       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11541       uint64_t Index = Entry.getAsArrayIndex();
11542       if (Index + 1 != CAT->getSize())
11543         return false;
11544       BaseType = CAT->getElementType();
11545     } else if (BaseType->isAnyComplexType()) {
11546       const auto *CT = BaseType->castAs<ComplexType>();
11547       uint64_t Index = Entry.getAsArrayIndex();
11548       if (Index != 1)
11549         return false;
11550       BaseType = CT->getElementType();
11551     } else if (auto *FD = getAsField(Entry)) {
11552       bool Invalid;
11553       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11554         return Invalid;
11555       BaseType = FD->getType();
11556     } else {
11557       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11558       return false;
11559     }
11560   }
11561   return true;
11562 }
11563 
11564 /// Tests to see if the LValue has a user-specified designator (that isn't
11565 /// necessarily valid). Note that this always returns 'true' if the LValue has
11566 /// an unsized array as its first designator entry, because there's currently no
11567 /// way to tell if the user typed *foo or foo[0].
refersToCompleteObject(const LValue & LVal)11568 static bool refersToCompleteObject(const LValue &LVal) {
11569   if (LVal.Designator.Invalid)
11570     return false;
11571 
11572   if (!LVal.Designator.Entries.empty())
11573     return LVal.Designator.isMostDerivedAnUnsizedArray();
11574 
11575   if (!LVal.InvalidBase)
11576     return true;
11577 
11578   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11579   // the LValueBase.
11580   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11581   return !E || !isa<MemberExpr>(E);
11582 }
11583 
11584 /// Attempts to detect a user writing into a piece of memory that's impossible
11585 /// to figure out the size of by just using types.
isUserWritingOffTheEnd(const ASTContext & Ctx,const LValue & LVal)11586 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11587   const SubobjectDesignator &Designator = LVal.Designator;
11588   // Notes:
11589   // - Users can only write off of the end when we have an invalid base. Invalid
11590   //   bases imply we don't know where the memory came from.
11591   // - We used to be a bit more aggressive here; we'd only be conservative if
11592   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11593   //   broke some common standard library extensions (PR30346), but was
11594   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11595   //   with some sort of list. OTOH, it seems that GCC is always
11596   //   conservative with the last element in structs (if it's an array), so our
11597   //   current behavior is more compatible than an explicit list approach would
11598   //   be.
11599   int StrictFlexArraysLevel = Ctx.getLangOpts().StrictFlexArrays;
11600   return LVal.InvalidBase &&
11601          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11602          Designator.MostDerivedIsArrayElement &&
11603          (Designator.isMostDerivedAnUnsizedArray() ||
11604           Designator.getMostDerivedArraySize() == 0 ||
11605           (Designator.getMostDerivedArraySize() == 1 &&
11606            StrictFlexArraysLevel < 2) ||
11607           StrictFlexArraysLevel == 0) &&
11608          isDesignatorAtObjectEnd(Ctx, LVal);
11609 }
11610 
11611 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11612 /// Fails if the conversion would cause loss of precision.
convertUnsignedAPIntToCharUnits(const llvm::APInt & Int,CharUnits & Result)11613 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11614                                             CharUnits &Result) {
11615   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11616   if (Int.ugt(CharUnitsMax))
11617     return false;
11618   Result = CharUnits::fromQuantity(Int.getZExtValue());
11619   return true;
11620 }
11621 
11622 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11623 /// determine how many bytes exist from the beginning of the object to either
11624 /// the end of the current subobject, or the end of the object itself, depending
11625 /// on what the LValue looks like + the value of Type.
11626 ///
11627 /// If this returns false, the value of Result is undefined.
determineEndOffset(EvalInfo & Info,SourceLocation ExprLoc,unsigned Type,const LValue & LVal,CharUnits & EndOffset)11628 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11629                                unsigned Type, const LValue &LVal,
11630                                CharUnits &EndOffset) {
11631   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11632 
11633   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11634     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11635       return false;
11636     return HandleSizeof(Info, ExprLoc, Ty, Result);
11637   };
11638 
11639   // We want to evaluate the size of the entire object. This is a valid fallback
11640   // for when Type=1 and the designator is invalid, because we're asked for an
11641   // upper-bound.
11642   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11643     // Type=3 wants a lower bound, so we can't fall back to this.
11644     if (Type == 3 && !DetermineForCompleteObject)
11645       return false;
11646 
11647     llvm::APInt APEndOffset;
11648     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11649         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11650       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11651 
11652     if (LVal.InvalidBase)
11653       return false;
11654 
11655     QualType BaseTy = getObjectType(LVal.getLValueBase());
11656     return CheckedHandleSizeof(BaseTy, EndOffset);
11657   }
11658 
11659   // We want to evaluate the size of a subobject.
11660   const SubobjectDesignator &Designator = LVal.Designator;
11661 
11662   // The following is a moderately common idiom in C:
11663   //
11664   // struct Foo { int a; char c[1]; };
11665   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11666   // strcpy(&F->c[0], Bar);
11667   //
11668   // In order to not break too much legacy code, we need to support it.
11669   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11670     // If we can resolve this to an alloc_size call, we can hand that back,
11671     // because we know for certain how many bytes there are to write to.
11672     llvm::APInt APEndOffset;
11673     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11674         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11675       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11676 
11677     // If we cannot determine the size of the initial allocation, then we can't
11678     // given an accurate upper-bound. However, we are still able to give
11679     // conservative lower-bounds for Type=3.
11680     if (Type == 1)
11681       return false;
11682   }
11683 
11684   CharUnits BytesPerElem;
11685   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11686     return false;
11687 
11688   // According to the GCC documentation, we want the size of the subobject
11689   // denoted by the pointer. But that's not quite right -- what we actually
11690   // want is the size of the immediately-enclosing array, if there is one.
11691   int64_t ElemsRemaining;
11692   if (Designator.MostDerivedIsArrayElement &&
11693       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11694     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11695     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11696     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11697   } else {
11698     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11699   }
11700 
11701   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11702   return true;
11703 }
11704 
11705 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11706 /// returns true and stores the result in @p Size.
11707 ///
11708 /// If @p WasError is non-null, this will report whether the failure to evaluate
11709 /// is to be treated as an Error in IntExprEvaluator.
tryEvaluateBuiltinObjectSize(const Expr * E,unsigned Type,EvalInfo & Info,uint64_t & Size)11710 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11711                                          EvalInfo &Info, uint64_t &Size) {
11712   // Determine the denoted object.
11713   LValue LVal;
11714   {
11715     // The operand of __builtin_object_size is never evaluated for side-effects.
11716     // If there are any, but we can determine the pointed-to object anyway, then
11717     // ignore the side-effects.
11718     SpeculativeEvaluationRAII SpeculativeEval(Info);
11719     IgnoreSideEffectsRAII Fold(Info);
11720 
11721     if (E->isGLValue()) {
11722       // It's possible for us to be given GLValues if we're called via
11723       // Expr::tryEvaluateObjectSize.
11724       APValue RVal;
11725       if (!EvaluateAsRValue(Info, E, RVal))
11726         return false;
11727       LVal.setFrom(Info.Ctx, RVal);
11728     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11729                                 /*InvalidBaseOK=*/true))
11730       return false;
11731   }
11732 
11733   // If we point to before the start of the object, there are no accessible
11734   // bytes.
11735   if (LVal.getLValueOffset().isNegative()) {
11736     Size = 0;
11737     return true;
11738   }
11739 
11740   CharUnits EndOffset;
11741   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11742     return false;
11743 
11744   // If we've fallen outside of the end offset, just pretend there's nothing to
11745   // write to/read from.
11746   if (EndOffset <= LVal.getLValueOffset())
11747     Size = 0;
11748   else
11749     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11750   return true;
11751 }
11752 
VisitCallExpr(const CallExpr * E)11753 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11754   if (unsigned BuiltinOp = E->getBuiltinCallee())
11755     return VisitBuiltinCallExpr(E, BuiltinOp);
11756 
11757   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11758 }
11759 
getBuiltinAlignArguments(const CallExpr * E,EvalInfo & Info,APValue & Val,APSInt & Alignment)11760 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11761                                      APValue &Val, APSInt &Alignment) {
11762   QualType SrcTy = E->getArg(0)->getType();
11763   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11764     return false;
11765   // Even though we are evaluating integer expressions we could get a pointer
11766   // argument for the __builtin_is_aligned() case.
11767   if (SrcTy->isPointerType()) {
11768     LValue Ptr;
11769     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11770       return false;
11771     Ptr.moveInto(Val);
11772   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11773     Info.FFDiag(E->getArg(0));
11774     return false;
11775   } else {
11776     APSInt SrcInt;
11777     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11778       return false;
11779     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11780            "Bit widths must be the same");
11781     Val = APValue(SrcInt);
11782   }
11783   assert(Val.hasValue());
11784   return true;
11785 }
11786 
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)11787 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11788                                             unsigned BuiltinOp) {
11789   switch (BuiltinOp) {
11790   default:
11791     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11792 
11793   case Builtin::BI__builtin_dynamic_object_size:
11794   case Builtin::BI__builtin_object_size: {
11795     // The type was checked when we built the expression.
11796     unsigned Type =
11797         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11798     assert(Type <= 3 && "unexpected type");
11799 
11800     uint64_t Size;
11801     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11802       return Success(Size, E);
11803 
11804     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11805       return Success((Type & 2) ? 0 : -1, E);
11806 
11807     // Expression had no side effects, but we couldn't statically determine the
11808     // size of the referenced object.
11809     switch (Info.EvalMode) {
11810     case EvalInfo::EM_ConstantExpression:
11811     case EvalInfo::EM_ConstantFold:
11812     case EvalInfo::EM_IgnoreSideEffects:
11813       // Leave it to IR generation.
11814       return Error(E);
11815     case EvalInfo::EM_ConstantExpressionUnevaluated:
11816       // Reduce it to a constant now.
11817       return Success((Type & 2) ? 0 : -1, E);
11818     }
11819 
11820     llvm_unreachable("unexpected EvalMode");
11821   }
11822 
11823   case Builtin::BI__builtin_os_log_format_buffer_size: {
11824     analyze_os_log::OSLogBufferLayout Layout;
11825     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11826     return Success(Layout.size().getQuantity(), E);
11827   }
11828 
11829   case Builtin::BI__builtin_is_aligned: {
11830     APValue Src;
11831     APSInt Alignment;
11832     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11833       return false;
11834     if (Src.isLValue()) {
11835       // If we evaluated a pointer, check the minimum known alignment.
11836       LValue Ptr;
11837       Ptr.setFrom(Info.Ctx, Src);
11838       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11839       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11840       // We can return true if the known alignment at the computed offset is
11841       // greater than the requested alignment.
11842       assert(PtrAlign.isPowerOfTwo());
11843       assert(Alignment.isPowerOf2());
11844       if (PtrAlign.getQuantity() >= Alignment)
11845         return Success(1, E);
11846       // If the alignment is not known to be sufficient, some cases could still
11847       // be aligned at run time. However, if the requested alignment is less or
11848       // equal to the base alignment and the offset is not aligned, we know that
11849       // the run-time value can never be aligned.
11850       if (BaseAlignment.getQuantity() >= Alignment &&
11851           PtrAlign.getQuantity() < Alignment)
11852         return Success(0, E);
11853       // Otherwise we can't infer whether the value is sufficiently aligned.
11854       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11855       //  in cases where we can't fully evaluate the pointer.
11856       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11857           << Alignment;
11858       return false;
11859     }
11860     assert(Src.isInt());
11861     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11862   }
11863   case Builtin::BI__builtin_align_up: {
11864     APValue Src;
11865     APSInt Alignment;
11866     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11867       return false;
11868     if (!Src.isInt())
11869       return Error(E);
11870     APSInt AlignedVal =
11871         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11872                Src.getInt().isUnsigned());
11873     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11874     return Success(AlignedVal, E);
11875   }
11876   case Builtin::BI__builtin_align_down: {
11877     APValue Src;
11878     APSInt Alignment;
11879     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11880       return false;
11881     if (!Src.isInt())
11882       return Error(E);
11883     APSInt AlignedVal =
11884         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11885     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11886     return Success(AlignedVal, E);
11887   }
11888 
11889   case Builtin::BI__builtin_bitreverse8:
11890   case Builtin::BI__builtin_bitreverse16:
11891   case Builtin::BI__builtin_bitreverse32:
11892   case Builtin::BI__builtin_bitreverse64: {
11893     APSInt Val;
11894     if (!EvaluateInteger(E->getArg(0), Val, Info))
11895       return false;
11896 
11897     return Success(Val.reverseBits(), E);
11898   }
11899 
11900   case Builtin::BI__builtin_bswap16:
11901   case Builtin::BI__builtin_bswap32:
11902   case Builtin::BI__builtin_bswap64: {
11903     APSInt Val;
11904     if (!EvaluateInteger(E->getArg(0), Val, Info))
11905       return false;
11906 
11907     return Success(Val.byteSwap(), E);
11908   }
11909 
11910   case Builtin::BI__builtin_classify_type:
11911     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11912 
11913   case Builtin::BI__builtin_clrsb:
11914   case Builtin::BI__builtin_clrsbl:
11915   case Builtin::BI__builtin_clrsbll: {
11916     APSInt Val;
11917     if (!EvaluateInteger(E->getArg(0), Val, Info))
11918       return false;
11919 
11920     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11921   }
11922 
11923   case Builtin::BI__builtin_clz:
11924   case Builtin::BI__builtin_clzl:
11925   case Builtin::BI__builtin_clzll:
11926   case Builtin::BI__builtin_clzs: {
11927     APSInt Val;
11928     if (!EvaluateInteger(E->getArg(0), Val, Info))
11929       return false;
11930     if (!Val)
11931       return Error(E);
11932 
11933     return Success(Val.countLeadingZeros(), E);
11934   }
11935 
11936   case Builtin::BI__builtin_constant_p: {
11937     const Expr *Arg = E->getArg(0);
11938     if (EvaluateBuiltinConstantP(Info, Arg))
11939       return Success(true, E);
11940     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11941       // Outside a constant context, eagerly evaluate to false in the presence
11942       // of side-effects in order to avoid -Wunsequenced false-positives in
11943       // a branch on __builtin_constant_p(expr).
11944       return Success(false, E);
11945     }
11946     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11947     return false;
11948   }
11949 
11950   case Builtin::BI__builtin_is_constant_evaluated: {
11951     const auto *Callee = Info.CurrentCall->getCallee();
11952     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11953         (Info.CallStackDepth == 1 ||
11954          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11955           Callee->getIdentifier() &&
11956           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11957       // FIXME: Find a better way to avoid duplicated diagnostics.
11958       if (Info.EvalStatus.Diag)
11959         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11960                                                : Info.CurrentCall->CallLoc,
11961                     diag::warn_is_constant_evaluated_always_true_constexpr)
11962             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11963                                          : "std::is_constant_evaluated");
11964     }
11965 
11966     return Success(Info.InConstantContext, E);
11967   }
11968 
11969   case Builtin::BI__builtin_ctz:
11970   case Builtin::BI__builtin_ctzl:
11971   case Builtin::BI__builtin_ctzll:
11972   case Builtin::BI__builtin_ctzs: {
11973     APSInt Val;
11974     if (!EvaluateInteger(E->getArg(0), Val, Info))
11975       return false;
11976     if (!Val)
11977       return Error(E);
11978 
11979     return Success(Val.countTrailingZeros(), E);
11980   }
11981 
11982   case Builtin::BI__builtin_eh_return_data_regno: {
11983     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11984     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11985     return Success(Operand, E);
11986   }
11987 
11988   case Builtin::BI__builtin_expect:
11989   case Builtin::BI__builtin_expect_with_probability:
11990     return Visit(E->getArg(0));
11991 
11992   case Builtin::BI__builtin_ffs:
11993   case Builtin::BI__builtin_ffsl:
11994   case Builtin::BI__builtin_ffsll: {
11995     APSInt Val;
11996     if (!EvaluateInteger(E->getArg(0), Val, Info))
11997       return false;
11998 
11999     unsigned N = Val.countTrailingZeros();
12000     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12001   }
12002 
12003   case Builtin::BI__builtin_fpclassify: {
12004     APFloat Val(0.0);
12005     if (!EvaluateFloat(E->getArg(5), Val, Info))
12006       return false;
12007     unsigned Arg;
12008     switch (Val.getCategory()) {
12009     case APFloat::fcNaN: Arg = 0; break;
12010     case APFloat::fcInfinity: Arg = 1; break;
12011     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12012     case APFloat::fcZero: Arg = 4; break;
12013     }
12014     return Visit(E->getArg(Arg));
12015   }
12016 
12017   case Builtin::BI__builtin_isinf_sign: {
12018     APFloat Val(0.0);
12019     return EvaluateFloat(E->getArg(0), Val, Info) &&
12020            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12021   }
12022 
12023   case Builtin::BI__builtin_isinf: {
12024     APFloat Val(0.0);
12025     return EvaluateFloat(E->getArg(0), Val, Info) &&
12026            Success(Val.isInfinity() ? 1 : 0, E);
12027   }
12028 
12029   case Builtin::BI__builtin_isfinite: {
12030     APFloat Val(0.0);
12031     return EvaluateFloat(E->getArg(0), Val, Info) &&
12032            Success(Val.isFinite() ? 1 : 0, E);
12033   }
12034 
12035   case Builtin::BI__builtin_isnan: {
12036     APFloat Val(0.0);
12037     return EvaluateFloat(E->getArg(0), Val, Info) &&
12038            Success(Val.isNaN() ? 1 : 0, E);
12039   }
12040 
12041   case Builtin::BI__builtin_isnormal: {
12042     APFloat Val(0.0);
12043     return EvaluateFloat(E->getArg(0), Val, Info) &&
12044            Success(Val.isNormal() ? 1 : 0, E);
12045   }
12046 
12047   case Builtin::BI__builtin_parity:
12048   case Builtin::BI__builtin_parityl:
12049   case Builtin::BI__builtin_parityll: {
12050     APSInt Val;
12051     if (!EvaluateInteger(E->getArg(0), Val, Info))
12052       return false;
12053 
12054     return Success(Val.countPopulation() % 2, E);
12055   }
12056 
12057   case Builtin::BI__builtin_popcount:
12058   case Builtin::BI__builtin_popcountl:
12059   case Builtin::BI__builtin_popcountll: {
12060     APSInt Val;
12061     if (!EvaluateInteger(E->getArg(0), Val, Info))
12062       return false;
12063 
12064     return Success(Val.countPopulation(), E);
12065   }
12066 
12067   case Builtin::BI__builtin_rotateleft8:
12068   case Builtin::BI__builtin_rotateleft16:
12069   case Builtin::BI__builtin_rotateleft32:
12070   case Builtin::BI__builtin_rotateleft64:
12071   case Builtin::BI_rotl8: // Microsoft variants of rotate right
12072   case Builtin::BI_rotl16:
12073   case Builtin::BI_rotl:
12074   case Builtin::BI_lrotl:
12075   case Builtin::BI_rotl64: {
12076     APSInt Val, Amt;
12077     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12078         !EvaluateInteger(E->getArg(1), Amt, Info))
12079       return false;
12080 
12081     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12082   }
12083 
12084   case Builtin::BI__builtin_rotateright8:
12085   case Builtin::BI__builtin_rotateright16:
12086   case Builtin::BI__builtin_rotateright32:
12087   case Builtin::BI__builtin_rotateright64:
12088   case Builtin::BI_rotr8: // Microsoft variants of rotate right
12089   case Builtin::BI_rotr16:
12090   case Builtin::BI_rotr:
12091   case Builtin::BI_lrotr:
12092   case Builtin::BI_rotr64: {
12093     APSInt Val, Amt;
12094     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12095         !EvaluateInteger(E->getArg(1), Amt, Info))
12096       return false;
12097 
12098     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12099   }
12100 
12101   case Builtin::BIstrlen:
12102   case Builtin::BIwcslen:
12103     // A call to strlen is not a constant expression.
12104     if (Info.getLangOpts().CPlusPlus11)
12105       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12106         << /*isConstexpr*/0 << /*isConstructor*/0
12107         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12108     else
12109       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12110     LLVM_FALLTHROUGH;
12111   case Builtin::BI__builtin_strlen:
12112   case Builtin::BI__builtin_wcslen: {
12113     // As an extension, we support __builtin_strlen() as a constant expression,
12114     // and support folding strlen() to a constant.
12115     uint64_t StrLen;
12116     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12117       return Success(StrLen, E);
12118     return false;
12119   }
12120 
12121   case Builtin::BIstrcmp:
12122   case Builtin::BIwcscmp:
12123   case Builtin::BIstrncmp:
12124   case Builtin::BIwcsncmp:
12125   case Builtin::BImemcmp:
12126   case Builtin::BIbcmp:
12127   case Builtin::BIwmemcmp:
12128     // A call to strlen is not a constant expression.
12129     if (Info.getLangOpts().CPlusPlus11)
12130       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12131         << /*isConstexpr*/0 << /*isConstructor*/0
12132         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12133     else
12134       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12135     LLVM_FALLTHROUGH;
12136   case Builtin::BI__builtin_strcmp:
12137   case Builtin::BI__builtin_wcscmp:
12138   case Builtin::BI__builtin_strncmp:
12139   case Builtin::BI__builtin_wcsncmp:
12140   case Builtin::BI__builtin_memcmp:
12141   case Builtin::BI__builtin_bcmp:
12142   case Builtin::BI__builtin_wmemcmp: {
12143     LValue String1, String2;
12144     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12145         !EvaluatePointer(E->getArg(1), String2, Info))
12146       return false;
12147 
12148     uint64_t MaxLength = uint64_t(-1);
12149     if (BuiltinOp != Builtin::BIstrcmp &&
12150         BuiltinOp != Builtin::BIwcscmp &&
12151         BuiltinOp != Builtin::BI__builtin_strcmp &&
12152         BuiltinOp != Builtin::BI__builtin_wcscmp) {
12153       APSInt N;
12154       if (!EvaluateInteger(E->getArg(2), N, Info))
12155         return false;
12156       MaxLength = N.getExtValue();
12157     }
12158 
12159     // Empty substrings compare equal by definition.
12160     if (MaxLength == 0u)
12161       return Success(0, E);
12162 
12163     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12164         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12165         String1.Designator.Invalid || String2.Designator.Invalid)
12166       return false;
12167 
12168     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12169     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12170 
12171     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12172                      BuiltinOp == Builtin::BIbcmp ||
12173                      BuiltinOp == Builtin::BI__builtin_memcmp ||
12174                      BuiltinOp == Builtin::BI__builtin_bcmp;
12175 
12176     assert(IsRawByte ||
12177            (Info.Ctx.hasSameUnqualifiedType(
12178                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12179             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12180 
12181     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12182     // 'char8_t', but no other types.
12183     if (IsRawByte &&
12184         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12185       // FIXME: Consider using our bit_cast implementation to support this.
12186       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12187           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
12188           << CharTy1 << CharTy2;
12189       return false;
12190     }
12191 
12192     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12193       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12194              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12195              Char1.isInt() && Char2.isInt();
12196     };
12197     const auto &AdvanceElems = [&] {
12198       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12199              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12200     };
12201 
12202     bool StopAtNull =
12203         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12204          BuiltinOp != Builtin::BIwmemcmp &&
12205          BuiltinOp != Builtin::BI__builtin_memcmp &&
12206          BuiltinOp != Builtin::BI__builtin_bcmp &&
12207          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12208     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12209                   BuiltinOp == Builtin::BIwcsncmp ||
12210                   BuiltinOp == Builtin::BIwmemcmp ||
12211                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12212                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12213                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12214 
12215     for (; MaxLength; --MaxLength) {
12216       APValue Char1, Char2;
12217       if (!ReadCurElems(Char1, Char2))
12218         return false;
12219       if (Char1.getInt().ne(Char2.getInt())) {
12220         if (IsWide) // wmemcmp compares with wchar_t signedness.
12221           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12222         // memcmp always compares unsigned chars.
12223         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12224       }
12225       if (StopAtNull && !Char1.getInt())
12226         return Success(0, E);
12227       assert(!(StopAtNull && !Char2.getInt()));
12228       if (!AdvanceElems())
12229         return false;
12230     }
12231     // We hit the strncmp / memcmp limit.
12232     return Success(0, E);
12233   }
12234 
12235   case Builtin::BI__atomic_always_lock_free:
12236   case Builtin::BI__atomic_is_lock_free:
12237   case Builtin::BI__c11_atomic_is_lock_free: {
12238     APSInt SizeVal;
12239     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12240       return false;
12241 
12242     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12243     // of two less than or equal to the maximum inline atomic width, we know it
12244     // is lock-free.  If the size isn't a power of two, or greater than the
12245     // maximum alignment where we promote atomics, we know it is not lock-free
12246     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12247     // the answer can only be determined at runtime; for example, 16-byte
12248     // atomics have lock-free implementations on some, but not all,
12249     // x86-64 processors.
12250 
12251     // Check power-of-two.
12252     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12253     if (Size.isPowerOfTwo()) {
12254       // Check against inlining width.
12255       unsigned InlineWidthBits =
12256           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12257       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12258         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12259             Size == CharUnits::One() ||
12260             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12261                                                 Expr::NPC_NeverValueDependent))
12262           // OK, we will inline appropriately-aligned operations of this size,
12263           // and _Atomic(T) is appropriately-aligned.
12264           return Success(1, E);
12265 
12266         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12267           castAs<PointerType>()->getPointeeType();
12268         if (!PointeeType->isIncompleteType() &&
12269             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12270           // OK, we will inline operations on this object.
12271           return Success(1, E);
12272         }
12273       }
12274     }
12275 
12276     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12277         Success(0, E) : Error(E);
12278   }
12279   case Builtin::BI__builtin_add_overflow:
12280   case Builtin::BI__builtin_sub_overflow:
12281   case Builtin::BI__builtin_mul_overflow:
12282   case Builtin::BI__builtin_sadd_overflow:
12283   case Builtin::BI__builtin_uadd_overflow:
12284   case Builtin::BI__builtin_uaddl_overflow:
12285   case Builtin::BI__builtin_uaddll_overflow:
12286   case Builtin::BI__builtin_usub_overflow:
12287   case Builtin::BI__builtin_usubl_overflow:
12288   case Builtin::BI__builtin_usubll_overflow:
12289   case Builtin::BI__builtin_umul_overflow:
12290   case Builtin::BI__builtin_umull_overflow:
12291   case Builtin::BI__builtin_umulll_overflow:
12292   case Builtin::BI__builtin_saddl_overflow:
12293   case Builtin::BI__builtin_saddll_overflow:
12294   case Builtin::BI__builtin_ssub_overflow:
12295   case Builtin::BI__builtin_ssubl_overflow:
12296   case Builtin::BI__builtin_ssubll_overflow:
12297   case Builtin::BI__builtin_smul_overflow:
12298   case Builtin::BI__builtin_smull_overflow:
12299   case Builtin::BI__builtin_smulll_overflow: {
12300     LValue ResultLValue;
12301     APSInt LHS, RHS;
12302 
12303     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12304     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12305         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12306         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12307       return false;
12308 
12309     APSInt Result;
12310     bool DidOverflow = false;
12311 
12312     // If the types don't have to match, enlarge all 3 to the largest of them.
12313     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12314         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12315         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12316       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12317                       ResultType->isSignedIntegerOrEnumerationType();
12318       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12319                       ResultType->isSignedIntegerOrEnumerationType();
12320       uint64_t LHSSize = LHS.getBitWidth();
12321       uint64_t RHSSize = RHS.getBitWidth();
12322       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12323       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12324 
12325       // Add an additional bit if the signedness isn't uniformly agreed to. We
12326       // could do this ONLY if there is a signed and an unsigned that both have
12327       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12328       // caught in the shrink-to-result later anyway.
12329       if (IsSigned && !AllSigned)
12330         ++MaxBits;
12331 
12332       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12333       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12334       Result = APSInt(MaxBits, !IsSigned);
12335     }
12336 
12337     // Find largest int.
12338     switch (BuiltinOp) {
12339     default:
12340       llvm_unreachable("Invalid value for BuiltinOp");
12341     case Builtin::BI__builtin_add_overflow:
12342     case Builtin::BI__builtin_sadd_overflow:
12343     case Builtin::BI__builtin_saddl_overflow:
12344     case Builtin::BI__builtin_saddll_overflow:
12345     case Builtin::BI__builtin_uadd_overflow:
12346     case Builtin::BI__builtin_uaddl_overflow:
12347     case Builtin::BI__builtin_uaddll_overflow:
12348       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12349                               : LHS.uadd_ov(RHS, DidOverflow);
12350       break;
12351     case Builtin::BI__builtin_sub_overflow:
12352     case Builtin::BI__builtin_ssub_overflow:
12353     case Builtin::BI__builtin_ssubl_overflow:
12354     case Builtin::BI__builtin_ssubll_overflow:
12355     case Builtin::BI__builtin_usub_overflow:
12356     case Builtin::BI__builtin_usubl_overflow:
12357     case Builtin::BI__builtin_usubll_overflow:
12358       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12359                               : LHS.usub_ov(RHS, DidOverflow);
12360       break;
12361     case Builtin::BI__builtin_mul_overflow:
12362     case Builtin::BI__builtin_smul_overflow:
12363     case Builtin::BI__builtin_smull_overflow:
12364     case Builtin::BI__builtin_smulll_overflow:
12365     case Builtin::BI__builtin_umul_overflow:
12366     case Builtin::BI__builtin_umull_overflow:
12367     case Builtin::BI__builtin_umulll_overflow:
12368       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12369                               : LHS.umul_ov(RHS, DidOverflow);
12370       break;
12371     }
12372 
12373     // In the case where multiple sizes are allowed, truncate and see if
12374     // the values are the same.
12375     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12376         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12377         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12378       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12379       // since it will give us the behavior of a TruncOrSelf in the case where
12380       // its parameter <= its size.  We previously set Result to be at least the
12381       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12382       // will work exactly like TruncOrSelf.
12383       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12384       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12385 
12386       if (!APSInt::isSameValue(Temp, Result))
12387         DidOverflow = true;
12388       Result = Temp;
12389     }
12390 
12391     APValue APV{Result};
12392     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12393       return false;
12394     return Success(DidOverflow, E);
12395   }
12396   }
12397 }
12398 
12399 /// Determine whether this is a pointer past the end of the complete
12400 /// object referred to by the lvalue.
isOnePastTheEndOfCompleteObject(const ASTContext & Ctx,const LValue & LV)12401 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12402                                             const LValue &LV) {
12403   // A null pointer can be viewed as being "past the end" but we don't
12404   // choose to look at it that way here.
12405   if (!LV.getLValueBase())
12406     return false;
12407 
12408   // If the designator is valid and refers to a subobject, we're not pointing
12409   // past the end.
12410   if (!LV.getLValueDesignator().Invalid &&
12411       !LV.getLValueDesignator().isOnePastTheEnd())
12412     return false;
12413 
12414   // A pointer to an incomplete type might be past-the-end if the type's size is
12415   // zero.  We cannot tell because the type is incomplete.
12416   QualType Ty = getType(LV.getLValueBase());
12417   if (Ty->isIncompleteType())
12418     return true;
12419 
12420   // We're a past-the-end pointer if we point to the byte after the object,
12421   // no matter what our type or path is.
12422   auto Size = Ctx.getTypeSizeInChars(Ty);
12423   return LV.getLValueOffset() == Size;
12424 }
12425 
12426 namespace {
12427 
12428 /// Data recursive integer evaluator of certain binary operators.
12429 ///
12430 /// We use a data recursive algorithm for binary operators so that we are able
12431 /// to handle extreme cases of chained binary operators without causing stack
12432 /// overflow.
12433 class DataRecursiveIntBinOpEvaluator {
12434   struct EvalResult {
12435     APValue Val;
12436     bool Failed;
12437 
EvalResult__anon7a1fdcea2811::DataRecursiveIntBinOpEvaluator::EvalResult12438     EvalResult() : Failed(false) { }
12439 
swap__anon7a1fdcea2811::DataRecursiveIntBinOpEvaluator::EvalResult12440     void swap(EvalResult &RHS) {
12441       Val.swap(RHS.Val);
12442       Failed = RHS.Failed;
12443       RHS.Failed = false;
12444     }
12445   };
12446 
12447   struct Job {
12448     const Expr *E;
12449     EvalResult LHSResult; // meaningful only for binary operator expression.
12450     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12451 
12452     Job() = default;
12453     Job(Job &&) = default;
12454 
startSpeculativeEval__anon7a1fdcea2811::DataRecursiveIntBinOpEvaluator::Job12455     void startSpeculativeEval(EvalInfo &Info) {
12456       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12457     }
12458 
12459   private:
12460     SpeculativeEvaluationRAII SpecEvalRAII;
12461   };
12462 
12463   SmallVector<Job, 16> Queue;
12464 
12465   IntExprEvaluator &IntEval;
12466   EvalInfo &Info;
12467   APValue &FinalResult;
12468 
12469 public:
DataRecursiveIntBinOpEvaluator(IntExprEvaluator & IntEval,APValue & Result)12470   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12471     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12472 
12473   /// True if \param E is a binary operator that we are going to handle
12474   /// data recursively.
12475   /// We handle binary operators that are comma, logical, or that have operands
12476   /// with integral or enumeration type.
shouldEnqueue(const BinaryOperator * E)12477   static bool shouldEnqueue(const BinaryOperator *E) {
12478     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12479            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12480             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12481             E->getRHS()->getType()->isIntegralOrEnumerationType());
12482   }
12483 
Traverse(const BinaryOperator * E)12484   bool Traverse(const BinaryOperator *E) {
12485     enqueue(E);
12486     EvalResult PrevResult;
12487     while (!Queue.empty())
12488       process(PrevResult);
12489 
12490     if (PrevResult.Failed) return false;
12491 
12492     FinalResult.swap(PrevResult.Val);
12493     return true;
12494   }
12495 
12496 private:
Success(uint64_t Value,const Expr * E,APValue & Result)12497   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12498     return IntEval.Success(Value, E, Result);
12499   }
Success(const APSInt & Value,const Expr * E,APValue & Result)12500   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12501     return IntEval.Success(Value, E, Result);
12502   }
Error(const Expr * E)12503   bool Error(const Expr *E) {
12504     return IntEval.Error(E);
12505   }
Error(const Expr * E,diag::kind D)12506   bool Error(const Expr *E, diag::kind D) {
12507     return IntEval.Error(E, D);
12508   }
12509 
CCEDiag(const Expr * E,diag::kind D)12510   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12511     return Info.CCEDiag(E, D);
12512   }
12513 
12514   // Returns true if visiting the RHS is necessary, false otherwise.
12515   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12516                          bool &SuppressRHSDiags);
12517 
12518   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12519                   const BinaryOperator *E, APValue &Result);
12520 
EvaluateExpr(const Expr * E,EvalResult & Result)12521   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12522     Result.Failed = !Evaluate(Result.Val, Info, E);
12523     if (Result.Failed)
12524       Result.Val = APValue();
12525   }
12526 
12527   void process(EvalResult &Result);
12528 
enqueue(const Expr * E)12529   void enqueue(const Expr *E) {
12530     E = E->IgnoreParens();
12531     Queue.resize(Queue.size()+1);
12532     Queue.back().E = E;
12533     Queue.back().Kind = Job::AnyExprKind;
12534   }
12535 };
12536 
12537 }
12538 
12539 bool DataRecursiveIntBinOpEvaluator::
VisitBinOpLHSOnly(EvalResult & LHSResult,const BinaryOperator * E,bool & SuppressRHSDiags)12540        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12541                          bool &SuppressRHSDiags) {
12542   if (E->getOpcode() == BO_Comma) {
12543     // Ignore LHS but note if we could not evaluate it.
12544     if (LHSResult.Failed)
12545       return Info.noteSideEffect();
12546     return true;
12547   }
12548 
12549   if (E->isLogicalOp()) {
12550     bool LHSAsBool;
12551     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12552       // We were able to evaluate the LHS, see if we can get away with not
12553       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12554       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12555         Success(LHSAsBool, E, LHSResult.Val);
12556         return false; // Ignore RHS
12557       }
12558     } else {
12559       LHSResult.Failed = true;
12560 
12561       // Since we weren't able to evaluate the left hand side, it
12562       // might have had side effects.
12563       if (!Info.noteSideEffect())
12564         return false;
12565 
12566       // We can't evaluate the LHS; however, sometimes the result
12567       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12568       // Don't ignore RHS and suppress diagnostics from this arm.
12569       SuppressRHSDiags = true;
12570     }
12571 
12572     return true;
12573   }
12574 
12575   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12576          E->getRHS()->getType()->isIntegralOrEnumerationType());
12577 
12578   if (LHSResult.Failed && !Info.noteFailure())
12579     return false; // Ignore RHS;
12580 
12581   return true;
12582 }
12583 
addOrSubLValueAsInteger(APValue & LVal,const APSInt & Index,bool IsSub)12584 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12585                                     bool IsSub) {
12586   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12587   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12588   // offsets.
12589   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12590   CharUnits &Offset = LVal.getLValueOffset();
12591   uint64_t Offset64 = Offset.getQuantity();
12592   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12593   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12594                                          : Offset64 + Index64);
12595 }
12596 
12597 bool DataRecursiveIntBinOpEvaluator::
VisitBinOp(const EvalResult & LHSResult,const EvalResult & RHSResult,const BinaryOperator * E,APValue & Result)12598        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12599                   const BinaryOperator *E, APValue &Result) {
12600   if (E->getOpcode() == BO_Comma) {
12601     if (RHSResult.Failed)
12602       return false;
12603     Result = RHSResult.Val;
12604     return true;
12605   }
12606 
12607   if (E->isLogicalOp()) {
12608     bool lhsResult, rhsResult;
12609     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12610     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12611 
12612     if (LHSIsOK) {
12613       if (RHSIsOK) {
12614         if (E->getOpcode() == BO_LOr)
12615           return Success(lhsResult || rhsResult, E, Result);
12616         else
12617           return Success(lhsResult && rhsResult, E, Result);
12618       }
12619     } else {
12620       if (RHSIsOK) {
12621         // We can't evaluate the LHS; however, sometimes the result
12622         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12623         if (rhsResult == (E->getOpcode() == BO_LOr))
12624           return Success(rhsResult, E, Result);
12625       }
12626     }
12627 
12628     return false;
12629   }
12630 
12631   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12632          E->getRHS()->getType()->isIntegralOrEnumerationType());
12633 
12634   if (LHSResult.Failed || RHSResult.Failed)
12635     return false;
12636 
12637   const APValue &LHSVal = LHSResult.Val;
12638   const APValue &RHSVal = RHSResult.Val;
12639 
12640   // Handle cases like (unsigned long)&a + 4.
12641   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12642     Result = LHSVal;
12643     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12644     return true;
12645   }
12646 
12647   // Handle cases like 4 + (unsigned long)&a
12648   if (E->getOpcode() == BO_Add &&
12649       RHSVal.isLValue() && LHSVal.isInt()) {
12650     Result = RHSVal;
12651     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12652     return true;
12653   }
12654 
12655   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12656     // Handle (intptr_t)&&A - (intptr_t)&&B.
12657     if (!LHSVal.getLValueOffset().isZero() ||
12658         !RHSVal.getLValueOffset().isZero())
12659       return false;
12660     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12661     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12662     if (!LHSExpr || !RHSExpr)
12663       return false;
12664     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12665     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12666     if (!LHSAddrExpr || !RHSAddrExpr)
12667       return false;
12668     // Make sure both labels come from the same function.
12669     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12670         RHSAddrExpr->getLabel()->getDeclContext())
12671       return false;
12672     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12673     return true;
12674   }
12675 
12676   // All the remaining cases expect both operands to be an integer
12677   if (!LHSVal.isInt() || !RHSVal.isInt())
12678     return Error(E);
12679 
12680   // Set up the width and signedness manually, in case it can't be deduced
12681   // from the operation we're performing.
12682   // FIXME: Don't do this in the cases where we can deduce it.
12683   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12684                E->getType()->isUnsignedIntegerOrEnumerationType());
12685   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12686                          RHSVal.getInt(), Value))
12687     return false;
12688   return Success(Value, E, Result);
12689 }
12690 
process(EvalResult & Result)12691 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12692   Job &job = Queue.back();
12693 
12694   switch (job.Kind) {
12695     case Job::AnyExprKind: {
12696       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12697         if (shouldEnqueue(Bop)) {
12698           job.Kind = Job::BinOpKind;
12699           enqueue(Bop->getLHS());
12700           return;
12701         }
12702       }
12703 
12704       EvaluateExpr(job.E, Result);
12705       Queue.pop_back();
12706       return;
12707     }
12708 
12709     case Job::BinOpKind: {
12710       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12711       bool SuppressRHSDiags = false;
12712       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12713         Queue.pop_back();
12714         return;
12715       }
12716       if (SuppressRHSDiags)
12717         job.startSpeculativeEval(Info);
12718       job.LHSResult.swap(Result);
12719       job.Kind = Job::BinOpVisitedLHSKind;
12720       enqueue(Bop->getRHS());
12721       return;
12722     }
12723 
12724     case Job::BinOpVisitedLHSKind: {
12725       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12726       EvalResult RHS;
12727       RHS.swap(Result);
12728       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12729       Queue.pop_back();
12730       return;
12731     }
12732   }
12733 
12734   llvm_unreachable("Invalid Job::Kind!");
12735 }
12736 
12737 namespace {
12738 enum class CmpResult {
12739   Unequal,
12740   Less,
12741   Equal,
12742   Greater,
12743   Unordered,
12744 };
12745 }
12746 
12747 template <class SuccessCB, class AfterCB>
12748 static bool
EvaluateComparisonBinaryOperator(EvalInfo & Info,const BinaryOperator * E,SuccessCB && Success,AfterCB && DoAfter)12749 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12750                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12751   assert(!E->isValueDependent());
12752   assert(E->isComparisonOp() && "expected comparison operator");
12753   assert((E->getOpcode() == BO_Cmp ||
12754           E->getType()->isIntegralOrEnumerationType()) &&
12755          "unsupported binary expression evaluation");
12756   auto Error = [&](const Expr *E) {
12757     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12758     return false;
12759   };
12760 
12761   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12762   bool IsEquality = E->isEqualityOp();
12763 
12764   QualType LHSTy = E->getLHS()->getType();
12765   QualType RHSTy = E->getRHS()->getType();
12766 
12767   if (LHSTy->isIntegralOrEnumerationType() &&
12768       RHSTy->isIntegralOrEnumerationType()) {
12769     APSInt LHS, RHS;
12770     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12771     if (!LHSOK && !Info.noteFailure())
12772       return false;
12773     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12774       return false;
12775     if (LHS < RHS)
12776       return Success(CmpResult::Less, E);
12777     if (LHS > RHS)
12778       return Success(CmpResult::Greater, E);
12779     return Success(CmpResult::Equal, E);
12780   }
12781 
12782   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12783     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12784     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12785 
12786     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12787     if (!LHSOK && !Info.noteFailure())
12788       return false;
12789     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12790       return false;
12791     if (LHSFX < RHSFX)
12792       return Success(CmpResult::Less, E);
12793     if (LHSFX > RHSFX)
12794       return Success(CmpResult::Greater, E);
12795     return Success(CmpResult::Equal, E);
12796   }
12797 
12798   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12799     ComplexValue LHS, RHS;
12800     bool LHSOK;
12801     if (E->isAssignmentOp()) {
12802       LValue LV;
12803       EvaluateLValue(E->getLHS(), LV, Info);
12804       LHSOK = false;
12805     } else if (LHSTy->isRealFloatingType()) {
12806       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12807       if (LHSOK) {
12808         LHS.makeComplexFloat();
12809         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12810       }
12811     } else {
12812       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12813     }
12814     if (!LHSOK && !Info.noteFailure())
12815       return false;
12816 
12817     if (E->getRHS()->getType()->isRealFloatingType()) {
12818       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12819         return false;
12820       RHS.makeComplexFloat();
12821       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12822     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12823       return false;
12824 
12825     if (LHS.isComplexFloat()) {
12826       APFloat::cmpResult CR_r =
12827         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12828       APFloat::cmpResult CR_i =
12829         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12830       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12831       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12832     } else {
12833       assert(IsEquality && "invalid complex comparison");
12834       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12835                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12836       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12837     }
12838   }
12839 
12840   if (LHSTy->isRealFloatingType() &&
12841       RHSTy->isRealFloatingType()) {
12842     APFloat RHS(0.0), LHS(0.0);
12843 
12844     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12845     if (!LHSOK && !Info.noteFailure())
12846       return false;
12847 
12848     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12849       return false;
12850 
12851     assert(E->isComparisonOp() && "Invalid binary operator!");
12852     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12853     if (!Info.InConstantContext &&
12854         APFloatCmpResult == APFloat::cmpUnordered &&
12855         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12856       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12857       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12858       return false;
12859     }
12860     auto GetCmpRes = [&]() {
12861       switch (APFloatCmpResult) {
12862       case APFloat::cmpEqual:
12863         return CmpResult::Equal;
12864       case APFloat::cmpLessThan:
12865         return CmpResult::Less;
12866       case APFloat::cmpGreaterThan:
12867         return CmpResult::Greater;
12868       case APFloat::cmpUnordered:
12869         return CmpResult::Unordered;
12870       }
12871       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12872     };
12873     return Success(GetCmpRes(), E);
12874   }
12875 
12876   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12877     LValue LHSValue, RHSValue;
12878 
12879     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12880     if (!LHSOK && !Info.noteFailure())
12881       return false;
12882 
12883     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12884       return false;
12885 
12886     // Reject differing bases from the normal codepath; we special-case
12887     // comparisons to null.
12888     if (!HasSameBase(LHSValue, RHSValue)) {
12889       // Inequalities and subtractions between unrelated pointers have
12890       // unspecified or undefined behavior.
12891       if (!IsEquality) {
12892         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12893         return false;
12894       }
12895       // A constant address may compare equal to the address of a symbol.
12896       // The one exception is that address of an object cannot compare equal
12897       // to a null pointer constant.
12898       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12899           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12900         return Error(E);
12901       // It's implementation-defined whether distinct literals will have
12902       // distinct addresses. In clang, the result of such a comparison is
12903       // unspecified, so it is not a constant expression. However, we do know
12904       // that the address of a literal will be non-null.
12905       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12906           LHSValue.Base && RHSValue.Base)
12907         return Error(E);
12908       // We can't tell whether weak symbols will end up pointing to the same
12909       // object.
12910       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12911         return Error(E);
12912       // We can't compare the address of the start of one object with the
12913       // past-the-end address of another object, per C++ DR1652.
12914       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12915            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12916           (RHSValue.Base && RHSValue.Offset.isZero() &&
12917            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12918         return Error(E);
12919       // We can't tell whether an object is at the same address as another
12920       // zero sized object.
12921       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12922           (LHSValue.Base && isZeroSized(RHSValue)))
12923         return Error(E);
12924       return Success(CmpResult::Unequal, E);
12925     }
12926 
12927     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12928     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12929 
12930     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12931     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12932 
12933     // C++11 [expr.rel]p3:
12934     //   Pointers to void (after pointer conversions) can be compared, with a
12935     //   result defined as follows: If both pointers represent the same
12936     //   address or are both the null pointer value, the result is true if the
12937     //   operator is <= or >= and false otherwise; otherwise the result is
12938     //   unspecified.
12939     // We interpret this as applying to pointers to *cv* void.
12940     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12941       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12942 
12943     // C++11 [expr.rel]p2:
12944     // - If two pointers point to non-static data members of the same object,
12945     //   or to subobjects or array elements fo such members, recursively, the
12946     //   pointer to the later declared member compares greater provided the
12947     //   two members have the same access control and provided their class is
12948     //   not a union.
12949     //   [...]
12950     // - Otherwise pointer comparisons are unspecified.
12951     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12952       bool WasArrayIndex;
12953       unsigned Mismatch = FindDesignatorMismatch(
12954           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12955       // At the point where the designators diverge, the comparison has a
12956       // specified value if:
12957       //  - we are comparing array indices
12958       //  - we are comparing fields of a union, or fields with the same access
12959       // Otherwise, the result is unspecified and thus the comparison is not a
12960       // constant expression.
12961       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12962           Mismatch < RHSDesignator.Entries.size()) {
12963         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12964         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12965         if (!LF && !RF)
12966           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12967         else if (!LF)
12968           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12969               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12970               << RF->getParent() << RF;
12971         else if (!RF)
12972           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12973               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12974               << LF->getParent() << LF;
12975         else if (!LF->getParent()->isUnion() &&
12976                  LF->getAccess() != RF->getAccess())
12977           Info.CCEDiag(E,
12978                        diag::note_constexpr_pointer_comparison_differing_access)
12979               << LF << LF->getAccess() << RF << RF->getAccess()
12980               << LF->getParent();
12981       }
12982     }
12983 
12984     // The comparison here must be unsigned, and performed with the same
12985     // width as the pointer.
12986     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12987     uint64_t CompareLHS = LHSOffset.getQuantity();
12988     uint64_t CompareRHS = RHSOffset.getQuantity();
12989     assert(PtrSize <= 64 && "Unexpected pointer width");
12990     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12991     CompareLHS &= Mask;
12992     CompareRHS &= Mask;
12993 
12994     // If there is a base and this is a relational operator, we can only
12995     // compare pointers within the object in question; otherwise, the result
12996     // depends on where the object is located in memory.
12997     if (!LHSValue.Base.isNull() && IsRelational) {
12998       QualType BaseTy = getType(LHSValue.Base);
12999       if (BaseTy->isIncompleteType())
13000         return Error(E);
13001       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13002       uint64_t OffsetLimit = Size.getQuantity();
13003       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13004         return Error(E);
13005     }
13006 
13007     if (CompareLHS < CompareRHS)
13008       return Success(CmpResult::Less, E);
13009     if (CompareLHS > CompareRHS)
13010       return Success(CmpResult::Greater, E);
13011     return Success(CmpResult::Equal, E);
13012   }
13013 
13014   if (LHSTy->isMemberPointerType()) {
13015     assert(IsEquality && "unexpected member pointer operation");
13016     assert(RHSTy->isMemberPointerType() && "invalid comparison");
13017 
13018     MemberPtr LHSValue, RHSValue;
13019 
13020     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13021     if (!LHSOK && !Info.noteFailure())
13022       return false;
13023 
13024     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13025       return false;
13026 
13027     // C++11 [expr.eq]p2:
13028     //   If both operands are null, they compare equal. Otherwise if only one is
13029     //   null, they compare unequal.
13030     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13031       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13032       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13033     }
13034 
13035     //   Otherwise if either is a pointer to a virtual member function, the
13036     //   result is unspecified.
13037     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13038       if (MD->isVirtual())
13039         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13040     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13041       if (MD->isVirtual())
13042         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13043 
13044     //   Otherwise they compare equal if and only if they would refer to the
13045     //   same member of the same most derived object or the same subobject if
13046     //   they were dereferenced with a hypothetical object of the associated
13047     //   class type.
13048     bool Equal = LHSValue == RHSValue;
13049     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13050   }
13051 
13052   if (LHSTy->isNullPtrType()) {
13053     assert(E->isComparisonOp() && "unexpected nullptr operation");
13054     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13055     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13056     // are compared, the result is true of the operator is <=, >= or ==, and
13057     // false otherwise.
13058     return Success(CmpResult::Equal, E);
13059   }
13060 
13061   return DoAfter();
13062 }
13063 
VisitBinCmp(const BinaryOperator * E)13064 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13065   if (!CheckLiteralType(Info, E))
13066     return false;
13067 
13068   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13069     ComparisonCategoryResult CCR;
13070     switch (CR) {
13071     case CmpResult::Unequal:
13072       llvm_unreachable("should never produce Unequal for three-way comparison");
13073     case CmpResult::Less:
13074       CCR = ComparisonCategoryResult::Less;
13075       break;
13076     case CmpResult::Equal:
13077       CCR = ComparisonCategoryResult::Equal;
13078       break;
13079     case CmpResult::Greater:
13080       CCR = ComparisonCategoryResult::Greater;
13081       break;
13082     case CmpResult::Unordered:
13083       CCR = ComparisonCategoryResult::Unordered;
13084       break;
13085     }
13086     // Evaluation succeeded. Lookup the information for the comparison category
13087     // type and fetch the VarDecl for the result.
13088     const ComparisonCategoryInfo &CmpInfo =
13089         Info.Ctx.CompCategories.getInfoForType(E->getType());
13090     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13091     // Check and evaluate the result as a constant expression.
13092     LValue LV;
13093     LV.set(VD);
13094     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13095       return false;
13096     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13097                                    ConstantExprKind::Normal);
13098   };
13099   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13100     return ExprEvaluatorBaseTy::VisitBinCmp(E);
13101   });
13102 }
13103 
VisitBinaryOperator(const BinaryOperator * E)13104 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13105   // We don't support assignment in C. C++ assignments don't get here because
13106   // assignment is an lvalue in C++.
13107   if (E->isAssignmentOp()) {
13108     Error(E);
13109     if (!Info.noteFailure())
13110       return false;
13111   }
13112 
13113   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13114     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13115 
13116   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13117           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13118          "DataRecursiveIntBinOpEvaluator should have handled integral types");
13119 
13120   if (E->isComparisonOp()) {
13121     // Evaluate builtin binary comparisons by evaluating them as three-way
13122     // comparisons and then translating the result.
13123     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13124       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13125              "should only produce Unequal for equality comparisons");
13126       bool IsEqual   = CR == CmpResult::Equal,
13127            IsLess    = CR == CmpResult::Less,
13128            IsGreater = CR == CmpResult::Greater;
13129       auto Op = E->getOpcode();
13130       switch (Op) {
13131       default:
13132         llvm_unreachable("unsupported binary operator");
13133       case BO_EQ:
13134       case BO_NE:
13135         return Success(IsEqual == (Op == BO_EQ), E);
13136       case BO_LT:
13137         return Success(IsLess, E);
13138       case BO_GT:
13139         return Success(IsGreater, E);
13140       case BO_LE:
13141         return Success(IsEqual || IsLess, E);
13142       case BO_GE:
13143         return Success(IsEqual || IsGreater, E);
13144       }
13145     };
13146     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13147       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13148     });
13149   }
13150 
13151   QualType LHSTy = E->getLHS()->getType();
13152   QualType RHSTy = E->getRHS()->getType();
13153 
13154   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13155       E->getOpcode() == BO_Sub) {
13156     LValue LHSValue, RHSValue;
13157 
13158     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13159     if (!LHSOK && !Info.noteFailure())
13160       return false;
13161 
13162     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13163       return false;
13164 
13165     // Reject differing bases from the normal codepath; we special-case
13166     // comparisons to null.
13167     if (!HasSameBase(LHSValue, RHSValue)) {
13168       // Handle &&A - &&B.
13169       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13170         return Error(E);
13171       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13172       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13173       if (!LHSExpr || !RHSExpr)
13174         return Error(E);
13175       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13176       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13177       if (!LHSAddrExpr || !RHSAddrExpr)
13178         return Error(E);
13179       // Make sure both labels come from the same function.
13180       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13181           RHSAddrExpr->getLabel()->getDeclContext())
13182         return Error(E);
13183       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13184     }
13185     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13186     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13187 
13188     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13189     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13190 
13191     // C++11 [expr.add]p6:
13192     //   Unless both pointers point to elements of the same array object, or
13193     //   one past the last element of the array object, the behavior is
13194     //   undefined.
13195     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13196         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13197                                 RHSDesignator))
13198       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13199 
13200     QualType Type = E->getLHS()->getType();
13201     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13202 
13203     CharUnits ElementSize;
13204     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13205       return false;
13206 
13207     // As an extension, a type may have zero size (empty struct or union in
13208     // C, array of zero length). Pointer subtraction in such cases has
13209     // undefined behavior, so is not constant.
13210     if (ElementSize.isZero()) {
13211       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13212           << ElementType;
13213       return false;
13214     }
13215 
13216     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13217     // and produce incorrect results when it overflows. Such behavior
13218     // appears to be non-conforming, but is common, so perhaps we should
13219     // assume the standard intended for such cases to be undefined behavior
13220     // and check for them.
13221 
13222     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13223     // overflow in the final conversion to ptrdiff_t.
13224     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13225     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13226     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13227                     false);
13228     APSInt TrueResult = (LHS - RHS) / ElemSize;
13229     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13230 
13231     if (Result.extend(65) != TrueResult &&
13232         !HandleOverflow(Info, E, TrueResult, E->getType()))
13233       return false;
13234     return Success(Result, E);
13235   }
13236 
13237   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13238 }
13239 
13240 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13241 /// a result as the expression's type.
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)13242 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13243                                     const UnaryExprOrTypeTraitExpr *E) {
13244   switch(E->getKind()) {
13245   case UETT_PreferredAlignOf:
13246   case UETT_AlignOf: {
13247     if (E->isArgumentType())
13248       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13249                      E);
13250     else
13251       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13252                      E);
13253   }
13254 
13255   case UETT_VecStep: {
13256     QualType Ty = E->getTypeOfArgument();
13257 
13258     if (Ty->isVectorType()) {
13259       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13260 
13261       // The vec_step built-in functions that take a 3-component
13262       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13263       if (n == 3)
13264         n = 4;
13265 
13266       return Success(n, E);
13267     } else
13268       return Success(1, E);
13269   }
13270 
13271   case UETT_SizeOf: {
13272     QualType SrcTy = E->getTypeOfArgument();
13273     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13274     //   the result is the size of the referenced type."
13275     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13276       SrcTy = Ref->getPointeeType();
13277 
13278     CharUnits Sizeof;
13279     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13280       return false;
13281     return Success(Sizeof, E);
13282   }
13283   case UETT_OpenMPRequiredSimdAlign:
13284     assert(E->isArgumentType());
13285     return Success(
13286         Info.Ctx.toCharUnitsFromBits(
13287                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13288             .getQuantity(),
13289         E);
13290   }
13291 
13292   llvm_unreachable("unknown expr/type trait");
13293 }
13294 
VisitOffsetOfExpr(const OffsetOfExpr * OOE)13295 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13296   CharUnits Result;
13297   unsigned n = OOE->getNumComponents();
13298   if (n == 0)
13299     return Error(OOE);
13300   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13301   for (unsigned i = 0; i != n; ++i) {
13302     OffsetOfNode ON = OOE->getComponent(i);
13303     switch (ON.getKind()) {
13304     case OffsetOfNode::Array: {
13305       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13306       APSInt IdxResult;
13307       if (!EvaluateInteger(Idx, IdxResult, Info))
13308         return false;
13309       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13310       if (!AT)
13311         return Error(OOE);
13312       CurrentType = AT->getElementType();
13313       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13314       Result += IdxResult.getSExtValue() * ElementSize;
13315       break;
13316     }
13317 
13318     case OffsetOfNode::Field: {
13319       FieldDecl *MemberDecl = ON.getField();
13320       const RecordType *RT = CurrentType->getAs<RecordType>();
13321       if (!RT)
13322         return Error(OOE);
13323       RecordDecl *RD = RT->getDecl();
13324       if (RD->isInvalidDecl()) return false;
13325       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13326       unsigned i = MemberDecl->getFieldIndex();
13327       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13328       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13329       CurrentType = MemberDecl->getType().getNonReferenceType();
13330       break;
13331     }
13332 
13333     case OffsetOfNode::Identifier:
13334       llvm_unreachable("dependent __builtin_offsetof");
13335 
13336     case OffsetOfNode::Base: {
13337       CXXBaseSpecifier *BaseSpec = ON.getBase();
13338       if (BaseSpec->isVirtual())
13339         return Error(OOE);
13340 
13341       // Find the layout of the class whose base we are looking into.
13342       const RecordType *RT = CurrentType->getAs<RecordType>();
13343       if (!RT)
13344         return Error(OOE);
13345       RecordDecl *RD = RT->getDecl();
13346       if (RD->isInvalidDecl()) return false;
13347       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13348 
13349       // Find the base class itself.
13350       CurrentType = BaseSpec->getType();
13351       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13352       if (!BaseRT)
13353         return Error(OOE);
13354 
13355       // Add the offset to the base.
13356       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13357       break;
13358     }
13359     }
13360   }
13361   return Success(Result, OOE);
13362 }
13363 
VisitUnaryOperator(const UnaryOperator * E)13364 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13365   switch (E->getOpcode()) {
13366   default:
13367     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13368     // See C99 6.6p3.
13369     return Error(E);
13370   case UO_Extension:
13371     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13372     // If so, we could clear the diagnostic ID.
13373     return Visit(E->getSubExpr());
13374   case UO_Plus:
13375     // The result is just the value.
13376     return Visit(E->getSubExpr());
13377   case UO_Minus: {
13378     if (!Visit(E->getSubExpr()))
13379       return false;
13380     if (!Result.isInt()) return Error(E);
13381     const APSInt &Value = Result.getInt();
13382     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13383         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13384                         E->getType()))
13385       return false;
13386     return Success(-Value, E);
13387   }
13388   case UO_Not: {
13389     if (!Visit(E->getSubExpr()))
13390       return false;
13391     if (!Result.isInt()) return Error(E);
13392     return Success(~Result.getInt(), E);
13393   }
13394   case UO_LNot: {
13395     bool bres;
13396     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13397       return false;
13398     return Success(!bres, E);
13399   }
13400   }
13401 }
13402 
13403 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13404 /// result type is integer.
VisitCastExpr(const CastExpr * E)13405 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13406   const Expr *SubExpr = E->getSubExpr();
13407   QualType DestType = E->getType();
13408   QualType SrcType = SubExpr->getType();
13409 
13410   switch (E->getCastKind()) {
13411   case CK_BaseToDerived:
13412   case CK_DerivedToBase:
13413   case CK_UncheckedDerivedToBase:
13414   case CK_Dynamic:
13415   case CK_ToUnion:
13416   case CK_ArrayToPointerDecay:
13417   case CK_FunctionToPointerDecay:
13418   case CK_NullToPointer:
13419   case CK_NullToMemberPointer:
13420   case CK_BaseToDerivedMemberPointer:
13421   case CK_DerivedToBaseMemberPointer:
13422   case CK_ReinterpretMemberPointer:
13423   case CK_ConstructorConversion:
13424   case CK_IntegralToPointer:
13425   case CK_ToVoid:
13426   case CK_VectorSplat:
13427   case CK_IntegralToFloating:
13428   case CK_FloatingCast:
13429   case CK_CPointerToObjCPointerCast:
13430   case CK_BlockPointerToObjCPointerCast:
13431   case CK_AnyPointerToBlockPointerCast:
13432   case CK_ObjCObjectLValueCast:
13433   case CK_FloatingRealToComplex:
13434   case CK_FloatingComplexToReal:
13435   case CK_FloatingComplexCast:
13436   case CK_FloatingComplexToIntegralComplex:
13437   case CK_IntegralRealToComplex:
13438   case CK_IntegralComplexCast:
13439   case CK_IntegralComplexToFloatingComplex:
13440   case CK_BuiltinFnToFnPtr:
13441   case CK_ZeroToOCLOpaqueType:
13442   case CK_NonAtomicToAtomic:
13443   case CK_AddressSpaceConversion:
13444   case CK_IntToOCLSampler:
13445   case CK_FloatingToFixedPoint:
13446   case CK_FixedPointToFloating:
13447   case CK_FixedPointCast:
13448   case CK_IntegralToFixedPoint:
13449   case CK_MatrixCast:
13450     llvm_unreachable("invalid cast kind for integral value");
13451 
13452   case CK_BitCast:
13453   case CK_Dependent:
13454   case CK_LValueBitCast:
13455   case CK_ARCProduceObject:
13456   case CK_ARCConsumeObject:
13457   case CK_ARCReclaimReturnedObject:
13458   case CK_ARCExtendBlockObject:
13459   case CK_CopyAndAutoreleaseBlockObject:
13460     return Error(E);
13461 
13462   case CK_UserDefinedConversion:
13463   case CK_LValueToRValue:
13464   case CK_AtomicToNonAtomic:
13465   case CK_NoOp:
13466   case CK_LValueToRValueBitCast:
13467     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13468 
13469   case CK_MemberPointerToBoolean:
13470   case CK_PointerToBoolean:
13471   case CK_IntegralToBoolean:
13472   case CK_FloatingToBoolean:
13473   case CK_BooleanToSignedIntegral:
13474   case CK_FloatingComplexToBoolean:
13475   case CK_IntegralComplexToBoolean: {
13476     bool BoolResult;
13477     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13478       return false;
13479     uint64_t IntResult = BoolResult;
13480     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13481       IntResult = (uint64_t)-1;
13482     return Success(IntResult, E);
13483   }
13484 
13485   case CK_FixedPointToIntegral: {
13486     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13487     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13488       return false;
13489     bool Overflowed;
13490     llvm::APSInt Result = Src.convertToInt(
13491         Info.Ctx.getIntWidth(DestType),
13492         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13493     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13494       return false;
13495     return Success(Result, E);
13496   }
13497 
13498   case CK_FixedPointToBoolean: {
13499     // Unsigned padding does not affect this.
13500     APValue Val;
13501     if (!Evaluate(Val, Info, SubExpr))
13502       return false;
13503     return Success(Val.getFixedPoint().getBoolValue(), E);
13504   }
13505 
13506   case CK_IntegralCast: {
13507     if (!Visit(SubExpr))
13508       return false;
13509 
13510     if (!Result.isInt()) {
13511       // Allow casts of address-of-label differences if they are no-ops
13512       // or narrowing.  (The narrowing case isn't actually guaranteed to
13513       // be constant-evaluatable except in some narrow cases which are hard
13514       // to detect here.  We let it through on the assumption the user knows
13515       // what they are doing.)
13516       if (Result.isAddrLabelDiff())
13517         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13518       // Only allow casts of lvalues if they are lossless.
13519       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13520     }
13521 
13522     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13523                                       Result.getInt()), E);
13524   }
13525 
13526   case CK_PointerToIntegral: {
13527     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13528 
13529     LValue LV;
13530     if (!EvaluatePointer(SubExpr, LV, Info))
13531       return false;
13532 
13533     if (LV.getLValueBase()) {
13534       // Only allow based lvalue casts if they are lossless.
13535       // FIXME: Allow a larger integer size than the pointer size, and allow
13536       // narrowing back down to pointer width in subsequent integral casts.
13537       // FIXME: Check integer type's active bits, not its type size.
13538       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13539         return Error(E);
13540 
13541       LV.Designator.setInvalid();
13542       LV.moveInto(Result);
13543       return true;
13544     }
13545 
13546     APSInt AsInt;
13547     APValue V;
13548     LV.moveInto(V);
13549     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13550       llvm_unreachable("Can't cast this!");
13551 
13552     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13553   }
13554 
13555   case CK_IntegralComplexToReal: {
13556     ComplexValue C;
13557     if (!EvaluateComplex(SubExpr, C, Info))
13558       return false;
13559     return Success(C.getComplexIntReal(), E);
13560   }
13561 
13562   case CK_FloatingToIntegral: {
13563     APFloat F(0.0);
13564     if (!EvaluateFloat(SubExpr, F, Info))
13565       return false;
13566 
13567     APSInt Value;
13568     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13569       return false;
13570     return Success(Value, E);
13571   }
13572   }
13573 
13574   llvm_unreachable("unknown cast resulting in integral value");
13575 }
13576 
VisitUnaryReal(const UnaryOperator * E)13577 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13578   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13579     ComplexValue LV;
13580     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13581       return false;
13582     if (!LV.isComplexInt())
13583       return Error(E);
13584     return Success(LV.getComplexIntReal(), E);
13585   }
13586 
13587   return Visit(E->getSubExpr());
13588 }
13589 
VisitUnaryImag(const UnaryOperator * E)13590 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13591   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13592     ComplexValue LV;
13593     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13594       return false;
13595     if (!LV.isComplexInt())
13596       return Error(E);
13597     return Success(LV.getComplexIntImag(), E);
13598   }
13599 
13600   VisitIgnoredValue(E->getSubExpr());
13601   return Success(0, E);
13602 }
13603 
VisitSizeOfPackExpr(const SizeOfPackExpr * E)13604 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13605   return Success(E->getPackLength(), E);
13606 }
13607 
VisitCXXNoexceptExpr(const CXXNoexceptExpr * E)13608 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13609   return Success(E->getValue(), E);
13610 }
13611 
VisitConceptSpecializationExpr(const ConceptSpecializationExpr * E)13612 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13613        const ConceptSpecializationExpr *E) {
13614   return Success(E->isSatisfied(), E);
13615 }
13616 
VisitRequiresExpr(const RequiresExpr * E)13617 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13618   return Success(E->isSatisfied(), E);
13619 }
13620 
VisitUnaryOperator(const UnaryOperator * E)13621 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13622   switch (E->getOpcode()) {
13623     default:
13624       // Invalid unary operators
13625       return Error(E);
13626     case UO_Plus:
13627       // The result is just the value.
13628       return Visit(E->getSubExpr());
13629     case UO_Minus: {
13630       if (!Visit(E->getSubExpr())) return false;
13631       if (!Result.isFixedPoint())
13632         return Error(E);
13633       bool Overflowed;
13634       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13635       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13636         return false;
13637       return Success(Negated, E);
13638     }
13639     case UO_LNot: {
13640       bool bres;
13641       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13642         return false;
13643       return Success(!bres, E);
13644     }
13645   }
13646 }
13647 
VisitCastExpr(const CastExpr * E)13648 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13649   const Expr *SubExpr = E->getSubExpr();
13650   QualType DestType = E->getType();
13651   assert(DestType->isFixedPointType() &&
13652          "Expected destination type to be a fixed point type");
13653   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13654 
13655   switch (E->getCastKind()) {
13656   case CK_FixedPointCast: {
13657     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13658     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13659       return false;
13660     bool Overflowed;
13661     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13662     if (Overflowed) {
13663       if (Info.checkingForUndefinedBehavior())
13664         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13665                                          diag::warn_fixedpoint_constant_overflow)
13666           << Result.toString() << E->getType();
13667       if (!HandleOverflow(Info, E, Result, E->getType()))
13668         return false;
13669     }
13670     return Success(Result, E);
13671   }
13672   case CK_IntegralToFixedPoint: {
13673     APSInt Src;
13674     if (!EvaluateInteger(SubExpr, Src, Info))
13675       return false;
13676 
13677     bool Overflowed;
13678     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13679         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13680 
13681     if (Overflowed) {
13682       if (Info.checkingForUndefinedBehavior())
13683         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13684                                          diag::warn_fixedpoint_constant_overflow)
13685           << IntResult.toString() << E->getType();
13686       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13687         return false;
13688     }
13689 
13690     return Success(IntResult, E);
13691   }
13692   case CK_FloatingToFixedPoint: {
13693     APFloat Src(0.0);
13694     if (!EvaluateFloat(SubExpr, Src, Info))
13695       return false;
13696 
13697     bool Overflowed;
13698     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13699         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13700 
13701     if (Overflowed) {
13702       if (Info.checkingForUndefinedBehavior())
13703         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13704                                          diag::warn_fixedpoint_constant_overflow)
13705           << Result.toString() << E->getType();
13706       if (!HandleOverflow(Info, E, Result, E->getType()))
13707         return false;
13708     }
13709 
13710     return Success(Result, E);
13711   }
13712   case CK_NoOp:
13713   case CK_LValueToRValue:
13714     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13715   default:
13716     return Error(E);
13717   }
13718 }
13719 
VisitBinaryOperator(const BinaryOperator * E)13720 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13721   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13722     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13723 
13724   const Expr *LHS = E->getLHS();
13725   const Expr *RHS = E->getRHS();
13726   FixedPointSemantics ResultFXSema =
13727       Info.Ctx.getFixedPointSemantics(E->getType());
13728 
13729   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13730   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13731     return false;
13732   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13733   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13734     return false;
13735 
13736   bool OpOverflow = false, ConversionOverflow = false;
13737   APFixedPoint Result(LHSFX.getSemantics());
13738   switch (E->getOpcode()) {
13739   case BO_Add: {
13740     Result = LHSFX.add(RHSFX, &OpOverflow)
13741                   .convert(ResultFXSema, &ConversionOverflow);
13742     break;
13743   }
13744   case BO_Sub: {
13745     Result = LHSFX.sub(RHSFX, &OpOverflow)
13746                   .convert(ResultFXSema, &ConversionOverflow);
13747     break;
13748   }
13749   case BO_Mul: {
13750     Result = LHSFX.mul(RHSFX, &OpOverflow)
13751                   .convert(ResultFXSema, &ConversionOverflow);
13752     break;
13753   }
13754   case BO_Div: {
13755     if (RHSFX.getValue() == 0) {
13756       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13757       return false;
13758     }
13759     Result = LHSFX.div(RHSFX, &OpOverflow)
13760                   .convert(ResultFXSema, &ConversionOverflow);
13761     break;
13762   }
13763   case BO_Shl:
13764   case BO_Shr: {
13765     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13766     llvm::APSInt RHSVal = RHSFX.getValue();
13767 
13768     unsigned ShiftBW =
13769         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13770     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13771     // Embedded-C 4.1.6.2.2:
13772     //   The right operand must be nonnegative and less than the total number
13773     //   of (nonpadding) bits of the fixed-point operand ...
13774     if (RHSVal.isNegative())
13775       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13776     else if (Amt != RHSVal)
13777       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13778           << RHSVal << E->getType() << ShiftBW;
13779 
13780     if (E->getOpcode() == BO_Shl)
13781       Result = LHSFX.shl(Amt, &OpOverflow);
13782     else
13783       Result = LHSFX.shr(Amt, &OpOverflow);
13784     break;
13785   }
13786   default:
13787     return false;
13788   }
13789   if (OpOverflow || ConversionOverflow) {
13790     if (Info.checkingForUndefinedBehavior())
13791       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13792                                        diag::warn_fixedpoint_constant_overflow)
13793         << Result.toString() << E->getType();
13794     if (!HandleOverflow(Info, E, Result, E->getType()))
13795       return false;
13796   }
13797   return Success(Result, E);
13798 }
13799 
13800 //===----------------------------------------------------------------------===//
13801 // Float Evaluation
13802 //===----------------------------------------------------------------------===//
13803 
13804 namespace {
13805 class FloatExprEvaluator
13806   : public ExprEvaluatorBase<FloatExprEvaluator> {
13807   APFloat &Result;
13808 public:
FloatExprEvaluator(EvalInfo & info,APFloat & result)13809   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13810     : ExprEvaluatorBaseTy(info), Result(result) {}
13811 
Success(const APValue & V,const Expr * e)13812   bool Success(const APValue &V, const Expr *e) {
13813     Result = V.getFloat();
13814     return true;
13815   }
13816 
ZeroInitialization(const Expr * E)13817   bool ZeroInitialization(const Expr *E) {
13818     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13819     return true;
13820   }
13821 
13822   bool VisitCallExpr(const CallExpr *E);
13823 
13824   bool VisitUnaryOperator(const UnaryOperator *E);
13825   bool VisitBinaryOperator(const BinaryOperator *E);
13826   bool VisitFloatingLiteral(const FloatingLiteral *E);
13827   bool VisitCastExpr(const CastExpr *E);
13828 
13829   bool VisitUnaryReal(const UnaryOperator *E);
13830   bool VisitUnaryImag(const UnaryOperator *E);
13831 
13832   // FIXME: Missing: array subscript of vector, member of vector
13833 };
13834 } // end anonymous namespace
13835 
EvaluateFloat(const Expr * E,APFloat & Result,EvalInfo & Info)13836 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13837   assert(!E->isValueDependent());
13838   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13839   return FloatExprEvaluator(Info, Result).Visit(E);
13840 }
13841 
TryEvaluateBuiltinNaN(const ASTContext & Context,QualType ResultTy,const Expr * Arg,bool SNaN,llvm::APFloat & Result)13842 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13843                                   QualType ResultTy,
13844                                   const Expr *Arg,
13845                                   bool SNaN,
13846                                   llvm::APFloat &Result) {
13847   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13848   if (!S) return false;
13849 
13850   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13851 
13852   llvm::APInt fill;
13853 
13854   // Treat empty strings as if they were zero.
13855   if (S->getString().empty())
13856     fill = llvm::APInt(32, 0);
13857   else if (S->getString().getAsInteger(0, fill))
13858     return false;
13859 
13860   if (Context.getTargetInfo().isNan2008()) {
13861     if (SNaN)
13862       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13863     else
13864       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13865   } else {
13866     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13867     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13868     // a different encoding to what became a standard in 2008, and for pre-
13869     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13870     // sNaN. This is now known as "legacy NaN" encoding.
13871     if (SNaN)
13872       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13873     else
13874       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13875   }
13876 
13877   return true;
13878 }
13879 
VisitCallExpr(const CallExpr * E)13880 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13881   switch (E->getBuiltinCallee()) {
13882   default:
13883     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13884 
13885   case Builtin::BI__builtin_huge_val:
13886   case Builtin::BI__builtin_huge_valf:
13887   case Builtin::BI__builtin_huge_vall:
13888   case Builtin::BI__builtin_huge_valf16:
13889   case Builtin::BI__builtin_huge_valf128:
13890   case Builtin::BI__builtin_inf:
13891   case Builtin::BI__builtin_inff:
13892   case Builtin::BI__builtin_infl:
13893   case Builtin::BI__builtin_inff16:
13894   case Builtin::BI__builtin_inff128: {
13895     const llvm::fltSemantics &Sem =
13896       Info.Ctx.getFloatTypeSemantics(E->getType());
13897     Result = llvm::APFloat::getInf(Sem);
13898     return true;
13899   }
13900 
13901   case Builtin::BI__builtin_nans:
13902   case Builtin::BI__builtin_nansf:
13903   case Builtin::BI__builtin_nansl:
13904   case Builtin::BI__builtin_nansf16:
13905   case Builtin::BI__builtin_nansf128:
13906     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13907                                true, Result))
13908       return Error(E);
13909     return true;
13910 
13911   case Builtin::BI__builtin_nan:
13912   case Builtin::BI__builtin_nanf:
13913   case Builtin::BI__builtin_nanl:
13914   case Builtin::BI__builtin_nanf16:
13915   case Builtin::BI__builtin_nanf128:
13916     // If this is __builtin_nan() turn this into a nan, otherwise we
13917     // can't constant fold it.
13918     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13919                                false, Result))
13920       return Error(E);
13921     return true;
13922 
13923   case Builtin::BI__builtin_fabs:
13924   case Builtin::BI__builtin_fabsf:
13925   case Builtin::BI__builtin_fabsl:
13926   case Builtin::BI__builtin_fabsf128:
13927     // The C standard says "fabs raises no floating-point exceptions,
13928     // even if x is a signaling NaN. The returned value is independent of
13929     // the current rounding direction mode."  Therefore constant folding can
13930     // proceed without regard to the floating point settings.
13931     // Reference, WG14 N2478 F.10.4.3
13932     if (!EvaluateFloat(E->getArg(0), Result, Info))
13933       return false;
13934 
13935     if (Result.isNegative())
13936       Result.changeSign();
13937     return true;
13938 
13939   case Builtin::BI__arithmetic_fence:
13940     return EvaluateFloat(E->getArg(0), Result, Info);
13941 
13942   // FIXME: Builtin::BI__builtin_powi
13943   // FIXME: Builtin::BI__builtin_powif
13944   // FIXME: Builtin::BI__builtin_powil
13945 
13946   case Builtin::BI__builtin_copysign:
13947   case Builtin::BI__builtin_copysignf:
13948   case Builtin::BI__builtin_copysignl:
13949   case Builtin::BI__builtin_copysignf128: {
13950     APFloat RHS(0.);
13951     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13952         !EvaluateFloat(E->getArg(1), RHS, Info))
13953       return false;
13954     Result.copySign(RHS);
13955     return true;
13956   }
13957   }
13958 }
13959 
VisitUnaryReal(const UnaryOperator * E)13960 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13961   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13962     ComplexValue CV;
13963     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13964       return false;
13965     Result = CV.FloatReal;
13966     return true;
13967   }
13968 
13969   return Visit(E->getSubExpr());
13970 }
13971 
VisitUnaryImag(const UnaryOperator * E)13972 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13973   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13974     ComplexValue CV;
13975     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13976       return false;
13977     Result = CV.FloatImag;
13978     return true;
13979   }
13980 
13981   VisitIgnoredValue(E->getSubExpr());
13982   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13983   Result = llvm::APFloat::getZero(Sem);
13984   return true;
13985 }
13986 
VisitUnaryOperator(const UnaryOperator * E)13987 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13988   switch (E->getOpcode()) {
13989   default: return Error(E);
13990   case UO_Plus:
13991     return EvaluateFloat(E->getSubExpr(), Result, Info);
13992   case UO_Minus:
13993     // In C standard, WG14 N2478 F.3 p4
13994     // "the unary - raises no floating point exceptions,
13995     // even if the operand is signalling."
13996     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13997       return false;
13998     Result.changeSign();
13999     return true;
14000   }
14001 }
14002 
VisitBinaryOperator(const BinaryOperator * E)14003 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14004   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14005     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14006 
14007   APFloat RHS(0.0);
14008   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14009   if (!LHSOK && !Info.noteFailure())
14010     return false;
14011   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14012          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14013 }
14014 
VisitFloatingLiteral(const FloatingLiteral * E)14015 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14016   Result = E->getValue();
14017   return true;
14018 }
14019 
VisitCastExpr(const CastExpr * E)14020 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14021   const Expr* SubExpr = E->getSubExpr();
14022 
14023   switch (E->getCastKind()) {
14024   default:
14025     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14026 
14027   case CK_IntegralToFloating: {
14028     APSInt IntResult;
14029     const FPOptions FPO = E->getFPFeaturesInEffect(
14030                                   Info.Ctx.getLangOpts());
14031     return EvaluateInteger(SubExpr, IntResult, Info) &&
14032            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14033                                 IntResult, E->getType(), Result);
14034   }
14035 
14036   case CK_FixedPointToFloating: {
14037     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14038     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14039       return false;
14040     Result =
14041         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14042     return true;
14043   }
14044 
14045   case CK_FloatingCast: {
14046     if (!Visit(SubExpr))
14047       return false;
14048     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14049                                   Result);
14050   }
14051 
14052   case CK_FloatingComplexToReal: {
14053     ComplexValue V;
14054     if (!EvaluateComplex(SubExpr, V, Info))
14055       return false;
14056     Result = V.getComplexFloatReal();
14057     return true;
14058   }
14059   }
14060 }
14061 
14062 //===----------------------------------------------------------------------===//
14063 // Complex Evaluation (for float and integer)
14064 //===----------------------------------------------------------------------===//
14065 
14066 namespace {
14067 class ComplexExprEvaluator
14068   : public ExprEvaluatorBase<ComplexExprEvaluator> {
14069   ComplexValue &Result;
14070 
14071 public:
ComplexExprEvaluator(EvalInfo & info,ComplexValue & Result)14072   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14073     : ExprEvaluatorBaseTy(info), Result(Result) {}
14074 
Success(const APValue & V,const Expr * e)14075   bool Success(const APValue &V, const Expr *e) {
14076     Result.setFrom(V);
14077     return true;
14078   }
14079 
14080   bool ZeroInitialization(const Expr *E);
14081 
14082   //===--------------------------------------------------------------------===//
14083   //                            Visitor Methods
14084   //===--------------------------------------------------------------------===//
14085 
14086   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14087   bool VisitCastExpr(const CastExpr *E);
14088   bool VisitBinaryOperator(const BinaryOperator *E);
14089   bool VisitUnaryOperator(const UnaryOperator *E);
14090   bool VisitInitListExpr(const InitListExpr *E);
14091   bool VisitCallExpr(const CallExpr *E);
14092 };
14093 } // end anonymous namespace
14094 
EvaluateComplex(const Expr * E,ComplexValue & Result,EvalInfo & Info)14095 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14096                             EvalInfo &Info) {
14097   assert(!E->isValueDependent());
14098   assert(E->isPRValue() && E->getType()->isAnyComplexType());
14099   return ComplexExprEvaluator(Info, Result).Visit(E);
14100 }
14101 
ZeroInitialization(const Expr * E)14102 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14103   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14104   if (ElemTy->isRealFloatingType()) {
14105     Result.makeComplexFloat();
14106     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14107     Result.FloatReal = Zero;
14108     Result.FloatImag = Zero;
14109   } else {
14110     Result.makeComplexInt();
14111     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14112     Result.IntReal = Zero;
14113     Result.IntImag = Zero;
14114   }
14115   return true;
14116 }
14117 
VisitImaginaryLiteral(const ImaginaryLiteral * E)14118 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14119   const Expr* SubExpr = E->getSubExpr();
14120 
14121   if (SubExpr->getType()->isRealFloatingType()) {
14122     Result.makeComplexFloat();
14123     APFloat &Imag = Result.FloatImag;
14124     if (!EvaluateFloat(SubExpr, Imag, Info))
14125       return false;
14126 
14127     Result.FloatReal = APFloat(Imag.getSemantics());
14128     return true;
14129   } else {
14130     assert(SubExpr->getType()->isIntegerType() &&
14131            "Unexpected imaginary literal.");
14132 
14133     Result.makeComplexInt();
14134     APSInt &Imag = Result.IntImag;
14135     if (!EvaluateInteger(SubExpr, Imag, Info))
14136       return false;
14137 
14138     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14139     return true;
14140   }
14141 }
14142 
VisitCastExpr(const CastExpr * E)14143 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14144 
14145   switch (E->getCastKind()) {
14146   case CK_BitCast:
14147   case CK_BaseToDerived:
14148   case CK_DerivedToBase:
14149   case CK_UncheckedDerivedToBase:
14150   case CK_Dynamic:
14151   case CK_ToUnion:
14152   case CK_ArrayToPointerDecay:
14153   case CK_FunctionToPointerDecay:
14154   case CK_NullToPointer:
14155   case CK_NullToMemberPointer:
14156   case CK_BaseToDerivedMemberPointer:
14157   case CK_DerivedToBaseMemberPointer:
14158   case CK_MemberPointerToBoolean:
14159   case CK_ReinterpretMemberPointer:
14160   case CK_ConstructorConversion:
14161   case CK_IntegralToPointer:
14162   case CK_PointerToIntegral:
14163   case CK_PointerToBoolean:
14164   case CK_ToVoid:
14165   case CK_VectorSplat:
14166   case CK_IntegralCast:
14167   case CK_BooleanToSignedIntegral:
14168   case CK_IntegralToBoolean:
14169   case CK_IntegralToFloating:
14170   case CK_FloatingToIntegral:
14171   case CK_FloatingToBoolean:
14172   case CK_FloatingCast:
14173   case CK_CPointerToObjCPointerCast:
14174   case CK_BlockPointerToObjCPointerCast:
14175   case CK_AnyPointerToBlockPointerCast:
14176   case CK_ObjCObjectLValueCast:
14177   case CK_FloatingComplexToReal:
14178   case CK_FloatingComplexToBoolean:
14179   case CK_IntegralComplexToReal:
14180   case CK_IntegralComplexToBoolean:
14181   case CK_ARCProduceObject:
14182   case CK_ARCConsumeObject:
14183   case CK_ARCReclaimReturnedObject:
14184   case CK_ARCExtendBlockObject:
14185   case CK_CopyAndAutoreleaseBlockObject:
14186   case CK_BuiltinFnToFnPtr:
14187   case CK_ZeroToOCLOpaqueType:
14188   case CK_NonAtomicToAtomic:
14189   case CK_AddressSpaceConversion:
14190   case CK_IntToOCLSampler:
14191   case CK_FloatingToFixedPoint:
14192   case CK_FixedPointToFloating:
14193   case CK_FixedPointCast:
14194   case CK_FixedPointToBoolean:
14195   case CK_FixedPointToIntegral:
14196   case CK_IntegralToFixedPoint:
14197   case CK_MatrixCast:
14198     llvm_unreachable("invalid cast kind for complex value");
14199 
14200   case CK_LValueToRValue:
14201   case CK_AtomicToNonAtomic:
14202   case CK_NoOp:
14203   case CK_LValueToRValueBitCast:
14204     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14205 
14206   case CK_Dependent:
14207   case CK_LValueBitCast:
14208   case CK_UserDefinedConversion:
14209     return Error(E);
14210 
14211   case CK_FloatingRealToComplex: {
14212     APFloat &Real = Result.FloatReal;
14213     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14214       return false;
14215 
14216     Result.makeComplexFloat();
14217     Result.FloatImag = APFloat(Real.getSemantics());
14218     return true;
14219   }
14220 
14221   case CK_FloatingComplexCast: {
14222     if (!Visit(E->getSubExpr()))
14223       return false;
14224 
14225     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14226     QualType From
14227       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14228 
14229     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14230            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14231   }
14232 
14233   case CK_FloatingComplexToIntegralComplex: {
14234     if (!Visit(E->getSubExpr()))
14235       return false;
14236 
14237     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14238     QualType From
14239       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14240     Result.makeComplexInt();
14241     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14242                                 To, Result.IntReal) &&
14243            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14244                                 To, Result.IntImag);
14245   }
14246 
14247   case CK_IntegralRealToComplex: {
14248     APSInt &Real = Result.IntReal;
14249     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14250       return false;
14251 
14252     Result.makeComplexInt();
14253     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14254     return true;
14255   }
14256 
14257   case CK_IntegralComplexCast: {
14258     if (!Visit(E->getSubExpr()))
14259       return false;
14260 
14261     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14262     QualType From
14263       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14264 
14265     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14266     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14267     return true;
14268   }
14269 
14270   case CK_IntegralComplexToFloatingComplex: {
14271     if (!Visit(E->getSubExpr()))
14272       return false;
14273 
14274     const FPOptions FPO = E->getFPFeaturesInEffect(
14275                                   Info.Ctx.getLangOpts());
14276     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14277     QualType From
14278       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14279     Result.makeComplexFloat();
14280     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14281                                 To, Result.FloatReal) &&
14282            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14283                                 To, Result.FloatImag);
14284   }
14285   }
14286 
14287   llvm_unreachable("unknown cast resulting in complex value");
14288 }
14289 
VisitBinaryOperator(const BinaryOperator * E)14290 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14291   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14292     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14293 
14294   // Track whether the LHS or RHS is real at the type system level. When this is
14295   // the case we can simplify our evaluation strategy.
14296   bool LHSReal = false, RHSReal = false;
14297 
14298   bool LHSOK;
14299   if (E->getLHS()->getType()->isRealFloatingType()) {
14300     LHSReal = true;
14301     APFloat &Real = Result.FloatReal;
14302     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14303     if (LHSOK) {
14304       Result.makeComplexFloat();
14305       Result.FloatImag = APFloat(Real.getSemantics());
14306     }
14307   } else {
14308     LHSOK = Visit(E->getLHS());
14309   }
14310   if (!LHSOK && !Info.noteFailure())
14311     return false;
14312 
14313   ComplexValue RHS;
14314   if (E->getRHS()->getType()->isRealFloatingType()) {
14315     RHSReal = true;
14316     APFloat &Real = RHS.FloatReal;
14317     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14318       return false;
14319     RHS.makeComplexFloat();
14320     RHS.FloatImag = APFloat(Real.getSemantics());
14321   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14322     return false;
14323 
14324   assert(!(LHSReal && RHSReal) &&
14325          "Cannot have both operands of a complex operation be real.");
14326   switch (E->getOpcode()) {
14327   default: return Error(E);
14328   case BO_Add:
14329     if (Result.isComplexFloat()) {
14330       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14331                                        APFloat::rmNearestTiesToEven);
14332       if (LHSReal)
14333         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14334       else if (!RHSReal)
14335         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14336                                          APFloat::rmNearestTiesToEven);
14337     } else {
14338       Result.getComplexIntReal() += RHS.getComplexIntReal();
14339       Result.getComplexIntImag() += RHS.getComplexIntImag();
14340     }
14341     break;
14342   case BO_Sub:
14343     if (Result.isComplexFloat()) {
14344       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14345                                             APFloat::rmNearestTiesToEven);
14346       if (LHSReal) {
14347         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14348         Result.getComplexFloatImag().changeSign();
14349       } else if (!RHSReal) {
14350         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14351                                               APFloat::rmNearestTiesToEven);
14352       }
14353     } else {
14354       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14355       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14356     }
14357     break;
14358   case BO_Mul:
14359     if (Result.isComplexFloat()) {
14360       // This is an implementation of complex multiplication according to the
14361       // constraints laid out in C11 Annex G. The implementation uses the
14362       // following naming scheme:
14363       //   (a + ib) * (c + id)
14364       ComplexValue LHS = Result;
14365       APFloat &A = LHS.getComplexFloatReal();
14366       APFloat &B = LHS.getComplexFloatImag();
14367       APFloat &C = RHS.getComplexFloatReal();
14368       APFloat &D = RHS.getComplexFloatImag();
14369       APFloat &ResR = Result.getComplexFloatReal();
14370       APFloat &ResI = Result.getComplexFloatImag();
14371       if (LHSReal) {
14372         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14373         ResR = A * C;
14374         ResI = A * D;
14375       } else if (RHSReal) {
14376         ResR = C * A;
14377         ResI = C * B;
14378       } else {
14379         // In the fully general case, we need to handle NaNs and infinities
14380         // robustly.
14381         APFloat AC = A * C;
14382         APFloat BD = B * D;
14383         APFloat AD = A * D;
14384         APFloat BC = B * C;
14385         ResR = AC - BD;
14386         ResI = AD + BC;
14387         if (ResR.isNaN() && ResI.isNaN()) {
14388           bool Recalc = false;
14389           if (A.isInfinity() || B.isInfinity()) {
14390             A = APFloat::copySign(
14391                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14392             B = APFloat::copySign(
14393                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14394             if (C.isNaN())
14395               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14396             if (D.isNaN())
14397               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14398             Recalc = true;
14399           }
14400           if (C.isInfinity() || D.isInfinity()) {
14401             C = APFloat::copySign(
14402                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14403             D = APFloat::copySign(
14404                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14405             if (A.isNaN())
14406               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14407             if (B.isNaN())
14408               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14409             Recalc = true;
14410           }
14411           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14412                           AD.isInfinity() || BC.isInfinity())) {
14413             if (A.isNaN())
14414               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14415             if (B.isNaN())
14416               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14417             if (C.isNaN())
14418               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14419             if (D.isNaN())
14420               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14421             Recalc = true;
14422           }
14423           if (Recalc) {
14424             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14425             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14426           }
14427         }
14428       }
14429     } else {
14430       ComplexValue LHS = Result;
14431       Result.getComplexIntReal() =
14432         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14433          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14434       Result.getComplexIntImag() =
14435         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14436          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14437     }
14438     break;
14439   case BO_Div:
14440     if (Result.isComplexFloat()) {
14441       // This is an implementation of complex division according to the
14442       // constraints laid out in C11 Annex G. The implementation uses the
14443       // following naming scheme:
14444       //   (a + ib) / (c + id)
14445       ComplexValue LHS = Result;
14446       APFloat &A = LHS.getComplexFloatReal();
14447       APFloat &B = LHS.getComplexFloatImag();
14448       APFloat &C = RHS.getComplexFloatReal();
14449       APFloat &D = RHS.getComplexFloatImag();
14450       APFloat &ResR = Result.getComplexFloatReal();
14451       APFloat &ResI = Result.getComplexFloatImag();
14452       if (RHSReal) {
14453         ResR = A / C;
14454         ResI = B / C;
14455       } else {
14456         if (LHSReal) {
14457           // No real optimizations we can do here, stub out with zero.
14458           B = APFloat::getZero(A.getSemantics());
14459         }
14460         int DenomLogB = 0;
14461         APFloat MaxCD = maxnum(abs(C), abs(D));
14462         if (MaxCD.isFinite()) {
14463           DenomLogB = ilogb(MaxCD);
14464           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14465           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14466         }
14467         APFloat Denom = C * C + D * D;
14468         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14469                       APFloat::rmNearestTiesToEven);
14470         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14471                       APFloat::rmNearestTiesToEven);
14472         if (ResR.isNaN() && ResI.isNaN()) {
14473           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14474             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14475             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14476           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14477                      D.isFinite()) {
14478             A = APFloat::copySign(
14479                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14480             B = APFloat::copySign(
14481                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14482             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14483             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14484           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14485             C = APFloat::copySign(
14486                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14487             D = APFloat::copySign(
14488                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14489             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14490             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14491           }
14492         }
14493       }
14494     } else {
14495       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14496         return Error(E, diag::note_expr_divide_by_zero);
14497 
14498       ComplexValue LHS = Result;
14499       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14500         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14501       Result.getComplexIntReal() =
14502         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14503          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14504       Result.getComplexIntImag() =
14505         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14506          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14507     }
14508     break;
14509   }
14510 
14511   return true;
14512 }
14513 
VisitUnaryOperator(const UnaryOperator * E)14514 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14515   // Get the operand value into 'Result'.
14516   if (!Visit(E->getSubExpr()))
14517     return false;
14518 
14519   switch (E->getOpcode()) {
14520   default:
14521     return Error(E);
14522   case UO_Extension:
14523     return true;
14524   case UO_Plus:
14525     // The result is always just the subexpr.
14526     return true;
14527   case UO_Minus:
14528     if (Result.isComplexFloat()) {
14529       Result.getComplexFloatReal().changeSign();
14530       Result.getComplexFloatImag().changeSign();
14531     }
14532     else {
14533       Result.getComplexIntReal() = -Result.getComplexIntReal();
14534       Result.getComplexIntImag() = -Result.getComplexIntImag();
14535     }
14536     return true;
14537   case UO_Not:
14538     if (Result.isComplexFloat())
14539       Result.getComplexFloatImag().changeSign();
14540     else
14541       Result.getComplexIntImag() = -Result.getComplexIntImag();
14542     return true;
14543   }
14544 }
14545 
VisitInitListExpr(const InitListExpr * E)14546 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14547   if (E->getNumInits() == 2) {
14548     if (E->getType()->isComplexType()) {
14549       Result.makeComplexFloat();
14550       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14551         return false;
14552       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14553         return false;
14554     } else {
14555       Result.makeComplexInt();
14556       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14557         return false;
14558       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14559         return false;
14560     }
14561     return true;
14562   }
14563   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14564 }
14565 
VisitCallExpr(const CallExpr * E)14566 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14567   switch (E->getBuiltinCallee()) {
14568   case Builtin::BI__builtin_complex:
14569     Result.makeComplexFloat();
14570     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14571       return false;
14572     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14573       return false;
14574     return true;
14575 
14576   default:
14577     break;
14578   }
14579 
14580   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14581 }
14582 
14583 //===----------------------------------------------------------------------===//
14584 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14585 // implicit conversion.
14586 //===----------------------------------------------------------------------===//
14587 
14588 namespace {
14589 class AtomicExprEvaluator :
14590     public ExprEvaluatorBase<AtomicExprEvaluator> {
14591   const LValue *This;
14592   APValue &Result;
14593 public:
AtomicExprEvaluator(EvalInfo & Info,const LValue * This,APValue & Result)14594   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14595       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14596 
Success(const APValue & V,const Expr * E)14597   bool Success(const APValue &V, const Expr *E) {
14598     Result = V;
14599     return true;
14600   }
14601 
ZeroInitialization(const Expr * E)14602   bool ZeroInitialization(const Expr *E) {
14603     ImplicitValueInitExpr VIE(
14604         E->getType()->castAs<AtomicType>()->getValueType());
14605     // For atomic-qualified class (and array) types in C++, initialize the
14606     // _Atomic-wrapped subobject directly, in-place.
14607     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14608                 : Evaluate(Result, Info, &VIE);
14609   }
14610 
VisitCastExpr(const CastExpr * E)14611   bool VisitCastExpr(const CastExpr *E) {
14612     switch (E->getCastKind()) {
14613     default:
14614       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14615     case CK_NonAtomicToAtomic:
14616       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14617                   : Evaluate(Result, Info, E->getSubExpr());
14618     }
14619   }
14620 };
14621 } // end anonymous namespace
14622 
EvaluateAtomic(const Expr * E,const LValue * This,APValue & Result,EvalInfo & Info)14623 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14624                            EvalInfo &Info) {
14625   assert(!E->isValueDependent());
14626   assert(E->isPRValue() && E->getType()->isAtomicType());
14627   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14628 }
14629 
14630 //===----------------------------------------------------------------------===//
14631 // Void expression evaluation, primarily for a cast to void on the LHS of a
14632 // comma operator
14633 //===----------------------------------------------------------------------===//
14634 
14635 namespace {
14636 class VoidExprEvaluator
14637   : public ExprEvaluatorBase<VoidExprEvaluator> {
14638 public:
VoidExprEvaluator(EvalInfo & Info)14639   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14640 
Success(const APValue & V,const Expr * e)14641   bool Success(const APValue &V, const Expr *e) { return true; }
14642 
ZeroInitialization(const Expr * E)14643   bool ZeroInitialization(const Expr *E) { return true; }
14644 
VisitCastExpr(const CastExpr * E)14645   bool VisitCastExpr(const CastExpr *E) {
14646     switch (E->getCastKind()) {
14647     default:
14648       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14649     case CK_ToVoid:
14650       VisitIgnoredValue(E->getSubExpr());
14651       return true;
14652     }
14653   }
14654 
VisitCallExpr(const CallExpr * E)14655   bool VisitCallExpr(const CallExpr *E) {
14656     switch (E->getBuiltinCallee()) {
14657     case Builtin::BI__assume:
14658     case Builtin::BI__builtin_assume:
14659       // The argument is not evaluated!
14660       return true;
14661 
14662     case Builtin::BI__builtin_operator_delete:
14663       return HandleOperatorDeleteCall(Info, E);
14664 
14665     default:
14666       break;
14667     }
14668 
14669     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14670   }
14671 
14672   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14673 };
14674 } // end anonymous namespace
14675 
VisitCXXDeleteExpr(const CXXDeleteExpr * E)14676 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14677   // We cannot speculatively evaluate a delete expression.
14678   if (Info.SpeculativeEvaluationDepth)
14679     return false;
14680 
14681   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14682   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14683     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14684         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14685     return false;
14686   }
14687 
14688   const Expr *Arg = E->getArgument();
14689 
14690   LValue Pointer;
14691   if (!EvaluatePointer(Arg, Pointer, Info))
14692     return false;
14693   if (Pointer.Designator.Invalid)
14694     return false;
14695 
14696   // Deleting a null pointer has no effect.
14697   if (Pointer.isNullPointer()) {
14698     // This is the only case where we need to produce an extension warning:
14699     // the only other way we can succeed is if we find a dynamic allocation,
14700     // and we will have warned when we allocated it in that case.
14701     if (!Info.getLangOpts().CPlusPlus20)
14702       Info.CCEDiag(E, diag::note_constexpr_new);
14703     return true;
14704   }
14705 
14706   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14707       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14708   if (!Alloc)
14709     return false;
14710   QualType AllocType = Pointer.Base.getDynamicAllocType();
14711 
14712   // For the non-array case, the designator must be empty if the static type
14713   // does not have a virtual destructor.
14714   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14715       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14716     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14717         << Arg->getType()->getPointeeType() << AllocType;
14718     return false;
14719   }
14720 
14721   // For a class type with a virtual destructor, the selected operator delete
14722   // is the one looked up when building the destructor.
14723   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14724     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14725     if (VirtualDelete &&
14726         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14727       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14728           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14729       return false;
14730     }
14731   }
14732 
14733   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14734                          (*Alloc)->Value, AllocType))
14735     return false;
14736 
14737   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14738     // The element was already erased. This means the destructor call also
14739     // deleted the object.
14740     // FIXME: This probably results in undefined behavior before we get this
14741     // far, and should be diagnosed elsewhere first.
14742     Info.FFDiag(E, diag::note_constexpr_double_delete);
14743     return false;
14744   }
14745 
14746   return true;
14747 }
14748 
EvaluateVoid(const Expr * E,EvalInfo & Info)14749 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14750   assert(!E->isValueDependent());
14751   assert(E->isPRValue() && E->getType()->isVoidType());
14752   return VoidExprEvaluator(Info).Visit(E);
14753 }
14754 
14755 //===----------------------------------------------------------------------===//
14756 // Top level Expr::EvaluateAsRValue method.
14757 //===----------------------------------------------------------------------===//
14758 
Evaluate(APValue & Result,EvalInfo & Info,const Expr * E)14759 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14760   assert(!E->isValueDependent());
14761   // In C, function designators are not lvalues, but we evaluate them as if they
14762   // are.
14763   QualType T = E->getType();
14764   if (E->isGLValue() || T->isFunctionType()) {
14765     LValue LV;
14766     if (!EvaluateLValue(E, LV, Info))
14767       return false;
14768     LV.moveInto(Result);
14769   } else if (T->isVectorType()) {
14770     if (!EvaluateVector(E, Result, Info))
14771       return false;
14772   } else if (T->isIntegralOrEnumerationType()) {
14773     if (!IntExprEvaluator(Info, Result).Visit(E))
14774       return false;
14775   } else if (T->hasPointerRepresentation()) {
14776     LValue LV;
14777     if (!EvaluatePointer(E, LV, Info))
14778       return false;
14779     LV.moveInto(Result);
14780   } else if (T->isRealFloatingType()) {
14781     llvm::APFloat F(0.0);
14782     if (!EvaluateFloat(E, F, Info))
14783       return false;
14784     Result = APValue(F);
14785   } else if (T->isAnyComplexType()) {
14786     ComplexValue C;
14787     if (!EvaluateComplex(E, C, Info))
14788       return false;
14789     C.moveInto(Result);
14790   } else if (T->isFixedPointType()) {
14791     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14792   } else if (T->isMemberPointerType()) {
14793     MemberPtr P;
14794     if (!EvaluateMemberPointer(E, P, Info))
14795       return false;
14796     P.moveInto(Result);
14797     return true;
14798   } else if (T->isArrayType()) {
14799     LValue LV;
14800     APValue &Value =
14801         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14802     if (!EvaluateArray(E, LV, Value, Info))
14803       return false;
14804     Result = Value;
14805   } else if (T->isRecordType()) {
14806     LValue LV;
14807     APValue &Value =
14808         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14809     if (!EvaluateRecord(E, LV, Value, Info))
14810       return false;
14811     Result = Value;
14812   } else if (T->isVoidType()) {
14813     if (!Info.getLangOpts().CPlusPlus11)
14814       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14815         << E->getType();
14816     if (!EvaluateVoid(E, Info))
14817       return false;
14818   } else if (T->isAtomicType()) {
14819     QualType Unqual = T.getAtomicUnqualifiedType();
14820     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14821       LValue LV;
14822       APValue &Value = Info.CurrentCall->createTemporary(
14823           E, Unqual, ScopeKind::FullExpression, LV);
14824       if (!EvaluateAtomic(E, &LV, Value, Info))
14825         return false;
14826     } else {
14827       if (!EvaluateAtomic(E, nullptr, Result, Info))
14828         return false;
14829     }
14830   } else if (Info.getLangOpts().CPlusPlus11) {
14831     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14832     return false;
14833   } else {
14834     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14835     return false;
14836   }
14837 
14838   return true;
14839 }
14840 
14841 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14842 /// cases, the in-place evaluation is essential, since later initializers for
14843 /// an object can indirectly refer to subobjects which were initialized earlier.
EvaluateInPlace(APValue & Result,EvalInfo & Info,const LValue & This,const Expr * E,bool AllowNonLiteralTypes)14844 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14845                             const Expr *E, bool AllowNonLiteralTypes) {
14846   assert(!E->isValueDependent());
14847 
14848   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14849     return false;
14850 
14851   if (E->isPRValue()) {
14852     // Evaluate arrays and record types in-place, so that later initializers can
14853     // refer to earlier-initialized members of the object.
14854     QualType T = E->getType();
14855     if (T->isArrayType())
14856       return EvaluateArray(E, This, Result, Info);
14857     else if (T->isRecordType())
14858       return EvaluateRecord(E, This, Result, Info);
14859     else if (T->isAtomicType()) {
14860       QualType Unqual = T.getAtomicUnqualifiedType();
14861       if (Unqual->isArrayType() || Unqual->isRecordType())
14862         return EvaluateAtomic(E, &This, Result, Info);
14863     }
14864   }
14865 
14866   // For any other type, in-place evaluation is unimportant.
14867   return Evaluate(Result, Info, E);
14868 }
14869 
14870 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14871 /// lvalue-to-rvalue cast if it is an lvalue.
EvaluateAsRValue(EvalInfo & Info,const Expr * E,APValue & Result)14872 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14873   assert(!E->isValueDependent());
14874   if (Info.EnableNewConstInterp) {
14875     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14876       return false;
14877   } else {
14878     if (E->getType().isNull())
14879       return false;
14880 
14881     if (!CheckLiteralType(Info, E))
14882       return false;
14883 
14884     if (!::Evaluate(Result, Info, E))
14885       return false;
14886 
14887     if (E->isGLValue()) {
14888       LValue LV;
14889       LV.setFrom(Info.Ctx, Result);
14890       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14891         return false;
14892     }
14893   }
14894 
14895   // Check this core constant expression is a constant expression.
14896   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14897                                  ConstantExprKind::Normal) &&
14898          CheckMemoryLeaks(Info);
14899 }
14900 
FastEvaluateAsRValue(const Expr * Exp,Expr::EvalResult & Result,const ASTContext & Ctx,bool & IsConst)14901 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14902                                  const ASTContext &Ctx, bool &IsConst) {
14903   // Fast-path evaluations of integer literals, since we sometimes see files
14904   // containing vast quantities of these.
14905   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14906     Result.Val = APValue(APSInt(L->getValue(),
14907                                 L->getType()->isUnsignedIntegerType()));
14908     IsConst = true;
14909     return true;
14910   }
14911 
14912   // This case should be rare, but we need to check it before we check on
14913   // the type below.
14914   if (Exp->getType().isNull()) {
14915     IsConst = false;
14916     return true;
14917   }
14918 
14919   // FIXME: Evaluating values of large array and record types can cause
14920   // performance problems. Only do so in C++11 for now.
14921   if (Exp->isPRValue() &&
14922       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14923       !Ctx.getLangOpts().CPlusPlus11) {
14924     IsConst = false;
14925     return true;
14926   }
14927   return false;
14928 }
14929 
hasUnacceptableSideEffect(Expr::EvalStatus & Result,Expr::SideEffectsKind SEK)14930 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14931                                       Expr::SideEffectsKind SEK) {
14932   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14933          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14934 }
14935 
EvaluateAsRValue(const Expr * E,Expr::EvalResult & Result,const ASTContext & Ctx,EvalInfo & Info)14936 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14937                              const ASTContext &Ctx, EvalInfo &Info) {
14938   assert(!E->isValueDependent());
14939   bool IsConst;
14940   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14941     return IsConst;
14942 
14943   return EvaluateAsRValue(Info, E, Result.Val);
14944 }
14945 
EvaluateAsInt(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)14946 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14947                           const ASTContext &Ctx,
14948                           Expr::SideEffectsKind AllowSideEffects,
14949                           EvalInfo &Info) {
14950   assert(!E->isValueDependent());
14951   if (!E->getType()->isIntegralOrEnumerationType())
14952     return false;
14953 
14954   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14955       !ExprResult.Val.isInt() ||
14956       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14957     return false;
14958 
14959   return true;
14960 }
14961 
EvaluateAsFixedPoint(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)14962 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14963                                  const ASTContext &Ctx,
14964                                  Expr::SideEffectsKind AllowSideEffects,
14965                                  EvalInfo &Info) {
14966   assert(!E->isValueDependent());
14967   if (!E->getType()->isFixedPointType())
14968     return false;
14969 
14970   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14971     return false;
14972 
14973   if (!ExprResult.Val.isFixedPoint() ||
14974       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14975     return false;
14976 
14977   return true;
14978 }
14979 
14980 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14981 /// any crazy technique (that has nothing to do with language standards) that
14982 /// we want to.  If this function returns true, it returns the folded constant
14983 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14984 /// will be applied to the result.
EvaluateAsRValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const14985 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14986                             bool InConstantContext) const {
14987   assert(!isValueDependent() &&
14988          "Expression evaluator can't be called on a dependent expression.");
14989   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14990   Info.InConstantContext = InConstantContext;
14991   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14992 }
14993 
EvaluateAsBooleanCondition(bool & Result,const ASTContext & Ctx,bool InConstantContext) const14994 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14995                                       bool InConstantContext) const {
14996   assert(!isValueDependent() &&
14997          "Expression evaluator can't be called on a dependent expression.");
14998   EvalResult Scratch;
14999   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
15000          HandleConversionToBool(Scratch.Val, Result);
15001 }
15002 
EvaluateAsInt(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const15003 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
15004                          SideEffectsKind AllowSideEffects,
15005                          bool InConstantContext) const {
15006   assert(!isValueDependent() &&
15007          "Expression evaluator can't be called on a dependent expression.");
15008   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15009   Info.InConstantContext = InConstantContext;
15010   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15011 }
15012 
EvaluateAsFixedPoint(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const15013 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
15014                                 SideEffectsKind AllowSideEffects,
15015                                 bool InConstantContext) const {
15016   assert(!isValueDependent() &&
15017          "Expression evaluator can't be called on a dependent expression.");
15018   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15019   Info.InConstantContext = InConstantContext;
15020   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15021 }
15022 
EvaluateAsFloat(APFloat & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const15023 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15024                            SideEffectsKind AllowSideEffects,
15025                            bool InConstantContext) const {
15026   assert(!isValueDependent() &&
15027          "Expression evaluator can't be called on a dependent expression.");
15028 
15029   if (!getType()->isRealFloatingType())
15030     return false;
15031 
15032   EvalResult ExprResult;
15033   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15034       !ExprResult.Val.isFloat() ||
15035       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15036     return false;
15037 
15038   Result = ExprResult.Val.getFloat();
15039   return true;
15040 }
15041 
EvaluateAsLValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const15042 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
15043                             bool InConstantContext) const {
15044   assert(!isValueDependent() &&
15045          "Expression evaluator can't be called on a dependent expression.");
15046 
15047   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15048   Info.InConstantContext = InConstantContext;
15049   LValue LV;
15050   CheckedTemporaries CheckedTemps;
15051   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
15052       Result.HasSideEffects ||
15053       !CheckLValueConstantExpression(Info, getExprLoc(),
15054                                      Ctx.getLValueReferenceType(getType()), LV,
15055                                      ConstantExprKind::Normal, CheckedTemps))
15056     return false;
15057 
15058   LV.moveInto(Result.Val);
15059   return true;
15060 }
15061 
EvaluateDestruction(const ASTContext & Ctx,APValue::LValueBase Base,APValue DestroyedValue,QualType Type,SourceLocation Loc,Expr::EvalStatus & EStatus,bool IsConstantDestruction)15062 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15063                                 APValue DestroyedValue, QualType Type,
15064                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
15065                                 bool IsConstantDestruction) {
15066   EvalInfo Info(Ctx, EStatus,
15067                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15068                                       : EvalInfo::EM_ConstantFold);
15069   Info.setEvaluatingDecl(Base, DestroyedValue,
15070                          EvalInfo::EvaluatingDeclKind::Dtor);
15071   Info.InConstantContext = IsConstantDestruction;
15072 
15073   LValue LVal;
15074   LVal.set(Base);
15075 
15076   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15077       EStatus.HasSideEffects)
15078     return false;
15079 
15080   if (!Info.discardCleanups())
15081     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15082 
15083   return true;
15084 }
15085 
EvaluateAsConstantExpr(EvalResult & Result,const ASTContext & Ctx,ConstantExprKind Kind) const15086 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15087                                   ConstantExprKind Kind) const {
15088   assert(!isValueDependent() &&
15089          "Expression evaluator can't be called on a dependent expression.");
15090 
15091   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15092   EvalInfo Info(Ctx, Result, EM);
15093   Info.InConstantContext = true;
15094 
15095   // The type of the object we're initializing is 'const T' for a class NTTP.
15096   QualType T = getType();
15097   if (Kind == ConstantExprKind::ClassTemplateArgument)
15098     T.addConst();
15099 
15100   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15101   // represent the result of the evaluation. CheckConstantExpression ensures
15102   // this doesn't escape.
15103   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15104   APValue::LValueBase Base(&BaseMTE);
15105 
15106   Info.setEvaluatingDecl(Base, Result.Val);
15107   LValue LVal;
15108   LVal.set(Base);
15109 
15110   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
15111     return false;
15112 
15113   if (!Info.discardCleanups())
15114     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15115 
15116   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15117                                Result.Val, Kind))
15118     return false;
15119   if (!CheckMemoryLeaks(Info))
15120     return false;
15121 
15122   // If this is a class template argument, it's required to have constant
15123   // destruction too.
15124   if (Kind == ConstantExprKind::ClassTemplateArgument &&
15125       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15126                             true) ||
15127        Result.HasSideEffects)) {
15128     // FIXME: Prefix a note to indicate that the problem is lack of constant
15129     // destruction.
15130     return false;
15131   }
15132 
15133   return true;
15134 }
15135 
EvaluateAsInitializer(APValue & Value,const ASTContext & Ctx,const VarDecl * VD,SmallVectorImpl<PartialDiagnosticAt> & Notes,bool IsConstantInitialization) const15136 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15137                                  const VarDecl *VD,
15138                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
15139                                  bool IsConstantInitialization) const {
15140   assert(!isValueDependent() &&
15141          "Expression evaluator can't be called on a dependent expression.");
15142 
15143   // FIXME: Evaluating initializers for large array and record types can cause
15144   // performance problems. Only do so in C++11 for now.
15145   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15146       !Ctx.getLangOpts().CPlusPlus11)
15147     return false;
15148 
15149   Expr::EvalStatus EStatus;
15150   EStatus.Diag = &Notes;
15151 
15152   EvalInfo Info(Ctx, EStatus,
15153                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
15154                     ? EvalInfo::EM_ConstantExpression
15155                     : EvalInfo::EM_ConstantFold);
15156   Info.setEvaluatingDecl(VD, Value);
15157   Info.InConstantContext = IsConstantInitialization;
15158 
15159   SourceLocation DeclLoc = VD->getLocation();
15160   QualType DeclTy = VD->getType();
15161 
15162   if (Info.EnableNewConstInterp) {
15163     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15164     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15165       return false;
15166   } else {
15167     LValue LVal;
15168     LVal.set(VD);
15169 
15170     if (!EvaluateInPlace(Value, Info, LVal, this,
15171                          /*AllowNonLiteralTypes=*/true) ||
15172         EStatus.HasSideEffects)
15173       return false;
15174 
15175     // At this point, any lifetime-extended temporaries are completely
15176     // initialized.
15177     Info.performLifetimeExtension();
15178 
15179     if (!Info.discardCleanups())
15180       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15181   }
15182   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15183                                  ConstantExprKind::Normal) &&
15184          CheckMemoryLeaks(Info);
15185 }
15186 
evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> & Notes) const15187 bool VarDecl::evaluateDestruction(
15188     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15189   Expr::EvalStatus EStatus;
15190   EStatus.Diag = &Notes;
15191 
15192   // Only treat the destruction as constant destruction if we formally have
15193   // constant initialization (or are usable in a constant expression).
15194   bool IsConstantDestruction = hasConstantInitialization();
15195 
15196   // Make a copy of the value for the destructor to mutate, if we know it.
15197   // Otherwise, treat the value as default-initialized; if the destructor works
15198   // anyway, then the destruction is constant (and must be essentially empty).
15199   APValue DestroyedValue;
15200   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15201     DestroyedValue = *getEvaluatedValue();
15202   else if (!getDefaultInitValue(getType(), DestroyedValue))
15203     return false;
15204 
15205   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15206                            getType(), getLocation(), EStatus,
15207                            IsConstantDestruction) ||
15208       EStatus.HasSideEffects)
15209     return false;
15210 
15211   ensureEvaluatedStmt()->HasConstantDestruction = true;
15212   return true;
15213 }
15214 
15215 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15216 /// constant folded, but discard the result.
isEvaluatable(const ASTContext & Ctx,SideEffectsKind SEK) const15217 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15218   assert(!isValueDependent() &&
15219          "Expression evaluator can't be called on a dependent expression.");
15220 
15221   EvalResult Result;
15222   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15223          !hasUnacceptableSideEffect(Result, SEK);
15224 }
15225 
EvaluateKnownConstInt(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const15226 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15227                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15228   assert(!isValueDependent() &&
15229          "Expression evaluator can't be called on a dependent expression.");
15230 
15231   EvalResult EVResult;
15232   EVResult.Diag = Diag;
15233   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15234   Info.InConstantContext = true;
15235 
15236   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15237   (void)Result;
15238   assert(Result && "Could not evaluate expression");
15239   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15240 
15241   return EVResult.Val.getInt();
15242 }
15243 
EvaluateKnownConstIntCheckOverflow(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const15244 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15245     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15246   assert(!isValueDependent() &&
15247          "Expression evaluator can't be called on a dependent expression.");
15248 
15249   EvalResult EVResult;
15250   EVResult.Diag = Diag;
15251   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15252   Info.InConstantContext = true;
15253   Info.CheckingForUndefinedBehavior = true;
15254 
15255   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15256   (void)Result;
15257   assert(Result && "Could not evaluate expression");
15258   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15259 
15260   return EVResult.Val.getInt();
15261 }
15262 
EvaluateForOverflow(const ASTContext & Ctx) const15263 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15264   assert(!isValueDependent() &&
15265          "Expression evaluator can't be called on a dependent expression.");
15266 
15267   bool IsConst;
15268   EvalResult EVResult;
15269   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15270     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15271     Info.CheckingForUndefinedBehavior = true;
15272     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15273   }
15274 }
15275 
isGlobalLValue() const15276 bool Expr::EvalResult::isGlobalLValue() const {
15277   assert(Val.isLValue());
15278   return IsGlobalLValue(Val.getLValueBase());
15279 }
15280 
15281 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15282 /// an integer constant expression.
15283 
15284 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15285 /// comma, etc
15286 
15287 // CheckICE - This function does the fundamental ICE checking: the returned
15288 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15289 // and a (possibly null) SourceLocation indicating the location of the problem.
15290 //
15291 // Note that to reduce code duplication, this helper does no evaluation
15292 // itself; the caller checks whether the expression is evaluatable, and
15293 // in the rare cases where CheckICE actually cares about the evaluated
15294 // value, it calls into Evaluate.
15295 
15296 namespace {
15297 
15298 enum ICEKind {
15299   /// This expression is an ICE.
15300   IK_ICE,
15301   /// This expression is not an ICE, but if it isn't evaluated, it's
15302   /// a legal subexpression for an ICE. This return value is used to handle
15303   /// the comma operator in C99 mode, and non-constant subexpressions.
15304   IK_ICEIfUnevaluated,
15305   /// This expression is not an ICE, and is not a legal subexpression for one.
15306   IK_NotICE
15307 };
15308 
15309 struct ICEDiag {
15310   ICEKind Kind;
15311   SourceLocation Loc;
15312 
ICEDiag__anon7a1fdcea3511::ICEDiag15313   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15314 };
15315 
15316 }
15317 
NoDiag()15318 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15319 
Worst(ICEDiag A,ICEDiag B)15320 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15321 
CheckEvalInICE(const Expr * E,const ASTContext & Ctx)15322 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15323   Expr::EvalResult EVResult;
15324   Expr::EvalStatus Status;
15325   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15326 
15327   Info.InConstantContext = true;
15328   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15329       !EVResult.Val.isInt())
15330     return ICEDiag(IK_NotICE, E->getBeginLoc());
15331 
15332   return NoDiag();
15333 }
15334 
CheckICE(const Expr * E,const ASTContext & Ctx)15335 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15336   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15337   if (!E->getType()->isIntegralOrEnumerationType())
15338     return ICEDiag(IK_NotICE, E->getBeginLoc());
15339 
15340   switch (E->getStmtClass()) {
15341 #define ABSTRACT_STMT(Node)
15342 #define STMT(Node, Base) case Expr::Node##Class:
15343 #define EXPR(Node, Base)
15344 #include "clang/AST/StmtNodes.inc"
15345   case Expr::PredefinedExprClass:
15346   case Expr::FloatingLiteralClass:
15347   case Expr::ImaginaryLiteralClass:
15348   case Expr::StringLiteralClass:
15349   case Expr::ArraySubscriptExprClass:
15350   case Expr::MatrixSubscriptExprClass:
15351   case Expr::OMPArraySectionExprClass:
15352   case Expr::OMPArrayShapingExprClass:
15353   case Expr::OMPIteratorExprClass:
15354   case Expr::MemberExprClass:
15355   case Expr::CompoundAssignOperatorClass:
15356   case Expr::CompoundLiteralExprClass:
15357   case Expr::ExtVectorElementExprClass:
15358   case Expr::DesignatedInitExprClass:
15359   case Expr::ArrayInitLoopExprClass:
15360   case Expr::ArrayInitIndexExprClass:
15361   case Expr::NoInitExprClass:
15362   case Expr::DesignatedInitUpdateExprClass:
15363   case Expr::ImplicitValueInitExprClass:
15364   case Expr::ParenListExprClass:
15365   case Expr::VAArgExprClass:
15366   case Expr::AddrLabelExprClass:
15367   case Expr::StmtExprClass:
15368   case Expr::CXXMemberCallExprClass:
15369   case Expr::CUDAKernelCallExprClass:
15370   case Expr::CXXAddrspaceCastExprClass:
15371   case Expr::CXXDynamicCastExprClass:
15372   case Expr::CXXTypeidExprClass:
15373   case Expr::CXXUuidofExprClass:
15374   case Expr::MSPropertyRefExprClass:
15375   case Expr::MSPropertySubscriptExprClass:
15376   case Expr::CXXNullPtrLiteralExprClass:
15377   case Expr::UserDefinedLiteralClass:
15378   case Expr::CXXThisExprClass:
15379   case Expr::CXXThrowExprClass:
15380   case Expr::CXXNewExprClass:
15381   case Expr::CXXDeleteExprClass:
15382   case Expr::CXXPseudoDestructorExprClass:
15383   case Expr::UnresolvedLookupExprClass:
15384   case Expr::TypoExprClass:
15385   case Expr::RecoveryExprClass:
15386   case Expr::DependentScopeDeclRefExprClass:
15387   case Expr::CXXConstructExprClass:
15388   case Expr::CXXInheritedCtorInitExprClass:
15389   case Expr::CXXStdInitializerListExprClass:
15390   case Expr::CXXBindTemporaryExprClass:
15391   case Expr::ExprWithCleanupsClass:
15392   case Expr::CXXTemporaryObjectExprClass:
15393   case Expr::CXXUnresolvedConstructExprClass:
15394   case Expr::CXXDependentScopeMemberExprClass:
15395   case Expr::UnresolvedMemberExprClass:
15396   case Expr::ObjCStringLiteralClass:
15397   case Expr::ObjCBoxedExprClass:
15398   case Expr::ObjCArrayLiteralClass:
15399   case Expr::ObjCDictionaryLiteralClass:
15400   case Expr::ObjCEncodeExprClass:
15401   case Expr::ObjCMessageExprClass:
15402   case Expr::ObjCSelectorExprClass:
15403   case Expr::ObjCProtocolExprClass:
15404   case Expr::ObjCIvarRefExprClass:
15405   case Expr::ObjCPropertyRefExprClass:
15406   case Expr::ObjCSubscriptRefExprClass:
15407   case Expr::ObjCIsaExprClass:
15408   case Expr::ObjCAvailabilityCheckExprClass:
15409   case Expr::ShuffleVectorExprClass:
15410   case Expr::ConvertVectorExprClass:
15411   case Expr::BlockExprClass:
15412   case Expr::NoStmtClass:
15413   case Expr::OpaqueValueExprClass:
15414   case Expr::PackExpansionExprClass:
15415   case Expr::SubstNonTypeTemplateParmPackExprClass:
15416   case Expr::FunctionParmPackExprClass:
15417   case Expr::AsTypeExprClass:
15418   case Expr::ObjCIndirectCopyRestoreExprClass:
15419   case Expr::MaterializeTemporaryExprClass:
15420   case Expr::PseudoObjectExprClass:
15421   case Expr::AtomicExprClass:
15422   case Expr::LambdaExprClass:
15423   case Expr::CXXFoldExprClass:
15424   case Expr::CoawaitExprClass:
15425   case Expr::DependentCoawaitExprClass:
15426   case Expr::CoyieldExprClass:
15427   case Expr::SYCLUniqueStableNameExprClass:
15428     return ICEDiag(IK_NotICE, E->getBeginLoc());
15429 
15430   case Expr::InitListExprClass: {
15431     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15432     // form "T x = { a };" is equivalent to "T x = a;".
15433     // Unless we're initializing a reference, T is a scalar as it is known to be
15434     // of integral or enumeration type.
15435     if (E->isPRValue())
15436       if (cast<InitListExpr>(E)->getNumInits() == 1)
15437         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15438     return ICEDiag(IK_NotICE, E->getBeginLoc());
15439   }
15440 
15441   case Expr::SizeOfPackExprClass:
15442   case Expr::GNUNullExprClass:
15443   case Expr::SourceLocExprClass:
15444     return NoDiag();
15445 
15446   case Expr::SubstNonTypeTemplateParmExprClass:
15447     return
15448       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15449 
15450   case Expr::ConstantExprClass:
15451     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15452 
15453   case Expr::ParenExprClass:
15454     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15455   case Expr::GenericSelectionExprClass:
15456     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15457   case Expr::IntegerLiteralClass:
15458   case Expr::FixedPointLiteralClass:
15459   case Expr::CharacterLiteralClass:
15460   case Expr::ObjCBoolLiteralExprClass:
15461   case Expr::CXXBoolLiteralExprClass:
15462   case Expr::CXXScalarValueInitExprClass:
15463   case Expr::TypeTraitExprClass:
15464   case Expr::ConceptSpecializationExprClass:
15465   case Expr::RequiresExprClass:
15466   case Expr::ArrayTypeTraitExprClass:
15467   case Expr::ExpressionTraitExprClass:
15468   case Expr::CXXNoexceptExprClass:
15469     return NoDiag();
15470   case Expr::CallExprClass:
15471   case Expr::CXXOperatorCallExprClass: {
15472     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15473     // constant expressions, but they can never be ICEs because an ICE cannot
15474     // contain an operand of (pointer to) function type.
15475     const CallExpr *CE = cast<CallExpr>(E);
15476     if (CE->getBuiltinCallee())
15477       return CheckEvalInICE(E, Ctx);
15478     return ICEDiag(IK_NotICE, E->getBeginLoc());
15479   }
15480   case Expr::CXXRewrittenBinaryOperatorClass:
15481     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15482                     Ctx);
15483   case Expr::DeclRefExprClass: {
15484     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15485     if (isa<EnumConstantDecl>(D))
15486       return NoDiag();
15487 
15488     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15489     // integer variables in constant expressions:
15490     //
15491     // C++ 7.1.5.1p2
15492     //   A variable of non-volatile const-qualified integral or enumeration
15493     //   type initialized by an ICE can be used in ICEs.
15494     //
15495     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15496     // that mode, use of reference variables should not be allowed.
15497     const VarDecl *VD = dyn_cast<VarDecl>(D);
15498     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15499         !VD->getType()->isReferenceType())
15500       return NoDiag();
15501 
15502     return ICEDiag(IK_NotICE, E->getBeginLoc());
15503   }
15504   case Expr::UnaryOperatorClass: {
15505     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15506     switch (Exp->getOpcode()) {
15507     case UO_PostInc:
15508     case UO_PostDec:
15509     case UO_PreInc:
15510     case UO_PreDec:
15511     case UO_AddrOf:
15512     case UO_Deref:
15513     case UO_Coawait:
15514       // C99 6.6/3 allows increment and decrement within unevaluated
15515       // subexpressions of constant expressions, but they can never be ICEs
15516       // because an ICE cannot contain an lvalue operand.
15517       return ICEDiag(IK_NotICE, E->getBeginLoc());
15518     case UO_Extension:
15519     case UO_LNot:
15520     case UO_Plus:
15521     case UO_Minus:
15522     case UO_Not:
15523     case UO_Real:
15524     case UO_Imag:
15525       return CheckICE(Exp->getSubExpr(), Ctx);
15526     }
15527     llvm_unreachable("invalid unary operator class");
15528   }
15529   case Expr::OffsetOfExprClass: {
15530     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15531     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15532     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15533     // compliance: we should warn earlier for offsetof expressions with
15534     // array subscripts that aren't ICEs, and if the array subscripts
15535     // are ICEs, the value of the offsetof must be an integer constant.
15536     return CheckEvalInICE(E, Ctx);
15537   }
15538   case Expr::UnaryExprOrTypeTraitExprClass: {
15539     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15540     if ((Exp->getKind() ==  UETT_SizeOf) &&
15541         Exp->getTypeOfArgument()->isVariableArrayType())
15542       return ICEDiag(IK_NotICE, E->getBeginLoc());
15543     return NoDiag();
15544   }
15545   case Expr::BinaryOperatorClass: {
15546     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15547     switch (Exp->getOpcode()) {
15548     case BO_PtrMemD:
15549     case BO_PtrMemI:
15550     case BO_Assign:
15551     case BO_MulAssign:
15552     case BO_DivAssign:
15553     case BO_RemAssign:
15554     case BO_AddAssign:
15555     case BO_SubAssign:
15556     case BO_ShlAssign:
15557     case BO_ShrAssign:
15558     case BO_AndAssign:
15559     case BO_XorAssign:
15560     case BO_OrAssign:
15561       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15562       // constant expressions, but they can never be ICEs because an ICE cannot
15563       // contain an lvalue operand.
15564       return ICEDiag(IK_NotICE, E->getBeginLoc());
15565 
15566     case BO_Mul:
15567     case BO_Div:
15568     case BO_Rem:
15569     case BO_Add:
15570     case BO_Sub:
15571     case BO_Shl:
15572     case BO_Shr:
15573     case BO_LT:
15574     case BO_GT:
15575     case BO_LE:
15576     case BO_GE:
15577     case BO_EQ:
15578     case BO_NE:
15579     case BO_And:
15580     case BO_Xor:
15581     case BO_Or:
15582     case BO_Comma:
15583     case BO_Cmp: {
15584       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15585       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15586       if (Exp->getOpcode() == BO_Div ||
15587           Exp->getOpcode() == BO_Rem) {
15588         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15589         // we don't evaluate one.
15590         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15591           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15592           if (REval == 0)
15593             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15594           if (REval.isSigned() && REval.isAllOnes()) {
15595             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15596             if (LEval.isMinSignedValue())
15597               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15598           }
15599         }
15600       }
15601       if (Exp->getOpcode() == BO_Comma) {
15602         if (Ctx.getLangOpts().C99) {
15603           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15604           // if it isn't evaluated.
15605           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15606             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15607         } else {
15608           // In both C89 and C++, commas in ICEs are illegal.
15609           return ICEDiag(IK_NotICE, E->getBeginLoc());
15610         }
15611       }
15612       return Worst(LHSResult, RHSResult);
15613     }
15614     case BO_LAnd:
15615     case BO_LOr: {
15616       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15617       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15618       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15619         // Rare case where the RHS has a comma "side-effect"; we need
15620         // to actually check the condition to see whether the side
15621         // with the comma is evaluated.
15622         if ((Exp->getOpcode() == BO_LAnd) !=
15623             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15624           return RHSResult;
15625         return NoDiag();
15626       }
15627 
15628       return Worst(LHSResult, RHSResult);
15629     }
15630     }
15631     llvm_unreachable("invalid binary operator kind");
15632   }
15633   case Expr::ImplicitCastExprClass:
15634   case Expr::CStyleCastExprClass:
15635   case Expr::CXXFunctionalCastExprClass:
15636   case Expr::CXXStaticCastExprClass:
15637   case Expr::CXXReinterpretCastExprClass:
15638   case Expr::CXXConstCastExprClass:
15639   case Expr::ObjCBridgedCastExprClass: {
15640     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15641     if (isa<ExplicitCastExpr>(E)) {
15642       if (const FloatingLiteral *FL
15643             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15644         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15645         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15646         APSInt IgnoredVal(DestWidth, !DestSigned);
15647         bool Ignored;
15648         // If the value does not fit in the destination type, the behavior is
15649         // undefined, so we are not required to treat it as a constant
15650         // expression.
15651         if (FL->getValue().convertToInteger(IgnoredVal,
15652                                             llvm::APFloat::rmTowardZero,
15653                                             &Ignored) & APFloat::opInvalidOp)
15654           return ICEDiag(IK_NotICE, E->getBeginLoc());
15655         return NoDiag();
15656       }
15657     }
15658     switch (cast<CastExpr>(E)->getCastKind()) {
15659     case CK_LValueToRValue:
15660     case CK_AtomicToNonAtomic:
15661     case CK_NonAtomicToAtomic:
15662     case CK_NoOp:
15663     case CK_IntegralToBoolean:
15664     case CK_IntegralCast:
15665       return CheckICE(SubExpr, Ctx);
15666     default:
15667       return ICEDiag(IK_NotICE, E->getBeginLoc());
15668     }
15669   }
15670   case Expr::BinaryConditionalOperatorClass: {
15671     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15672     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15673     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15674     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15675     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15676     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15677     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15678         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15679     return FalseResult;
15680   }
15681   case Expr::ConditionalOperatorClass: {
15682     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15683     // If the condition (ignoring parens) is a __builtin_constant_p call,
15684     // then only the true side is actually considered in an integer constant
15685     // expression, and it is fully evaluated.  This is an important GNU
15686     // extension.  See GCC PR38377 for discussion.
15687     if (const CallExpr *CallCE
15688         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15689       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15690         return CheckEvalInICE(E, Ctx);
15691     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15692     if (CondResult.Kind == IK_NotICE)
15693       return CondResult;
15694 
15695     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15696     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15697 
15698     if (TrueResult.Kind == IK_NotICE)
15699       return TrueResult;
15700     if (FalseResult.Kind == IK_NotICE)
15701       return FalseResult;
15702     if (CondResult.Kind == IK_ICEIfUnevaluated)
15703       return CondResult;
15704     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15705       return NoDiag();
15706     // Rare case where the diagnostics depend on which side is evaluated
15707     // Note that if we get here, CondResult is 0, and at least one of
15708     // TrueResult and FalseResult is non-zero.
15709     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15710       return FalseResult;
15711     return TrueResult;
15712   }
15713   case Expr::CXXDefaultArgExprClass:
15714     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15715   case Expr::CXXDefaultInitExprClass:
15716     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15717   case Expr::ChooseExprClass: {
15718     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15719   }
15720   case Expr::BuiltinBitCastExprClass: {
15721     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15722       return ICEDiag(IK_NotICE, E->getBeginLoc());
15723     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15724   }
15725   }
15726 
15727   llvm_unreachable("Invalid StmtClass!");
15728 }
15729 
15730 /// Evaluate an expression as a C++11 integral constant expression.
EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext & Ctx,const Expr * E,llvm::APSInt * Value,SourceLocation * Loc)15731 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15732                                                     const Expr *E,
15733                                                     llvm::APSInt *Value,
15734                                                     SourceLocation *Loc) {
15735   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15736     if (Loc) *Loc = E->getExprLoc();
15737     return false;
15738   }
15739 
15740   APValue Result;
15741   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15742     return false;
15743 
15744   if (!Result.isInt()) {
15745     if (Loc) *Loc = E->getExprLoc();
15746     return false;
15747   }
15748 
15749   if (Value) *Value = Result.getInt();
15750   return true;
15751 }
15752 
isIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc) const15753 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15754                                  SourceLocation *Loc) const {
15755   assert(!isValueDependent() &&
15756          "Expression evaluator can't be called on a dependent expression.");
15757 
15758   if (Ctx.getLangOpts().CPlusPlus11)
15759     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15760 
15761   ICEDiag D = CheckICE(this, Ctx);
15762   if (D.Kind != IK_ICE) {
15763     if (Loc) *Loc = D.Loc;
15764     return false;
15765   }
15766   return true;
15767 }
15768 
getIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc,bool isEvaluated) const15769 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15770                                                     SourceLocation *Loc,
15771                                                     bool isEvaluated) const {
15772   if (isValueDependent()) {
15773     // Expression evaluator can't succeed on a dependent expression.
15774     return None;
15775   }
15776 
15777   APSInt Value;
15778 
15779   if (Ctx.getLangOpts().CPlusPlus11) {
15780     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15781       return Value;
15782     return None;
15783   }
15784 
15785   if (!isIntegerConstantExpr(Ctx, Loc))
15786     return None;
15787 
15788   // The only possible side-effects here are due to UB discovered in the
15789   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15790   // required to treat the expression as an ICE, so we produce the folded
15791   // value.
15792   EvalResult ExprResult;
15793   Expr::EvalStatus Status;
15794   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15795   Info.InConstantContext = true;
15796 
15797   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15798     llvm_unreachable("ICE cannot be evaluated!");
15799 
15800   return ExprResult.Val.getInt();
15801 }
15802 
isCXX98IntegralConstantExpr(const ASTContext & Ctx) const15803 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15804   assert(!isValueDependent() &&
15805          "Expression evaluator can't be called on a dependent expression.");
15806 
15807   return CheckICE(this, Ctx).Kind == IK_ICE;
15808 }
15809 
isCXX11ConstantExpr(const ASTContext & Ctx,APValue * Result,SourceLocation * Loc) const15810 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15811                                SourceLocation *Loc) const {
15812   assert(!isValueDependent() &&
15813          "Expression evaluator can't be called on a dependent expression.");
15814 
15815   // We support this checking in C++98 mode in order to diagnose compatibility
15816   // issues.
15817   assert(Ctx.getLangOpts().CPlusPlus);
15818 
15819   // Build evaluation settings.
15820   Expr::EvalStatus Status;
15821   SmallVector<PartialDiagnosticAt, 8> Diags;
15822   Status.Diag = &Diags;
15823   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15824 
15825   APValue Scratch;
15826   bool IsConstExpr =
15827       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15828       // FIXME: We don't produce a diagnostic for this, but the callers that
15829       // call us on arbitrary full-expressions should generally not care.
15830       Info.discardCleanups() && !Status.HasSideEffects;
15831 
15832   if (!Diags.empty()) {
15833     IsConstExpr = false;
15834     if (Loc) *Loc = Diags[0].first;
15835   } else if (!IsConstExpr) {
15836     // FIXME: This shouldn't happen.
15837     if (Loc) *Loc = getExprLoc();
15838   }
15839 
15840   return IsConstExpr;
15841 }
15842 
EvaluateWithSubstitution(APValue & Value,ASTContext & Ctx,const FunctionDecl * Callee,ArrayRef<const Expr * > Args,const Expr * This) const15843 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15844                                     const FunctionDecl *Callee,
15845                                     ArrayRef<const Expr*> Args,
15846                                     const Expr *This) const {
15847   assert(!isValueDependent() &&
15848          "Expression evaluator can't be called on a dependent expression.");
15849 
15850   Expr::EvalStatus Status;
15851   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15852   Info.InConstantContext = true;
15853 
15854   LValue ThisVal;
15855   const LValue *ThisPtr = nullptr;
15856   if (This) {
15857 #ifndef NDEBUG
15858     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15859     assert(MD && "Don't provide `this` for non-methods.");
15860     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15861 #endif
15862     if (!This->isValueDependent() &&
15863         EvaluateObjectArgument(Info, This, ThisVal) &&
15864         !Info.EvalStatus.HasSideEffects)
15865       ThisPtr = &ThisVal;
15866 
15867     // Ignore any side-effects from a failed evaluation. This is safe because
15868     // they can't interfere with any other argument evaluation.
15869     Info.EvalStatus.HasSideEffects = false;
15870   }
15871 
15872   CallRef Call = Info.CurrentCall->createCall(Callee);
15873   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15874        I != E; ++I) {
15875     unsigned Idx = I - Args.begin();
15876     if (Idx >= Callee->getNumParams())
15877       break;
15878     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15879     if ((*I)->isValueDependent() ||
15880         !EvaluateCallArg(PVD, *I, Call, Info) ||
15881         Info.EvalStatus.HasSideEffects) {
15882       // If evaluation fails, throw away the argument entirely.
15883       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15884         *Slot = APValue();
15885     }
15886 
15887     // Ignore any side-effects from a failed evaluation. This is safe because
15888     // they can't interfere with any other argument evaluation.
15889     Info.EvalStatus.HasSideEffects = false;
15890   }
15891 
15892   // Parameter cleanups happen in the caller and are not part of this
15893   // evaluation.
15894   Info.discardCleanups();
15895   Info.EvalStatus.HasSideEffects = false;
15896 
15897   // Build fake call to Callee.
15898   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15899   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15900   FullExpressionRAII Scope(Info);
15901   return Evaluate(Value, Info, this) && Scope.destroy() &&
15902          !Info.EvalStatus.HasSideEffects;
15903 }
15904 
isPotentialConstantExpr(const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)15905 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15906                                    SmallVectorImpl<
15907                                      PartialDiagnosticAt> &Diags) {
15908   // FIXME: It would be useful to check constexpr function templates, but at the
15909   // moment the constant expression evaluator cannot cope with the non-rigorous
15910   // ASTs which we build for dependent expressions.
15911   if (FD->isDependentContext())
15912     return true;
15913 
15914   Expr::EvalStatus Status;
15915   Status.Diag = &Diags;
15916 
15917   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15918   Info.InConstantContext = true;
15919   Info.CheckingPotentialConstantExpression = true;
15920 
15921   // The constexpr VM attempts to compile all methods to bytecode here.
15922   if (Info.EnableNewConstInterp) {
15923     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15924     return Diags.empty();
15925   }
15926 
15927   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15928   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15929 
15930   // Fabricate an arbitrary expression on the stack and pretend that it
15931   // is a temporary being used as the 'this' pointer.
15932   LValue This;
15933   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15934   This.set({&VIE, Info.CurrentCall->Index});
15935 
15936   ArrayRef<const Expr*> Args;
15937 
15938   APValue Scratch;
15939   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15940     // Evaluate the call as a constant initializer, to allow the construction
15941     // of objects of non-literal types.
15942     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15943     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15944   } else {
15945     SourceLocation Loc = FD->getLocation();
15946     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15947                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15948   }
15949 
15950   return Diags.empty();
15951 }
15952 
isPotentialConstantExprUnevaluated(Expr * E,const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)15953 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15954                                               const FunctionDecl *FD,
15955                                               SmallVectorImpl<
15956                                                 PartialDiagnosticAt> &Diags) {
15957   assert(!E->isValueDependent() &&
15958          "Expression evaluator can't be called on a dependent expression.");
15959 
15960   Expr::EvalStatus Status;
15961   Status.Diag = &Diags;
15962 
15963   EvalInfo Info(FD->getASTContext(), Status,
15964                 EvalInfo::EM_ConstantExpressionUnevaluated);
15965   Info.InConstantContext = true;
15966   Info.CheckingPotentialConstantExpression = true;
15967 
15968   // Fabricate a call stack frame to give the arguments a plausible cover story.
15969   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15970 
15971   APValue ResultScratch;
15972   Evaluate(ResultScratch, Info, E);
15973   return Diags.empty();
15974 }
15975 
tryEvaluateObjectSize(uint64_t & Result,ASTContext & Ctx,unsigned Type) const15976 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15977                                  unsigned Type) const {
15978   if (!getType()->isPointerType())
15979     return false;
15980 
15981   Expr::EvalStatus Status;
15982   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15983   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15984 }
15985 
EvaluateBuiltinStrLen(const Expr * E,uint64_t & Result,EvalInfo & Info)15986 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
15987                                   EvalInfo &Info) {
15988   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
15989     return false;
15990 
15991   LValue String;
15992 
15993   if (!EvaluatePointer(E, String, Info))
15994     return false;
15995 
15996   QualType CharTy = E->getType()->getPointeeType();
15997 
15998   // Fast path: if it's a string literal, search the string value.
15999   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
16000           String.getLValueBase().dyn_cast<const Expr *>())) {
16001     StringRef Str = S->getBytes();
16002     int64_t Off = String.Offset.getQuantity();
16003     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
16004         S->getCharByteWidth() == 1 &&
16005         // FIXME: Add fast-path for wchar_t too.
16006         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
16007       Str = Str.substr(Off);
16008 
16009       StringRef::size_type Pos = Str.find(0);
16010       if (Pos != StringRef::npos)
16011         Str = Str.substr(0, Pos);
16012 
16013       Result = Str.size();
16014       return true;
16015     }
16016 
16017     // Fall through to slow path.
16018   }
16019 
16020   // Slow path: scan the bytes of the string looking for the terminating 0.
16021   for (uint64_t Strlen = 0; /**/; ++Strlen) {
16022     APValue Char;
16023     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16024         !Char.isInt())
16025       return false;
16026     if (!Char.getInt()) {
16027       Result = Strlen;
16028       return true;
16029     }
16030     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16031       return false;
16032   }
16033 }
16034 
tryEvaluateStrLen(uint64_t & Result,ASTContext & Ctx) const16035 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
16036   Expr::EvalStatus Status;
16037   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16038   return EvaluateBuiltinStrLen(this, Result, Info);
16039 }
16040