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__anon4a4db2530111::SubobjectDesignator272     SubobjectDesignator() : Invalid(true) {}
273 
SubobjectDesignator__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530111::CallRef495     CallRef() : OrigCallee(), CallIndex(0), Version() {}
CallRef__anon4a4db2530111::CallRef496     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
498 
operator bool__anon4a4db2530111::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__anon4a4db2530111::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__anon4a4db2530311::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 ()__anon4a4db2530311::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__anon4a4db2530311::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__anon4a4db2530311::EvalInfo::EvaluatingConstructorRAII867       void finishedConstructingBases() {
868         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
869       }
finishedConstructingFields__anon4a4db2530311::EvalInfo::EvaluatingConstructorRAII870       void finishedConstructingFields() {
871         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
872       }
~EvaluatingConstructorRAII__anon4a4db2530311::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__anon4a4db2530311::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__anon4a4db2530311::EvalInfo::EvaluatingDestructorRAII888       void startedDestroyingBases() {
889         EI.ObjectsUnderConstruction[Object] =
890             ConstructionPhase::DestroyingBases;
891       }
~EvaluatingDestructorRAII__anon4a4db2530311::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 
setEvaluatingDecl(APValue::LValueBase Base,APValue & Value,EvaluatingDeclKind EDK=EvaluatingDeclKind::Ctor)986     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
987                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
988       EvaluatingDecl = Base;
989       IsEvaluatingDecl = EDK;
990       EvaluatingDeclValue = &Value;
991     }
992 
CheckCallLimit(SourceLocation Loc)993     bool CheckCallLimit(SourceLocation Loc) {
994       // Don't perform any constexpr calls (other than the call we're checking)
995       // when checking a potential constant expression.
996       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
997         return false;
998       if (NextCallIndex == 0) {
999         // NextCallIndex has wrapped around.
1000         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1001         return false;
1002       }
1003       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1004         return true;
1005       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1006         << getLangOpts().ConstexprCallDepth;
1007       return false;
1008     }
1009 
1010     std::pair<CallStackFrame *, unsigned>
getCallFrameAndDepth(unsigned CallIndex)1011     getCallFrameAndDepth(unsigned CallIndex) {
1012       assert(CallIndex && "no call index in getCallFrameAndDepth");
1013       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1014       // be null in this loop.
1015       unsigned Depth = CallStackDepth;
1016       CallStackFrame *Frame = CurrentCall;
1017       while (Frame->Index > CallIndex) {
1018         Frame = Frame->Caller;
1019         --Depth;
1020       }
1021       if (Frame->Index == CallIndex)
1022         return {Frame, Depth};
1023       return {nullptr, 0};
1024     }
1025 
nextStep(const Stmt * S)1026     bool nextStep(const Stmt *S) {
1027       if (!StepsLeft) {
1028         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1029         return false;
1030       }
1031       --StepsLeft;
1032       return true;
1033     }
1034 
1035     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1036 
lookupDynamicAlloc(DynamicAllocLValue DA)1037     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1038       Optional<DynAlloc*> Result;
1039       auto It = HeapAllocs.find(DA);
1040       if (It != HeapAllocs.end())
1041         Result = &It->second;
1042       return Result;
1043     }
1044 
1045     /// Get the allocated storage for the given parameter of the given call.
getParamSlot(CallRef Call,const ParmVarDecl * PVD)1046     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1047       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1048       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1049                    : nullptr;
1050     }
1051 
1052     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1053     struct StdAllocatorCaller {
1054       unsigned FrameIndex;
1055       QualType ElemType;
operator bool__anon4a4db2530311::EvalInfo::StdAllocatorCaller1056       explicit operator bool() const { return FrameIndex != 0; };
1057     };
1058 
getStdAllocatorCaller(StringRef FnName) const1059     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1060       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1061            Call = Call->Caller) {
1062         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1063         if (!MD)
1064           continue;
1065         const IdentifierInfo *FnII = MD->getIdentifier();
1066         if (!FnII || !FnII->isStr(FnName))
1067           continue;
1068 
1069         const auto *CTSD =
1070             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1071         if (!CTSD)
1072           continue;
1073 
1074         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1075         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1076         if (CTSD->isInStdNamespace() && ClassII &&
1077             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1078             TAL[0].getKind() == TemplateArgument::Type)
1079           return {Call->Index, TAL[0].getAsType()};
1080       }
1081 
1082       return {};
1083     }
1084 
performLifetimeExtension()1085     void performLifetimeExtension() {
1086       // Disable the cleanups for lifetime-extended temporaries.
1087       CleanupStack.erase(std::remove_if(CleanupStack.begin(),
1088                                         CleanupStack.end(),
1089                                         [](Cleanup &C) {
1090                                           return !C.isDestroyedAtEndOf(
1091                                               ScopeKind::FullExpression);
1092                                         }),
1093                          CleanupStack.end());
1094      }
1095 
1096     /// Throw away any remaining cleanups at the end of evaluation. If any
1097     /// cleanups would have had a side-effect, note that as an unmodeled
1098     /// side-effect and return false. Otherwise, return true.
discardCleanups()1099     bool discardCleanups() {
1100       for (Cleanup &C : CleanupStack) {
1101         if (C.hasSideEffect() && !noteSideEffect()) {
1102           CleanupStack.clear();
1103           return false;
1104         }
1105       }
1106       CleanupStack.clear();
1107       return true;
1108     }
1109 
1110   private:
getCurrentFrame()1111     interp::Frame *getCurrentFrame() override { return CurrentCall; }
getBottomFrame() const1112     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1113 
hasActiveDiagnostic()1114     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
setActiveDiagnostic(bool Flag)1115     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1116 
setFoldFailureDiagnostic(bool Flag)1117     void setFoldFailureDiagnostic(bool Flag) override {
1118       HasFoldFailureDiagnostic = Flag;
1119     }
1120 
getEvalStatus() const1121     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1122 
getCtx() const1123     ASTContext &getCtx() const override { return Ctx; }
1124 
1125     // If we have a prior diagnostic, it will be noting that the expression
1126     // isn't a constant expression. This diagnostic is more important,
1127     // unless we require this evaluation to produce a constant expression.
1128     //
1129     // FIXME: We might want to show both diagnostics to the user in
1130     // EM_ConstantFold mode.
hasPriorDiagnostic()1131     bool hasPriorDiagnostic() override {
1132       if (!EvalStatus.Diag->empty()) {
1133         switch (EvalMode) {
1134         case EM_ConstantFold:
1135         case EM_IgnoreSideEffects:
1136           if (!HasFoldFailureDiagnostic)
1137             break;
1138           // We've already failed to fold something. Keep that diagnostic.
1139           LLVM_FALLTHROUGH;
1140         case EM_ConstantExpression:
1141         case EM_ConstantExpressionUnevaluated:
1142           setActiveDiagnostic(false);
1143           return true;
1144         }
1145       }
1146       return false;
1147     }
1148 
getCallStackDepth()1149     unsigned getCallStackDepth() override { return CallStackDepth; }
1150 
1151   public:
1152     /// Should we continue evaluation after encountering a side-effect that we
1153     /// couldn't model?
keepEvaluatingAfterSideEffect()1154     bool keepEvaluatingAfterSideEffect() {
1155       switch (EvalMode) {
1156       case EM_IgnoreSideEffects:
1157         return true;
1158 
1159       case EM_ConstantExpression:
1160       case EM_ConstantExpressionUnevaluated:
1161       case EM_ConstantFold:
1162         // By default, assume any side effect might be valid in some other
1163         // evaluation of this expression from a different context.
1164         return checkingPotentialConstantExpression() ||
1165                checkingForUndefinedBehavior();
1166       }
1167       llvm_unreachable("Missed EvalMode case");
1168     }
1169 
1170     /// Note that we have had a side-effect, and determine whether we should
1171     /// keep evaluating.
noteSideEffect()1172     bool noteSideEffect() {
1173       EvalStatus.HasSideEffects = true;
1174       return keepEvaluatingAfterSideEffect();
1175     }
1176 
1177     /// Should we continue evaluation after encountering undefined behavior?
keepEvaluatingAfterUndefinedBehavior()1178     bool keepEvaluatingAfterUndefinedBehavior() {
1179       switch (EvalMode) {
1180       case EM_IgnoreSideEffects:
1181       case EM_ConstantFold:
1182         return true;
1183 
1184       case EM_ConstantExpression:
1185       case EM_ConstantExpressionUnevaluated:
1186         return checkingForUndefinedBehavior();
1187       }
1188       llvm_unreachable("Missed EvalMode case");
1189     }
1190 
1191     /// Note that we hit something that was technically undefined behavior, but
1192     /// that we can evaluate past it (such as signed overflow or floating-point
1193     /// division by zero.)
noteUndefinedBehavior()1194     bool noteUndefinedBehavior() override {
1195       EvalStatus.HasUndefinedBehavior = true;
1196       return keepEvaluatingAfterUndefinedBehavior();
1197     }
1198 
1199     /// Should we continue evaluation as much as possible after encountering a
1200     /// construct which can't be reduced to a value?
keepEvaluatingAfterFailure() const1201     bool keepEvaluatingAfterFailure() const override {
1202       if (!StepsLeft)
1203         return false;
1204 
1205       switch (EvalMode) {
1206       case EM_ConstantExpression:
1207       case EM_ConstantExpressionUnevaluated:
1208       case EM_ConstantFold:
1209       case EM_IgnoreSideEffects:
1210         return checkingPotentialConstantExpression() ||
1211                checkingForUndefinedBehavior();
1212       }
1213       llvm_unreachable("Missed EvalMode case");
1214     }
1215 
1216     /// Notes that we failed to evaluate an expression that other expressions
1217     /// directly depend on, and determine if we should keep evaluating. This
1218     /// should only be called if we actually intend to keep evaluating.
1219     ///
1220     /// Call noteSideEffect() instead if we may be able to ignore the value that
1221     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1222     ///
1223     /// (Foo(), 1)      // use noteSideEffect
1224     /// (Foo() || true) // use noteSideEffect
1225     /// Foo() + 1       // use noteFailure
noteFailure()1226     LLVM_NODISCARD bool noteFailure() {
1227       // Failure when evaluating some expression often means there is some
1228       // subexpression whose evaluation was skipped. Therefore, (because we
1229       // don't track whether we skipped an expression when unwinding after an
1230       // evaluation failure) every evaluation failure that bubbles up from a
1231       // subexpression implies that a side-effect has potentially happened. We
1232       // skip setting the HasSideEffects flag to true until we decide to
1233       // continue evaluating after that point, which happens here.
1234       bool KeepGoing = keepEvaluatingAfterFailure();
1235       EvalStatus.HasSideEffects |= KeepGoing;
1236       return KeepGoing;
1237     }
1238 
1239     class ArrayInitLoopIndex {
1240       EvalInfo &Info;
1241       uint64_t OuterIndex;
1242 
1243     public:
ArrayInitLoopIndex(EvalInfo & Info)1244       ArrayInitLoopIndex(EvalInfo &Info)
1245           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1246         Info.ArrayInitIndex = 0;
1247       }
~ArrayInitLoopIndex()1248       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1249 
operator uint64_t&()1250       operator uint64_t&() { return Info.ArrayInitIndex; }
1251     };
1252   };
1253 
1254   /// Object used to treat all foldable expressions as constant expressions.
1255   struct FoldConstant {
1256     EvalInfo &Info;
1257     bool Enabled;
1258     bool HadNoPriorDiags;
1259     EvalInfo::EvaluationMode OldMode;
1260 
FoldConstant__anon4a4db2530311::FoldConstant1261     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1262       : Info(Info),
1263         Enabled(Enabled),
1264         HadNoPriorDiags(Info.EvalStatus.Diag &&
1265                         Info.EvalStatus.Diag->empty() &&
1266                         !Info.EvalStatus.HasSideEffects),
1267         OldMode(Info.EvalMode) {
1268       if (Enabled)
1269         Info.EvalMode = EvalInfo::EM_ConstantFold;
1270     }
keepDiagnostics__anon4a4db2530311::FoldConstant1271     void keepDiagnostics() { Enabled = false; }
~FoldConstant__anon4a4db2530311::FoldConstant1272     ~FoldConstant() {
1273       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1274           !Info.EvalStatus.HasSideEffects)
1275         Info.EvalStatus.Diag->clear();
1276       Info.EvalMode = OldMode;
1277     }
1278   };
1279 
1280   /// RAII object used to set the current evaluation mode to ignore
1281   /// side-effects.
1282   struct IgnoreSideEffectsRAII {
1283     EvalInfo &Info;
1284     EvalInfo::EvaluationMode OldMode;
IgnoreSideEffectsRAII__anon4a4db2530311::IgnoreSideEffectsRAII1285     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1286         : Info(Info), OldMode(Info.EvalMode) {
1287       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1288     }
1289 
~IgnoreSideEffectsRAII__anon4a4db2530311::IgnoreSideEffectsRAII1290     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1291   };
1292 
1293   /// RAII object used to optionally suppress diagnostics and side-effects from
1294   /// a speculative evaluation.
1295   class SpeculativeEvaluationRAII {
1296     EvalInfo *Info = nullptr;
1297     Expr::EvalStatus OldStatus;
1298     unsigned OldSpeculativeEvaluationDepth;
1299 
moveFromAndCancel(SpeculativeEvaluationRAII && Other)1300     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1301       Info = Other.Info;
1302       OldStatus = Other.OldStatus;
1303       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1304       Other.Info = nullptr;
1305     }
1306 
maybeRestoreState()1307     void maybeRestoreState() {
1308       if (!Info)
1309         return;
1310 
1311       Info->EvalStatus = OldStatus;
1312       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1313     }
1314 
1315   public:
1316     SpeculativeEvaluationRAII() = default;
1317 
SpeculativeEvaluationRAII(EvalInfo & Info,SmallVectorImpl<PartialDiagnosticAt> * NewDiag=nullptr)1318     SpeculativeEvaluationRAII(
1319         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1320         : Info(&Info), OldStatus(Info.EvalStatus),
1321           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1322       Info.EvalStatus.Diag = NewDiag;
1323       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1324     }
1325 
1326     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
SpeculativeEvaluationRAII(SpeculativeEvaluationRAII && Other)1327     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1328       moveFromAndCancel(std::move(Other));
1329     }
1330 
operator =(SpeculativeEvaluationRAII && Other)1331     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1332       maybeRestoreState();
1333       moveFromAndCancel(std::move(Other));
1334       return *this;
1335     }
1336 
~SpeculativeEvaluationRAII()1337     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1338   };
1339 
1340   /// RAII object wrapping a full-expression or block scope, and handling
1341   /// the ending of the lifetime of temporaries created within it.
1342   template<ScopeKind Kind>
1343   class ScopeRAII {
1344     EvalInfo &Info;
1345     unsigned OldStackSize;
1346   public:
ScopeRAII(EvalInfo & Info)1347     ScopeRAII(EvalInfo &Info)
1348         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1349       // Push a new temporary version. This is needed to distinguish between
1350       // temporaries created in different iterations of a loop.
1351       Info.CurrentCall->pushTempVersion();
1352     }
destroy(bool RunDestructors=true)1353     bool destroy(bool RunDestructors = true) {
1354       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1355       OldStackSize = -1U;
1356       return OK;
1357     }
~ScopeRAII()1358     ~ScopeRAII() {
1359       if (OldStackSize != -1U)
1360         destroy(false);
1361       // Body moved to a static method to encourage the compiler to inline away
1362       // instances of this class.
1363       Info.CurrentCall->popTempVersion();
1364     }
1365   private:
cleanup(EvalInfo & Info,bool RunDestructors,unsigned OldStackSize)1366     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1367                         unsigned OldStackSize) {
1368       assert(OldStackSize <= Info.CleanupStack.size() &&
1369              "running cleanups out of order?");
1370 
1371       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1372       // for a full-expression scope.
1373       bool Success = true;
1374       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1375         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1376           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1377             Success = false;
1378             break;
1379           }
1380         }
1381       }
1382 
1383       // Compact any retained cleanups.
1384       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1385       if (Kind != ScopeKind::Block)
1386         NewEnd =
1387             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1388               return C.isDestroyedAtEndOf(Kind);
1389             });
1390       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1391       return Success;
1392     }
1393   };
1394   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1395   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1396   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1397 }
1398 
checkSubobject(EvalInfo & Info,const Expr * E,CheckSubobjectKind CSK)1399 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1400                                          CheckSubobjectKind CSK) {
1401   if (Invalid)
1402     return false;
1403   if (isOnePastTheEnd()) {
1404     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1405       << CSK;
1406     setInvalid();
1407     return false;
1408   }
1409   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1410   // must actually be at least one array element; even a VLA cannot have a
1411   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1412   return true;
1413 }
1414 
diagnoseUnsizedArrayPointerArithmetic(EvalInfo & Info,const Expr * E)1415 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1416                                                                 const Expr *E) {
1417   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1418   // Do not set the designator as invalid: we can represent this situation,
1419   // and correct handling of __builtin_object_size requires us to do so.
1420 }
1421 
diagnosePointerArithmetic(EvalInfo & Info,const Expr * E,const APSInt & N)1422 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1423                                                     const Expr *E,
1424                                                     const APSInt &N) {
1425   // If we're complaining, we must be able to statically determine the size of
1426   // the most derived array.
1427   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1428     Info.CCEDiag(E, diag::note_constexpr_array_index)
1429       << N << /*array*/ 0
1430       << static_cast<unsigned>(getMostDerivedArraySize());
1431   else
1432     Info.CCEDiag(E, diag::note_constexpr_array_index)
1433       << N << /*non-array*/ 1;
1434   setInvalid();
1435 }
1436 
CallStackFrame(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Callee,const LValue * This,CallRef Call)1437 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1438                                const FunctionDecl *Callee, const LValue *This,
1439                                CallRef Call)
1440     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1441       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1442   Info.CurrentCall = this;
1443   ++Info.CallStackDepth;
1444 }
1445 
~CallStackFrame()1446 CallStackFrame::~CallStackFrame() {
1447   assert(Info.CurrentCall == this && "calls retired out of order");
1448   --Info.CallStackDepth;
1449   Info.CurrentCall = Caller;
1450 }
1451 
isRead(AccessKinds AK)1452 static bool isRead(AccessKinds AK) {
1453   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1454 }
1455 
isModification(AccessKinds AK)1456 static bool isModification(AccessKinds AK) {
1457   switch (AK) {
1458   case AK_Read:
1459   case AK_ReadObjectRepresentation:
1460   case AK_MemberCall:
1461   case AK_DynamicCast:
1462   case AK_TypeId:
1463     return false;
1464   case AK_Assign:
1465   case AK_Increment:
1466   case AK_Decrement:
1467   case AK_Construct:
1468   case AK_Destroy:
1469     return true;
1470   }
1471   llvm_unreachable("unknown access kind");
1472 }
1473 
isAnyAccess(AccessKinds AK)1474 static bool isAnyAccess(AccessKinds AK) {
1475   return isRead(AK) || isModification(AK);
1476 }
1477 
1478 /// Is this an access per the C++ definition?
isFormalAccess(AccessKinds AK)1479 static bool isFormalAccess(AccessKinds AK) {
1480   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1481 }
1482 
1483 /// Is this kind of axcess valid on an indeterminate object value?
isValidIndeterminateAccess(AccessKinds AK)1484 static bool isValidIndeterminateAccess(AccessKinds AK) {
1485   switch (AK) {
1486   case AK_Read:
1487   case AK_Increment:
1488   case AK_Decrement:
1489     // These need the object's value.
1490     return false;
1491 
1492   case AK_ReadObjectRepresentation:
1493   case AK_Assign:
1494   case AK_Construct:
1495   case AK_Destroy:
1496     // Construction and destruction don't need the value.
1497     return true;
1498 
1499   case AK_MemberCall:
1500   case AK_DynamicCast:
1501   case AK_TypeId:
1502     // These aren't really meaningful on scalars.
1503     return true;
1504   }
1505   llvm_unreachable("unknown access kind");
1506 }
1507 
1508 namespace {
1509   struct ComplexValue {
1510   private:
1511     bool IsInt;
1512 
1513   public:
1514     APSInt IntReal, IntImag;
1515     APFloat FloatReal, FloatImag;
1516 
ComplexValue__anon4a4db2530611::ComplexValue1517     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1518 
makeComplexFloat__anon4a4db2530611::ComplexValue1519     void makeComplexFloat() { IsInt = false; }
isComplexFloat__anon4a4db2530611::ComplexValue1520     bool isComplexFloat() const { return !IsInt; }
getComplexFloatReal__anon4a4db2530611::ComplexValue1521     APFloat &getComplexFloatReal() { return FloatReal; }
getComplexFloatImag__anon4a4db2530611::ComplexValue1522     APFloat &getComplexFloatImag() { return FloatImag; }
1523 
makeComplexInt__anon4a4db2530611::ComplexValue1524     void makeComplexInt() { IsInt = true; }
isComplexInt__anon4a4db2530611::ComplexValue1525     bool isComplexInt() const { return IsInt; }
getComplexIntReal__anon4a4db2530611::ComplexValue1526     APSInt &getComplexIntReal() { return IntReal; }
getComplexIntImag__anon4a4db2530611::ComplexValue1527     APSInt &getComplexIntImag() { return IntImag; }
1528 
moveInto__anon4a4db2530611::ComplexValue1529     void moveInto(APValue &v) const {
1530       if (isComplexFloat())
1531         v = APValue(FloatReal, FloatImag);
1532       else
1533         v = APValue(IntReal, IntImag);
1534     }
setFrom__anon4a4db2530611::ComplexValue1535     void setFrom(const APValue &v) {
1536       assert(v.isComplexFloat() || v.isComplexInt());
1537       if (v.isComplexFloat()) {
1538         makeComplexFloat();
1539         FloatReal = v.getComplexFloatReal();
1540         FloatImag = v.getComplexFloatImag();
1541       } else {
1542         makeComplexInt();
1543         IntReal = v.getComplexIntReal();
1544         IntImag = v.getComplexIntImag();
1545       }
1546     }
1547   };
1548 
1549   struct LValue {
1550     APValue::LValueBase Base;
1551     CharUnits Offset;
1552     SubobjectDesignator Designator;
1553     bool IsNullPtr : 1;
1554     bool InvalidBase : 1;
1555 
getLValueBase__anon4a4db2530611::LValue1556     const APValue::LValueBase getLValueBase() const { return Base; }
getLValueOffset__anon4a4db2530611::LValue1557     CharUnits &getLValueOffset() { return Offset; }
getLValueOffset__anon4a4db2530611::LValue1558     const CharUnits &getLValueOffset() const { return Offset; }
getLValueDesignator__anon4a4db2530611::LValue1559     SubobjectDesignator &getLValueDesignator() { return Designator; }
getLValueDesignator__anon4a4db2530611::LValue1560     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
isNullPointer__anon4a4db2530611::LValue1561     bool isNullPointer() const { return IsNullPtr;}
1562 
getLValueCallIndex__anon4a4db2530611::LValue1563     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
getLValueVersion__anon4a4db2530611::LValue1564     unsigned getLValueVersion() const { return Base.getVersion(); }
1565 
moveInto__anon4a4db2530611::LValue1566     void moveInto(APValue &V) const {
1567       if (Designator.Invalid)
1568         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1569       else {
1570         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1571         V = APValue(Base, Offset, Designator.Entries,
1572                     Designator.IsOnePastTheEnd, IsNullPtr);
1573       }
1574     }
setFrom__anon4a4db2530611::LValue1575     void setFrom(ASTContext &Ctx, const APValue &V) {
1576       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1577       Base = V.getLValueBase();
1578       Offset = V.getLValueOffset();
1579       InvalidBase = false;
1580       Designator = SubobjectDesignator(Ctx, V);
1581       IsNullPtr = V.isNullPointer();
1582     }
1583 
set__anon4a4db2530611::LValue1584     void set(APValue::LValueBase B, bool BInvalid = false) {
1585 #ifndef NDEBUG
1586       // We only allow a few types of invalid bases. Enforce that here.
1587       if (BInvalid) {
1588         const auto *E = B.get<const Expr *>();
1589         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1590                "Unexpected type of invalid base");
1591       }
1592 #endif
1593 
1594       Base = B;
1595       Offset = CharUnits::fromQuantity(0);
1596       InvalidBase = BInvalid;
1597       Designator = SubobjectDesignator(getType(B));
1598       IsNullPtr = false;
1599     }
1600 
setNull__anon4a4db2530611::LValue1601     void setNull(ASTContext &Ctx, QualType PointerTy) {
1602       Base = (const ValueDecl *)nullptr;
1603       Offset =
1604           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1605       InvalidBase = false;
1606       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1607       IsNullPtr = true;
1608     }
1609 
setInvalid__anon4a4db2530611::LValue1610     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1611       set(B, true);
1612     }
1613 
toString__anon4a4db2530611::LValue1614     std::string toString(ASTContext &Ctx, QualType T) const {
1615       APValue Printable;
1616       moveInto(Printable);
1617       return Printable.getAsString(Ctx, T);
1618     }
1619 
1620   private:
1621     // Check that this LValue is not based on a null pointer. If it is, produce
1622     // a diagnostic and mark the designator as invalid.
1623     template <typename GenDiagType>
checkNullPointerDiagnosingWith__anon4a4db2530611::LValue1624     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1625       if (Designator.Invalid)
1626         return false;
1627       if (IsNullPtr) {
1628         GenDiag();
1629         Designator.setInvalid();
1630         return false;
1631       }
1632       return true;
1633     }
1634 
1635   public:
checkNullPointer__anon4a4db2530611::LValue1636     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1637                           CheckSubobjectKind CSK) {
1638       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1639         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1640       });
1641     }
1642 
checkNullPointerForFoldAccess__anon4a4db2530611::LValue1643     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1644                                        AccessKinds AK) {
1645       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1646         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1647       });
1648     }
1649 
1650     // Check this LValue refers to an object. If not, set the designator to be
1651     // invalid and emit a diagnostic.
checkSubobject__anon4a4db2530611::LValue1652     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1653       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1654              Designator.checkSubobject(Info, E, CSK);
1655     }
1656 
addDecl__anon4a4db2530611::LValue1657     void addDecl(EvalInfo &Info, const Expr *E,
1658                  const Decl *D, bool Virtual = false) {
1659       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1660         Designator.addDeclUnchecked(D, Virtual);
1661     }
addUnsizedArray__anon4a4db2530611::LValue1662     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1663       if (!Designator.Entries.empty()) {
1664         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1665         Designator.setInvalid();
1666         return;
1667       }
1668       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1669         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1670         Designator.FirstEntryIsAnUnsizedArray = true;
1671         Designator.addUnsizedArrayUnchecked(ElemTy);
1672       }
1673     }
addArray__anon4a4db2530611::LValue1674     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1675       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1676         Designator.addArrayUnchecked(CAT);
1677     }
addComplex__anon4a4db2530611::LValue1678     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1679       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1680         Designator.addComplexUnchecked(EltTy, Imag);
1681     }
clearIsNullPointer__anon4a4db2530611::LValue1682     void clearIsNullPointer() {
1683       IsNullPtr = false;
1684     }
adjustOffsetAndIndex__anon4a4db2530611::LValue1685     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1686                               const APSInt &Index, CharUnits ElementSize) {
1687       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1688       // but we're not required to diagnose it and it's valid in C++.)
1689       if (!Index)
1690         return;
1691 
1692       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1693       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1694       // offsets.
1695       uint64_t Offset64 = Offset.getQuantity();
1696       uint64_t ElemSize64 = ElementSize.getQuantity();
1697       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1698       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1699 
1700       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1701         Designator.adjustIndex(Info, E, Index);
1702       clearIsNullPointer();
1703     }
adjustOffset__anon4a4db2530611::LValue1704     void adjustOffset(CharUnits N) {
1705       Offset += N;
1706       if (N.getQuantity())
1707         clearIsNullPointer();
1708     }
1709   };
1710 
1711   struct MemberPtr {
MemberPtr__anon4a4db2530611::MemberPtr1712     MemberPtr() {}
MemberPtr__anon4a4db2530611::MemberPtr1713     explicit MemberPtr(const ValueDecl *Decl) :
1714       DeclAndIsDerivedMember(Decl, false), Path() {}
1715 
1716     /// The member or (direct or indirect) field referred to by this member
1717     /// pointer, or 0 if this is a null member pointer.
getDecl__anon4a4db2530611::MemberPtr1718     const ValueDecl *getDecl() const {
1719       return DeclAndIsDerivedMember.getPointer();
1720     }
1721     /// Is this actually a member of some type derived from the relevant class?
isDerivedMember__anon4a4db2530611::MemberPtr1722     bool isDerivedMember() const {
1723       return DeclAndIsDerivedMember.getInt();
1724     }
1725     /// Get the class which the declaration actually lives in.
getContainingRecord__anon4a4db2530611::MemberPtr1726     const CXXRecordDecl *getContainingRecord() const {
1727       return cast<CXXRecordDecl>(
1728           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1729     }
1730 
moveInto__anon4a4db2530611::MemberPtr1731     void moveInto(APValue &V) const {
1732       V = APValue(getDecl(), isDerivedMember(), Path);
1733     }
setFrom__anon4a4db2530611::MemberPtr1734     void setFrom(const APValue &V) {
1735       assert(V.isMemberPointer());
1736       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1737       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1738       Path.clear();
1739       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1740       Path.insert(Path.end(), P.begin(), P.end());
1741     }
1742 
1743     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1744     /// whether the member is a member of some class derived from the class type
1745     /// of the member pointer.
1746     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1747     /// Path - The path of base/derived classes from the member declaration's
1748     /// class (exclusive) to the class type of the member pointer (inclusive).
1749     SmallVector<const CXXRecordDecl*, 4> Path;
1750 
1751     /// Perform a cast towards the class of the Decl (either up or down the
1752     /// hierarchy).
castBack__anon4a4db2530611::MemberPtr1753     bool castBack(const CXXRecordDecl *Class) {
1754       assert(!Path.empty());
1755       const CXXRecordDecl *Expected;
1756       if (Path.size() >= 2)
1757         Expected = Path[Path.size() - 2];
1758       else
1759         Expected = getContainingRecord();
1760       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1761         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1762         // if B does not contain the original member and is not a base or
1763         // derived class of the class containing the original member, the result
1764         // of the cast is undefined.
1765         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1766         // (D::*). We consider that to be a language defect.
1767         return false;
1768       }
1769       Path.pop_back();
1770       return true;
1771     }
1772     /// Perform a base-to-derived member pointer cast.
castToDerived__anon4a4db2530611::MemberPtr1773     bool castToDerived(const CXXRecordDecl *Derived) {
1774       if (!getDecl())
1775         return true;
1776       if (!isDerivedMember()) {
1777         Path.push_back(Derived);
1778         return true;
1779       }
1780       if (!castBack(Derived))
1781         return false;
1782       if (Path.empty())
1783         DeclAndIsDerivedMember.setInt(false);
1784       return true;
1785     }
1786     /// Perform a derived-to-base member pointer cast.
castToBase__anon4a4db2530611::MemberPtr1787     bool castToBase(const CXXRecordDecl *Base) {
1788       if (!getDecl())
1789         return true;
1790       if (Path.empty())
1791         DeclAndIsDerivedMember.setInt(true);
1792       if (isDerivedMember()) {
1793         Path.push_back(Base);
1794         return true;
1795       }
1796       return castBack(Base);
1797     }
1798   };
1799 
1800   /// Compare two member pointers, which are assumed to be of the same type.
operator ==(const MemberPtr & LHS,const MemberPtr & RHS)1801   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1802     if (!LHS.getDecl() || !RHS.getDecl())
1803       return !LHS.getDecl() && !RHS.getDecl();
1804     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1805       return false;
1806     return LHS.Path == RHS.Path;
1807   }
1808 }
1809 
1810 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1811 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1812                             const LValue &This, const Expr *E,
1813                             bool AllowNonLiteralTypes = false);
1814 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1815                            bool InvalidBaseOK = false);
1816 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1817                             bool InvalidBaseOK = false);
1818 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1819                                   EvalInfo &Info);
1820 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1821 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1822 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1823                                     EvalInfo &Info);
1824 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1825 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1826 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1827                            EvalInfo &Info);
1828 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1829 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1830                                   EvalInfo &Info);
1831 
1832 /// Evaluate an integer or fixed point expression into an APResult.
1833 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1834                                         EvalInfo &Info);
1835 
1836 /// Evaluate only a fixed point expression into an APResult.
1837 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1838                                EvalInfo &Info);
1839 
1840 //===----------------------------------------------------------------------===//
1841 // Misc utilities
1842 //===----------------------------------------------------------------------===//
1843 
1844 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1845 /// preserving its value (by extending by up to one bit as needed).
negateAsSigned(APSInt & Int)1846 static void negateAsSigned(APSInt &Int) {
1847   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1848     Int = Int.extend(Int.getBitWidth() + 1);
1849     Int.setIsSigned(true);
1850   }
1851   Int = -Int;
1852 }
1853 
1854 template<typename KeyT>
createTemporary(const KeyT * Key,QualType T,ScopeKind Scope,LValue & LV)1855 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1856                                          ScopeKind Scope, LValue &LV) {
1857   unsigned Version = getTempVersion();
1858   APValue::LValueBase Base(Key, Index, Version);
1859   LV.set(Base);
1860   return createLocal(Base, Key, T, Scope);
1861 }
1862 
1863 /// Allocate storage for a parameter of a function call made in this frame.
createParam(CallRef Args,const ParmVarDecl * PVD,LValue & LV)1864 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1865                                      LValue &LV) {
1866   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1867   APValue::LValueBase Base(PVD, Index, Args.Version);
1868   LV.set(Base);
1869   // We always destroy parameters at the end of the call, even if we'd allow
1870   // them to live to the end of the full-expression at runtime, in order to
1871   // give portable results and match other compilers.
1872   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1873 }
1874 
createLocal(APValue::LValueBase Base,const void * Key,QualType T,ScopeKind Scope)1875 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1876                                      QualType T, ScopeKind Scope) {
1877   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1878   unsigned Version = Base.getVersion();
1879   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1880   assert(Result.isAbsent() && "local created multiple times");
1881 
1882   // If we're creating a local immediately in the operand of a speculative
1883   // evaluation, don't register a cleanup to be run outside the speculative
1884   // evaluation context, since we won't actually be able to initialize this
1885   // object.
1886   if (Index <= Info.SpeculativeEvaluationDepth) {
1887     if (T.isDestructedType())
1888       Info.noteSideEffect();
1889   } else {
1890     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1891   }
1892   return Result;
1893 }
1894 
createHeapAlloc(const Expr * E,QualType T,LValue & LV)1895 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1896   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1897     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1898     return nullptr;
1899   }
1900 
1901   DynamicAllocLValue DA(NumHeapAllocs++);
1902   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1903   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1904                                    std::forward_as_tuple(DA), std::tuple<>());
1905   assert(Result.second && "reused a heap alloc index?");
1906   Result.first->second.AllocExpr = E;
1907   return &Result.first->second.Value;
1908 }
1909 
1910 /// Produce a string describing the given constexpr call.
describe(raw_ostream & Out)1911 void CallStackFrame::describe(raw_ostream &Out) {
1912   unsigned ArgIndex = 0;
1913   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1914                       !isa<CXXConstructorDecl>(Callee) &&
1915                       cast<CXXMethodDecl>(Callee)->isInstance();
1916 
1917   if (!IsMemberCall)
1918     Out << *Callee << '(';
1919 
1920   if (This && IsMemberCall) {
1921     APValue Val;
1922     This->moveInto(Val);
1923     Val.printPretty(Out, Info.Ctx,
1924                     This->Designator.MostDerivedType);
1925     // FIXME: Add parens around Val if needed.
1926     Out << "->" << *Callee << '(';
1927     IsMemberCall = false;
1928   }
1929 
1930   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1931        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1932     if (ArgIndex > (unsigned)IsMemberCall)
1933       Out << ", ";
1934 
1935     const ParmVarDecl *Param = *I;
1936     APValue *V = Info.getParamSlot(Arguments, Param);
1937     if (V)
1938       V->printPretty(Out, Info.Ctx, Param->getType());
1939     else
1940       Out << "<...>";
1941 
1942     if (ArgIndex == 0 && IsMemberCall)
1943       Out << "->" << *Callee << '(';
1944   }
1945 
1946   Out << ')';
1947 }
1948 
1949 /// Evaluate an expression to see if it had side-effects, and discard its
1950 /// result.
1951 /// \return \c true if the caller should keep evaluating.
EvaluateIgnoredValue(EvalInfo & Info,const Expr * E)1952 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1953   assert(!E->isValueDependent());
1954   APValue Scratch;
1955   if (!Evaluate(Scratch, Info, E))
1956     // We don't need the value, but we might have skipped a side effect here.
1957     return Info.noteSideEffect();
1958   return true;
1959 }
1960 
1961 /// Should this call expression be treated as a string literal?
IsStringLiteralCall(const CallExpr * E)1962 static bool IsStringLiteralCall(const CallExpr *E) {
1963   unsigned Builtin = E->getBuiltinCallee();
1964   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1965           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1966 }
1967 
IsGlobalLValue(APValue::LValueBase B)1968 static bool IsGlobalLValue(APValue::LValueBase B) {
1969   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1970   // constant expression of pointer type that evaluates to...
1971 
1972   // ... a null pointer value, or a prvalue core constant expression of type
1973   // std::nullptr_t.
1974   if (!B) return true;
1975 
1976   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1977     // ... the address of an object with static storage duration,
1978     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1979       return VD->hasGlobalStorage();
1980     if (isa<TemplateParamObjectDecl>(D))
1981       return true;
1982     // ... the address of a function,
1983     // ... the address of a GUID [MS extension],
1984     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1985   }
1986 
1987   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1988     return true;
1989 
1990   const Expr *E = B.get<const Expr*>();
1991   switch (E->getStmtClass()) {
1992   default:
1993     return false;
1994   case Expr::CompoundLiteralExprClass: {
1995     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1996     return CLE->isFileScope() && CLE->isLValue();
1997   }
1998   case Expr::MaterializeTemporaryExprClass:
1999     // A materialized temporary might have been lifetime-extended to static
2000     // storage duration.
2001     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2002   // A string literal has static storage duration.
2003   case Expr::StringLiteralClass:
2004   case Expr::PredefinedExprClass:
2005   case Expr::ObjCStringLiteralClass:
2006   case Expr::ObjCEncodeExprClass:
2007     return true;
2008   case Expr::ObjCBoxedExprClass:
2009     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2010   case Expr::CallExprClass:
2011     return IsStringLiteralCall(cast<CallExpr>(E));
2012   // For GCC compatibility, &&label has static storage duration.
2013   case Expr::AddrLabelExprClass:
2014     return true;
2015   // A Block literal expression may be used as the initialization value for
2016   // Block variables at global or local static scope.
2017   case Expr::BlockExprClass:
2018     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2019   case Expr::ImplicitValueInitExprClass:
2020     // FIXME:
2021     // We can never form an lvalue with an implicit value initialization as its
2022     // base through expression evaluation, so these only appear in one case: the
2023     // implicit variable declaration we invent when checking whether a constexpr
2024     // constructor can produce a constant expression. We must assume that such
2025     // an expression might be a global lvalue.
2026     return true;
2027   }
2028 }
2029 
GetLValueBaseDecl(const LValue & LVal)2030 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2031   return LVal.Base.dyn_cast<const ValueDecl*>();
2032 }
2033 
IsLiteralLValue(const LValue & Value)2034 static bool IsLiteralLValue(const LValue &Value) {
2035   if (Value.getLValueCallIndex())
2036     return false;
2037   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2038   return E && !isa<MaterializeTemporaryExpr>(E);
2039 }
2040 
IsWeakLValue(const LValue & Value)2041 static bool IsWeakLValue(const LValue &Value) {
2042   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2043   return Decl && Decl->isWeak();
2044 }
2045 
isZeroSized(const LValue & Value)2046 static bool isZeroSized(const LValue &Value) {
2047   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2048   if (Decl && isa<VarDecl>(Decl)) {
2049     QualType Ty = Decl->getType();
2050     if (Ty->isArrayType())
2051       return Ty->isIncompleteType() ||
2052              Decl->getASTContext().getTypeSize(Ty) == 0;
2053   }
2054   return false;
2055 }
2056 
HasSameBase(const LValue & A,const LValue & B)2057 static bool HasSameBase(const LValue &A, const LValue &B) {
2058   if (!A.getLValueBase())
2059     return !B.getLValueBase();
2060   if (!B.getLValueBase())
2061     return false;
2062 
2063   if (A.getLValueBase().getOpaqueValue() !=
2064       B.getLValueBase().getOpaqueValue())
2065     return false;
2066 
2067   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2068          A.getLValueVersion() == B.getLValueVersion();
2069 }
2070 
NoteLValueLocation(EvalInfo & Info,APValue::LValueBase Base)2071 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2072   assert(Base && "no location for a null lvalue");
2073   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2074 
2075   // For a parameter, find the corresponding call stack frame (if it still
2076   // exists), and point at the parameter of the function definition we actually
2077   // invoked.
2078   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2079     unsigned Idx = PVD->getFunctionScopeIndex();
2080     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2081       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2082           F->Arguments.Version == Base.getVersion() && F->Callee &&
2083           Idx < F->Callee->getNumParams()) {
2084         VD = F->Callee->getParamDecl(Idx);
2085         break;
2086       }
2087     }
2088   }
2089 
2090   if (VD)
2091     Info.Note(VD->getLocation(), diag::note_declared_at);
2092   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2093     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2094   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2095     // FIXME: Produce a note for dangling pointers too.
2096     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2097       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2098                 diag::note_constexpr_dynamic_alloc_here);
2099   }
2100   // We have no information to show for a typeid(T) object.
2101 }
2102 
2103 enum class CheckEvaluationResultKind {
2104   ConstantExpression,
2105   FullyInitialized,
2106 };
2107 
2108 /// Materialized temporaries that we've already checked to determine if they're
2109 /// initializsed by a constant expression.
2110 using CheckedTemporaries =
2111     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2112 
2113 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2114                                   EvalInfo &Info, SourceLocation DiagLoc,
2115                                   QualType Type, const APValue &Value,
2116                                   ConstantExprKind Kind,
2117                                   SourceLocation SubobjectLoc,
2118                                   CheckedTemporaries &CheckedTemps);
2119 
2120 /// Check that this reference or pointer core constant expression is a valid
2121 /// value for an address or reference constant expression. Return true if we
2122 /// 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)2123 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2124                                           QualType Type, const LValue &LVal,
2125                                           ConstantExprKind Kind,
2126                                           CheckedTemporaries &CheckedTemps) {
2127   bool IsReferenceType = Type->isReferenceType();
2128 
2129   APValue::LValueBase Base = LVal.getLValueBase();
2130   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2131 
2132   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2133   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2134 
2135   // Additional restrictions apply in a template argument. We only enforce the
2136   // C++20 restrictions here; additional syntactic and semantic restrictions
2137   // are applied elsewhere.
2138   if (isTemplateArgument(Kind)) {
2139     int InvalidBaseKind = -1;
2140     StringRef Ident;
2141     if (Base.is<TypeInfoLValue>())
2142       InvalidBaseKind = 0;
2143     else if (isa_and_nonnull<StringLiteral>(BaseE))
2144       InvalidBaseKind = 1;
2145     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2146              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2147       InvalidBaseKind = 2;
2148     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2149       InvalidBaseKind = 3;
2150       Ident = PE->getIdentKindName();
2151     }
2152 
2153     if (InvalidBaseKind != -1) {
2154       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2155           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2156           << Ident;
2157       return false;
2158     }
2159   }
2160 
2161   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2162     if (FD->isConsteval()) {
2163       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2164           << !Type->isAnyPointerType();
2165       Info.Note(FD->getLocation(), diag::note_declared_at);
2166       return false;
2167     }
2168   }
2169 
2170   // Check that the object is a global. Note that the fake 'this' object we
2171   // manufacture when checking potential constant expressions is conservatively
2172   // assumed to be global here.
2173   if (!IsGlobalLValue(Base)) {
2174     if (Info.getLangOpts().CPlusPlus11) {
2175       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2176       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2177         << IsReferenceType << !Designator.Entries.empty()
2178         << !!VD << VD;
2179 
2180       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2181       if (VarD && VarD->isConstexpr()) {
2182         // Non-static local constexpr variables have unintuitive semantics:
2183         //   constexpr int a = 1;
2184         //   constexpr const int *p = &a;
2185         // ... is invalid because the address of 'a' is not constant. Suggest
2186         // adding a 'static' in this case.
2187         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2188             << VarD
2189             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2190       } else {
2191         NoteLValueLocation(Info, Base);
2192       }
2193     } else {
2194       Info.FFDiag(Loc);
2195     }
2196     // Don't allow references to temporaries to escape.
2197     return false;
2198   }
2199   assert((Info.checkingPotentialConstantExpression() ||
2200           LVal.getLValueCallIndex() == 0) &&
2201          "have call index for global lvalue");
2202 
2203   if (Base.is<DynamicAllocLValue>()) {
2204     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2205         << IsReferenceType << !Designator.Entries.empty();
2206     NoteLValueLocation(Info, Base);
2207     return false;
2208   }
2209 
2210   if (BaseVD) {
2211     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2212       // Check if this is a thread-local variable.
2213       if (Var->getTLSKind())
2214         // FIXME: Diagnostic!
2215         return false;
2216 
2217       // A dllimport variable never acts like a constant, unless we're
2218       // evaluating a value for use only in name mangling.
2219       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2220         // FIXME: Diagnostic!
2221         return false;
2222     }
2223     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2224       // __declspec(dllimport) must be handled very carefully:
2225       // We must never initialize an expression with the thunk in C++.
2226       // Doing otherwise would allow the same id-expression to yield
2227       // different addresses for the same function in different translation
2228       // units.  However, this means that we must dynamically initialize the
2229       // expression with the contents of the import address table at runtime.
2230       //
2231       // The C language has no notion of ODR; furthermore, it has no notion of
2232       // dynamic initialization.  This means that we are permitted to
2233       // perform initialization with the address of the thunk.
2234       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2235           FD->hasAttr<DLLImportAttr>())
2236         // FIXME: Diagnostic!
2237         return false;
2238     }
2239   } else if (const auto *MTE =
2240                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2241     if (CheckedTemps.insert(MTE).second) {
2242       QualType TempType = getType(Base);
2243       if (TempType.isDestructedType()) {
2244         Info.FFDiag(MTE->getExprLoc(),
2245                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2246             << TempType;
2247         return false;
2248       }
2249 
2250       APValue *V = MTE->getOrCreateValue(false);
2251       assert(V && "evasluation result refers to uninitialised temporary");
2252       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2253                                  Info, MTE->getExprLoc(), TempType, *V,
2254                                  Kind, SourceLocation(), CheckedTemps))
2255         return false;
2256     }
2257   }
2258 
2259   // Allow address constant expressions to be past-the-end pointers. This is
2260   // an extension: the standard requires them to point to an object.
2261   if (!IsReferenceType)
2262     return true;
2263 
2264   // A reference constant expression must refer to an object.
2265   if (!Base) {
2266     // FIXME: diagnostic
2267     Info.CCEDiag(Loc);
2268     return true;
2269   }
2270 
2271   // Does this refer one past the end of some object?
2272   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2273     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2274       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2275     NoteLValueLocation(Info, Base);
2276   }
2277 
2278   return true;
2279 }
2280 
2281 /// Member pointers are constant expressions unless they point to a
2282 /// non-virtual dllimport member function.
CheckMemberPointerConstantExpression(EvalInfo & Info,SourceLocation Loc,QualType Type,const APValue & Value,ConstantExprKind Kind)2283 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2284                                                  SourceLocation Loc,
2285                                                  QualType Type,
2286                                                  const APValue &Value,
2287                                                  ConstantExprKind Kind) {
2288   const ValueDecl *Member = Value.getMemberPointerDecl();
2289   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2290   if (!FD)
2291     return true;
2292   if (FD->isConsteval()) {
2293     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2294     Info.Note(FD->getLocation(), diag::note_declared_at);
2295     return false;
2296   }
2297   return isForManglingOnly(Kind) || FD->isVirtual() ||
2298          !FD->hasAttr<DLLImportAttr>();
2299 }
2300 
2301 /// Check that this core constant expression is of literal type, and if not,
2302 /// produce an appropriate diagnostic.
CheckLiteralType(EvalInfo & Info,const Expr * E,const LValue * This=nullptr)2303 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2304                              const LValue *This = nullptr) {
2305   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2306     return true;
2307 
2308   // C++1y: A constant initializer for an object o [...] may also invoke
2309   // constexpr constructors for o and its subobjects even if those objects
2310   // are of non-literal class types.
2311   //
2312   // C++11 missed this detail for aggregates, so classes like this:
2313   //   struct foo_t { union { int i; volatile int j; } u; };
2314   // are not (obviously) initializable like so:
2315   //   __attribute__((__require_constant_initialization__))
2316   //   static const foo_t x = {{0}};
2317   // because "i" is a subobject with non-literal initialization (due to the
2318   // volatile member of the union). See:
2319   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2320   // Therefore, we use the C++1y behavior.
2321   if (This && Info.EvaluatingDecl == This->getLValueBase())
2322     return true;
2323 
2324   // Prvalue constant expressions must be of literal types.
2325   if (Info.getLangOpts().CPlusPlus11)
2326     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2327       << E->getType();
2328   else
2329     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2330   return false;
2331 }
2332 
CheckEvaluationResult(CheckEvaluationResultKind CERK,EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value,ConstantExprKind Kind,SourceLocation SubobjectLoc,CheckedTemporaries & CheckedTemps)2333 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2334                                   EvalInfo &Info, SourceLocation DiagLoc,
2335                                   QualType Type, const APValue &Value,
2336                                   ConstantExprKind Kind,
2337                                   SourceLocation SubobjectLoc,
2338                                   CheckedTemporaries &CheckedTemps) {
2339   if (!Value.hasValue()) {
2340     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2341       << true << Type;
2342     if (SubobjectLoc.isValid())
2343       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2344     return false;
2345   }
2346 
2347   // We allow _Atomic(T) to be initialized from anything that T can be
2348   // initialized from.
2349   if (const AtomicType *AT = Type->getAs<AtomicType>())
2350     Type = AT->getValueType();
2351 
2352   // Core issue 1454: For a literal constant expression of array or class type,
2353   // each subobject of its value shall have been initialized by a constant
2354   // expression.
2355   if (Value.isArray()) {
2356     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2357     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2358       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2359                                  Value.getArrayInitializedElt(I), Kind,
2360                                  SubobjectLoc, CheckedTemps))
2361         return false;
2362     }
2363     if (!Value.hasArrayFiller())
2364       return true;
2365     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2366                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2367                                  CheckedTemps);
2368   }
2369   if (Value.isUnion() && Value.getUnionField()) {
2370     return CheckEvaluationResult(
2371         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2372         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2373         CheckedTemps);
2374   }
2375   if (Value.isStruct()) {
2376     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2377     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2378       unsigned BaseIndex = 0;
2379       for (const CXXBaseSpecifier &BS : CD->bases()) {
2380         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2381                                    Value.getStructBase(BaseIndex), Kind,
2382                                    BS.getBeginLoc(), CheckedTemps))
2383           return false;
2384         ++BaseIndex;
2385       }
2386     }
2387     for (const auto *I : RD->fields()) {
2388       if (I->isUnnamedBitfield())
2389         continue;
2390 
2391       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2392                                  Value.getStructField(I->getFieldIndex()),
2393                                  Kind, I->getLocation(), CheckedTemps))
2394         return false;
2395     }
2396   }
2397 
2398   if (Value.isLValue() &&
2399       CERK == CheckEvaluationResultKind::ConstantExpression) {
2400     LValue LVal;
2401     LVal.setFrom(Info.Ctx, Value);
2402     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2403                                          CheckedTemps);
2404   }
2405 
2406   if (Value.isMemberPointer() &&
2407       CERK == CheckEvaluationResultKind::ConstantExpression)
2408     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2409 
2410   // Everything else is fine.
2411   return true;
2412 }
2413 
2414 /// Check that this core constant expression value is a valid value for a
2415 /// constant expression. If not, report an appropriate diagnostic. Does not
2416 /// check that the expression is of literal type.
CheckConstantExpression(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value,ConstantExprKind Kind)2417 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2418                                     QualType Type, const APValue &Value,
2419                                     ConstantExprKind Kind) {
2420   // Nothing to check for a constant expression of type 'cv void'.
2421   if (Type->isVoidType())
2422     return true;
2423 
2424   CheckedTemporaries CheckedTemps;
2425   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2426                                Info, DiagLoc, Type, Value, Kind,
2427                                SourceLocation(), CheckedTemps);
2428 }
2429 
2430 /// Check that this evaluated value is fully-initialized and can be loaded by
2431 /// an lvalue-to-rvalue conversion.
CheckFullyInitialized(EvalInfo & Info,SourceLocation DiagLoc,QualType Type,const APValue & Value)2432 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2433                                   QualType Type, const APValue &Value) {
2434   CheckedTemporaries CheckedTemps;
2435   return CheckEvaluationResult(
2436       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2437       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2438 }
2439 
2440 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2441 /// "the allocated storage is deallocated within the evaluation".
CheckMemoryLeaks(EvalInfo & Info)2442 static bool CheckMemoryLeaks(EvalInfo &Info) {
2443   if (!Info.HeapAllocs.empty()) {
2444     // We can still fold to a constant despite a compile-time memory leak,
2445     // so long as the heap allocation isn't referenced in the result (we check
2446     // that in CheckConstantExpression).
2447     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2448                  diag::note_constexpr_memory_leak)
2449         << unsigned(Info.HeapAllocs.size() - 1);
2450   }
2451   return true;
2452 }
2453 
EvalPointerValueAsBool(const APValue & Value,bool & Result)2454 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2455   // A null base expression indicates a null pointer.  These are always
2456   // evaluatable, and they are false unless the offset is zero.
2457   if (!Value.getLValueBase()) {
2458     Result = !Value.getLValueOffset().isZero();
2459     return true;
2460   }
2461 
2462   // We have a non-null base.  These are generally known to be true, but if it's
2463   // a weak declaration it can be null at runtime.
2464   Result = true;
2465   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2466   return !Decl || !Decl->isWeak();
2467 }
2468 
HandleConversionToBool(const APValue & Val,bool & Result)2469 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2470   switch (Val.getKind()) {
2471   case APValue::None:
2472   case APValue::Indeterminate:
2473     return false;
2474   case APValue::Int:
2475     Result = Val.getInt().getBoolValue();
2476     return true;
2477   case APValue::FixedPoint:
2478     Result = Val.getFixedPoint().getBoolValue();
2479     return true;
2480   case APValue::Float:
2481     Result = !Val.getFloat().isZero();
2482     return true;
2483   case APValue::ComplexInt:
2484     Result = Val.getComplexIntReal().getBoolValue() ||
2485              Val.getComplexIntImag().getBoolValue();
2486     return true;
2487   case APValue::ComplexFloat:
2488     Result = !Val.getComplexFloatReal().isZero() ||
2489              !Val.getComplexFloatImag().isZero();
2490     return true;
2491   case APValue::LValue:
2492     return EvalPointerValueAsBool(Val, Result);
2493   case APValue::MemberPointer:
2494     Result = Val.getMemberPointerDecl();
2495     return true;
2496   case APValue::Vector:
2497   case APValue::Array:
2498   case APValue::Struct:
2499   case APValue::Union:
2500   case APValue::AddrLabelDiff:
2501     return false;
2502   }
2503 
2504   llvm_unreachable("unknown APValue kind");
2505 }
2506 
EvaluateAsBooleanCondition(const Expr * E,bool & Result,EvalInfo & Info)2507 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2508                                        EvalInfo &Info) {
2509   assert(!E->isValueDependent());
2510   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2511   APValue Val;
2512   if (!Evaluate(Val, Info, E))
2513     return false;
2514   return HandleConversionToBool(Val, Result);
2515 }
2516 
2517 template<typename T>
HandleOverflow(EvalInfo & Info,const Expr * E,const T & SrcValue,QualType DestType)2518 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2519                            const T &SrcValue, QualType DestType) {
2520   Info.CCEDiag(E, diag::note_constexpr_overflow)
2521     << SrcValue << DestType;
2522   return Info.noteUndefinedBehavior();
2523 }
2524 
HandleFloatToIntCast(EvalInfo & Info,const Expr * E,QualType SrcType,const APFloat & Value,QualType DestType,APSInt & Result)2525 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2526                                  QualType SrcType, const APFloat &Value,
2527                                  QualType DestType, APSInt &Result) {
2528   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2529   // Determine whether we are converting to unsigned or signed.
2530   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2531 
2532   Result = APSInt(DestWidth, !DestSigned);
2533   bool ignored;
2534   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2535       & APFloat::opInvalidOp)
2536     return HandleOverflow(Info, E, Value, DestType);
2537   return true;
2538 }
2539 
2540 /// Get rounding mode used for evaluation of the specified expression.
2541 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2542 ///                       dynamic.
2543 /// If rounding mode is unknown at compile time, still try to evaluate the
2544 /// expression. If the result is exact, it does not depend on rounding mode.
2545 /// So return "tonearest" mode instead of "dynamic".
getActiveRoundingMode(EvalInfo & Info,const Expr * E,bool & DynamicRM)2546 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2547                                                 bool &DynamicRM) {
2548   llvm::RoundingMode RM =
2549       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2550   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2551   if (DynamicRM)
2552     RM = llvm::RoundingMode::NearestTiesToEven;
2553   return RM;
2554 }
2555 
2556 /// Check if the given evaluation result is allowed for constant evaluation.
checkFloatingPointResult(EvalInfo & Info,const Expr * E,APFloat::opStatus St)2557 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2558                                      APFloat::opStatus St) {
2559   // In a constant context, assume that any dynamic rounding mode or FP
2560   // exception state matches the default floating-point environment.
2561   if (Info.InConstantContext)
2562     return true;
2563 
2564   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2565   if ((St & APFloat::opInexact) &&
2566       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2567     // Inexact result means that it depends on rounding mode. If the requested
2568     // mode is dynamic, the evaluation cannot be made in compile time.
2569     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2570     return false;
2571   }
2572 
2573   if ((St != APFloat::opOK) &&
2574       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2575        FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2576        FPO.getAllowFEnvAccess())) {
2577     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2578     return false;
2579   }
2580 
2581   if ((St & APFloat::opStatus::opInvalidOp) &&
2582       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2583     // There is no usefully definable result.
2584     Info.FFDiag(E);
2585     return false;
2586   }
2587 
2588   // FIXME: if:
2589   // - evaluation triggered other FP exception, and
2590   // - exception mode is not "ignore", and
2591   // - the expression being evaluated is not a part of global variable
2592   //   initializer,
2593   // the evaluation probably need to be rejected.
2594   return true;
2595 }
2596 
HandleFloatToFloatCast(EvalInfo & Info,const Expr * E,QualType SrcType,QualType DestType,APFloat & Result)2597 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2598                                    QualType SrcType, QualType DestType,
2599                                    APFloat &Result) {
2600   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2601   bool DynamicRM;
2602   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2603   APFloat::opStatus St;
2604   APFloat Value = Result;
2605   bool ignored;
2606   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2607   return checkFloatingPointResult(Info, E, St);
2608 }
2609 
HandleIntToIntCast(EvalInfo & Info,const Expr * E,QualType DestType,QualType SrcType,const APSInt & Value)2610 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2611                                  QualType DestType, QualType SrcType,
2612                                  const APSInt &Value) {
2613   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2614   // Figure out if this is a truncate, extend or noop cast.
2615   // If the input is signed, do a sign extend, noop, or truncate.
2616   APSInt Result = Value.extOrTrunc(DestWidth);
2617   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2618   if (DestType->isBooleanType())
2619     Result = Value.getBoolValue();
2620   return Result;
2621 }
2622 
HandleIntToFloatCast(EvalInfo & Info,const Expr * E,const FPOptions FPO,QualType SrcType,const APSInt & Value,QualType DestType,APFloat & Result)2623 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2624                                  const FPOptions FPO,
2625                                  QualType SrcType, const APSInt &Value,
2626                                  QualType DestType, APFloat &Result) {
2627   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2628   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2629        APFloat::rmNearestTiesToEven);
2630   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2631       FPO.isFPConstrained()) {
2632     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2633     return false;
2634   }
2635   return true;
2636 }
2637 
truncateBitfieldValue(EvalInfo & Info,const Expr * E,APValue & Value,const FieldDecl * FD)2638 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2639                                   APValue &Value, const FieldDecl *FD) {
2640   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2641 
2642   if (!Value.isInt()) {
2643     // Trying to store a pointer-cast-to-integer into a bitfield.
2644     // FIXME: In this case, we should provide the diagnostic for casting
2645     // a pointer to an integer.
2646     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2647     Info.FFDiag(E);
2648     return false;
2649   }
2650 
2651   APSInt &Int = Value.getInt();
2652   unsigned OldBitWidth = Int.getBitWidth();
2653   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2654   if (NewBitWidth < OldBitWidth)
2655     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2656   return true;
2657 }
2658 
EvalAndBitcastToAPInt(EvalInfo & Info,const Expr * E,llvm::APInt & Res)2659 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2660                                   llvm::APInt &Res) {
2661   APValue SVal;
2662   if (!Evaluate(SVal, Info, E))
2663     return false;
2664   if (SVal.isInt()) {
2665     Res = SVal.getInt();
2666     return true;
2667   }
2668   if (SVal.isFloat()) {
2669     Res = SVal.getFloat().bitcastToAPInt();
2670     return true;
2671   }
2672   if (SVal.isVector()) {
2673     QualType VecTy = E->getType();
2674     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2675     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2676     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2677     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2678     Res = llvm::APInt::getZero(VecSize);
2679     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2680       APValue &Elt = SVal.getVectorElt(i);
2681       llvm::APInt EltAsInt;
2682       if (Elt.isInt()) {
2683         EltAsInt = Elt.getInt();
2684       } else if (Elt.isFloat()) {
2685         EltAsInt = Elt.getFloat().bitcastToAPInt();
2686       } else {
2687         // Don't try to handle vectors of anything other than int or float
2688         // (not sure if it's possible to hit this case).
2689         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2690         return false;
2691       }
2692       unsigned BaseEltSize = EltAsInt.getBitWidth();
2693       if (BigEndian)
2694         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2695       else
2696         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2697     }
2698     return true;
2699   }
2700   // Give up if the input isn't an int, float, or vector.  For example, we
2701   // reject "(v4i16)(intptr_t)&a".
2702   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2703   return false;
2704 }
2705 
2706 /// Perform the given integer operation, which is known to need at most BitWidth
2707 /// bits, and check for overflow in the original type (if that type was not an
2708 /// unsigned type).
2709 template<typename Operation>
CheckedIntArithmetic(EvalInfo & Info,const Expr * E,const APSInt & LHS,const APSInt & RHS,unsigned BitWidth,Operation Op,APSInt & Result)2710 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2711                                  const APSInt &LHS, const APSInt &RHS,
2712                                  unsigned BitWidth, Operation Op,
2713                                  APSInt &Result) {
2714   if (LHS.isUnsigned()) {
2715     Result = Op(LHS, RHS);
2716     return true;
2717   }
2718 
2719   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2720   Result = Value.trunc(LHS.getBitWidth());
2721   if (Result.extend(BitWidth) != Value) {
2722     if (Info.checkingForUndefinedBehavior())
2723       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2724                                        diag::warn_integer_constant_overflow)
2725           << toString(Result, 10) << E->getType();
2726     return HandleOverflow(Info, E, Value, E->getType());
2727   }
2728   return true;
2729 }
2730 
2731 /// Perform the given binary integer operation.
handleIntIntBinOp(EvalInfo & Info,const Expr * E,const APSInt & LHS,BinaryOperatorKind Opcode,APSInt RHS,APSInt & Result)2732 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2733                               BinaryOperatorKind Opcode, APSInt RHS,
2734                               APSInt &Result) {
2735   switch (Opcode) {
2736   default:
2737     Info.FFDiag(E);
2738     return false;
2739   case BO_Mul:
2740     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2741                                 std::multiplies<APSInt>(), Result);
2742   case BO_Add:
2743     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2744                                 std::plus<APSInt>(), Result);
2745   case BO_Sub:
2746     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2747                                 std::minus<APSInt>(), Result);
2748   case BO_And: Result = LHS & RHS; return true;
2749   case BO_Xor: Result = LHS ^ RHS; return true;
2750   case BO_Or:  Result = LHS | RHS; return true;
2751   case BO_Div:
2752   case BO_Rem:
2753     if (RHS == 0) {
2754       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2755       return false;
2756     }
2757     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2758     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2759     // this operation and gives the two's complement result.
2760     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2761         LHS.isMinSignedValue())
2762       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2763                             E->getType());
2764     return true;
2765   case BO_Shl: {
2766     if (Info.getLangOpts().OpenCL)
2767       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2768       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2769                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2770                     RHS.isUnsigned());
2771     else if (RHS.isSigned() && RHS.isNegative()) {
2772       // During constant-folding, a negative shift is an opposite shift. Such
2773       // a shift is not a constant expression.
2774       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2775       RHS = -RHS;
2776       goto shift_right;
2777     }
2778   shift_left:
2779     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2780     // the shifted type.
2781     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2782     if (SA != RHS) {
2783       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2784         << RHS << E->getType() << LHS.getBitWidth();
2785     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2786       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2787       // operand, and must not overflow the corresponding unsigned type.
2788       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2789       // E1 x 2^E2 module 2^N.
2790       if (LHS.isNegative())
2791         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2792       else if (LHS.countLeadingZeros() < SA)
2793         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2794     }
2795     Result = LHS << SA;
2796     return true;
2797   }
2798   case BO_Shr: {
2799     if (Info.getLangOpts().OpenCL)
2800       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2801       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2802                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2803                     RHS.isUnsigned());
2804     else if (RHS.isSigned() && RHS.isNegative()) {
2805       // During constant-folding, a negative shift is an opposite shift. Such a
2806       // shift is not a constant expression.
2807       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2808       RHS = -RHS;
2809       goto shift_left;
2810     }
2811   shift_right:
2812     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2813     // shifted type.
2814     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2815     if (SA != RHS)
2816       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2817         << RHS << E->getType() << LHS.getBitWidth();
2818     Result = LHS >> SA;
2819     return true;
2820   }
2821 
2822   case BO_LT: Result = LHS < RHS; return true;
2823   case BO_GT: Result = LHS > RHS; return true;
2824   case BO_LE: Result = LHS <= RHS; return true;
2825   case BO_GE: Result = LHS >= RHS; return true;
2826   case BO_EQ: Result = LHS == RHS; return true;
2827   case BO_NE: Result = LHS != RHS; return true;
2828   case BO_Cmp:
2829     llvm_unreachable("BO_Cmp should be handled elsewhere");
2830   }
2831 }
2832 
2833 /// Perform the given binary floating-point operation, in-place, on LHS.
handleFloatFloatBinOp(EvalInfo & Info,const BinaryOperator * E,APFloat & LHS,BinaryOperatorKind Opcode,const APFloat & RHS)2834 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2835                                   APFloat &LHS, BinaryOperatorKind Opcode,
2836                                   const APFloat &RHS) {
2837   bool DynamicRM;
2838   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2839   APFloat::opStatus St;
2840   switch (Opcode) {
2841   default:
2842     Info.FFDiag(E);
2843     return false;
2844   case BO_Mul:
2845     St = LHS.multiply(RHS, RM);
2846     break;
2847   case BO_Add:
2848     St = LHS.add(RHS, RM);
2849     break;
2850   case BO_Sub:
2851     St = LHS.subtract(RHS, RM);
2852     break;
2853   case BO_Div:
2854     // [expr.mul]p4:
2855     //   If the second operand of / or % is zero the behavior is undefined.
2856     if (RHS.isZero())
2857       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2858     St = LHS.divide(RHS, RM);
2859     break;
2860   }
2861 
2862   // [expr.pre]p4:
2863   //   If during the evaluation of an expression, the result is not
2864   //   mathematically defined [...], the behavior is undefined.
2865   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2866   if (LHS.isNaN()) {
2867     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2868     return Info.noteUndefinedBehavior();
2869   }
2870 
2871   return checkFloatingPointResult(Info, E, St);
2872 }
2873 
handleLogicalOpForVector(const APInt & LHSValue,BinaryOperatorKind Opcode,const APInt & RHSValue,APInt & Result)2874 static bool handleLogicalOpForVector(const APInt &LHSValue,
2875                                      BinaryOperatorKind Opcode,
2876                                      const APInt &RHSValue, APInt &Result) {
2877   bool LHS = (LHSValue != 0);
2878   bool RHS = (RHSValue != 0);
2879 
2880   if (Opcode == BO_LAnd)
2881     Result = LHS && RHS;
2882   else
2883     Result = LHS || RHS;
2884   return true;
2885 }
handleLogicalOpForVector(const APFloat & LHSValue,BinaryOperatorKind Opcode,const APFloat & RHSValue,APInt & Result)2886 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2887                                      BinaryOperatorKind Opcode,
2888                                      const APFloat &RHSValue, APInt &Result) {
2889   bool LHS = !LHSValue.isZero();
2890   bool RHS = !RHSValue.isZero();
2891 
2892   if (Opcode == BO_LAnd)
2893     Result = LHS && RHS;
2894   else
2895     Result = LHS || RHS;
2896   return true;
2897 }
2898 
handleLogicalOpForVector(const APValue & LHSValue,BinaryOperatorKind Opcode,const APValue & RHSValue,APInt & Result)2899 static bool handleLogicalOpForVector(const APValue &LHSValue,
2900                                      BinaryOperatorKind Opcode,
2901                                      const APValue &RHSValue, APInt &Result) {
2902   // The result is always an int type, however operands match the first.
2903   if (LHSValue.getKind() == APValue::Int)
2904     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2905                                     RHSValue.getInt(), Result);
2906   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2907   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2908                                   RHSValue.getFloat(), Result);
2909 }
2910 
2911 template <typename APTy>
2912 static bool
handleCompareOpForVectorHelper(const APTy & LHSValue,BinaryOperatorKind Opcode,const APTy & RHSValue,APInt & Result)2913 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2914                                const APTy &RHSValue, APInt &Result) {
2915   switch (Opcode) {
2916   default:
2917     llvm_unreachable("unsupported binary operator");
2918   case BO_EQ:
2919     Result = (LHSValue == RHSValue);
2920     break;
2921   case BO_NE:
2922     Result = (LHSValue != RHSValue);
2923     break;
2924   case BO_LT:
2925     Result = (LHSValue < RHSValue);
2926     break;
2927   case BO_GT:
2928     Result = (LHSValue > RHSValue);
2929     break;
2930   case BO_LE:
2931     Result = (LHSValue <= RHSValue);
2932     break;
2933   case BO_GE:
2934     Result = (LHSValue >= RHSValue);
2935     break;
2936   }
2937 
2938   return true;
2939 }
2940 
handleCompareOpForVector(const APValue & LHSValue,BinaryOperatorKind Opcode,const APValue & RHSValue,APInt & Result)2941 static bool handleCompareOpForVector(const APValue &LHSValue,
2942                                      BinaryOperatorKind Opcode,
2943                                      const APValue &RHSValue, APInt &Result) {
2944   // The result is always an int type, however operands match the first.
2945   if (LHSValue.getKind() == APValue::Int)
2946     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2947                                           RHSValue.getInt(), Result);
2948   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2949   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2950                                         RHSValue.getFloat(), Result);
2951 }
2952 
2953 // Perform binary operations for vector types, in place on the LHS.
handleVectorVectorBinOp(EvalInfo & Info,const BinaryOperator * E,BinaryOperatorKind Opcode,APValue & LHSValue,const APValue & RHSValue)2954 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2955                                     BinaryOperatorKind Opcode,
2956                                     APValue &LHSValue,
2957                                     const APValue &RHSValue) {
2958   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2959          "Operation not supported on vector types");
2960 
2961   const auto *VT = E->getType()->castAs<VectorType>();
2962   unsigned NumElements = VT->getNumElements();
2963   QualType EltTy = VT->getElementType();
2964 
2965   // In the cases (typically C as I've observed) where we aren't evaluating
2966   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2967   // just give up.
2968   if (!LHSValue.isVector()) {
2969     assert(LHSValue.isLValue() &&
2970            "A vector result that isn't a vector OR uncalculated LValue");
2971     Info.FFDiag(E);
2972     return false;
2973   }
2974 
2975   assert(LHSValue.getVectorLength() == NumElements &&
2976          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2977 
2978   SmallVector<APValue, 4> ResultElements;
2979 
2980   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2981     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2982     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2983 
2984     if (EltTy->isIntegerType()) {
2985       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2986                        EltTy->isUnsignedIntegerType()};
2987       bool Success = true;
2988 
2989       if (BinaryOperator::isLogicalOp(Opcode))
2990         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2991       else if (BinaryOperator::isComparisonOp(Opcode))
2992         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2993       else
2994         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2995                                     RHSElt.getInt(), EltResult);
2996 
2997       if (!Success) {
2998         Info.FFDiag(E);
2999         return false;
3000       }
3001       ResultElements.emplace_back(EltResult);
3002 
3003     } else if (EltTy->isFloatingType()) {
3004       assert(LHSElt.getKind() == APValue::Float &&
3005              RHSElt.getKind() == APValue::Float &&
3006              "Mismatched LHS/RHS/Result Type");
3007       APFloat LHSFloat = LHSElt.getFloat();
3008 
3009       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3010                                  RHSElt.getFloat())) {
3011         Info.FFDiag(E);
3012         return false;
3013       }
3014 
3015       ResultElements.emplace_back(LHSFloat);
3016     }
3017   }
3018 
3019   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3020   return true;
3021 }
3022 
3023 /// Cast an lvalue referring to a base subobject to a derived class, by
3024 /// truncating the lvalue's path to the given length.
CastToDerivedClass(EvalInfo & Info,const Expr * E,LValue & Result,const RecordDecl * TruncatedType,unsigned TruncatedElements)3025 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3026                                const RecordDecl *TruncatedType,
3027                                unsigned TruncatedElements) {
3028   SubobjectDesignator &D = Result.Designator;
3029 
3030   // Check we actually point to a derived class object.
3031   if (TruncatedElements == D.Entries.size())
3032     return true;
3033   assert(TruncatedElements >= D.MostDerivedPathLength &&
3034          "not casting to a derived class");
3035   if (!Result.checkSubobject(Info, E, CSK_Derived))
3036     return false;
3037 
3038   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3039   const RecordDecl *RD = TruncatedType;
3040   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3041     if (RD->isInvalidDecl()) return false;
3042     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3043     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3044     if (isVirtualBaseClass(D.Entries[I]))
3045       Result.Offset -= Layout.getVBaseClassOffset(Base);
3046     else
3047       Result.Offset -= Layout.getBaseClassOffset(Base);
3048     RD = Base;
3049   }
3050   D.Entries.resize(TruncatedElements);
3051   return true;
3052 }
3053 
HandleLValueDirectBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * Derived,const CXXRecordDecl * Base,const ASTRecordLayout * RL=nullptr)3054 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3055                                    const CXXRecordDecl *Derived,
3056                                    const CXXRecordDecl *Base,
3057                                    const ASTRecordLayout *RL = nullptr) {
3058   if (!RL) {
3059     if (Derived->isInvalidDecl()) return false;
3060     RL = &Info.Ctx.getASTRecordLayout(Derived);
3061   }
3062 
3063   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3064   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3065   return true;
3066 }
3067 
HandleLValueBase(EvalInfo & Info,const Expr * E,LValue & Obj,const CXXRecordDecl * DerivedDecl,const CXXBaseSpecifier * Base)3068 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3069                              const CXXRecordDecl *DerivedDecl,
3070                              const CXXBaseSpecifier *Base) {
3071   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3072 
3073   if (!Base->isVirtual())
3074     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3075 
3076   SubobjectDesignator &D = Obj.Designator;
3077   if (D.Invalid)
3078     return false;
3079 
3080   // Extract most-derived object and corresponding type.
3081   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3082   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3083     return false;
3084 
3085   // Find the virtual base class.
3086   if (DerivedDecl->isInvalidDecl()) return false;
3087   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3088   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3089   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3090   return true;
3091 }
3092 
HandleLValueBasePath(EvalInfo & Info,const CastExpr * E,QualType Type,LValue & Result)3093 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3094                                  QualType Type, LValue &Result) {
3095   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3096                                      PathE = E->path_end();
3097        PathI != PathE; ++PathI) {
3098     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3099                           *PathI))
3100       return false;
3101     Type = (*PathI)->getType();
3102   }
3103   return true;
3104 }
3105 
3106 /// 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)3107 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3108                             const CXXRecordDecl *DerivedRD,
3109                             const CXXRecordDecl *BaseRD) {
3110   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3111                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3112   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3113     llvm_unreachable("Class must be derived from the passed in base class!");
3114 
3115   for (CXXBasePathElement &Elem : Paths.front())
3116     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3117       return false;
3118   return true;
3119 }
3120 
3121 /// Update LVal to refer to the given field, which must be a member of the type
3122 /// currently described by LVal.
HandleLValueMember(EvalInfo & Info,const Expr * E,LValue & LVal,const FieldDecl * FD,const ASTRecordLayout * RL=nullptr)3123 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3124                                const FieldDecl *FD,
3125                                const ASTRecordLayout *RL = nullptr) {
3126   if (!RL) {
3127     if (FD->getParent()->isInvalidDecl()) return false;
3128     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3129   }
3130 
3131   unsigned I = FD->getFieldIndex();
3132   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3133   LVal.addDecl(Info, E, FD);
3134   return true;
3135 }
3136 
3137 /// Update LVal to refer to the given indirect field.
HandleLValueIndirectMember(EvalInfo & Info,const Expr * E,LValue & LVal,const IndirectFieldDecl * IFD)3138 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3139                                        LValue &LVal,
3140                                        const IndirectFieldDecl *IFD) {
3141   for (const auto *C : IFD->chain())
3142     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3143       return false;
3144   return true;
3145 }
3146 
3147 /// Get the size of the given type in char units.
HandleSizeof(EvalInfo & Info,SourceLocation Loc,QualType Type,CharUnits & Size)3148 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3149                          QualType Type, CharUnits &Size) {
3150   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3151   // extension.
3152   if (Type->isVoidType() || Type->isFunctionType()) {
3153     Size = CharUnits::One();
3154     return true;
3155   }
3156 
3157   if (Type->isDependentType()) {
3158     Info.FFDiag(Loc);
3159     return false;
3160   }
3161 
3162   if (!Type->isConstantSizeType()) {
3163     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3164     // FIXME: Better diagnostic.
3165     Info.FFDiag(Loc);
3166     return false;
3167   }
3168 
3169   Size = Info.Ctx.getTypeSizeInChars(Type);
3170   return true;
3171 }
3172 
3173 /// Update a pointer value to model pointer arithmetic.
3174 /// \param Info - Information about the ongoing evaluation.
3175 /// \param E - The expression being evaluated, for diagnostic purposes.
3176 /// \param LVal - The pointer value to be updated.
3177 /// \param EltTy - The pointee type represented by LVal.
3178 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,APSInt Adjustment)3179 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3180                                         LValue &LVal, QualType EltTy,
3181                                         APSInt Adjustment) {
3182   CharUnits SizeOfPointee;
3183   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3184     return false;
3185 
3186   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3187   return true;
3188 }
3189 
HandleLValueArrayAdjustment(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,int64_t Adjustment)3190 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3191                                         LValue &LVal, QualType EltTy,
3192                                         int64_t Adjustment) {
3193   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3194                                      APSInt::get(Adjustment));
3195 }
3196 
3197 /// Update an lvalue to refer to a component of a complex number.
3198 /// \param Info - Information about the ongoing evaluation.
3199 /// \param LVal - The lvalue to be updated.
3200 /// \param EltTy - The complex number's component type.
3201 /// \param Imag - False for the real component, true for the imaginary.
HandleLValueComplexElement(EvalInfo & Info,const Expr * E,LValue & LVal,QualType EltTy,bool Imag)3202 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3203                                        LValue &LVal, QualType EltTy,
3204                                        bool Imag) {
3205   if (Imag) {
3206     CharUnits SizeOfComponent;
3207     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3208       return false;
3209     LVal.Offset += SizeOfComponent;
3210   }
3211   LVal.addComplex(Info, E, EltTy, Imag);
3212   return true;
3213 }
3214 
3215 /// Try to evaluate the initializer for a variable declaration.
3216 ///
3217 /// \param Info   Information about the ongoing evaluation.
3218 /// \param E      An expression to be used when printing diagnostics.
3219 /// \param VD     The variable whose initializer should be obtained.
3220 /// \param Version The version of the variable within the frame.
3221 /// \param Frame  The frame in which the variable was created. Must be null
3222 ///               if this variable is not local to the evaluation.
3223 /// \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)3224 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3225                                 const VarDecl *VD, CallStackFrame *Frame,
3226                                 unsigned Version, APValue *&Result) {
3227   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3228 
3229   // If this is a local variable, dig out its value.
3230   if (Frame) {
3231     Result = Frame->getTemporary(VD, Version);
3232     if (Result)
3233       return true;
3234 
3235     if (!isa<ParmVarDecl>(VD)) {
3236       // Assume variables referenced within a lambda's call operator that were
3237       // not declared within the call operator are captures and during checking
3238       // of a potential constant expression, assume they are unknown constant
3239       // expressions.
3240       assert(isLambdaCallOperator(Frame->Callee) &&
3241              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3242              "missing value for local variable");
3243       if (Info.checkingPotentialConstantExpression())
3244         return false;
3245       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3246       // still reachable at all?
3247       Info.FFDiag(E->getBeginLoc(),
3248                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3249           << "captures not currently allowed";
3250       return false;
3251     }
3252   }
3253 
3254   // If we're currently evaluating the initializer of this declaration, use that
3255   // in-flight value.
3256   if (Info.EvaluatingDecl == Base) {
3257     Result = Info.EvaluatingDeclValue;
3258     return true;
3259   }
3260 
3261   if (isa<ParmVarDecl>(VD)) {
3262     // Assume parameters of a potential constant expression are usable in
3263     // constant expressions.
3264     if (!Info.checkingPotentialConstantExpression() ||
3265         !Info.CurrentCall->Callee ||
3266         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3267       if (Info.getLangOpts().CPlusPlus11) {
3268         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3269             << VD;
3270         NoteLValueLocation(Info, Base);
3271       } else {
3272         Info.FFDiag(E);
3273       }
3274     }
3275     return false;
3276   }
3277 
3278   // Dig out the initializer, and use the declaration which it's attached to.
3279   // FIXME: We should eventually check whether the variable has a reachable
3280   // initializing declaration.
3281   const Expr *Init = VD->getAnyInitializer(VD);
3282   if (!Init) {
3283     // Don't diagnose during potential constant expression checking; an
3284     // initializer might be added later.
3285     if (!Info.checkingPotentialConstantExpression()) {
3286       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3287         << VD;
3288       NoteLValueLocation(Info, Base);
3289     }
3290     return false;
3291   }
3292 
3293   if (Init->isValueDependent()) {
3294     // The DeclRefExpr is not value-dependent, but the variable it refers to
3295     // has a value-dependent initializer. This should only happen in
3296     // constant-folding cases, where the variable is not actually of a suitable
3297     // type for use in a constant expression (otherwise the DeclRefExpr would
3298     // have been value-dependent too), so diagnose that.
3299     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3300     if (!Info.checkingPotentialConstantExpression()) {
3301       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3302                          ? diag::note_constexpr_ltor_non_constexpr
3303                          : diag::note_constexpr_ltor_non_integral, 1)
3304           << VD << VD->getType();
3305       NoteLValueLocation(Info, Base);
3306     }
3307     return false;
3308   }
3309 
3310   // Check that we can fold the initializer. In C++, we will have already done
3311   // this in the cases where it matters for conformance.
3312   if (!VD->evaluateValue()) {
3313     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3314     NoteLValueLocation(Info, Base);
3315     return false;
3316   }
3317 
3318   // Check that the variable is actually usable in constant expressions. For a
3319   // const integral variable or a reference, we might have a non-constant
3320   // initializer that we can nonetheless evaluate the initializer for. Such
3321   // variables are not usable in constant expressions. In C++98, the
3322   // initializer also syntactically needs to be an ICE.
3323   //
3324   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3325   // expressions here; doing so would regress diagnostics for things like
3326   // reading from a volatile constexpr variable.
3327   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3328        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3329       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3330        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3331     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3332     NoteLValueLocation(Info, Base);
3333   }
3334 
3335   // Never use the initializer of a weak variable, not even for constant
3336   // folding. We can't be sure that this is the definition that will be used.
3337   if (VD->isWeak()) {
3338     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3339     NoteLValueLocation(Info, Base);
3340     return false;
3341   }
3342 
3343   Result = VD->getEvaluatedValue();
3344   return true;
3345 }
3346 
3347 /// Get the base index of the given base class within an APValue representing
3348 /// the given derived class.
getBaseIndex(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)3349 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3350                              const CXXRecordDecl *Base) {
3351   Base = Base->getCanonicalDecl();
3352   unsigned Index = 0;
3353   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3354          E = Derived->bases_end(); I != E; ++I, ++Index) {
3355     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3356       return Index;
3357   }
3358 
3359   llvm_unreachable("base class missing from derived class's bases list");
3360 }
3361 
3362 /// Extract the value of a character from a string literal.
extractStringLiteralCharacter(EvalInfo & Info,const Expr * Lit,uint64_t Index)3363 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3364                                             uint64_t Index) {
3365   assert(!isa<SourceLocExpr>(Lit) &&
3366          "SourceLocExpr should have already been converted to a StringLiteral");
3367 
3368   // FIXME: Support MakeStringConstant
3369   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3370     std::string Str;
3371     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3372     assert(Index <= Str.size() && "Index too large");
3373     return APSInt::getUnsigned(Str.c_str()[Index]);
3374   }
3375 
3376   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3377     Lit = PE->getFunctionName();
3378   const StringLiteral *S = cast<StringLiteral>(Lit);
3379   const ConstantArrayType *CAT =
3380       Info.Ctx.getAsConstantArrayType(S->getType());
3381   assert(CAT && "string literal isn't an array");
3382   QualType CharType = CAT->getElementType();
3383   assert(CharType->isIntegerType() && "unexpected character type");
3384 
3385   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3386                CharType->isUnsignedIntegerType());
3387   if (Index < S->getLength())
3388     Value = S->getCodeUnit(Index);
3389   return Value;
3390 }
3391 
3392 // Expand a string literal into an array of characters.
3393 //
3394 // FIXME: This is inefficient; we should probably introduce something similar
3395 // to the LLVM ConstantDataArray to make this cheaper.
expandStringLiteral(EvalInfo & Info,const StringLiteral * S,APValue & Result,QualType AllocType=QualType ())3396 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3397                                 APValue &Result,
3398                                 QualType AllocType = QualType()) {
3399   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3400       AllocType.isNull() ? S->getType() : AllocType);
3401   assert(CAT && "string literal isn't an array");
3402   QualType CharType = CAT->getElementType();
3403   assert(CharType->isIntegerType() && "unexpected character type");
3404 
3405   unsigned Elts = CAT->getSize().getZExtValue();
3406   Result = APValue(APValue::UninitArray(),
3407                    std::min(S->getLength(), Elts), Elts);
3408   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3409                CharType->isUnsignedIntegerType());
3410   if (Result.hasArrayFiller())
3411     Result.getArrayFiller() = APValue(Value);
3412   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3413     Value = S->getCodeUnit(I);
3414     Result.getArrayInitializedElt(I) = APValue(Value);
3415   }
3416 }
3417 
3418 // Expand an array so that it has more than Index filled elements.
expandArray(APValue & Array,unsigned Index)3419 static void expandArray(APValue &Array, unsigned Index) {
3420   unsigned Size = Array.getArraySize();
3421   assert(Index < Size);
3422 
3423   // Always at least double the number of elements for which we store a value.
3424   unsigned OldElts = Array.getArrayInitializedElts();
3425   unsigned NewElts = std::max(Index+1, OldElts * 2);
3426   NewElts = std::min(Size, std::max(NewElts, 8u));
3427 
3428   // Copy the data across.
3429   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3430   for (unsigned I = 0; I != OldElts; ++I)
3431     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3432   for (unsigned I = OldElts; I != NewElts; ++I)
3433     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3434   if (NewValue.hasArrayFiller())
3435     NewValue.getArrayFiller() = Array.getArrayFiller();
3436   Array.swap(NewValue);
3437 }
3438 
3439 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3440 /// conversion. If it's of class type, we may assume that the copy operation
3441 /// is trivial. Note that this is never true for a union type with fields
3442 /// (because the copy always "reads" the active member) and always true for
3443 /// a non-class type.
3444 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
isReadByLvalueToRvalueConversion(QualType T)3445 static bool isReadByLvalueToRvalueConversion(QualType T) {
3446   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3447   return !RD || isReadByLvalueToRvalueConversion(RD);
3448 }
isReadByLvalueToRvalueConversion(const CXXRecordDecl * RD)3449 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3450   // FIXME: A trivial copy of a union copies the object representation, even if
3451   // the union is empty.
3452   if (RD->isUnion())
3453     return !RD->field_empty();
3454   if (RD->isEmpty())
3455     return false;
3456 
3457   for (auto *Field : RD->fields())
3458     if (!Field->isUnnamedBitfield() &&
3459         isReadByLvalueToRvalueConversion(Field->getType()))
3460       return true;
3461 
3462   for (auto &BaseSpec : RD->bases())
3463     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3464       return true;
3465 
3466   return false;
3467 }
3468 
3469 /// Diagnose an attempt to read from any unreadable field within the specified
3470 /// type, which might be a class type.
diagnoseMutableFields(EvalInfo & Info,const Expr * E,AccessKinds AK,QualType T)3471 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3472                                   QualType T) {
3473   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3474   if (!RD)
3475     return false;
3476 
3477   if (!RD->hasMutableFields())
3478     return false;
3479 
3480   for (auto *Field : RD->fields()) {
3481     // If we're actually going to read this field in some way, then it can't
3482     // be mutable. If we're in a union, then assigning to a mutable field
3483     // (even an empty one) can change the active member, so that's not OK.
3484     // FIXME: Add core issue number for the union case.
3485     if (Field->isMutable() &&
3486         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3487       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3488       Info.Note(Field->getLocation(), diag::note_declared_at);
3489       return true;
3490     }
3491 
3492     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3493       return true;
3494   }
3495 
3496   for (auto &BaseSpec : RD->bases())
3497     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3498       return true;
3499 
3500   // All mutable fields were empty, and thus not actually read.
3501   return false;
3502 }
3503 
lifetimeStartedInEvaluation(EvalInfo & Info,APValue::LValueBase Base,bool MutableSubobject=false)3504 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3505                                         APValue::LValueBase Base,
3506                                         bool MutableSubobject = false) {
3507   // A temporary or transient heap allocation we created.
3508   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3509     return true;
3510 
3511   switch (Info.IsEvaluatingDecl) {
3512   case EvalInfo::EvaluatingDeclKind::None:
3513     return false;
3514 
3515   case EvalInfo::EvaluatingDeclKind::Ctor:
3516     // The variable whose initializer we're evaluating.
3517     if (Info.EvaluatingDecl == Base)
3518       return true;
3519 
3520     // A temporary lifetime-extended by the variable whose initializer we're
3521     // evaluating.
3522     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3523       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3524         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3525     return false;
3526 
3527   case EvalInfo::EvaluatingDeclKind::Dtor:
3528     // C++2a [expr.const]p6:
3529     //   [during constant destruction] the lifetime of a and its non-mutable
3530     //   subobjects (but not its mutable subobjects) [are] considered to start
3531     //   within e.
3532     if (MutableSubobject || Base != Info.EvaluatingDecl)
3533       return false;
3534     // FIXME: We can meaningfully extend this to cover non-const objects, but
3535     // we will need special handling: we should be able to access only
3536     // subobjects of such objects that are themselves declared const.
3537     QualType T = getType(Base);
3538     return T.isConstQualified() || T->isReferenceType();
3539   }
3540 
3541   llvm_unreachable("unknown evaluating decl kind");
3542 }
3543 
3544 namespace {
3545 /// A handle to a complete object (an object that is not a subobject of
3546 /// another object).
3547 struct CompleteObject {
3548   /// The identity of the object.
3549   APValue::LValueBase Base;
3550   /// The value of the complete object.
3551   APValue *Value;
3552   /// The type of the complete object.
3553   QualType Type;
3554 
CompleteObject__anon4a4db2530911::CompleteObject3555   CompleteObject() : Value(nullptr) {}
CompleteObject__anon4a4db2530911::CompleteObject3556   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3557       : Base(Base), Value(Value), Type(Type) {}
3558 
mayAccessMutableMembers__anon4a4db2530911::CompleteObject3559   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3560     // If this isn't a "real" access (eg, if it's just accessing the type
3561     // info), allow it. We assume the type doesn't change dynamically for
3562     // subobjects of constexpr objects (even though we'd hit UB here if it
3563     // did). FIXME: Is this right?
3564     if (!isAnyAccess(AK))
3565       return true;
3566 
3567     // In C++14 onwards, it is permitted to read a mutable member whose
3568     // lifetime began within the evaluation.
3569     // FIXME: Should we also allow this in C++11?
3570     if (!Info.getLangOpts().CPlusPlus14)
3571       return false;
3572     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3573   }
3574 
operator bool__anon4a4db2530911::CompleteObject3575   explicit operator bool() const { return !Type.isNull(); }
3576 };
3577 } // end anonymous namespace
3578 
getSubobjectType(QualType ObjType,QualType SubobjType,bool IsMutable=false)3579 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3580                                  bool IsMutable = false) {
3581   // C++ [basic.type.qualifier]p1:
3582   // - A const object is an object of type const T or a non-mutable subobject
3583   //   of a const object.
3584   if (ObjType.isConstQualified() && !IsMutable)
3585     SubobjType.addConst();
3586   // - A volatile object is an object of type const T or a subobject of a
3587   //   volatile object.
3588   if (ObjType.isVolatileQualified())
3589     SubobjType.addVolatile();
3590   return SubobjType;
3591 }
3592 
3593 /// Find the designated sub-object of an rvalue.
3594 template<typename SubobjectHandler>
3595 typename SubobjectHandler::result_type
findSubobject(EvalInfo & Info,const Expr * E,const CompleteObject & Obj,const SubobjectDesignator & Sub,SubobjectHandler & handler)3596 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3597               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3598   if (Sub.Invalid)
3599     // A diagnostic will have already been produced.
3600     return handler.failed();
3601   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3602     if (Info.getLangOpts().CPlusPlus11)
3603       Info.FFDiag(E, Sub.isOnePastTheEnd()
3604                          ? diag::note_constexpr_access_past_end
3605                          : diag::note_constexpr_access_unsized_array)
3606           << handler.AccessKind;
3607     else
3608       Info.FFDiag(E);
3609     return handler.failed();
3610   }
3611 
3612   APValue *O = Obj.Value;
3613   QualType ObjType = Obj.Type;
3614   const FieldDecl *LastField = nullptr;
3615   const FieldDecl *VolatileField = nullptr;
3616 
3617   // Walk the designator's path to find the subobject.
3618   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3619     // Reading an indeterminate value is undefined, but assigning over one is OK.
3620     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3621         (O->isIndeterminate() &&
3622          !isValidIndeterminateAccess(handler.AccessKind))) {
3623       if (!Info.checkingPotentialConstantExpression())
3624         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3625             << handler.AccessKind << O->isIndeterminate();
3626       return handler.failed();
3627     }
3628 
3629     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3630     //    const and volatile semantics are not applied on an object under
3631     //    {con,de}struction.
3632     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3633         ObjType->isRecordType() &&
3634         Info.isEvaluatingCtorDtor(
3635             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3636                                          Sub.Entries.begin() + I)) !=
3637                           ConstructionPhase::None) {
3638       ObjType = Info.Ctx.getCanonicalType(ObjType);
3639       ObjType.removeLocalConst();
3640       ObjType.removeLocalVolatile();
3641     }
3642 
3643     // If this is our last pass, check that the final object type is OK.
3644     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3645       // Accesses to volatile objects are prohibited.
3646       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3647         if (Info.getLangOpts().CPlusPlus) {
3648           int DiagKind;
3649           SourceLocation Loc;
3650           const NamedDecl *Decl = nullptr;
3651           if (VolatileField) {
3652             DiagKind = 2;
3653             Loc = VolatileField->getLocation();
3654             Decl = VolatileField;
3655           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3656             DiagKind = 1;
3657             Loc = VD->getLocation();
3658             Decl = VD;
3659           } else {
3660             DiagKind = 0;
3661             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3662               Loc = E->getExprLoc();
3663           }
3664           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3665               << handler.AccessKind << DiagKind << Decl;
3666           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3667         } else {
3668           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3669         }
3670         return handler.failed();
3671       }
3672 
3673       // If we are reading an object of class type, there may still be more
3674       // things we need to check: if there are any mutable subobjects, we
3675       // cannot perform this read. (This only happens when performing a trivial
3676       // copy or assignment.)
3677       if (ObjType->isRecordType() &&
3678           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3679           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3680         return handler.failed();
3681     }
3682 
3683     if (I == N) {
3684       if (!handler.found(*O, ObjType))
3685         return false;
3686 
3687       // If we modified a bit-field, truncate it to the right width.
3688       if (isModification(handler.AccessKind) &&
3689           LastField && LastField->isBitField() &&
3690           !truncateBitfieldValue(Info, E, *O, LastField))
3691         return false;
3692 
3693       return true;
3694     }
3695 
3696     LastField = nullptr;
3697     if (ObjType->isArrayType()) {
3698       // Next subobject is an array element.
3699       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3700       assert(CAT && "vla in literal type?");
3701       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3702       if (CAT->getSize().ule(Index)) {
3703         // Note, it should not be possible to form a pointer with a valid
3704         // designator which points more than one past the end of the array.
3705         if (Info.getLangOpts().CPlusPlus11)
3706           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3707             << handler.AccessKind;
3708         else
3709           Info.FFDiag(E);
3710         return handler.failed();
3711       }
3712 
3713       ObjType = CAT->getElementType();
3714 
3715       if (O->getArrayInitializedElts() > Index)
3716         O = &O->getArrayInitializedElt(Index);
3717       else if (!isRead(handler.AccessKind)) {
3718         expandArray(*O, Index);
3719         O = &O->getArrayInitializedElt(Index);
3720       } else
3721         O = &O->getArrayFiller();
3722     } else if (ObjType->isAnyComplexType()) {
3723       // Next subobject is a complex number.
3724       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3725       if (Index > 1) {
3726         if (Info.getLangOpts().CPlusPlus11)
3727           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3728             << handler.AccessKind;
3729         else
3730           Info.FFDiag(E);
3731         return handler.failed();
3732       }
3733 
3734       ObjType = getSubobjectType(
3735           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3736 
3737       assert(I == N - 1 && "extracting subobject of scalar?");
3738       if (O->isComplexInt()) {
3739         return handler.found(Index ? O->getComplexIntImag()
3740                                    : O->getComplexIntReal(), ObjType);
3741       } else {
3742         assert(O->isComplexFloat());
3743         return handler.found(Index ? O->getComplexFloatImag()
3744                                    : O->getComplexFloatReal(), ObjType);
3745       }
3746     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3747       if (Field->isMutable() &&
3748           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3749         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3750           << handler.AccessKind << Field;
3751         Info.Note(Field->getLocation(), diag::note_declared_at);
3752         return handler.failed();
3753       }
3754 
3755       // Next subobject is a class, struct or union field.
3756       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3757       if (RD->isUnion()) {
3758         const FieldDecl *UnionField = O->getUnionField();
3759         if (!UnionField ||
3760             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3761           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3762             // Placement new onto an inactive union member makes it active.
3763             O->setUnion(Field, APValue());
3764           } else {
3765             // FIXME: If O->getUnionValue() is absent, report that there's no
3766             // active union member rather than reporting the prior active union
3767             // member. We'll need to fix nullptr_t to not use APValue() as its
3768             // representation first.
3769             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3770                 << handler.AccessKind << Field << !UnionField << UnionField;
3771             return handler.failed();
3772           }
3773         }
3774         O = &O->getUnionValue();
3775       } else
3776         O = &O->getStructField(Field->getFieldIndex());
3777 
3778       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3779       LastField = Field;
3780       if (Field->getType().isVolatileQualified())
3781         VolatileField = Field;
3782     } else {
3783       // Next subobject is a base class.
3784       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3785       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3786       O = &O->getStructBase(getBaseIndex(Derived, Base));
3787 
3788       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3789     }
3790   }
3791 }
3792 
3793 namespace {
3794 struct ExtractSubobjectHandler {
3795   EvalInfo &Info;
3796   const Expr *E;
3797   APValue &Result;
3798   const AccessKinds AccessKind;
3799 
3800   typedef bool result_type;
failed__anon4a4db2530a11::ExtractSubobjectHandler3801   bool failed() { return false; }
found__anon4a4db2530a11::ExtractSubobjectHandler3802   bool found(APValue &Subobj, QualType SubobjType) {
3803     Result = Subobj;
3804     if (AccessKind == AK_ReadObjectRepresentation)
3805       return true;
3806     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3807   }
found__anon4a4db2530a11::ExtractSubobjectHandler3808   bool found(APSInt &Value, QualType SubobjType) {
3809     Result = APValue(Value);
3810     return true;
3811   }
found__anon4a4db2530a11::ExtractSubobjectHandler3812   bool found(APFloat &Value, QualType SubobjType) {
3813     Result = APValue(Value);
3814     return true;
3815   }
3816 };
3817 } // end anonymous namespace
3818 
3819 /// 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)3820 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3821                              const CompleteObject &Obj,
3822                              const SubobjectDesignator &Sub, APValue &Result,
3823                              AccessKinds AK = AK_Read) {
3824   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3825   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3826   return findSubobject(Info, E, Obj, Sub, Handler);
3827 }
3828 
3829 namespace {
3830 struct ModifySubobjectHandler {
3831   EvalInfo &Info;
3832   APValue &NewVal;
3833   const Expr *E;
3834 
3835   typedef bool result_type;
3836   static const AccessKinds AccessKind = AK_Assign;
3837 
checkConst__anon4a4db2530b11::ModifySubobjectHandler3838   bool checkConst(QualType QT) {
3839     // Assigning to a const object has undefined behavior.
3840     if (QT.isConstQualified()) {
3841       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3842       return false;
3843     }
3844     return true;
3845   }
3846 
failed__anon4a4db2530b11::ModifySubobjectHandler3847   bool failed() { return false; }
found__anon4a4db2530b11::ModifySubobjectHandler3848   bool found(APValue &Subobj, QualType SubobjType) {
3849     if (!checkConst(SubobjType))
3850       return false;
3851     // We've been given ownership of NewVal, so just swap it in.
3852     Subobj.swap(NewVal);
3853     return true;
3854   }
found__anon4a4db2530b11::ModifySubobjectHandler3855   bool found(APSInt &Value, QualType SubobjType) {
3856     if (!checkConst(SubobjType))
3857       return false;
3858     if (!NewVal.isInt()) {
3859       // Maybe trying to write a cast pointer value into a complex?
3860       Info.FFDiag(E);
3861       return false;
3862     }
3863     Value = NewVal.getInt();
3864     return true;
3865   }
found__anon4a4db2530b11::ModifySubobjectHandler3866   bool found(APFloat &Value, QualType SubobjType) {
3867     if (!checkConst(SubobjType))
3868       return false;
3869     Value = NewVal.getFloat();
3870     return true;
3871   }
3872 };
3873 } // end anonymous namespace
3874 
3875 const AccessKinds ModifySubobjectHandler::AccessKind;
3876 
3877 /// 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)3878 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3879                             const CompleteObject &Obj,
3880                             const SubobjectDesignator &Sub,
3881                             APValue &NewVal) {
3882   ModifySubobjectHandler Handler = { Info, NewVal, E };
3883   return findSubobject(Info, E, Obj, Sub, Handler);
3884 }
3885 
3886 /// Find the position where two subobject designators diverge, or equivalently
3887 /// the length of the common initial subsequence.
FindDesignatorMismatch(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B,bool & WasArrayIndex)3888 static unsigned FindDesignatorMismatch(QualType ObjType,
3889                                        const SubobjectDesignator &A,
3890                                        const SubobjectDesignator &B,
3891                                        bool &WasArrayIndex) {
3892   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3893   for (/**/; I != N; ++I) {
3894     if (!ObjType.isNull() &&
3895         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3896       // Next subobject is an array element.
3897       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3898         WasArrayIndex = true;
3899         return I;
3900       }
3901       if (ObjType->isAnyComplexType())
3902         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3903       else
3904         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3905     } else {
3906       if (A.Entries[I].getAsBaseOrMember() !=
3907           B.Entries[I].getAsBaseOrMember()) {
3908         WasArrayIndex = false;
3909         return I;
3910       }
3911       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3912         // Next subobject is a field.
3913         ObjType = FD->getType();
3914       else
3915         // Next subobject is a base class.
3916         ObjType = QualType();
3917     }
3918   }
3919   WasArrayIndex = false;
3920   return I;
3921 }
3922 
3923 /// Determine whether the given subobject designators refer to elements of the
3924 /// same array object.
AreElementsOfSameArray(QualType ObjType,const SubobjectDesignator & A,const SubobjectDesignator & B)3925 static bool AreElementsOfSameArray(QualType ObjType,
3926                                    const SubobjectDesignator &A,
3927                                    const SubobjectDesignator &B) {
3928   if (A.Entries.size() != B.Entries.size())
3929     return false;
3930 
3931   bool IsArray = A.MostDerivedIsArrayElement;
3932   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3933     // A is a subobject of the array element.
3934     return false;
3935 
3936   // If A (and B) designates an array element, the last entry will be the array
3937   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3938   // of length 1' case, and the entire path must match.
3939   bool WasArrayIndex;
3940   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3941   return CommonLength >= A.Entries.size() - IsArray;
3942 }
3943 
3944 /// Find the complete object to which an LValue refers.
findCompleteObject(EvalInfo & Info,const Expr * E,AccessKinds AK,const LValue & LVal,QualType LValType)3945 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3946                                          AccessKinds AK, const LValue &LVal,
3947                                          QualType LValType) {
3948   if (LVal.InvalidBase) {
3949     Info.FFDiag(E);
3950     return CompleteObject();
3951   }
3952 
3953   if (!LVal.Base) {
3954     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3955     return CompleteObject();
3956   }
3957 
3958   CallStackFrame *Frame = nullptr;
3959   unsigned Depth = 0;
3960   if (LVal.getLValueCallIndex()) {
3961     std::tie(Frame, Depth) =
3962         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3963     if (!Frame) {
3964       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3965         << AK << LVal.Base.is<const ValueDecl*>();
3966       NoteLValueLocation(Info, LVal.Base);
3967       return CompleteObject();
3968     }
3969   }
3970 
3971   bool IsAccess = isAnyAccess(AK);
3972 
3973   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3974   // is not a constant expression (even if the object is non-volatile). We also
3975   // apply this rule to C++98, in order to conform to the expected 'volatile'
3976   // semantics.
3977   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3978     if (Info.getLangOpts().CPlusPlus)
3979       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3980         << AK << LValType;
3981     else
3982       Info.FFDiag(E);
3983     return CompleteObject();
3984   }
3985 
3986   // Compute value storage location and type of base object.
3987   APValue *BaseVal = nullptr;
3988   QualType BaseType = getType(LVal.Base);
3989 
3990   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
3991       lifetimeStartedInEvaluation(Info, LVal.Base)) {
3992     // This is the object whose initializer we're evaluating, so its lifetime
3993     // started in the current evaluation.
3994     BaseVal = Info.EvaluatingDeclValue;
3995   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3996     // Allow reading from a GUID declaration.
3997     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3998       if (isModification(AK)) {
3999         // All the remaining cases do not permit modification of the object.
4000         Info.FFDiag(E, diag::note_constexpr_modify_global);
4001         return CompleteObject();
4002       }
4003       APValue &V = GD->getAsAPValue();
4004       if (V.isAbsent()) {
4005         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4006             << GD->getType();
4007         return CompleteObject();
4008       }
4009       return CompleteObject(LVal.Base, &V, GD->getType());
4010     }
4011 
4012     // Allow reading from template parameter objects.
4013     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4014       if (isModification(AK)) {
4015         Info.FFDiag(E, diag::note_constexpr_modify_global);
4016         return CompleteObject();
4017       }
4018       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4019                             TPO->getType());
4020     }
4021 
4022     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4023     // In C++11, constexpr, non-volatile variables initialized with constant
4024     // expressions are constant expressions too. Inside constexpr functions,
4025     // parameters are constant expressions even if they're non-const.
4026     // In C++1y, objects local to a constant expression (those with a Frame) are
4027     // both readable and writable inside constant expressions.
4028     // In C, such things can also be folded, although they are not ICEs.
4029     const VarDecl *VD = dyn_cast<VarDecl>(D);
4030     if (VD) {
4031       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4032         VD = VDef;
4033     }
4034     if (!VD || VD->isInvalidDecl()) {
4035       Info.FFDiag(E);
4036       return CompleteObject();
4037     }
4038 
4039     bool IsConstant = BaseType.isConstant(Info.Ctx);
4040 
4041     // Unless we're looking at a local variable or argument in a constexpr call,
4042     // the variable we're reading must be const.
4043     if (!Frame) {
4044       if (IsAccess && isa<ParmVarDecl>(VD)) {
4045         // Access of a parameter that's not associated with a frame isn't going
4046         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4047         // suitable diagnostic.
4048       } else if (Info.getLangOpts().CPlusPlus14 &&
4049                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4050         // OK, we can read and modify an object if we're in the process of
4051         // evaluating its initializer, because its lifetime began in this
4052         // evaluation.
4053       } else if (isModification(AK)) {
4054         // All the remaining cases do not permit modification of the object.
4055         Info.FFDiag(E, diag::note_constexpr_modify_global);
4056         return CompleteObject();
4057       } else if (VD->isConstexpr()) {
4058         // OK, we can read this variable.
4059       } else if (BaseType->isIntegralOrEnumerationType()) {
4060         if (!IsConstant) {
4061           if (!IsAccess)
4062             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4063           if (Info.getLangOpts().CPlusPlus) {
4064             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4065             Info.Note(VD->getLocation(), diag::note_declared_at);
4066           } else {
4067             Info.FFDiag(E);
4068           }
4069           return CompleteObject();
4070         }
4071       } else if (!IsAccess) {
4072         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4073       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4074                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4075         // This variable might end up being constexpr. Don't diagnose it yet.
4076       } else if (IsConstant) {
4077         // Keep evaluating to see what we can do. In particular, we support
4078         // folding of const floating-point types, in order to make static const
4079         // data members of such types (supported as an extension) more useful.
4080         if (Info.getLangOpts().CPlusPlus) {
4081           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4082                               ? diag::note_constexpr_ltor_non_constexpr
4083                               : diag::note_constexpr_ltor_non_integral, 1)
4084               << VD << BaseType;
4085           Info.Note(VD->getLocation(), diag::note_declared_at);
4086         } else {
4087           Info.CCEDiag(E);
4088         }
4089       } else {
4090         // Never allow reading a non-const value.
4091         if (Info.getLangOpts().CPlusPlus) {
4092           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4093                              ? diag::note_constexpr_ltor_non_constexpr
4094                              : diag::note_constexpr_ltor_non_integral, 1)
4095               << VD << BaseType;
4096           Info.Note(VD->getLocation(), diag::note_declared_at);
4097         } else {
4098           Info.FFDiag(E);
4099         }
4100         return CompleteObject();
4101       }
4102     }
4103 
4104     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4105       return CompleteObject();
4106   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4107     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4108     if (!Alloc) {
4109       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4110       return CompleteObject();
4111     }
4112     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4113                           LVal.Base.getDynamicAllocType());
4114   } else {
4115     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4116 
4117     if (!Frame) {
4118       if (const MaterializeTemporaryExpr *MTE =
4119               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4120         assert(MTE->getStorageDuration() == SD_Static &&
4121                "should have a frame for a non-global materialized temporary");
4122 
4123         // C++20 [expr.const]p4: [DR2126]
4124         //   An object or reference is usable in constant expressions if it is
4125         //   - a temporary object of non-volatile const-qualified literal type
4126         //     whose lifetime is extended to that of a variable that is usable
4127         //     in constant expressions
4128         //
4129         // C++20 [expr.const]p5:
4130         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4131         //   - a non-volatile glvalue that refers to an object that is usable
4132         //     in constant expressions, or
4133         //   - a non-volatile glvalue of literal type that refers to a
4134         //     non-volatile object whose lifetime began within the evaluation
4135         //     of E;
4136         //
4137         // C++11 misses the 'began within the evaluation of e' check and
4138         // instead allows all temporaries, including things like:
4139         //   int &&r = 1;
4140         //   int x = ++r;
4141         //   constexpr int k = r;
4142         // Therefore we use the C++14-onwards rules in C++11 too.
4143         //
4144         // Note that temporaries whose lifetimes began while evaluating a
4145         // variable's constructor are not usable while evaluating the
4146         // corresponding destructor, not even if they're of const-qualified
4147         // types.
4148         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4149             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4150           if (!IsAccess)
4151             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4152           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4153           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4154           return CompleteObject();
4155         }
4156 
4157         BaseVal = MTE->getOrCreateValue(false);
4158         assert(BaseVal && "got reference to unevaluated temporary");
4159       } else {
4160         if (!IsAccess)
4161           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4162         APValue Val;
4163         LVal.moveInto(Val);
4164         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4165             << AK
4166             << Val.getAsString(Info.Ctx,
4167                                Info.Ctx.getLValueReferenceType(LValType));
4168         NoteLValueLocation(Info, LVal.Base);
4169         return CompleteObject();
4170       }
4171     } else {
4172       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4173       assert(BaseVal && "missing value for temporary");
4174     }
4175   }
4176 
4177   // In C++14, we can't safely access any mutable state when we might be
4178   // evaluating after an unmodeled side effect. Parameters are modeled as state
4179   // in the caller, but aren't visible once the call returns, so they can be
4180   // modified in a speculatively-evaluated call.
4181   //
4182   // FIXME: Not all local state is mutable. Allow local constant subobjects
4183   // to be read here (but take care with 'mutable' fields).
4184   unsigned VisibleDepth = Depth;
4185   if (llvm::isa_and_nonnull<ParmVarDecl>(
4186           LVal.Base.dyn_cast<const ValueDecl *>()))
4187     ++VisibleDepth;
4188   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4189        Info.EvalStatus.HasSideEffects) ||
4190       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4191     return CompleteObject();
4192 
4193   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4194 }
4195 
4196 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4197 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4198 /// glvalue referred to by an entity of reference type.
4199 ///
4200 /// \param Info - Information about the ongoing evaluation.
4201 /// \param Conv - The expression for which we are performing the conversion.
4202 ///               Used for diagnostics.
4203 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4204 ///               case of a non-class type).
4205 /// \param LVal - The glvalue on which we are attempting to perform this action.
4206 /// \param RVal - The produced value will be placed here.
4207 /// \param WantObjectRepresentation - If true, we're looking for the object
4208 ///               representation rather than the value, and in particular,
4209 ///               there is no requirement that the result be fully initialized.
4210 static bool
handleLValueToRValueConversion(EvalInfo & Info,const Expr * Conv,QualType Type,const LValue & LVal,APValue & RVal,bool WantObjectRepresentation=false)4211 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4212                                const LValue &LVal, APValue &RVal,
4213                                bool WantObjectRepresentation = false) {
4214   if (LVal.Designator.Invalid)
4215     return false;
4216 
4217   // Check for special cases where there is no existing APValue to look at.
4218   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4219 
4220   AccessKinds AK =
4221       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4222 
4223   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4224     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4225       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4226       // initializer until now for such expressions. Such an expression can't be
4227       // an ICE in C, so this only matters for fold.
4228       if (Type.isVolatileQualified()) {
4229         Info.FFDiag(Conv);
4230         return false;
4231       }
4232       APValue Lit;
4233       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4234         return false;
4235       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4236       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4237     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4238       // Special-case character extraction so we don't have to construct an
4239       // APValue for the whole string.
4240       assert(LVal.Designator.Entries.size() <= 1 &&
4241              "Can only read characters from string literals");
4242       if (LVal.Designator.Entries.empty()) {
4243         // Fail for now for LValue to RValue conversion of an array.
4244         // (This shouldn't show up in C/C++, but it could be triggered by a
4245         // weird EvaluateAsRValue call from a tool.)
4246         Info.FFDiag(Conv);
4247         return false;
4248       }
4249       if (LVal.Designator.isOnePastTheEnd()) {
4250         if (Info.getLangOpts().CPlusPlus11)
4251           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4252         else
4253           Info.FFDiag(Conv);
4254         return false;
4255       }
4256       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4257       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4258       return true;
4259     }
4260   }
4261 
4262   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4263   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4264 }
4265 
4266 /// Perform an assignment of Val to LVal. Takes ownership of Val.
handleAssignment(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,APValue & Val)4267 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4268                              QualType LValType, APValue &Val) {
4269   if (LVal.Designator.Invalid)
4270     return false;
4271 
4272   if (!Info.getLangOpts().CPlusPlus14) {
4273     Info.FFDiag(E);
4274     return false;
4275   }
4276 
4277   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4278   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4279 }
4280 
4281 namespace {
4282 struct CompoundAssignSubobjectHandler {
4283   EvalInfo &Info;
4284   const CompoundAssignOperator *E;
4285   QualType PromotedLHSType;
4286   BinaryOperatorKind Opcode;
4287   const APValue &RHS;
4288 
4289   static const AccessKinds AccessKind = AK_Assign;
4290 
4291   typedef bool result_type;
4292 
checkConst__anon4a4db2530c11::CompoundAssignSubobjectHandler4293   bool checkConst(QualType QT) {
4294     // Assigning to a const object has undefined behavior.
4295     if (QT.isConstQualified()) {
4296       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4297       return false;
4298     }
4299     return true;
4300   }
4301 
failed__anon4a4db2530c11::CompoundAssignSubobjectHandler4302   bool failed() { return false; }
found__anon4a4db2530c11::CompoundAssignSubobjectHandler4303   bool found(APValue &Subobj, QualType SubobjType) {
4304     switch (Subobj.getKind()) {
4305     case APValue::Int:
4306       return found(Subobj.getInt(), SubobjType);
4307     case APValue::Float:
4308       return found(Subobj.getFloat(), SubobjType);
4309     case APValue::ComplexInt:
4310     case APValue::ComplexFloat:
4311       // FIXME: Implement complex compound assignment.
4312       Info.FFDiag(E);
4313       return false;
4314     case APValue::LValue:
4315       return foundPointer(Subobj, SubobjType);
4316     case APValue::Vector:
4317       return foundVector(Subobj, SubobjType);
4318     default:
4319       // FIXME: can this happen?
4320       Info.FFDiag(E);
4321       return false;
4322     }
4323   }
4324 
foundVector__anon4a4db2530c11::CompoundAssignSubobjectHandler4325   bool foundVector(APValue &Value, QualType SubobjType) {
4326     if (!checkConst(SubobjType))
4327       return false;
4328 
4329     if (!SubobjType->isVectorType()) {
4330       Info.FFDiag(E);
4331       return false;
4332     }
4333     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4334   }
4335 
found__anon4a4db2530c11::CompoundAssignSubobjectHandler4336   bool found(APSInt &Value, QualType SubobjType) {
4337     if (!checkConst(SubobjType))
4338       return false;
4339 
4340     if (!SubobjType->isIntegerType()) {
4341       // We don't support compound assignment on integer-cast-to-pointer
4342       // values.
4343       Info.FFDiag(E);
4344       return false;
4345     }
4346 
4347     if (RHS.isInt()) {
4348       APSInt LHS =
4349           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4350       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4351         return false;
4352       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4353       return true;
4354     } else if (RHS.isFloat()) {
4355       const FPOptions FPO = E->getFPFeaturesInEffect(
4356                                     Info.Ctx.getLangOpts());
4357       APFloat FValue(0.0);
4358       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4359                                   PromotedLHSType, FValue) &&
4360              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4361              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4362                                   Value);
4363     }
4364 
4365     Info.FFDiag(E);
4366     return false;
4367   }
found__anon4a4db2530c11::CompoundAssignSubobjectHandler4368   bool found(APFloat &Value, QualType SubobjType) {
4369     return checkConst(SubobjType) &&
4370            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4371                                   Value) &&
4372            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4373            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4374   }
foundPointer__anon4a4db2530c11::CompoundAssignSubobjectHandler4375   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4376     if (!checkConst(SubobjType))
4377       return false;
4378 
4379     QualType PointeeType;
4380     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4381       PointeeType = PT->getPointeeType();
4382 
4383     if (PointeeType.isNull() || !RHS.isInt() ||
4384         (Opcode != BO_Add && Opcode != BO_Sub)) {
4385       Info.FFDiag(E);
4386       return false;
4387     }
4388 
4389     APSInt Offset = RHS.getInt();
4390     if (Opcode == BO_Sub)
4391       negateAsSigned(Offset);
4392 
4393     LValue LVal;
4394     LVal.setFrom(Info.Ctx, Subobj);
4395     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4396       return false;
4397     LVal.moveInto(Subobj);
4398     return true;
4399   }
4400 };
4401 } // end anonymous namespace
4402 
4403 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4404 
4405 /// 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)4406 static bool handleCompoundAssignment(EvalInfo &Info,
4407                                      const CompoundAssignOperator *E,
4408                                      const LValue &LVal, QualType LValType,
4409                                      QualType PromotedLValType,
4410                                      BinaryOperatorKind Opcode,
4411                                      const APValue &RVal) {
4412   if (LVal.Designator.Invalid)
4413     return false;
4414 
4415   if (!Info.getLangOpts().CPlusPlus14) {
4416     Info.FFDiag(E);
4417     return false;
4418   }
4419 
4420   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4421   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4422                                              RVal };
4423   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4424 }
4425 
4426 namespace {
4427 struct IncDecSubobjectHandler {
4428   EvalInfo &Info;
4429   const UnaryOperator *E;
4430   AccessKinds AccessKind;
4431   APValue *Old;
4432 
4433   typedef bool result_type;
4434 
checkConst__anon4a4db2530d11::IncDecSubobjectHandler4435   bool checkConst(QualType QT) {
4436     // Assigning to a const object has undefined behavior.
4437     if (QT.isConstQualified()) {
4438       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4439       return false;
4440     }
4441     return true;
4442   }
4443 
failed__anon4a4db2530d11::IncDecSubobjectHandler4444   bool failed() { return false; }
found__anon4a4db2530d11::IncDecSubobjectHandler4445   bool found(APValue &Subobj, QualType SubobjType) {
4446     // Stash the old value. Also clear Old, so we don't clobber it later
4447     // if we're post-incrementing a complex.
4448     if (Old) {
4449       *Old = Subobj;
4450       Old = nullptr;
4451     }
4452 
4453     switch (Subobj.getKind()) {
4454     case APValue::Int:
4455       return found(Subobj.getInt(), SubobjType);
4456     case APValue::Float:
4457       return found(Subobj.getFloat(), SubobjType);
4458     case APValue::ComplexInt:
4459       return found(Subobj.getComplexIntReal(),
4460                    SubobjType->castAs<ComplexType>()->getElementType()
4461                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4462     case APValue::ComplexFloat:
4463       return found(Subobj.getComplexFloatReal(),
4464                    SubobjType->castAs<ComplexType>()->getElementType()
4465                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4466     case APValue::LValue:
4467       return foundPointer(Subobj, SubobjType);
4468     default:
4469       // FIXME: can this happen?
4470       Info.FFDiag(E);
4471       return false;
4472     }
4473   }
found__anon4a4db2530d11::IncDecSubobjectHandler4474   bool found(APSInt &Value, QualType SubobjType) {
4475     if (!checkConst(SubobjType))
4476       return false;
4477 
4478     if (!SubobjType->isIntegerType()) {
4479       // We don't support increment / decrement on integer-cast-to-pointer
4480       // values.
4481       Info.FFDiag(E);
4482       return false;
4483     }
4484 
4485     if (Old) *Old = APValue(Value);
4486 
4487     // bool arithmetic promotes to int, and the conversion back to bool
4488     // doesn't reduce mod 2^n, so special-case it.
4489     if (SubobjType->isBooleanType()) {
4490       if (AccessKind == AK_Increment)
4491         Value = 1;
4492       else
4493         Value = !Value;
4494       return true;
4495     }
4496 
4497     bool WasNegative = Value.isNegative();
4498     if (AccessKind == AK_Increment) {
4499       ++Value;
4500 
4501       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4502         APSInt ActualValue(Value, /*IsUnsigned*/true);
4503         return HandleOverflow(Info, E, ActualValue, SubobjType);
4504       }
4505     } else {
4506       --Value;
4507 
4508       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4509         unsigned BitWidth = Value.getBitWidth();
4510         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4511         ActualValue.setBit(BitWidth);
4512         return HandleOverflow(Info, E, ActualValue, SubobjType);
4513       }
4514     }
4515     return true;
4516   }
found__anon4a4db2530d11::IncDecSubobjectHandler4517   bool found(APFloat &Value, QualType SubobjType) {
4518     if (!checkConst(SubobjType))
4519       return false;
4520 
4521     if (Old) *Old = APValue(Value);
4522 
4523     APFloat One(Value.getSemantics(), 1);
4524     if (AccessKind == AK_Increment)
4525       Value.add(One, APFloat::rmNearestTiesToEven);
4526     else
4527       Value.subtract(One, APFloat::rmNearestTiesToEven);
4528     return true;
4529   }
foundPointer__anon4a4db2530d11::IncDecSubobjectHandler4530   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4531     if (!checkConst(SubobjType))
4532       return false;
4533 
4534     QualType PointeeType;
4535     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4536       PointeeType = PT->getPointeeType();
4537     else {
4538       Info.FFDiag(E);
4539       return false;
4540     }
4541 
4542     LValue LVal;
4543     LVal.setFrom(Info.Ctx, Subobj);
4544     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4545                                      AccessKind == AK_Increment ? 1 : -1))
4546       return false;
4547     LVal.moveInto(Subobj);
4548     return true;
4549   }
4550 };
4551 } // end anonymous namespace
4552 
4553 /// Perform an increment or decrement on LVal.
handleIncDec(EvalInfo & Info,const Expr * E,const LValue & LVal,QualType LValType,bool IsIncrement,APValue * Old)4554 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4555                          QualType LValType, bool IsIncrement, APValue *Old) {
4556   if (LVal.Designator.Invalid)
4557     return false;
4558 
4559   if (!Info.getLangOpts().CPlusPlus14) {
4560     Info.FFDiag(E);
4561     return false;
4562   }
4563 
4564   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4565   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4566   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4567   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4568 }
4569 
4570 /// Build an lvalue for the object argument of a member function call.
EvaluateObjectArgument(EvalInfo & Info,const Expr * Object,LValue & This)4571 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4572                                    LValue &This) {
4573   if (Object->getType()->isPointerType() && Object->isPRValue())
4574     return EvaluatePointer(Object, This, Info);
4575 
4576   if (Object->isGLValue())
4577     return EvaluateLValue(Object, This, Info);
4578 
4579   if (Object->getType()->isLiteralType(Info.Ctx))
4580     return EvaluateTemporary(Object, This, Info);
4581 
4582   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4583   return false;
4584 }
4585 
4586 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4587 /// lvalue referring to the result.
4588 ///
4589 /// \param Info - Information about the ongoing evaluation.
4590 /// \param LV - An lvalue referring to the base of the member pointer.
4591 /// \param RHS - The member pointer expression.
4592 /// \param IncludeMember - Specifies whether the member itself is included in
4593 ///        the resulting LValue subobject designator. This is not possible when
4594 ///        creating a bound member function.
4595 /// \return The field or method declaration to which the member pointer refers,
4596 ///         or 0 if evaluation fails.
HandleMemberPointerAccess(EvalInfo & Info,QualType LVType,LValue & LV,const Expr * RHS,bool IncludeMember=true)4597 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4598                                                   QualType LVType,
4599                                                   LValue &LV,
4600                                                   const Expr *RHS,
4601                                                   bool IncludeMember = true) {
4602   MemberPtr MemPtr;
4603   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4604     return nullptr;
4605 
4606   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4607   // member value, the behavior is undefined.
4608   if (!MemPtr.getDecl()) {
4609     // FIXME: Specific diagnostic.
4610     Info.FFDiag(RHS);
4611     return nullptr;
4612   }
4613 
4614   if (MemPtr.isDerivedMember()) {
4615     // This is a member of some derived class. Truncate LV appropriately.
4616     // The end of the derived-to-base path for the base object must match the
4617     // derived-to-base path for the member pointer.
4618     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4619         LV.Designator.Entries.size()) {
4620       Info.FFDiag(RHS);
4621       return nullptr;
4622     }
4623     unsigned PathLengthToMember =
4624         LV.Designator.Entries.size() - MemPtr.Path.size();
4625     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4626       const CXXRecordDecl *LVDecl = getAsBaseClass(
4627           LV.Designator.Entries[PathLengthToMember + I]);
4628       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4629       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4630         Info.FFDiag(RHS);
4631         return nullptr;
4632       }
4633     }
4634 
4635     // Truncate the lvalue to the appropriate derived class.
4636     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4637                             PathLengthToMember))
4638       return nullptr;
4639   } else if (!MemPtr.Path.empty()) {
4640     // Extend the LValue path with the member pointer's path.
4641     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4642                                   MemPtr.Path.size() + IncludeMember);
4643 
4644     // Walk down to the appropriate base class.
4645     if (const PointerType *PT = LVType->getAs<PointerType>())
4646       LVType = PT->getPointeeType();
4647     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4648     assert(RD && "member pointer access on non-class-type expression");
4649     // The first class in the path is that of the lvalue.
4650     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4651       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4652       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4653         return nullptr;
4654       RD = Base;
4655     }
4656     // Finally cast to the class containing the member.
4657     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4658                                 MemPtr.getContainingRecord()))
4659       return nullptr;
4660   }
4661 
4662   // Add the member. Note that we cannot build bound member functions here.
4663   if (IncludeMember) {
4664     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4665       if (!HandleLValueMember(Info, RHS, LV, FD))
4666         return nullptr;
4667     } else if (const IndirectFieldDecl *IFD =
4668                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4669       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4670         return nullptr;
4671     } else {
4672       llvm_unreachable("can't construct reference to bound member function");
4673     }
4674   }
4675 
4676   return MemPtr.getDecl();
4677 }
4678 
HandleMemberPointerAccess(EvalInfo & Info,const BinaryOperator * BO,LValue & LV,bool IncludeMember=true)4679 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4680                                                   const BinaryOperator *BO,
4681                                                   LValue &LV,
4682                                                   bool IncludeMember = true) {
4683   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4684 
4685   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4686     if (Info.noteFailure()) {
4687       MemberPtr MemPtr;
4688       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4689     }
4690     return nullptr;
4691   }
4692 
4693   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4694                                    BO->getRHS(), IncludeMember);
4695 }
4696 
4697 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4698 /// the provided lvalue, which currently refers to the base object.
HandleBaseToDerivedCast(EvalInfo & Info,const CastExpr * E,LValue & Result)4699 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4700                                     LValue &Result) {
4701   SubobjectDesignator &D = Result.Designator;
4702   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4703     return false;
4704 
4705   QualType TargetQT = E->getType();
4706   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4707     TargetQT = PT->getPointeeType();
4708 
4709   // Check this cast lands within the final derived-to-base subobject path.
4710   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4711     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4712       << D.MostDerivedType << TargetQT;
4713     return false;
4714   }
4715 
4716   // Check the type of the final cast. We don't need to check the path,
4717   // since a cast can only be formed if the path is unique.
4718   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4719   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4720   const CXXRecordDecl *FinalType;
4721   if (NewEntriesSize == D.MostDerivedPathLength)
4722     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4723   else
4724     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4725   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4726     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4727       << D.MostDerivedType << TargetQT;
4728     return false;
4729   }
4730 
4731   // Truncate the lvalue to the appropriate derived class.
4732   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4733 }
4734 
4735 /// Get the value to use for a default-initialized object of type T.
4736 /// Return false if it encounters something invalid.
getDefaultInitValue(QualType T,APValue & Result)4737 static bool getDefaultInitValue(QualType T, APValue &Result) {
4738   bool Success = true;
4739   if (auto *RD = T->getAsCXXRecordDecl()) {
4740     if (RD->isInvalidDecl()) {
4741       Result = APValue();
4742       return false;
4743     }
4744     if (RD->isUnion()) {
4745       Result = APValue((const FieldDecl *)nullptr);
4746       return true;
4747     }
4748     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4749                      std::distance(RD->field_begin(), RD->field_end()));
4750 
4751     unsigned Index = 0;
4752     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4753                                                   End = RD->bases_end();
4754          I != End; ++I, ++Index)
4755       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4756 
4757     for (const auto *I : RD->fields()) {
4758       if (I->isUnnamedBitfield())
4759         continue;
4760       Success &= getDefaultInitValue(I->getType(),
4761                                      Result.getStructField(I->getFieldIndex()));
4762     }
4763     return Success;
4764   }
4765 
4766   if (auto *AT =
4767           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4768     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4769     if (Result.hasArrayFiller())
4770       Success &=
4771           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4772 
4773     return Success;
4774   }
4775 
4776   Result = APValue::IndeterminateValue();
4777   return true;
4778 }
4779 
4780 namespace {
4781 enum EvalStmtResult {
4782   /// Evaluation failed.
4783   ESR_Failed,
4784   /// Hit a 'return' statement.
4785   ESR_Returned,
4786   /// Evaluation succeeded.
4787   ESR_Succeeded,
4788   /// Hit a 'continue' statement.
4789   ESR_Continue,
4790   /// Hit a 'break' statement.
4791   ESR_Break,
4792   /// Still scanning for 'case' or 'default' statement.
4793   ESR_CaseNotFound
4794 };
4795 }
4796 
EvaluateVarDecl(EvalInfo & Info,const VarDecl * VD)4797 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4798   // We don't need to evaluate the initializer for a static local.
4799   if (!VD->hasLocalStorage())
4800     return true;
4801 
4802   LValue Result;
4803   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4804                                                    ScopeKind::Block, Result);
4805 
4806   const Expr *InitE = VD->getInit();
4807   if (!InitE) {
4808     if (VD->getType()->isDependentType())
4809       return Info.noteSideEffect();
4810     return getDefaultInitValue(VD->getType(), Val);
4811   }
4812   if (InitE->isValueDependent())
4813     return false;
4814 
4815   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4816     // Wipe out any partially-computed value, to allow tracking that this
4817     // evaluation failed.
4818     Val = APValue();
4819     return false;
4820   }
4821 
4822   return true;
4823 }
4824 
EvaluateDecl(EvalInfo & Info,const Decl * D)4825 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4826   bool OK = true;
4827 
4828   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4829     OK &= EvaluateVarDecl(Info, VD);
4830 
4831   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4832     for (auto *BD : DD->bindings())
4833       if (auto *VD = BD->getHoldingVar())
4834         OK &= EvaluateDecl(Info, VD);
4835 
4836   return OK;
4837 }
4838 
EvaluateDependentExpr(const Expr * E,EvalInfo & Info)4839 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4840   assert(E->isValueDependent());
4841   if (Info.noteSideEffect())
4842     return true;
4843   assert(E->containsErrors() && "valid value-dependent expression should never "
4844                                 "reach invalid code path.");
4845   return false;
4846 }
4847 
4848 /// Evaluate a condition (either a variable declaration or an expression).
EvaluateCond(EvalInfo & Info,const VarDecl * CondDecl,const Expr * Cond,bool & Result)4849 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4850                          const Expr *Cond, bool &Result) {
4851   if (Cond->isValueDependent())
4852     return false;
4853   FullExpressionRAII Scope(Info);
4854   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4855     return false;
4856   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4857     return false;
4858   return Scope.destroy();
4859 }
4860 
4861 namespace {
4862 /// A location where the result (returned value) of evaluating a
4863 /// statement should be stored.
4864 struct StmtResult {
4865   /// The APValue that should be filled in with the returned value.
4866   APValue &Value;
4867   /// The location containing the result, if any (used to support RVO).
4868   const LValue *Slot;
4869 };
4870 
4871 struct TempVersionRAII {
4872   CallStackFrame &Frame;
4873 
TempVersionRAII__anon4a4db2530f11::TempVersionRAII4874   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4875     Frame.pushTempVersion();
4876   }
4877 
~TempVersionRAII__anon4a4db2530f11::TempVersionRAII4878   ~TempVersionRAII() {
4879     Frame.popTempVersion();
4880   }
4881 };
4882 
4883 }
4884 
4885 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4886                                    const Stmt *S,
4887                                    const SwitchCase *SC = nullptr);
4888 
4889 /// Evaluate the body of a loop, and translate the result as appropriate.
EvaluateLoopBody(StmtResult & Result,EvalInfo & Info,const Stmt * Body,const SwitchCase * Case=nullptr)4890 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4891                                        const Stmt *Body,
4892                                        const SwitchCase *Case = nullptr) {
4893   BlockScopeRAII Scope(Info);
4894 
4895   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4896   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4897     ESR = ESR_Failed;
4898 
4899   switch (ESR) {
4900   case ESR_Break:
4901     return ESR_Succeeded;
4902   case ESR_Succeeded:
4903   case ESR_Continue:
4904     return ESR_Continue;
4905   case ESR_Failed:
4906   case ESR_Returned:
4907   case ESR_CaseNotFound:
4908     return ESR;
4909   }
4910   llvm_unreachable("Invalid EvalStmtResult!");
4911 }
4912 
4913 /// Evaluate a switch statement.
EvaluateSwitch(StmtResult & Result,EvalInfo & Info,const SwitchStmt * SS)4914 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4915                                      const SwitchStmt *SS) {
4916   BlockScopeRAII Scope(Info);
4917 
4918   // Evaluate the switch condition.
4919   APSInt Value;
4920   {
4921     if (const Stmt *Init = SS->getInit()) {
4922       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4923       if (ESR != ESR_Succeeded) {
4924         if (ESR != ESR_Failed && !Scope.destroy())
4925           ESR = ESR_Failed;
4926         return ESR;
4927       }
4928     }
4929 
4930     FullExpressionRAII CondScope(Info);
4931     if (SS->getConditionVariable() &&
4932         !EvaluateDecl(Info, SS->getConditionVariable()))
4933       return ESR_Failed;
4934     if (!EvaluateInteger(SS->getCond(), Value, Info))
4935       return ESR_Failed;
4936     if (!CondScope.destroy())
4937       return ESR_Failed;
4938   }
4939 
4940   // Find the switch case corresponding to the value of the condition.
4941   // FIXME: Cache this lookup.
4942   const SwitchCase *Found = nullptr;
4943   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4944        SC = SC->getNextSwitchCase()) {
4945     if (isa<DefaultStmt>(SC)) {
4946       Found = SC;
4947       continue;
4948     }
4949 
4950     const CaseStmt *CS = cast<CaseStmt>(SC);
4951     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4952     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4953                               : LHS;
4954     if (LHS <= Value && Value <= RHS) {
4955       Found = SC;
4956       break;
4957     }
4958   }
4959 
4960   if (!Found)
4961     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4962 
4963   // Search the switch body for the switch case and evaluate it from there.
4964   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4965   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4966     return ESR_Failed;
4967 
4968   switch (ESR) {
4969   case ESR_Break:
4970     return ESR_Succeeded;
4971   case ESR_Succeeded:
4972   case ESR_Continue:
4973   case ESR_Failed:
4974   case ESR_Returned:
4975     return ESR;
4976   case ESR_CaseNotFound:
4977     // This can only happen if the switch case is nested within a statement
4978     // expression. We have no intention of supporting that.
4979     Info.FFDiag(Found->getBeginLoc(),
4980                 diag::note_constexpr_stmt_expr_unsupported);
4981     return ESR_Failed;
4982   }
4983   llvm_unreachable("Invalid EvalStmtResult!");
4984 }
4985 
4986 // Evaluate a statement.
EvaluateStmt(StmtResult & Result,EvalInfo & Info,const Stmt * S,const SwitchCase * Case)4987 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4988                                    const Stmt *S, const SwitchCase *Case) {
4989   if (!Info.nextStep(S))
4990     return ESR_Failed;
4991 
4992   // If we're hunting down a 'case' or 'default' label, recurse through
4993   // substatements until we hit the label.
4994   if (Case) {
4995     switch (S->getStmtClass()) {
4996     case Stmt::CompoundStmtClass:
4997       // FIXME: Precompute which substatement of a compound statement we
4998       // would jump to, and go straight there rather than performing a
4999       // linear scan each time.
5000     case Stmt::LabelStmtClass:
5001     case Stmt::AttributedStmtClass:
5002     case Stmt::DoStmtClass:
5003       break;
5004 
5005     case Stmt::CaseStmtClass:
5006     case Stmt::DefaultStmtClass:
5007       if (Case == S)
5008         Case = nullptr;
5009       break;
5010 
5011     case Stmt::IfStmtClass: {
5012       // FIXME: Precompute which side of an 'if' we would jump to, and go
5013       // straight there rather than scanning both sides.
5014       const IfStmt *IS = cast<IfStmt>(S);
5015 
5016       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5017       // preceded by our switch label.
5018       BlockScopeRAII Scope(Info);
5019 
5020       // Step into the init statement in case it brings an (uninitialized)
5021       // variable into scope.
5022       if (const Stmt *Init = IS->getInit()) {
5023         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5024         if (ESR != ESR_CaseNotFound) {
5025           assert(ESR != ESR_Succeeded);
5026           return ESR;
5027         }
5028       }
5029 
5030       // Condition variable must be initialized if it exists.
5031       // FIXME: We can skip evaluating the body if there's a condition
5032       // variable, as there can't be any case labels within it.
5033       // (The same is true for 'for' statements.)
5034 
5035       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5036       if (ESR == ESR_Failed)
5037         return ESR;
5038       if (ESR != ESR_CaseNotFound)
5039         return Scope.destroy() ? ESR : ESR_Failed;
5040       if (!IS->getElse())
5041         return ESR_CaseNotFound;
5042 
5043       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5044       if (ESR == ESR_Failed)
5045         return ESR;
5046       if (ESR != ESR_CaseNotFound)
5047         return Scope.destroy() ? ESR : ESR_Failed;
5048       return ESR_CaseNotFound;
5049     }
5050 
5051     case Stmt::WhileStmtClass: {
5052       EvalStmtResult ESR =
5053           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5054       if (ESR != ESR_Continue)
5055         return ESR;
5056       break;
5057     }
5058 
5059     case Stmt::ForStmtClass: {
5060       const ForStmt *FS = cast<ForStmt>(S);
5061       BlockScopeRAII Scope(Info);
5062 
5063       // Step into the init statement in case it brings an (uninitialized)
5064       // variable into scope.
5065       if (const Stmt *Init = FS->getInit()) {
5066         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5067         if (ESR != ESR_CaseNotFound) {
5068           assert(ESR != ESR_Succeeded);
5069           return ESR;
5070         }
5071       }
5072 
5073       EvalStmtResult ESR =
5074           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5075       if (ESR != ESR_Continue)
5076         return ESR;
5077       if (const auto *Inc = FS->getInc()) {
5078         if (Inc->isValueDependent()) {
5079           if (!EvaluateDependentExpr(Inc, Info))
5080             return ESR_Failed;
5081         } else {
5082           FullExpressionRAII IncScope(Info);
5083           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5084             return ESR_Failed;
5085         }
5086       }
5087       break;
5088     }
5089 
5090     case Stmt::DeclStmtClass: {
5091       // Start the lifetime of any uninitialized variables we encounter. They
5092       // might be used by the selected branch of the switch.
5093       const DeclStmt *DS = cast<DeclStmt>(S);
5094       for (const auto *D : DS->decls()) {
5095         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5096           if (VD->hasLocalStorage() && !VD->getInit())
5097             if (!EvaluateVarDecl(Info, VD))
5098               return ESR_Failed;
5099           // FIXME: If the variable has initialization that can't be jumped
5100           // over, bail out of any immediately-surrounding compound-statement
5101           // too. There can't be any case labels here.
5102         }
5103       }
5104       return ESR_CaseNotFound;
5105     }
5106 
5107     default:
5108       return ESR_CaseNotFound;
5109     }
5110   }
5111 
5112   switch (S->getStmtClass()) {
5113   default:
5114     if (const Expr *E = dyn_cast<Expr>(S)) {
5115       if (E->isValueDependent()) {
5116         if (!EvaluateDependentExpr(E, Info))
5117           return ESR_Failed;
5118       } else {
5119         // Don't bother evaluating beyond an expression-statement which couldn't
5120         // be evaluated.
5121         // FIXME: Do we need the FullExpressionRAII object here?
5122         // VisitExprWithCleanups should create one when necessary.
5123         FullExpressionRAII Scope(Info);
5124         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5125           return ESR_Failed;
5126       }
5127       return ESR_Succeeded;
5128     }
5129 
5130     Info.FFDiag(S->getBeginLoc());
5131     return ESR_Failed;
5132 
5133   case Stmt::NullStmtClass:
5134     return ESR_Succeeded;
5135 
5136   case Stmt::DeclStmtClass: {
5137     const DeclStmt *DS = cast<DeclStmt>(S);
5138     for (const auto *D : DS->decls()) {
5139       // Each declaration initialization is its own full-expression.
5140       FullExpressionRAII Scope(Info);
5141       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5142         return ESR_Failed;
5143       if (!Scope.destroy())
5144         return ESR_Failed;
5145     }
5146     return ESR_Succeeded;
5147   }
5148 
5149   case Stmt::ReturnStmtClass: {
5150     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5151     FullExpressionRAII Scope(Info);
5152     if (RetExpr && RetExpr->isValueDependent()) {
5153       EvaluateDependentExpr(RetExpr, Info);
5154       // We know we returned, but we don't know what the value is.
5155       return ESR_Failed;
5156     }
5157     if (RetExpr &&
5158         !(Result.Slot
5159               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5160               : Evaluate(Result.Value, Info, RetExpr)))
5161       return ESR_Failed;
5162     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5163   }
5164 
5165   case Stmt::CompoundStmtClass: {
5166     BlockScopeRAII Scope(Info);
5167 
5168     const CompoundStmt *CS = cast<CompoundStmt>(S);
5169     for (const auto *BI : CS->body()) {
5170       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5171       if (ESR == ESR_Succeeded)
5172         Case = nullptr;
5173       else if (ESR != ESR_CaseNotFound) {
5174         if (ESR != ESR_Failed && !Scope.destroy())
5175           return ESR_Failed;
5176         return ESR;
5177       }
5178     }
5179     if (Case)
5180       return ESR_CaseNotFound;
5181     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5182   }
5183 
5184   case Stmt::IfStmtClass: {
5185     const IfStmt *IS = cast<IfStmt>(S);
5186 
5187     // Evaluate the condition, as either a var decl or as an expression.
5188     BlockScopeRAII Scope(Info);
5189     if (const Stmt *Init = IS->getInit()) {
5190       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5191       if (ESR != ESR_Succeeded) {
5192         if (ESR != ESR_Failed && !Scope.destroy())
5193           return ESR_Failed;
5194         return ESR;
5195       }
5196     }
5197     bool Cond;
5198     if (IS->isConsteval())
5199       Cond = IS->isNonNegatedConsteval();
5200     else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5201                            Cond))
5202       return ESR_Failed;
5203 
5204     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5205       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5206       if (ESR != ESR_Succeeded) {
5207         if (ESR != ESR_Failed && !Scope.destroy())
5208           return ESR_Failed;
5209         return ESR;
5210       }
5211     }
5212     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5213   }
5214 
5215   case Stmt::WhileStmtClass: {
5216     const WhileStmt *WS = cast<WhileStmt>(S);
5217     while (true) {
5218       BlockScopeRAII Scope(Info);
5219       bool Continue;
5220       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5221                         Continue))
5222         return ESR_Failed;
5223       if (!Continue)
5224         break;
5225 
5226       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5227       if (ESR != ESR_Continue) {
5228         if (ESR != ESR_Failed && !Scope.destroy())
5229           return ESR_Failed;
5230         return ESR;
5231       }
5232       if (!Scope.destroy())
5233         return ESR_Failed;
5234     }
5235     return ESR_Succeeded;
5236   }
5237 
5238   case Stmt::DoStmtClass: {
5239     const DoStmt *DS = cast<DoStmt>(S);
5240     bool Continue;
5241     do {
5242       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5243       if (ESR != ESR_Continue)
5244         return ESR;
5245       Case = nullptr;
5246 
5247       if (DS->getCond()->isValueDependent()) {
5248         EvaluateDependentExpr(DS->getCond(), Info);
5249         // Bailout as we don't know whether to keep going or terminate the loop.
5250         return ESR_Failed;
5251       }
5252       FullExpressionRAII CondScope(Info);
5253       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5254           !CondScope.destroy())
5255         return ESR_Failed;
5256     } while (Continue);
5257     return ESR_Succeeded;
5258   }
5259 
5260   case Stmt::ForStmtClass: {
5261     const ForStmt *FS = cast<ForStmt>(S);
5262     BlockScopeRAII ForScope(Info);
5263     if (FS->getInit()) {
5264       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5265       if (ESR != ESR_Succeeded) {
5266         if (ESR != ESR_Failed && !ForScope.destroy())
5267           return ESR_Failed;
5268         return ESR;
5269       }
5270     }
5271     while (true) {
5272       BlockScopeRAII IterScope(Info);
5273       bool Continue = true;
5274       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5275                                          FS->getCond(), Continue))
5276         return ESR_Failed;
5277       if (!Continue)
5278         break;
5279 
5280       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5281       if (ESR != ESR_Continue) {
5282         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5283           return ESR_Failed;
5284         return ESR;
5285       }
5286 
5287       if (const auto *Inc = FS->getInc()) {
5288         if (Inc->isValueDependent()) {
5289           if (!EvaluateDependentExpr(Inc, Info))
5290             return ESR_Failed;
5291         } else {
5292           FullExpressionRAII IncScope(Info);
5293           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5294             return ESR_Failed;
5295         }
5296       }
5297 
5298       if (!IterScope.destroy())
5299         return ESR_Failed;
5300     }
5301     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5302   }
5303 
5304   case Stmt::CXXForRangeStmtClass: {
5305     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5306     BlockScopeRAII Scope(Info);
5307 
5308     // Evaluate the init-statement if present.
5309     if (FS->getInit()) {
5310       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5311       if (ESR != ESR_Succeeded) {
5312         if (ESR != ESR_Failed && !Scope.destroy())
5313           return ESR_Failed;
5314         return ESR;
5315       }
5316     }
5317 
5318     // Initialize the __range variable.
5319     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5320     if (ESR != ESR_Succeeded) {
5321       if (ESR != ESR_Failed && !Scope.destroy())
5322         return ESR_Failed;
5323       return ESR;
5324     }
5325 
5326     // Create the __begin and __end iterators.
5327     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5328     if (ESR != ESR_Succeeded) {
5329       if (ESR != ESR_Failed && !Scope.destroy())
5330         return ESR_Failed;
5331       return ESR;
5332     }
5333     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5334     if (ESR != ESR_Succeeded) {
5335       if (ESR != ESR_Failed && !Scope.destroy())
5336         return ESR_Failed;
5337       return ESR;
5338     }
5339 
5340     while (true) {
5341       // Condition: __begin != __end.
5342       {
5343         if (FS->getCond()->isValueDependent()) {
5344           EvaluateDependentExpr(FS->getCond(), Info);
5345           // We don't know whether to keep going or terminate the loop.
5346           return ESR_Failed;
5347         }
5348         bool Continue = true;
5349         FullExpressionRAII CondExpr(Info);
5350         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5351           return ESR_Failed;
5352         if (!Continue)
5353           break;
5354       }
5355 
5356       // User's variable declaration, initialized by *__begin.
5357       BlockScopeRAII InnerScope(Info);
5358       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5359       if (ESR != ESR_Succeeded) {
5360         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5361           return ESR_Failed;
5362         return ESR;
5363       }
5364 
5365       // Loop body.
5366       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5367       if (ESR != ESR_Continue) {
5368         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5369           return ESR_Failed;
5370         return ESR;
5371       }
5372       if (FS->getInc()->isValueDependent()) {
5373         if (!EvaluateDependentExpr(FS->getInc(), Info))
5374           return ESR_Failed;
5375       } else {
5376         // Increment: ++__begin
5377         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5378           return ESR_Failed;
5379       }
5380 
5381       if (!InnerScope.destroy())
5382         return ESR_Failed;
5383     }
5384 
5385     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5386   }
5387 
5388   case Stmt::SwitchStmtClass:
5389     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5390 
5391   case Stmt::ContinueStmtClass:
5392     return ESR_Continue;
5393 
5394   case Stmt::BreakStmtClass:
5395     return ESR_Break;
5396 
5397   case Stmt::LabelStmtClass:
5398     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5399 
5400   case Stmt::AttributedStmtClass:
5401     // As a general principle, C++11 attributes can be ignored without
5402     // any semantic impact.
5403     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5404                         Case);
5405 
5406   case Stmt::CaseStmtClass:
5407   case Stmt::DefaultStmtClass:
5408     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5409   case Stmt::CXXTryStmtClass:
5410     // Evaluate try blocks by evaluating all sub statements.
5411     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5412   }
5413 }
5414 
5415 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5416 /// default constructor. If so, we'll fold it whether or not it's marked as
5417 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5418 /// so we need special handling.
CheckTrivialDefaultConstructor(EvalInfo & Info,SourceLocation Loc,const CXXConstructorDecl * CD,bool IsValueInitialization)5419 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5420                                            const CXXConstructorDecl *CD,
5421                                            bool IsValueInitialization) {
5422   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5423     return false;
5424 
5425   // Value-initialization does not call a trivial default constructor, so such a
5426   // call is a core constant expression whether or not the constructor is
5427   // constexpr.
5428   if (!CD->isConstexpr() && !IsValueInitialization) {
5429     if (Info.getLangOpts().CPlusPlus11) {
5430       // FIXME: If DiagDecl is an implicitly-declared special member function,
5431       // we should be much more explicit about why it's not constexpr.
5432       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5433         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5434       Info.Note(CD->getLocation(), diag::note_declared_at);
5435     } else {
5436       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5437     }
5438   }
5439   return true;
5440 }
5441 
5442 /// CheckConstexprFunction - Check that a function can be called in a constant
5443 /// expression.
CheckConstexprFunction(EvalInfo & Info,SourceLocation CallLoc,const FunctionDecl * Declaration,const FunctionDecl * Definition,const Stmt * Body)5444 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5445                                    const FunctionDecl *Declaration,
5446                                    const FunctionDecl *Definition,
5447                                    const Stmt *Body) {
5448   // Potential constant expressions can contain calls to declared, but not yet
5449   // defined, constexpr functions.
5450   if (Info.checkingPotentialConstantExpression() && !Definition &&
5451       Declaration->isConstexpr())
5452     return false;
5453 
5454   // Bail out if the function declaration itself is invalid.  We will
5455   // have produced a relevant diagnostic while parsing it, so just
5456   // note the problematic sub-expression.
5457   if (Declaration->isInvalidDecl()) {
5458     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5459     return false;
5460   }
5461 
5462   // DR1872: An instantiated virtual constexpr function can't be called in a
5463   // constant expression (prior to C++20). We can still constant-fold such a
5464   // call.
5465   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5466       cast<CXXMethodDecl>(Declaration)->isVirtual())
5467     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5468 
5469   if (Definition && Definition->isInvalidDecl()) {
5470     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5471     return false;
5472   }
5473 
5474   // Can we evaluate this function call?
5475   if (Definition && Definition->isConstexpr() && Body)
5476     return true;
5477 
5478   if (Info.getLangOpts().CPlusPlus11) {
5479     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5480 
5481     // If this function is not constexpr because it is an inherited
5482     // non-constexpr constructor, diagnose that directly.
5483     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5484     if (CD && CD->isInheritingConstructor()) {
5485       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5486       if (!Inherited->isConstexpr())
5487         DiagDecl = CD = Inherited;
5488     }
5489 
5490     // FIXME: If DiagDecl is an implicitly-declared special member function
5491     // or an inheriting constructor, we should be much more explicit about why
5492     // it's not constexpr.
5493     if (CD && CD->isInheritingConstructor())
5494       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5495         << CD->getInheritedConstructor().getConstructor()->getParent();
5496     else
5497       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5498         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5499     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5500   } else {
5501     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5502   }
5503   return false;
5504 }
5505 
5506 namespace {
5507 struct CheckDynamicTypeHandler {
5508   AccessKinds AccessKind;
5509   typedef bool result_type;
failed__anon4a4db2531011::CheckDynamicTypeHandler5510   bool failed() { return false; }
found__anon4a4db2531011::CheckDynamicTypeHandler5511   bool found(APValue &Subobj, QualType SubobjType) { return true; }
found__anon4a4db2531011::CheckDynamicTypeHandler5512   bool found(APSInt &Value, QualType SubobjType) { return true; }
found__anon4a4db2531011::CheckDynamicTypeHandler5513   bool found(APFloat &Value, QualType SubobjType) { return true; }
5514 };
5515 } // end anonymous namespace
5516 
5517 /// Check that we can access the notional vptr of an object / determine its
5518 /// dynamic type.
checkDynamicType(EvalInfo & Info,const Expr * E,const LValue & This,AccessKinds AK,bool Polymorphic)5519 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5520                              AccessKinds AK, bool Polymorphic) {
5521   if (This.Designator.Invalid)
5522     return false;
5523 
5524   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5525 
5526   if (!Obj)
5527     return false;
5528 
5529   if (!Obj.Value) {
5530     // The object is not usable in constant expressions, so we can't inspect
5531     // its value to see if it's in-lifetime or what the active union members
5532     // are. We can still check for a one-past-the-end lvalue.
5533     if (This.Designator.isOnePastTheEnd() ||
5534         This.Designator.isMostDerivedAnUnsizedArray()) {
5535       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5536                          ? diag::note_constexpr_access_past_end
5537                          : diag::note_constexpr_access_unsized_array)
5538           << AK;
5539       return false;
5540     } else if (Polymorphic) {
5541       // Conservatively refuse to perform a polymorphic operation if we would
5542       // not be able to read a notional 'vptr' value.
5543       APValue Val;
5544       This.moveInto(Val);
5545       QualType StarThisType =
5546           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5547       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5548           << AK << Val.getAsString(Info.Ctx, StarThisType);
5549       return false;
5550     }
5551     return true;
5552   }
5553 
5554   CheckDynamicTypeHandler Handler{AK};
5555   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5556 }
5557 
5558 /// Check that the pointee of the 'this' pointer in a member function call is
5559 /// either within its lifetime or in its period of construction or destruction.
5560 static bool
checkNonVirtualMemberCallThisPointer(EvalInfo & Info,const Expr * E,const LValue & This,const CXXMethodDecl * NamedMember)5561 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5562                                      const LValue &This,
5563                                      const CXXMethodDecl *NamedMember) {
5564   return checkDynamicType(
5565       Info, E, This,
5566       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5567 }
5568 
5569 struct DynamicType {
5570   /// The dynamic class type of the object.
5571   const CXXRecordDecl *Type;
5572   /// The corresponding path length in the lvalue.
5573   unsigned PathLength;
5574 };
5575 
getBaseClassType(SubobjectDesignator & Designator,unsigned PathLength)5576 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5577                                              unsigned PathLength) {
5578   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5579       Designator.Entries.size() && "invalid path length");
5580   return (PathLength == Designator.MostDerivedPathLength)
5581              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5582              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5583 }
5584 
5585 /// Determine the dynamic type of an object.
ComputeDynamicType(EvalInfo & Info,const Expr * E,LValue & This,AccessKinds AK)5586 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5587                                                 LValue &This, AccessKinds AK) {
5588   // If we don't have an lvalue denoting an object of class type, there is no
5589   // meaningful dynamic type. (We consider objects of non-class type to have no
5590   // dynamic type.)
5591   if (!checkDynamicType(Info, E, This, AK, true))
5592     return None;
5593 
5594   // Refuse to compute a dynamic type in the presence of virtual bases. This
5595   // shouldn't happen other than in constant-folding situations, since literal
5596   // types can't have virtual bases.
5597   //
5598   // Note that consumers of DynamicType assume that the type has no virtual
5599   // bases, and will need modifications if this restriction is relaxed.
5600   const CXXRecordDecl *Class =
5601       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5602   if (!Class || Class->getNumVBases()) {
5603     Info.FFDiag(E);
5604     return None;
5605   }
5606 
5607   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5608   // binary search here instead. But the overwhelmingly common case is that
5609   // we're not in the middle of a constructor, so it probably doesn't matter
5610   // in practice.
5611   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5612   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5613        PathLength <= Path.size(); ++PathLength) {
5614     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5615                                       Path.slice(0, PathLength))) {
5616     case ConstructionPhase::Bases:
5617     case ConstructionPhase::DestroyingBases:
5618       // We're constructing or destroying a base class. This is not the dynamic
5619       // type.
5620       break;
5621 
5622     case ConstructionPhase::None:
5623     case ConstructionPhase::AfterBases:
5624     case ConstructionPhase::AfterFields:
5625     case ConstructionPhase::Destroying:
5626       // We've finished constructing the base classes and not yet started
5627       // destroying them again, so this is the dynamic type.
5628       return DynamicType{getBaseClassType(This.Designator, PathLength),
5629                          PathLength};
5630     }
5631   }
5632 
5633   // CWG issue 1517: we're constructing a base class of the object described by
5634   // 'This', so that object has not yet begun its period of construction and
5635   // any polymorphic operation on it results in undefined behavior.
5636   Info.FFDiag(E);
5637   return None;
5638 }
5639 
5640 /// Perform virtual dispatch.
HandleVirtualDispatch(EvalInfo & Info,const Expr * E,LValue & This,const CXXMethodDecl * Found,llvm::SmallVectorImpl<QualType> & CovariantAdjustmentPath)5641 static const CXXMethodDecl *HandleVirtualDispatch(
5642     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5643     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5644   Optional<DynamicType> DynType = ComputeDynamicType(
5645       Info, E, This,
5646       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5647   if (!DynType)
5648     return nullptr;
5649 
5650   // Find the final overrider. It must be declared in one of the classes on the
5651   // path from the dynamic type to the static type.
5652   // FIXME: If we ever allow literal types to have virtual base classes, that
5653   // won't be true.
5654   const CXXMethodDecl *Callee = Found;
5655   unsigned PathLength = DynType->PathLength;
5656   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5657     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5658     const CXXMethodDecl *Overrider =
5659         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5660     if (Overrider) {
5661       Callee = Overrider;
5662       break;
5663     }
5664   }
5665 
5666   // C++2a [class.abstract]p6:
5667   //   the effect of making a virtual call to a pure virtual function [...] is
5668   //   undefined
5669   if (Callee->isPure()) {
5670     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5671     Info.Note(Callee->getLocation(), diag::note_declared_at);
5672     return nullptr;
5673   }
5674 
5675   // If necessary, walk the rest of the path to determine the sequence of
5676   // covariant adjustment steps to apply.
5677   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5678                                        Found->getReturnType())) {
5679     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5680     for (unsigned CovariantPathLength = PathLength + 1;
5681          CovariantPathLength != This.Designator.Entries.size();
5682          ++CovariantPathLength) {
5683       const CXXRecordDecl *NextClass =
5684           getBaseClassType(This.Designator, CovariantPathLength);
5685       const CXXMethodDecl *Next =
5686           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5687       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5688                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5689         CovariantAdjustmentPath.push_back(Next->getReturnType());
5690     }
5691     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5692                                          CovariantAdjustmentPath.back()))
5693       CovariantAdjustmentPath.push_back(Found->getReturnType());
5694   }
5695 
5696   // Perform 'this' adjustment.
5697   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5698     return nullptr;
5699 
5700   return Callee;
5701 }
5702 
5703 /// Perform the adjustment from a value returned by a virtual function to
5704 /// a value of the statically expected type, which may be a pointer or
5705 /// reference to a base class of the returned type.
HandleCovariantReturnAdjustment(EvalInfo & Info,const Expr * E,APValue & Result,ArrayRef<QualType> Path)5706 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5707                                             APValue &Result,
5708                                             ArrayRef<QualType> Path) {
5709   assert(Result.isLValue() &&
5710          "unexpected kind of APValue for covariant return");
5711   if (Result.isNullPointer())
5712     return true;
5713 
5714   LValue LVal;
5715   LVal.setFrom(Info.Ctx, Result);
5716 
5717   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5718   for (unsigned I = 1; I != Path.size(); ++I) {
5719     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5720     assert(OldClass && NewClass && "unexpected kind of covariant return");
5721     if (OldClass != NewClass &&
5722         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5723       return false;
5724     OldClass = NewClass;
5725   }
5726 
5727   LVal.moveInto(Result);
5728   return true;
5729 }
5730 
5731 /// Determine whether \p Base, which is known to be a direct base class of
5732 /// \p Derived, is a public base class.
isBaseClassPublic(const CXXRecordDecl * Derived,const CXXRecordDecl * Base)5733 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5734                               const CXXRecordDecl *Base) {
5735   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5736     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5737     if (BaseClass && declaresSameEntity(BaseClass, Base))
5738       return BaseSpec.getAccessSpecifier() == AS_public;
5739   }
5740   llvm_unreachable("Base is not a direct base of Derived");
5741 }
5742 
5743 /// Apply the given dynamic cast operation on the provided lvalue.
5744 ///
5745 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5746 /// to find a suitable target subobject.
HandleDynamicCast(EvalInfo & Info,const ExplicitCastExpr * E,LValue & Ptr)5747 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5748                               LValue &Ptr) {
5749   // We can't do anything with a non-symbolic pointer value.
5750   SubobjectDesignator &D = Ptr.Designator;
5751   if (D.Invalid)
5752     return false;
5753 
5754   // C++ [expr.dynamic.cast]p6:
5755   //   If v is a null pointer value, the result is a null pointer value.
5756   if (Ptr.isNullPointer() && !E->isGLValue())
5757     return true;
5758 
5759   // For all the other cases, we need the pointer to point to an object within
5760   // its lifetime / period of construction / destruction, and we need to know
5761   // its dynamic type.
5762   Optional<DynamicType> DynType =
5763       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5764   if (!DynType)
5765     return false;
5766 
5767   // C++ [expr.dynamic.cast]p7:
5768   //   If T is "pointer to cv void", then the result is a pointer to the most
5769   //   derived object
5770   if (E->getType()->isVoidPointerType())
5771     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5772 
5773   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5774   assert(C && "dynamic_cast target is not void pointer nor class");
5775   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5776 
5777   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5778     // C++ [expr.dynamic.cast]p9:
5779     if (!E->isGLValue()) {
5780       //   The value of a failed cast to pointer type is the null pointer value
5781       //   of the required result type.
5782       Ptr.setNull(Info.Ctx, E->getType());
5783       return true;
5784     }
5785 
5786     //   A failed cast to reference type throws [...] std::bad_cast.
5787     unsigned DiagKind;
5788     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5789                    DynType->Type->isDerivedFrom(C)))
5790       DiagKind = 0;
5791     else if (!Paths || Paths->begin() == Paths->end())
5792       DiagKind = 1;
5793     else if (Paths->isAmbiguous(CQT))
5794       DiagKind = 2;
5795     else {
5796       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5797       DiagKind = 3;
5798     }
5799     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5800         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5801         << Info.Ctx.getRecordType(DynType->Type)
5802         << E->getType().getUnqualifiedType();
5803     return false;
5804   };
5805 
5806   // Runtime check, phase 1:
5807   //   Walk from the base subobject towards the derived object looking for the
5808   //   target type.
5809   for (int PathLength = Ptr.Designator.Entries.size();
5810        PathLength >= (int)DynType->PathLength; --PathLength) {
5811     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5812     if (declaresSameEntity(Class, C))
5813       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5814     // We can only walk across public inheritance edges.
5815     if (PathLength > (int)DynType->PathLength &&
5816         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5817                            Class))
5818       return RuntimeCheckFailed(nullptr);
5819   }
5820 
5821   // Runtime check, phase 2:
5822   //   Search the dynamic type for an unambiguous public base of type C.
5823   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5824                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5825   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5826       Paths.front().Access == AS_public) {
5827     // Downcast to the dynamic type...
5828     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5829       return false;
5830     // ... then upcast to the chosen base class subobject.
5831     for (CXXBasePathElement &Elem : Paths.front())
5832       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5833         return false;
5834     return true;
5835   }
5836 
5837   // Otherwise, the runtime check fails.
5838   return RuntimeCheckFailed(&Paths);
5839 }
5840 
5841 namespace {
5842 struct StartLifetimeOfUnionMemberHandler {
5843   EvalInfo &Info;
5844   const Expr *LHSExpr;
5845   const FieldDecl *Field;
5846   bool DuringInit;
5847   bool Failed = false;
5848   static const AccessKinds AccessKind = AK_Assign;
5849 
5850   typedef bool result_type;
failed__anon4a4db2531211::StartLifetimeOfUnionMemberHandler5851   bool failed() { return Failed; }
found__anon4a4db2531211::StartLifetimeOfUnionMemberHandler5852   bool found(APValue &Subobj, QualType SubobjType) {
5853     // We are supposed to perform no initialization but begin the lifetime of
5854     // the object. We interpret that as meaning to do what default
5855     // initialization of the object would do if all constructors involved were
5856     // trivial:
5857     //  * All base, non-variant member, and array element subobjects' lifetimes
5858     //    begin
5859     //  * No variant members' lifetimes begin
5860     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5861     assert(SubobjType->isUnionType());
5862     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5863       // This union member is already active. If it's also in-lifetime, there's
5864       // nothing to do.
5865       if (Subobj.getUnionValue().hasValue())
5866         return true;
5867     } else if (DuringInit) {
5868       // We're currently in the process of initializing a different union
5869       // member.  If we carried on, that initialization would attempt to
5870       // store to an inactive union member, resulting in undefined behavior.
5871       Info.FFDiag(LHSExpr,
5872                   diag::note_constexpr_union_member_change_during_init);
5873       return false;
5874     }
5875     APValue Result;
5876     Failed = !getDefaultInitValue(Field->getType(), Result);
5877     Subobj.setUnion(Field, Result);
5878     return true;
5879   }
found__anon4a4db2531211::StartLifetimeOfUnionMemberHandler5880   bool found(APSInt &Value, QualType SubobjType) {
5881     llvm_unreachable("wrong value kind for union object");
5882   }
found__anon4a4db2531211::StartLifetimeOfUnionMemberHandler5883   bool found(APFloat &Value, QualType SubobjType) {
5884     llvm_unreachable("wrong value kind for union object");
5885   }
5886 };
5887 } // end anonymous namespace
5888 
5889 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5890 
5891 /// Handle a builtin simple-assignment or a call to a trivial assignment
5892 /// operator whose left-hand side might involve a union member access. If it
5893 /// does, implicitly start the lifetime of any accessed union elements per
5894 /// C++20 [class.union]5.
HandleUnionActiveMemberChange(EvalInfo & Info,const Expr * LHSExpr,const LValue & LHS)5895 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5896                                           const LValue &LHS) {
5897   if (LHS.InvalidBase || LHS.Designator.Invalid)
5898     return false;
5899 
5900   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5901   // C++ [class.union]p5:
5902   //   define the set S(E) of subexpressions of E as follows:
5903   unsigned PathLength = LHS.Designator.Entries.size();
5904   for (const Expr *E = LHSExpr; E != nullptr;) {
5905     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5906     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5907       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5908       // Note that we can't implicitly start the lifetime of a reference,
5909       // so we don't need to proceed any further if we reach one.
5910       if (!FD || FD->getType()->isReferenceType())
5911         break;
5912 
5913       //    ... and also contains A.B if B names a union member ...
5914       if (FD->getParent()->isUnion()) {
5915         //    ... of a non-class, non-array type, or of a class type with a
5916         //    trivial default constructor that is not deleted, or an array of
5917         //    such types.
5918         auto *RD =
5919             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5920         if (!RD || RD->hasTrivialDefaultConstructor())
5921           UnionPathLengths.push_back({PathLength - 1, FD});
5922       }
5923 
5924       E = ME->getBase();
5925       --PathLength;
5926       assert(declaresSameEntity(FD,
5927                                 LHS.Designator.Entries[PathLength]
5928                                     .getAsBaseOrMember().getPointer()));
5929 
5930       //   -- If E is of the form A[B] and is interpreted as a built-in array
5931       //      subscripting operator, S(E) is [S(the array operand, if any)].
5932     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5933       // Step over an ArrayToPointerDecay implicit cast.
5934       auto *Base = ASE->getBase()->IgnoreImplicit();
5935       if (!Base->getType()->isArrayType())
5936         break;
5937 
5938       E = Base;
5939       --PathLength;
5940 
5941     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5942       // Step over a derived-to-base conversion.
5943       E = ICE->getSubExpr();
5944       if (ICE->getCastKind() == CK_NoOp)
5945         continue;
5946       if (ICE->getCastKind() != CK_DerivedToBase &&
5947           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5948         break;
5949       // Walk path backwards as we walk up from the base to the derived class.
5950       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5951         --PathLength;
5952         (void)Elt;
5953         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5954                                   LHS.Designator.Entries[PathLength]
5955                                       .getAsBaseOrMember().getPointer()));
5956       }
5957 
5958     //   -- Otherwise, S(E) is empty.
5959     } else {
5960       break;
5961     }
5962   }
5963 
5964   // Common case: no unions' lifetimes are started.
5965   if (UnionPathLengths.empty())
5966     return true;
5967 
5968   //   if modification of X [would access an inactive union member], an object
5969   //   of the type of X is implicitly created
5970   CompleteObject Obj =
5971       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5972   if (!Obj)
5973     return false;
5974   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5975            llvm::reverse(UnionPathLengths)) {
5976     // Form a designator for the union object.
5977     SubobjectDesignator D = LHS.Designator;
5978     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5979 
5980     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5981                       ConstructionPhase::AfterBases;
5982     StartLifetimeOfUnionMemberHandler StartLifetime{
5983         Info, LHSExpr, LengthAndField.second, DuringInit};
5984     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5985       return false;
5986   }
5987 
5988   return true;
5989 }
5990 
EvaluateCallArg(const ParmVarDecl * PVD,const Expr * Arg,CallRef Call,EvalInfo & Info,bool NonNull=false)5991 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
5992                             CallRef Call, EvalInfo &Info,
5993                             bool NonNull = false) {
5994   LValue LV;
5995   // Create the parameter slot and register its destruction. For a vararg
5996   // argument, create a temporary.
5997   // FIXME: For calling conventions that destroy parameters in the callee,
5998   // should we consider performing destruction when the function returns
5999   // instead?
6000   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6001                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6002                                                        ScopeKind::Call, LV);
6003   if (!EvaluateInPlace(V, Info, LV, Arg))
6004     return false;
6005 
6006   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6007   // undefined behavior, so is non-constant.
6008   if (NonNull && V.isLValue() && V.isNullPointer()) {
6009     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6010     return false;
6011   }
6012 
6013   return true;
6014 }
6015 
6016 /// Evaluate the arguments to a function call.
EvaluateArgs(ArrayRef<const Expr * > Args,CallRef Call,EvalInfo & Info,const FunctionDecl * Callee,bool RightToLeft=false)6017 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6018                          EvalInfo &Info, const FunctionDecl *Callee,
6019                          bool RightToLeft = false) {
6020   bool Success = true;
6021   llvm::SmallBitVector ForbiddenNullArgs;
6022   if (Callee->hasAttr<NonNullAttr>()) {
6023     ForbiddenNullArgs.resize(Args.size());
6024     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6025       if (!Attr->args_size()) {
6026         ForbiddenNullArgs.set();
6027         break;
6028       } else
6029         for (auto Idx : Attr->args()) {
6030           unsigned ASTIdx = Idx.getASTIndex();
6031           if (ASTIdx >= Args.size())
6032             continue;
6033           ForbiddenNullArgs[ASTIdx] = 1;
6034         }
6035     }
6036   }
6037   for (unsigned I = 0; I < Args.size(); I++) {
6038     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6039     const ParmVarDecl *PVD =
6040         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6041     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6042     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6043       // If we're checking for a potential constant expression, evaluate all
6044       // initializers even if some of them fail.
6045       if (!Info.noteFailure())
6046         return false;
6047       Success = false;
6048     }
6049   }
6050   return Success;
6051 }
6052 
6053 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6054 /// constructor or assignment operator.
handleTrivialCopy(EvalInfo & Info,const ParmVarDecl * Param,const Expr * E,APValue & Result,bool CopyObjectRepresentation)6055 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6056                               const Expr *E, APValue &Result,
6057                               bool CopyObjectRepresentation) {
6058   // Find the reference argument.
6059   CallStackFrame *Frame = Info.CurrentCall;
6060   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6061   if (!RefValue) {
6062     Info.FFDiag(E);
6063     return false;
6064   }
6065 
6066   // Copy out the contents of the RHS object.
6067   LValue RefLValue;
6068   RefLValue.setFrom(Info.Ctx, *RefValue);
6069   return handleLValueToRValueConversion(
6070       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6071       CopyObjectRepresentation);
6072 }
6073 
6074 /// 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)6075 static bool HandleFunctionCall(SourceLocation CallLoc,
6076                                const FunctionDecl *Callee, const LValue *This,
6077                                ArrayRef<const Expr *> Args, CallRef Call,
6078                                const Stmt *Body, EvalInfo &Info,
6079                                APValue &Result, const LValue *ResultSlot) {
6080   if (!Info.CheckCallLimit(CallLoc))
6081     return false;
6082 
6083   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6084 
6085   // For a trivial copy or move assignment, perform an APValue copy. This is
6086   // essential for unions, where the operations performed by the assignment
6087   // operator cannot be represented as statements.
6088   //
6089   // Skip this for non-union classes with no fields; in that case, the defaulted
6090   // copy/move does not actually read the object.
6091   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6092   if (MD && MD->isDefaulted() &&
6093       (MD->getParent()->isUnion() ||
6094        (MD->isTrivial() &&
6095         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6096     assert(This &&
6097            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6098     APValue RHSValue;
6099     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6100                            MD->getParent()->isUnion()))
6101       return false;
6102     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6103         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6104       return false;
6105     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6106                           RHSValue))
6107       return false;
6108     This->moveInto(Result);
6109     return true;
6110   } else if (MD && isLambdaCallOperator(MD)) {
6111     // We're in a lambda; determine the lambda capture field maps unless we're
6112     // just constexpr checking a lambda's call operator. constexpr checking is
6113     // done before the captures have been added to the closure object (unless
6114     // we're inferring constexpr-ness), so we don't have access to them in this
6115     // case. But since we don't need the captures to constexpr check, we can
6116     // just ignore them.
6117     if (!Info.checkingPotentialConstantExpression())
6118       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6119                                         Frame.LambdaThisCaptureField);
6120   }
6121 
6122   StmtResult Ret = {Result, ResultSlot};
6123   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6124   if (ESR == ESR_Succeeded) {
6125     if (Callee->getReturnType()->isVoidType())
6126       return true;
6127     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6128   }
6129   return ESR == ESR_Returned;
6130 }
6131 
6132 /// Evaluate a constructor call.
HandleConstructorCall(const Expr * E,const LValue & This,CallRef Call,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6133 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6134                                   CallRef Call,
6135                                   const CXXConstructorDecl *Definition,
6136                                   EvalInfo &Info, APValue &Result) {
6137   SourceLocation CallLoc = E->getExprLoc();
6138   if (!Info.CheckCallLimit(CallLoc))
6139     return false;
6140 
6141   const CXXRecordDecl *RD = Definition->getParent();
6142   if (RD->getNumVBases()) {
6143     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6144     return false;
6145   }
6146 
6147   EvalInfo::EvaluatingConstructorRAII EvalObj(
6148       Info,
6149       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6150       RD->getNumBases());
6151   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6152 
6153   // FIXME: Creating an APValue just to hold a nonexistent return value is
6154   // wasteful.
6155   APValue RetVal;
6156   StmtResult Ret = {RetVal, nullptr};
6157 
6158   // If it's a delegating constructor, delegate.
6159   if (Definition->isDelegatingConstructor()) {
6160     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6161     if ((*I)->getInit()->isValueDependent()) {
6162       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6163         return false;
6164     } else {
6165       FullExpressionRAII InitScope(Info);
6166       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6167           !InitScope.destroy())
6168         return false;
6169     }
6170     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6171   }
6172 
6173   // For a trivial copy or move constructor, perform an APValue copy. This is
6174   // essential for unions (or classes with anonymous union members), where the
6175   // operations performed by the constructor cannot be represented by
6176   // ctor-initializers.
6177   //
6178   // Skip this for empty non-union classes; we should not perform an
6179   // lvalue-to-rvalue conversion on them because their copy constructor does not
6180   // actually read them.
6181   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6182       (Definition->getParent()->isUnion() ||
6183        (Definition->isTrivial() &&
6184         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6185     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6186                              Definition->getParent()->isUnion());
6187   }
6188 
6189   // Reserve space for the struct members.
6190   if (!Result.hasValue()) {
6191     if (!RD->isUnion())
6192       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6193                        std::distance(RD->field_begin(), RD->field_end()));
6194     else
6195       // A union starts with no active member.
6196       Result = APValue((const FieldDecl*)nullptr);
6197   }
6198 
6199   if (RD->isInvalidDecl()) return false;
6200   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6201 
6202   // A scope for temporaries lifetime-extended by reference members.
6203   BlockScopeRAII LifetimeExtendedScope(Info);
6204 
6205   bool Success = true;
6206   unsigned BasesSeen = 0;
6207 #ifndef NDEBUG
6208   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6209 #endif
6210   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6211   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6212     // We might be initializing the same field again if this is an indirect
6213     // field initialization.
6214     if (FieldIt == RD->field_end() ||
6215         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6216       assert(Indirect && "fields out of order?");
6217       return;
6218     }
6219 
6220     // Default-initialize any fields with no explicit initializer.
6221     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6222       assert(FieldIt != RD->field_end() && "missing field?");
6223       if (!FieldIt->isUnnamedBitfield())
6224         Success &= getDefaultInitValue(
6225             FieldIt->getType(),
6226             Result.getStructField(FieldIt->getFieldIndex()));
6227     }
6228     ++FieldIt;
6229   };
6230   for (const auto *I : Definition->inits()) {
6231     LValue Subobject = This;
6232     LValue SubobjectParent = This;
6233     APValue *Value = &Result;
6234 
6235     // Determine the subobject to initialize.
6236     FieldDecl *FD = nullptr;
6237     if (I->isBaseInitializer()) {
6238       QualType BaseType(I->getBaseClass(), 0);
6239 #ifndef NDEBUG
6240       // Non-virtual base classes are initialized in the order in the class
6241       // definition. We have already checked for virtual base classes.
6242       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6243       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6244              "base class initializers not in expected order");
6245       ++BaseIt;
6246 #endif
6247       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6248                                   BaseType->getAsCXXRecordDecl(), &Layout))
6249         return false;
6250       Value = &Result.getStructBase(BasesSeen++);
6251     } else if ((FD = I->getMember())) {
6252       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6253         return false;
6254       if (RD->isUnion()) {
6255         Result = APValue(FD);
6256         Value = &Result.getUnionValue();
6257       } else {
6258         SkipToField(FD, false);
6259         Value = &Result.getStructField(FD->getFieldIndex());
6260       }
6261     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6262       // Walk the indirect field decl's chain to find the object to initialize,
6263       // and make sure we've initialized every step along it.
6264       auto IndirectFieldChain = IFD->chain();
6265       for (auto *C : IndirectFieldChain) {
6266         FD = cast<FieldDecl>(C);
6267         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6268         // Switch the union field if it differs. This happens if we had
6269         // preceding zero-initialization, and we're now initializing a union
6270         // subobject other than the first.
6271         // FIXME: In this case, the values of the other subobjects are
6272         // specified, since zero-initialization sets all padding bits to zero.
6273         if (!Value->hasValue() ||
6274             (Value->isUnion() && Value->getUnionField() != FD)) {
6275           if (CD->isUnion())
6276             *Value = APValue(FD);
6277           else
6278             // FIXME: This immediately starts the lifetime of all members of
6279             // an anonymous struct. It would be preferable to strictly start
6280             // member lifetime in initialization order.
6281             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6282         }
6283         // Store Subobject as its parent before updating it for the last element
6284         // in the chain.
6285         if (C == IndirectFieldChain.back())
6286           SubobjectParent = Subobject;
6287         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6288           return false;
6289         if (CD->isUnion())
6290           Value = &Value->getUnionValue();
6291         else {
6292           if (C == IndirectFieldChain.front() && !RD->isUnion())
6293             SkipToField(FD, true);
6294           Value = &Value->getStructField(FD->getFieldIndex());
6295         }
6296       }
6297     } else {
6298       llvm_unreachable("unknown base initializer kind");
6299     }
6300 
6301     // Need to override This for implicit field initializers as in this case
6302     // This refers to innermost anonymous struct/union containing initializer,
6303     // not to currently constructed class.
6304     const Expr *Init = I->getInit();
6305     if (Init->isValueDependent()) {
6306       if (!EvaluateDependentExpr(Init, Info))
6307         return false;
6308     } else {
6309       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6310                                     isa<CXXDefaultInitExpr>(Init));
6311       FullExpressionRAII InitScope(Info);
6312       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6313           (FD && FD->isBitField() &&
6314            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6315         // If we're checking for a potential constant expression, evaluate all
6316         // initializers even if some of them fail.
6317         if (!Info.noteFailure())
6318           return false;
6319         Success = false;
6320       }
6321     }
6322 
6323     // This is the point at which the dynamic type of the object becomes this
6324     // class type.
6325     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6326       EvalObj.finishedConstructingBases();
6327   }
6328 
6329   // Default-initialize any remaining fields.
6330   if (!RD->isUnion()) {
6331     for (; FieldIt != RD->field_end(); ++FieldIt) {
6332       if (!FieldIt->isUnnamedBitfield())
6333         Success &= getDefaultInitValue(
6334             FieldIt->getType(),
6335             Result.getStructField(FieldIt->getFieldIndex()));
6336     }
6337   }
6338 
6339   EvalObj.finishedConstructingFields();
6340 
6341   return Success &&
6342          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6343          LifetimeExtendedScope.destroy();
6344 }
6345 
HandleConstructorCall(const Expr * E,const LValue & This,ArrayRef<const Expr * > Args,const CXXConstructorDecl * Definition,EvalInfo & Info,APValue & Result)6346 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6347                                   ArrayRef<const Expr*> Args,
6348                                   const CXXConstructorDecl *Definition,
6349                                   EvalInfo &Info, APValue &Result) {
6350   CallScopeRAII CallScope(Info);
6351   CallRef Call = Info.CurrentCall->createCall(Definition);
6352   if (!EvaluateArgs(Args, Call, Info, Definition))
6353     return false;
6354 
6355   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6356          CallScope.destroy();
6357 }
6358 
HandleDestructionImpl(EvalInfo & Info,SourceLocation CallLoc,const LValue & This,APValue & Value,QualType T)6359 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6360                                   const LValue &This, APValue &Value,
6361                                   QualType T) {
6362   // Objects can only be destroyed while they're within their lifetimes.
6363   // FIXME: We have no representation for whether an object of type nullptr_t
6364   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6365   // as indeterminate instead?
6366   if (Value.isAbsent() && !T->isNullPtrType()) {
6367     APValue Printable;
6368     This.moveInto(Printable);
6369     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6370       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6371     return false;
6372   }
6373 
6374   // Invent an expression for location purposes.
6375   // FIXME: We shouldn't need to do this.
6376   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6377 
6378   // For arrays, destroy elements right-to-left.
6379   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6380     uint64_t Size = CAT->getSize().getZExtValue();
6381     QualType ElemT = CAT->getElementType();
6382 
6383     LValue ElemLV = This;
6384     ElemLV.addArray(Info, &LocE, CAT);
6385     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6386       return false;
6387 
6388     // Ensure that we have actual array elements available to destroy; the
6389     // destructors might mutate the value, so we can't run them on the array
6390     // filler.
6391     if (Size && Size > Value.getArrayInitializedElts())
6392       expandArray(Value, Value.getArraySize() - 1);
6393 
6394     for (; Size != 0; --Size) {
6395       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6396       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6397           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6398         return false;
6399     }
6400 
6401     // End the lifetime of this array now.
6402     Value = APValue();
6403     return true;
6404   }
6405 
6406   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6407   if (!RD) {
6408     if (T.isDestructedType()) {
6409       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6410       return false;
6411     }
6412 
6413     Value = APValue();
6414     return true;
6415   }
6416 
6417   if (RD->getNumVBases()) {
6418     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6419     return false;
6420   }
6421 
6422   const CXXDestructorDecl *DD = RD->getDestructor();
6423   if (!DD && !RD->hasTrivialDestructor()) {
6424     Info.FFDiag(CallLoc);
6425     return false;
6426   }
6427 
6428   if (!DD || DD->isTrivial() ||
6429       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6430     // A trivial destructor just ends the lifetime of the object. Check for
6431     // this case before checking for a body, because we might not bother
6432     // building a body for a trivial destructor. Note that it doesn't matter
6433     // whether the destructor is constexpr in this case; all trivial
6434     // destructors are constexpr.
6435     //
6436     // If an anonymous union would be destroyed, some enclosing destructor must
6437     // have been explicitly defined, and the anonymous union destruction should
6438     // have no effect.
6439     Value = APValue();
6440     return true;
6441   }
6442 
6443   if (!Info.CheckCallLimit(CallLoc))
6444     return false;
6445 
6446   const FunctionDecl *Definition = nullptr;
6447   const Stmt *Body = DD->getBody(Definition);
6448 
6449   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6450     return false;
6451 
6452   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6453 
6454   // We're now in the period of destruction of this object.
6455   unsigned BasesLeft = RD->getNumBases();
6456   EvalInfo::EvaluatingDestructorRAII EvalObj(
6457       Info,
6458       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6459   if (!EvalObj.DidInsert) {
6460     // C++2a [class.dtor]p19:
6461     //   the behavior is undefined if the destructor is invoked for an object
6462     //   whose lifetime has ended
6463     // (Note that formally the lifetime ends when the period of destruction
6464     // begins, even though certain uses of the object remain valid until the
6465     // period of destruction ends.)
6466     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6467     return false;
6468   }
6469 
6470   // FIXME: Creating an APValue just to hold a nonexistent return value is
6471   // wasteful.
6472   APValue RetVal;
6473   StmtResult Ret = {RetVal, nullptr};
6474   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6475     return false;
6476 
6477   // A union destructor does not implicitly destroy its members.
6478   if (RD->isUnion())
6479     return true;
6480 
6481   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6482 
6483   // We don't have a good way to iterate fields in reverse, so collect all the
6484   // fields first and then walk them backwards.
6485   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6486   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6487     if (FD->isUnnamedBitfield())
6488       continue;
6489 
6490     LValue Subobject = This;
6491     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6492       return false;
6493 
6494     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6495     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6496                                FD->getType()))
6497       return false;
6498   }
6499 
6500   if (BasesLeft != 0)
6501     EvalObj.startedDestroyingBases();
6502 
6503   // Destroy base classes in reverse order.
6504   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6505     --BasesLeft;
6506 
6507     QualType BaseType = Base.getType();
6508     LValue Subobject = This;
6509     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6510                                 BaseType->getAsCXXRecordDecl(), &Layout))
6511       return false;
6512 
6513     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6514     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6515                                BaseType))
6516       return false;
6517   }
6518   assert(BasesLeft == 0 && "NumBases was wrong?");
6519 
6520   // The period of destruction ends now. The object is gone.
6521   Value = APValue();
6522   return true;
6523 }
6524 
6525 namespace {
6526 struct DestroyObjectHandler {
6527   EvalInfo &Info;
6528   const Expr *E;
6529   const LValue &This;
6530   const AccessKinds AccessKind;
6531 
6532   typedef bool result_type;
failed__anon4a4db2531411::DestroyObjectHandler6533   bool failed() { return false; }
found__anon4a4db2531411::DestroyObjectHandler6534   bool found(APValue &Subobj, QualType SubobjType) {
6535     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6536                                  SubobjType);
6537   }
found__anon4a4db2531411::DestroyObjectHandler6538   bool found(APSInt &Value, QualType SubobjType) {
6539     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6540     return false;
6541   }
found__anon4a4db2531411::DestroyObjectHandler6542   bool found(APFloat &Value, QualType SubobjType) {
6543     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6544     return false;
6545   }
6546 };
6547 }
6548 
6549 /// Perform a destructor or pseudo-destructor call on the given object, which
6550 /// might in general not be a complete object.
HandleDestruction(EvalInfo & Info,const Expr * E,const LValue & This,QualType ThisType)6551 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6552                               const LValue &This, QualType ThisType) {
6553   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6554   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6555   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6556 }
6557 
6558 /// Destroy and end the lifetime of the given complete object.
HandleDestruction(EvalInfo & Info,SourceLocation Loc,APValue::LValueBase LVBase,APValue & Value,QualType T)6559 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6560                               APValue::LValueBase LVBase, APValue &Value,
6561                               QualType T) {
6562   // If we've had an unmodeled side-effect, we can't rely on mutable state
6563   // (such as the object we're about to destroy) being correct.
6564   if (Info.EvalStatus.HasSideEffects)
6565     return false;
6566 
6567   LValue LV;
6568   LV.set({LVBase});
6569   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6570 }
6571 
6572 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
HandleOperatorNewCall(EvalInfo & Info,const CallExpr * E,LValue & Result)6573 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6574                                   LValue &Result) {
6575   if (Info.checkingPotentialConstantExpression() ||
6576       Info.SpeculativeEvaluationDepth)
6577     return false;
6578 
6579   // This is permitted only within a call to std::allocator<T>::allocate.
6580   auto Caller = Info.getStdAllocatorCaller("allocate");
6581   if (!Caller) {
6582     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6583                                      ? diag::note_constexpr_new_untyped
6584                                      : diag::note_constexpr_new);
6585     return false;
6586   }
6587 
6588   QualType ElemType = Caller.ElemType;
6589   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6590     Info.FFDiag(E->getExprLoc(),
6591                 diag::note_constexpr_new_not_complete_object_type)
6592         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6593     return false;
6594   }
6595 
6596   APSInt ByteSize;
6597   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6598     return false;
6599   bool IsNothrow = false;
6600   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6601     EvaluateIgnoredValue(Info, E->getArg(I));
6602     IsNothrow |= E->getType()->isNothrowT();
6603   }
6604 
6605   CharUnits ElemSize;
6606   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6607     return false;
6608   APInt Size, Remainder;
6609   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6610   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6611   if (Remainder != 0) {
6612     // This likely indicates a bug in the implementation of 'std::allocator'.
6613     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6614         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6615     return false;
6616   }
6617 
6618   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6619     if (IsNothrow) {
6620       Result.setNull(Info.Ctx, E->getType());
6621       return true;
6622     }
6623 
6624     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6625     return false;
6626   }
6627 
6628   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6629                                                      ArrayType::Normal, 0);
6630   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6631   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6632   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6633   return true;
6634 }
6635 
hasVirtualDestructor(QualType T)6636 static bool hasVirtualDestructor(QualType T) {
6637   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6638     if (CXXDestructorDecl *DD = RD->getDestructor())
6639       return DD->isVirtual();
6640   return false;
6641 }
6642 
getVirtualOperatorDelete(QualType T)6643 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6644   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6645     if (CXXDestructorDecl *DD = RD->getDestructor())
6646       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6647   return nullptr;
6648 }
6649 
6650 /// Check that the given object is a suitable pointer to a heap allocation that
6651 /// still exists and is of the right kind for the purpose of a deletion.
6652 ///
6653 /// On success, returns the heap allocation to deallocate. On failure, produces
6654 /// a diagnostic and returns None.
CheckDeleteKind(EvalInfo & Info,const Expr * E,const LValue & Pointer,DynAlloc::Kind DeallocKind)6655 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6656                                             const LValue &Pointer,
6657                                             DynAlloc::Kind DeallocKind) {
6658   auto PointerAsString = [&] {
6659     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6660   };
6661 
6662   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6663   if (!DA) {
6664     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6665         << PointerAsString();
6666     if (Pointer.Base)
6667       NoteLValueLocation(Info, Pointer.Base);
6668     return None;
6669   }
6670 
6671   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6672   if (!Alloc) {
6673     Info.FFDiag(E, diag::note_constexpr_double_delete);
6674     return None;
6675   }
6676 
6677   QualType AllocType = Pointer.Base.getDynamicAllocType();
6678   if (DeallocKind != (*Alloc)->getKind()) {
6679     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6680         << DeallocKind << (*Alloc)->getKind() << AllocType;
6681     NoteLValueLocation(Info, Pointer.Base);
6682     return None;
6683   }
6684 
6685   bool Subobject = false;
6686   if (DeallocKind == DynAlloc::New) {
6687     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6688                 Pointer.Designator.isOnePastTheEnd();
6689   } else {
6690     Subobject = Pointer.Designator.Entries.size() != 1 ||
6691                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6692   }
6693   if (Subobject) {
6694     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6695         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6696     return None;
6697   }
6698 
6699   return Alloc;
6700 }
6701 
6702 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
HandleOperatorDeleteCall(EvalInfo & Info,const CallExpr * E)6703 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6704   if (Info.checkingPotentialConstantExpression() ||
6705       Info.SpeculativeEvaluationDepth)
6706     return false;
6707 
6708   // This is permitted only within a call to std::allocator<T>::deallocate.
6709   if (!Info.getStdAllocatorCaller("deallocate")) {
6710     Info.FFDiag(E->getExprLoc());
6711     return true;
6712   }
6713 
6714   LValue Pointer;
6715   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6716     return false;
6717   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6718     EvaluateIgnoredValue(Info, E->getArg(I));
6719 
6720   if (Pointer.Designator.Invalid)
6721     return false;
6722 
6723   // Deleting a null pointer would have no effect, but it's not permitted by
6724   // std::allocator<T>::deallocate's contract.
6725   if (Pointer.isNullPointer()) {
6726     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6727     return true;
6728   }
6729 
6730   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6731     return false;
6732 
6733   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6734   return true;
6735 }
6736 
6737 //===----------------------------------------------------------------------===//
6738 // Generic Evaluation
6739 //===----------------------------------------------------------------------===//
6740 namespace {
6741 
6742 class BitCastBuffer {
6743   // FIXME: We're going to need bit-level granularity when we support
6744   // bit-fields.
6745   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6746   // we don't support a host or target where that is the case. Still, we should
6747   // use a more generic type in case we ever do.
6748   SmallVector<Optional<unsigned char>, 32> Bytes;
6749 
6750   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6751                 "Need at least 8 bit unsigned char");
6752 
6753   bool TargetIsLittleEndian;
6754 
6755 public:
BitCastBuffer(CharUnits Width,bool TargetIsLittleEndian)6756   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6757       : Bytes(Width.getQuantity()),
6758         TargetIsLittleEndian(TargetIsLittleEndian) {}
6759 
6760   LLVM_NODISCARD
readObject(CharUnits Offset,CharUnits Width,SmallVectorImpl<unsigned char> & Output) const6761   bool readObject(CharUnits Offset, CharUnits Width,
6762                   SmallVectorImpl<unsigned char> &Output) const {
6763     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6764       // If a byte of an integer is uninitialized, then the whole integer is
6765       // uninitialized.
6766       if (!Bytes[I.getQuantity()])
6767         return false;
6768       Output.push_back(*Bytes[I.getQuantity()]);
6769     }
6770     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6771       std::reverse(Output.begin(), Output.end());
6772     return true;
6773   }
6774 
writeObject(CharUnits Offset,SmallVectorImpl<unsigned char> & Input)6775   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6776     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6777       std::reverse(Input.begin(), Input.end());
6778 
6779     size_t Index = 0;
6780     for (unsigned char Byte : Input) {
6781       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6782       Bytes[Offset.getQuantity() + Index] = Byte;
6783       ++Index;
6784     }
6785   }
6786 
size()6787   size_t size() { return Bytes.size(); }
6788 };
6789 
6790 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6791 /// target would represent the value at runtime.
6792 class APValueToBufferConverter {
6793   EvalInfo &Info;
6794   BitCastBuffer Buffer;
6795   const CastExpr *BCE;
6796 
APValueToBufferConverter(EvalInfo & Info,CharUnits ObjectWidth,const CastExpr * BCE)6797   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6798                            const CastExpr *BCE)
6799       : Info(Info),
6800         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6801         BCE(BCE) {}
6802 
visit(const APValue & Val,QualType Ty)6803   bool visit(const APValue &Val, QualType Ty) {
6804     return visit(Val, Ty, CharUnits::fromQuantity(0));
6805   }
6806 
6807   // Write out Val with type Ty into Buffer starting at Offset.
visit(const APValue & Val,QualType Ty,CharUnits Offset)6808   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6809     assert((size_t)Offset.getQuantity() <= Buffer.size());
6810 
6811     // As a special case, nullptr_t has an indeterminate value.
6812     if (Ty->isNullPtrType())
6813       return true;
6814 
6815     // Dig through Src to find the byte at SrcOffset.
6816     switch (Val.getKind()) {
6817     case APValue::Indeterminate:
6818     case APValue::None:
6819       return true;
6820 
6821     case APValue::Int:
6822       return visitInt(Val.getInt(), Ty, Offset);
6823     case APValue::Float:
6824       return visitFloat(Val.getFloat(), Ty, Offset);
6825     case APValue::Array:
6826       return visitArray(Val, Ty, Offset);
6827     case APValue::Struct:
6828       return visitRecord(Val, Ty, Offset);
6829 
6830     case APValue::ComplexInt:
6831     case APValue::ComplexFloat:
6832     case APValue::Vector:
6833     case APValue::FixedPoint:
6834       // FIXME: We should support these.
6835 
6836     case APValue::Union:
6837     case APValue::MemberPointer:
6838     case APValue::AddrLabelDiff: {
6839       Info.FFDiag(BCE->getBeginLoc(),
6840                   diag::note_constexpr_bit_cast_unsupported_type)
6841           << Ty;
6842       return false;
6843     }
6844 
6845     case APValue::LValue:
6846       llvm_unreachable("LValue subobject in bit_cast?");
6847     }
6848     llvm_unreachable("Unhandled APValue::ValueKind");
6849   }
6850 
visitRecord(const APValue & Val,QualType Ty,CharUnits Offset)6851   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6852     const RecordDecl *RD = Ty->getAsRecordDecl();
6853     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6854 
6855     // Visit the base classes.
6856     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6857       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6858         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6859         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6860 
6861         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6862                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6863           return false;
6864       }
6865     }
6866 
6867     // Visit the fields.
6868     unsigned FieldIdx = 0;
6869     for (FieldDecl *FD : RD->fields()) {
6870       if (FD->isBitField()) {
6871         Info.FFDiag(BCE->getBeginLoc(),
6872                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6873         return false;
6874       }
6875 
6876       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6877 
6878       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6879              "only bit-fields can have sub-char alignment");
6880       CharUnits FieldOffset =
6881           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6882       QualType FieldTy = FD->getType();
6883       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6884         return false;
6885       ++FieldIdx;
6886     }
6887 
6888     return true;
6889   }
6890 
visitArray(const APValue & Val,QualType Ty,CharUnits Offset)6891   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6892     const auto *CAT =
6893         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6894     if (!CAT)
6895       return false;
6896 
6897     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6898     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6899     unsigned ArraySize = Val.getArraySize();
6900     // First, initialize the initialized elements.
6901     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6902       const APValue &SubObj = Val.getArrayInitializedElt(I);
6903       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6904         return false;
6905     }
6906 
6907     // Next, initialize the rest of the array using the filler.
6908     if (Val.hasArrayFiller()) {
6909       const APValue &Filler = Val.getArrayFiller();
6910       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6911         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6912           return false;
6913       }
6914     }
6915 
6916     return true;
6917   }
6918 
visitInt(const APSInt & Val,QualType Ty,CharUnits Offset)6919   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6920     APSInt AdjustedVal = Val;
6921     unsigned Width = AdjustedVal.getBitWidth();
6922     if (Ty->isBooleanType()) {
6923       Width = Info.Ctx.getTypeSize(Ty);
6924       AdjustedVal = AdjustedVal.extend(Width);
6925     }
6926 
6927     SmallVector<unsigned char, 8> Bytes(Width / 8);
6928     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6929     Buffer.writeObject(Offset, Bytes);
6930     return true;
6931   }
6932 
visitFloat(const APFloat & Val,QualType Ty,CharUnits Offset)6933   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6934     APSInt AsInt(Val.bitcastToAPInt());
6935     return visitInt(AsInt, Ty, Offset);
6936   }
6937 
6938 public:
convert(EvalInfo & Info,const APValue & Src,const CastExpr * BCE)6939   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6940                                          const CastExpr *BCE) {
6941     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6942     APValueToBufferConverter Converter(Info, DstSize, BCE);
6943     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6944       return None;
6945     return Converter.Buffer;
6946   }
6947 };
6948 
6949 /// Write an BitCastBuffer into an APValue.
6950 class BufferToAPValueConverter {
6951   EvalInfo &Info;
6952   const BitCastBuffer &Buffer;
6953   const CastExpr *BCE;
6954 
BufferToAPValueConverter(EvalInfo & Info,const BitCastBuffer & Buffer,const CastExpr * BCE)6955   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6956                            const CastExpr *BCE)
6957       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6958 
6959   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6960   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6961   // Ideally this will be unreachable.
unsupportedType(QualType Ty)6962   llvm::NoneType unsupportedType(QualType Ty) {
6963     Info.FFDiag(BCE->getBeginLoc(),
6964                 diag::note_constexpr_bit_cast_unsupported_type)
6965         << Ty;
6966     return None;
6967   }
6968 
unrepresentableValue(QualType Ty,const APSInt & Val)6969   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6970     Info.FFDiag(BCE->getBeginLoc(),
6971                 diag::note_constexpr_bit_cast_unrepresentable_value)
6972         << Ty << toString(Val, /*Radix=*/10);
6973     return None;
6974   }
6975 
visit(const BuiltinType * T,CharUnits Offset,const EnumType * EnumSugar=nullptr)6976   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6977                           const EnumType *EnumSugar = nullptr) {
6978     if (T->isNullPtrType()) {
6979       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6980       return APValue((Expr *)nullptr,
6981                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6982                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6983     }
6984 
6985     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6986 
6987     // Work around floating point types that contain unused padding bytes. This
6988     // is really just `long double` on x86, which is the only fundamental type
6989     // with padding bytes.
6990     if (T->isRealFloatingType()) {
6991       const llvm::fltSemantics &Semantics =
6992           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6993       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
6994       assert(NumBits % 8 == 0);
6995       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
6996       if (NumBytes != SizeOf)
6997         SizeOf = NumBytes;
6998     }
6999 
7000     SmallVector<uint8_t, 8> Bytes;
7001     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7002       // If this is std::byte or unsigned char, then its okay to store an
7003       // indeterminate value.
7004       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7005       bool IsUChar =
7006           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7007                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7008       if (!IsStdByte && !IsUChar) {
7009         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7010         Info.FFDiag(BCE->getExprLoc(),
7011                     diag::note_constexpr_bit_cast_indet_dest)
7012             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7013         return None;
7014       }
7015 
7016       return APValue::IndeterminateValue();
7017     }
7018 
7019     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7020     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7021 
7022     if (T->isIntegralOrEnumerationType()) {
7023       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7024 
7025       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7026       if (IntWidth != Val.getBitWidth()) {
7027         APSInt Truncated = Val.trunc(IntWidth);
7028         if (Truncated.extend(Val.getBitWidth()) != Val)
7029           return unrepresentableValue(QualType(T, 0), Val);
7030         Val = Truncated;
7031       }
7032 
7033       return APValue(Val);
7034     }
7035 
7036     if (T->isRealFloatingType()) {
7037       const llvm::fltSemantics &Semantics =
7038           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7039       return APValue(APFloat(Semantics, Val));
7040     }
7041 
7042     return unsupportedType(QualType(T, 0));
7043   }
7044 
visit(const RecordType * RTy,CharUnits Offset)7045   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7046     const RecordDecl *RD = RTy->getAsRecordDecl();
7047     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7048 
7049     unsigned NumBases = 0;
7050     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7051       NumBases = CXXRD->getNumBases();
7052 
7053     APValue ResultVal(APValue::UninitStruct(), NumBases,
7054                       std::distance(RD->field_begin(), RD->field_end()));
7055 
7056     // Visit the base classes.
7057     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7058       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7059         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7060         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7061         if (BaseDecl->isEmpty() ||
7062             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7063           continue;
7064 
7065         Optional<APValue> SubObj = visitType(
7066             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7067         if (!SubObj)
7068           return None;
7069         ResultVal.getStructBase(I) = *SubObj;
7070       }
7071     }
7072 
7073     // Visit the fields.
7074     unsigned FieldIdx = 0;
7075     for (FieldDecl *FD : RD->fields()) {
7076       // FIXME: We don't currently support bit-fields. A lot of the logic for
7077       // this is in CodeGen, so we need to factor it around.
7078       if (FD->isBitField()) {
7079         Info.FFDiag(BCE->getBeginLoc(),
7080                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7081         return None;
7082       }
7083 
7084       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7085       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7086 
7087       CharUnits FieldOffset =
7088           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7089           Offset;
7090       QualType FieldTy = FD->getType();
7091       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7092       if (!SubObj)
7093         return None;
7094       ResultVal.getStructField(FieldIdx) = *SubObj;
7095       ++FieldIdx;
7096     }
7097 
7098     return ResultVal;
7099   }
7100 
visit(const EnumType * Ty,CharUnits Offset)7101   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7102     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7103     assert(!RepresentationType.isNull() &&
7104            "enum forward decl should be caught by Sema");
7105     const auto *AsBuiltin =
7106         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7107     // Recurse into the underlying type. Treat std::byte transparently as
7108     // unsigned char.
7109     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7110   }
7111 
visit(const ConstantArrayType * Ty,CharUnits Offset)7112   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7113     size_t Size = Ty->getSize().getLimitedValue();
7114     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7115 
7116     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7117     for (size_t I = 0; I != Size; ++I) {
7118       Optional<APValue> ElementValue =
7119           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7120       if (!ElementValue)
7121         return None;
7122       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7123     }
7124 
7125     return ArrayValue;
7126   }
7127 
visit(const Type * Ty,CharUnits Offset)7128   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7129     return unsupportedType(QualType(Ty, 0));
7130   }
7131 
visitType(QualType Ty,CharUnits Offset)7132   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7133     QualType Can = Ty.getCanonicalType();
7134 
7135     switch (Can->getTypeClass()) {
7136 #define TYPE(Class, Base)                                                      \
7137   case Type::Class:                                                            \
7138     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7139 #define ABSTRACT_TYPE(Class, Base)
7140 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7141   case Type::Class:                                                            \
7142     llvm_unreachable("non-canonical type should be impossible!");
7143 #define DEPENDENT_TYPE(Class, Base)                                            \
7144   case Type::Class:                                                            \
7145     llvm_unreachable(                                                          \
7146         "dependent types aren't supported in the constant evaluator!");
7147 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7148   case Type::Class:                                                            \
7149     llvm_unreachable("either dependent or not canonical!");
7150 #include "clang/AST/TypeNodes.inc"
7151     }
7152     llvm_unreachable("Unhandled Type::TypeClass");
7153   }
7154 
7155 public:
7156   // Pull out a full value of type DstType.
convert(EvalInfo & Info,BitCastBuffer & Buffer,const CastExpr * BCE)7157   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7158                                    const CastExpr *BCE) {
7159     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7160     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7161   }
7162 };
7163 
checkBitCastConstexprEligibilityType(SourceLocation Loc,QualType Ty,EvalInfo * Info,const ASTContext & Ctx,bool CheckingDest)7164 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7165                                                  QualType Ty, EvalInfo *Info,
7166                                                  const ASTContext &Ctx,
7167                                                  bool CheckingDest) {
7168   Ty = Ty.getCanonicalType();
7169 
7170   auto diag = [&](int Reason) {
7171     if (Info)
7172       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7173           << CheckingDest << (Reason == 4) << Reason;
7174     return false;
7175   };
7176   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7177     if (Info)
7178       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7179           << NoteTy << Construct << Ty;
7180     return false;
7181   };
7182 
7183   if (Ty->isUnionType())
7184     return diag(0);
7185   if (Ty->isPointerType())
7186     return diag(1);
7187   if (Ty->isMemberPointerType())
7188     return diag(2);
7189   if (Ty.isVolatileQualified())
7190     return diag(3);
7191 
7192   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7193     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7194       for (CXXBaseSpecifier &BS : CXXRD->bases())
7195         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7196                                                   CheckingDest))
7197           return note(1, BS.getType(), BS.getBeginLoc());
7198     }
7199     for (FieldDecl *FD : Record->fields()) {
7200       if (FD->getType()->isReferenceType())
7201         return diag(4);
7202       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7203                                                 CheckingDest))
7204         return note(0, FD->getType(), FD->getBeginLoc());
7205     }
7206   }
7207 
7208   if (Ty->isArrayType() &&
7209       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7210                                             Info, Ctx, CheckingDest))
7211     return false;
7212 
7213   return true;
7214 }
7215 
checkBitCastConstexprEligibility(EvalInfo * Info,const ASTContext & Ctx,const CastExpr * BCE)7216 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7217                                              const ASTContext &Ctx,
7218                                              const CastExpr *BCE) {
7219   bool DestOK = checkBitCastConstexprEligibilityType(
7220       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7221   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7222                                 BCE->getBeginLoc(),
7223                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7224   return SourceOK;
7225 }
7226 
handleLValueToRValueBitCast(EvalInfo & Info,APValue & DestValue,APValue & SourceValue,const CastExpr * BCE)7227 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7228                                         APValue &SourceValue,
7229                                         const CastExpr *BCE) {
7230   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7231          "no host or target supports non 8-bit chars");
7232   assert(SourceValue.isLValue() &&
7233          "LValueToRValueBitcast requires an lvalue operand!");
7234 
7235   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7236     return false;
7237 
7238   LValue SourceLValue;
7239   APValue SourceRValue;
7240   SourceLValue.setFrom(Info.Ctx, SourceValue);
7241   if (!handleLValueToRValueConversion(
7242           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7243           SourceRValue, /*WantObjectRepresentation=*/true))
7244     return false;
7245 
7246   // Read out SourceValue into a char buffer.
7247   Optional<BitCastBuffer> Buffer =
7248       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7249   if (!Buffer)
7250     return false;
7251 
7252   // Write out the buffer into a new APValue.
7253   Optional<APValue> MaybeDestValue =
7254       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7255   if (!MaybeDestValue)
7256     return false;
7257 
7258   DestValue = std::move(*MaybeDestValue);
7259   return true;
7260 }
7261 
7262 template <class Derived>
7263 class ExprEvaluatorBase
7264   : public ConstStmtVisitor<Derived, bool> {
7265 private:
getDerived()7266   Derived &getDerived() { return static_cast<Derived&>(*this); }
DerivedSuccess(const APValue & V,const Expr * E)7267   bool DerivedSuccess(const APValue &V, const Expr *E) {
7268     return getDerived().Success(V, E);
7269   }
DerivedZeroInitialization(const Expr * E)7270   bool DerivedZeroInitialization(const Expr *E) {
7271     return getDerived().ZeroInitialization(E);
7272   }
7273 
7274   // Check whether a conditional operator with a non-constant condition is a
7275   // potential constant expression. If neither arm is a potential constant
7276   // expression, then the conditional operator is not either.
7277   template<typename ConditionalOperator>
CheckPotentialConstantConditional(const ConditionalOperator * E)7278   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7279     assert(Info.checkingPotentialConstantExpression());
7280 
7281     // Speculatively evaluate both arms.
7282     SmallVector<PartialDiagnosticAt, 8> Diag;
7283     {
7284       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7285       StmtVisitorTy::Visit(E->getFalseExpr());
7286       if (Diag.empty())
7287         return;
7288     }
7289 
7290     {
7291       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7292       Diag.clear();
7293       StmtVisitorTy::Visit(E->getTrueExpr());
7294       if (Diag.empty())
7295         return;
7296     }
7297 
7298     Error(E, diag::note_constexpr_conditional_never_const);
7299   }
7300 
7301 
7302   template<typename ConditionalOperator>
HandleConditionalOperator(const ConditionalOperator * E)7303   bool HandleConditionalOperator(const ConditionalOperator *E) {
7304     bool BoolResult;
7305     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7306       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7307         CheckPotentialConstantConditional(E);
7308         return false;
7309       }
7310       if (Info.noteFailure()) {
7311         StmtVisitorTy::Visit(E->getTrueExpr());
7312         StmtVisitorTy::Visit(E->getFalseExpr());
7313       }
7314       return false;
7315     }
7316 
7317     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7318     return StmtVisitorTy::Visit(EvalExpr);
7319   }
7320 
7321 protected:
7322   EvalInfo &Info;
7323   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7324   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7325 
CCEDiag(const Expr * E,diag::kind D)7326   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7327     return Info.CCEDiag(E, D);
7328   }
7329 
ZeroInitialization(const Expr * E)7330   bool ZeroInitialization(const Expr *E) { return Error(E); }
7331 
7332 public:
ExprEvaluatorBase(EvalInfo & Info)7333   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7334 
getEvalInfo()7335   EvalInfo &getEvalInfo() { return Info; }
7336 
7337   /// Report an evaluation error. This should only be called when an error is
7338   /// first discovered. When propagating an error, just return false.
Error(const Expr * E,diag::kind D)7339   bool Error(const Expr *E, diag::kind D) {
7340     Info.FFDiag(E, D);
7341     return false;
7342   }
Error(const Expr * E)7343   bool Error(const Expr *E) {
7344     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7345   }
7346 
VisitStmt(const Stmt *)7347   bool VisitStmt(const Stmt *) {
7348     llvm_unreachable("Expression evaluator should not be called on stmts");
7349   }
VisitExpr(const Expr * E)7350   bool VisitExpr(const Expr *E) {
7351     return Error(E);
7352   }
7353 
VisitConstantExpr(const ConstantExpr * E)7354   bool VisitConstantExpr(const ConstantExpr *E) {
7355     if (E->hasAPValueResult())
7356       return DerivedSuccess(E->getAPValueResult(), E);
7357 
7358     return StmtVisitorTy::Visit(E->getSubExpr());
7359   }
7360 
VisitParenExpr(const ParenExpr * E)7361   bool VisitParenExpr(const ParenExpr *E)
7362     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryExtension(const UnaryOperator * E)7363   bool VisitUnaryExtension(const UnaryOperator *E)
7364     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitUnaryPlus(const UnaryOperator * E)7365   bool VisitUnaryPlus(const UnaryOperator *E)
7366     { return StmtVisitorTy::Visit(E->getSubExpr()); }
VisitChooseExpr(const ChooseExpr * E)7367   bool VisitChooseExpr(const ChooseExpr *E)
7368     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
VisitGenericSelectionExpr(const GenericSelectionExpr * E)7369   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7370     { return StmtVisitorTy::Visit(E->getResultExpr()); }
VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr * E)7371   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7372     { return StmtVisitorTy::Visit(E->getReplacement()); }
VisitCXXDefaultArgExpr(const CXXDefaultArgExpr * E)7373   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7374     TempVersionRAII RAII(*Info.CurrentCall);
7375     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7376     return StmtVisitorTy::Visit(E->getExpr());
7377   }
VisitCXXDefaultInitExpr(const CXXDefaultInitExpr * E)7378   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7379     TempVersionRAII RAII(*Info.CurrentCall);
7380     // The initializer may not have been parsed yet, or might be erroneous.
7381     if (!E->getExpr())
7382       return Error(E);
7383     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7384     return StmtVisitorTy::Visit(E->getExpr());
7385   }
7386 
VisitExprWithCleanups(const ExprWithCleanups * E)7387   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7388     FullExpressionRAII Scope(Info);
7389     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7390   }
7391 
7392   // Temporaries are registered when created, so we don't care about
7393   // CXXBindTemporaryExpr.
VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr * E)7394   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7395     return StmtVisitorTy::Visit(E->getSubExpr());
7396   }
7397 
VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr * E)7398   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7399     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7400     return static_cast<Derived*>(this)->VisitCastExpr(E);
7401   }
VisitCXXDynamicCastExpr(const CXXDynamicCastExpr * E)7402   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7403     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7404       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7405     return static_cast<Derived*>(this)->VisitCastExpr(E);
7406   }
VisitBuiltinBitCastExpr(const BuiltinBitCastExpr * E)7407   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7408     return static_cast<Derived*>(this)->VisitCastExpr(E);
7409   }
7410 
VisitBinaryOperator(const BinaryOperator * E)7411   bool VisitBinaryOperator(const BinaryOperator *E) {
7412     switch (E->getOpcode()) {
7413     default:
7414       return Error(E);
7415 
7416     case BO_Comma:
7417       VisitIgnoredValue(E->getLHS());
7418       return StmtVisitorTy::Visit(E->getRHS());
7419 
7420     case BO_PtrMemD:
7421     case BO_PtrMemI: {
7422       LValue Obj;
7423       if (!HandleMemberPointerAccess(Info, E, Obj))
7424         return false;
7425       APValue Result;
7426       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7427         return false;
7428       return DerivedSuccess(Result, E);
7429     }
7430     }
7431   }
7432 
VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator * E)7433   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7434     return StmtVisitorTy::Visit(E->getSemanticForm());
7435   }
7436 
VisitBinaryConditionalOperator(const BinaryConditionalOperator * E)7437   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7438     // Evaluate and cache the common expression. We treat it as a temporary,
7439     // even though it's not quite the same thing.
7440     LValue CommonLV;
7441     if (!Evaluate(Info.CurrentCall->createTemporary(
7442                       E->getOpaqueValue(),
7443                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7444                       ScopeKind::FullExpression, CommonLV),
7445                   Info, E->getCommon()))
7446       return false;
7447 
7448     return HandleConditionalOperator(E);
7449   }
7450 
VisitConditionalOperator(const ConditionalOperator * E)7451   bool VisitConditionalOperator(const ConditionalOperator *E) {
7452     bool IsBcpCall = false;
7453     // If the condition (ignoring parens) is a __builtin_constant_p call,
7454     // the result is a constant expression if it can be folded without
7455     // side-effects. This is an important GNU extension. See GCC PR38377
7456     // for discussion.
7457     if (const CallExpr *CallCE =
7458           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7459       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7460         IsBcpCall = true;
7461 
7462     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7463     // constant expression; we can't check whether it's potentially foldable.
7464     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7465     // it would return 'false' in this mode.
7466     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7467       return false;
7468 
7469     FoldConstant Fold(Info, IsBcpCall);
7470     if (!HandleConditionalOperator(E)) {
7471       Fold.keepDiagnostics();
7472       return false;
7473     }
7474 
7475     return true;
7476   }
7477 
VisitOpaqueValueExpr(const OpaqueValueExpr * E)7478   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7479     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7480       return DerivedSuccess(*Value, E);
7481 
7482     const Expr *Source = E->getSourceExpr();
7483     if (!Source)
7484       return Error(E);
7485     if (Source == E) { // sanity checking.
7486       assert(0 && "OpaqueValueExpr recursively refers to itself");
7487       return Error(E);
7488     }
7489     return StmtVisitorTy::Visit(Source);
7490   }
7491 
VisitPseudoObjectExpr(const PseudoObjectExpr * E)7492   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7493     for (const Expr *SemE : E->semantics()) {
7494       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7495         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7496         // result expression: there could be two different LValues that would
7497         // refer to the same object in that case, and we can't model that.
7498         if (SemE == E->getResultExpr())
7499           return Error(E);
7500 
7501         // Unique OVEs get evaluated if and when we encounter them when
7502         // emitting the rest of the semantic form, rather than eagerly.
7503         if (OVE->isUnique())
7504           continue;
7505 
7506         LValue LV;
7507         if (!Evaluate(Info.CurrentCall->createTemporary(
7508                           OVE, getStorageType(Info.Ctx, OVE),
7509                           ScopeKind::FullExpression, LV),
7510                       Info, OVE->getSourceExpr()))
7511           return false;
7512       } else if (SemE == E->getResultExpr()) {
7513         if (!StmtVisitorTy::Visit(SemE))
7514           return false;
7515       } else {
7516         if (!EvaluateIgnoredValue(Info, SemE))
7517           return false;
7518       }
7519     }
7520     return true;
7521   }
7522 
VisitCallExpr(const CallExpr * E)7523   bool VisitCallExpr(const CallExpr *E) {
7524     APValue Result;
7525     if (!handleCallExpr(E, Result, nullptr))
7526       return false;
7527     return DerivedSuccess(Result, E);
7528   }
7529 
handleCallExpr(const CallExpr * E,APValue & Result,const LValue * ResultSlot)7530   bool handleCallExpr(const CallExpr *E, APValue &Result,
7531                      const LValue *ResultSlot) {
7532     CallScopeRAII CallScope(Info);
7533 
7534     const Expr *Callee = E->getCallee()->IgnoreParens();
7535     QualType CalleeType = Callee->getType();
7536 
7537     const FunctionDecl *FD = nullptr;
7538     LValue *This = nullptr, ThisVal;
7539     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7540     bool HasQualifier = false;
7541 
7542     CallRef Call;
7543 
7544     // Extract function decl and 'this' pointer from the callee.
7545     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7546       const CXXMethodDecl *Member = nullptr;
7547       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7548         // Explicit bound member calls, such as x.f() or p->g();
7549         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7550           return false;
7551         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7552         if (!Member)
7553           return Error(Callee);
7554         This = &ThisVal;
7555         HasQualifier = ME->hasQualifier();
7556       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7557         // Indirect bound member calls ('.*' or '->*').
7558         const ValueDecl *D =
7559             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7560         if (!D)
7561           return false;
7562         Member = dyn_cast<CXXMethodDecl>(D);
7563         if (!Member)
7564           return Error(Callee);
7565         This = &ThisVal;
7566       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7567         if (!Info.getLangOpts().CPlusPlus20)
7568           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7569         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7570                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7571       } else
7572         return Error(Callee);
7573       FD = Member;
7574     } else if (CalleeType->isFunctionPointerType()) {
7575       LValue CalleeLV;
7576       if (!EvaluatePointer(Callee, CalleeLV, Info))
7577         return false;
7578 
7579       if (!CalleeLV.getLValueOffset().isZero())
7580         return Error(Callee);
7581       FD = dyn_cast_or_null<FunctionDecl>(
7582           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7583       if (!FD)
7584         return Error(Callee);
7585       // Don't call function pointers which have been cast to some other type.
7586       // Per DR (no number yet), the caller and callee can differ in noexcept.
7587       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7588         CalleeType->getPointeeType(), FD->getType())) {
7589         return Error(E);
7590       }
7591 
7592       // For an (overloaded) assignment expression, evaluate the RHS before the
7593       // LHS.
7594       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7595       if (OCE && OCE->isAssignmentOp()) {
7596         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7597         Call = Info.CurrentCall->createCall(FD);
7598         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7599                           Info, FD, /*RightToLeft=*/true))
7600           return false;
7601       }
7602 
7603       // Overloaded operator calls to member functions are represented as normal
7604       // calls with '*this' as the first argument.
7605       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7606       if (MD && !MD->isStatic()) {
7607         // FIXME: When selecting an implicit conversion for an overloaded
7608         // operator delete, we sometimes try to evaluate calls to conversion
7609         // operators without a 'this' parameter!
7610         if (Args.empty())
7611           return Error(E);
7612 
7613         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7614           return false;
7615         This = &ThisVal;
7616         Args = Args.slice(1);
7617       } else if (MD && MD->isLambdaStaticInvoker()) {
7618         // Map the static invoker for the lambda back to the call operator.
7619         // Conveniently, we don't have to slice out the 'this' argument (as is
7620         // being done for the non-static case), since a static member function
7621         // doesn't have an implicit argument passed in.
7622         const CXXRecordDecl *ClosureClass = MD->getParent();
7623         assert(
7624             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7625             "Number of captures must be zero for conversion to function-ptr");
7626 
7627         const CXXMethodDecl *LambdaCallOp =
7628             ClosureClass->getLambdaCallOperator();
7629 
7630         // Set 'FD', the function that will be called below, to the call
7631         // operator.  If the closure object represents a generic lambda, find
7632         // the corresponding specialization of the call operator.
7633 
7634         if (ClosureClass->isGenericLambda()) {
7635           assert(MD->isFunctionTemplateSpecialization() &&
7636                  "A generic lambda's static-invoker function must be a "
7637                  "template specialization");
7638           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7639           FunctionTemplateDecl *CallOpTemplate =
7640               LambdaCallOp->getDescribedFunctionTemplate();
7641           void *InsertPos = nullptr;
7642           FunctionDecl *CorrespondingCallOpSpecialization =
7643               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7644           assert(CorrespondingCallOpSpecialization &&
7645                  "We must always have a function call operator specialization "
7646                  "that corresponds to our static invoker specialization");
7647           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7648         } else
7649           FD = LambdaCallOp;
7650       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7651         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7652             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7653           LValue Ptr;
7654           if (!HandleOperatorNewCall(Info, E, Ptr))
7655             return false;
7656           Ptr.moveInto(Result);
7657           return CallScope.destroy();
7658         } else {
7659           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7660         }
7661       }
7662     } else
7663       return Error(E);
7664 
7665     // Evaluate the arguments now if we've not already done so.
7666     if (!Call) {
7667       Call = Info.CurrentCall->createCall(FD);
7668       if (!EvaluateArgs(Args, Call, Info, FD))
7669         return false;
7670     }
7671 
7672     SmallVector<QualType, 4> CovariantAdjustmentPath;
7673     if (This) {
7674       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7675       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7676         // Perform virtual dispatch, if necessary.
7677         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7678                                    CovariantAdjustmentPath);
7679         if (!FD)
7680           return false;
7681       } else {
7682         // Check that the 'this' pointer points to an object of the right type.
7683         // FIXME: If this is an assignment operator call, we may need to change
7684         // the active union member before we check this.
7685         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7686           return false;
7687       }
7688     }
7689 
7690     // Destructor calls are different enough that they have their own codepath.
7691     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7692       assert(This && "no 'this' pointer for destructor call");
7693       return HandleDestruction(Info, E, *This,
7694                                Info.Ctx.getRecordType(DD->getParent())) &&
7695              CallScope.destroy();
7696     }
7697 
7698     const FunctionDecl *Definition = nullptr;
7699     Stmt *Body = FD->getBody(Definition);
7700 
7701     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7702         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7703                             Body, Info, Result, ResultSlot))
7704       return false;
7705 
7706     if (!CovariantAdjustmentPath.empty() &&
7707         !HandleCovariantReturnAdjustment(Info, E, Result,
7708                                          CovariantAdjustmentPath))
7709       return false;
7710 
7711     return CallScope.destroy();
7712   }
7713 
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)7714   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7715     return StmtVisitorTy::Visit(E->getInitializer());
7716   }
VisitInitListExpr(const InitListExpr * E)7717   bool VisitInitListExpr(const InitListExpr *E) {
7718     if (E->getNumInits() == 0)
7719       return DerivedZeroInitialization(E);
7720     if (E->getNumInits() == 1)
7721       return StmtVisitorTy::Visit(E->getInit(0));
7722     return Error(E);
7723   }
VisitImplicitValueInitExpr(const ImplicitValueInitExpr * E)7724   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7725     return DerivedZeroInitialization(E);
7726   }
VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr * E)7727   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7728     return DerivedZeroInitialization(E);
7729   }
VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr * E)7730   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7731     return DerivedZeroInitialization(E);
7732   }
7733 
7734   /// A member expression where the object is a prvalue is itself a prvalue.
VisitMemberExpr(const MemberExpr * E)7735   bool VisitMemberExpr(const MemberExpr *E) {
7736     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7737            "missing temporary materialization conversion");
7738     assert(!E->isArrow() && "missing call to bound member function?");
7739 
7740     APValue Val;
7741     if (!Evaluate(Val, Info, E->getBase()))
7742       return false;
7743 
7744     QualType BaseTy = E->getBase()->getType();
7745 
7746     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7747     if (!FD) return Error(E);
7748     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7749     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7750            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7751 
7752     // Note: there is no lvalue base here. But this case should only ever
7753     // happen in C or in C++98, where we cannot be evaluating a constexpr
7754     // constructor, which is the only case the base matters.
7755     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7756     SubobjectDesignator Designator(BaseTy);
7757     Designator.addDeclUnchecked(FD);
7758 
7759     APValue Result;
7760     return extractSubobject(Info, E, Obj, Designator, Result) &&
7761            DerivedSuccess(Result, E);
7762   }
7763 
VisitExtVectorElementExpr(const ExtVectorElementExpr * E)7764   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7765     APValue Val;
7766     if (!Evaluate(Val, Info, E->getBase()))
7767       return false;
7768 
7769     if (Val.isVector()) {
7770       SmallVector<uint32_t, 4> Indices;
7771       E->getEncodedElementAccess(Indices);
7772       if (Indices.size() == 1) {
7773         // Return scalar.
7774         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7775       } else {
7776         // Construct new APValue vector.
7777         SmallVector<APValue, 4> Elts;
7778         for (unsigned I = 0; I < Indices.size(); ++I) {
7779           Elts.push_back(Val.getVectorElt(Indices[I]));
7780         }
7781         APValue VecResult(Elts.data(), Indices.size());
7782         return DerivedSuccess(VecResult, E);
7783       }
7784     }
7785 
7786     return false;
7787   }
7788 
VisitCastExpr(const CastExpr * E)7789   bool VisitCastExpr(const CastExpr *E) {
7790     switch (E->getCastKind()) {
7791     default:
7792       break;
7793 
7794     case CK_AtomicToNonAtomic: {
7795       APValue AtomicVal;
7796       // This does not need to be done in place even for class/array types:
7797       // atomic-to-non-atomic conversion implies copying the object
7798       // representation.
7799       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7800         return false;
7801       return DerivedSuccess(AtomicVal, E);
7802     }
7803 
7804     case CK_NoOp:
7805     case CK_UserDefinedConversion:
7806       return StmtVisitorTy::Visit(E->getSubExpr());
7807 
7808     case CK_LValueToRValue: {
7809       LValue LVal;
7810       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7811         return false;
7812       APValue RVal;
7813       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7814       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7815                                           LVal, RVal))
7816         return false;
7817       return DerivedSuccess(RVal, E);
7818     }
7819     case CK_LValueToRValueBitCast: {
7820       APValue DestValue, SourceValue;
7821       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7822         return false;
7823       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7824         return false;
7825       return DerivedSuccess(DestValue, E);
7826     }
7827 
7828     case CK_AddressSpaceConversion: {
7829       APValue Value;
7830       if (!Evaluate(Value, Info, E->getSubExpr()))
7831         return false;
7832       return DerivedSuccess(Value, E);
7833     }
7834     }
7835 
7836     return Error(E);
7837   }
7838 
VisitUnaryPostInc(const UnaryOperator * UO)7839   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7840     return VisitUnaryPostIncDec(UO);
7841   }
VisitUnaryPostDec(const UnaryOperator * UO)7842   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7843     return VisitUnaryPostIncDec(UO);
7844   }
VisitUnaryPostIncDec(const UnaryOperator * UO)7845   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7846     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7847       return Error(UO);
7848 
7849     LValue LVal;
7850     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7851       return false;
7852     APValue RVal;
7853     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7854                       UO->isIncrementOp(), &RVal))
7855       return false;
7856     return DerivedSuccess(RVal, UO);
7857   }
7858 
VisitStmtExpr(const StmtExpr * E)7859   bool VisitStmtExpr(const StmtExpr *E) {
7860     // We will have checked the full-expressions inside the statement expression
7861     // when they were completed, and don't need to check them again now.
7862     llvm::SaveAndRestore<bool> NotCheckingForUB(
7863         Info.CheckingForUndefinedBehavior, false);
7864 
7865     const CompoundStmt *CS = E->getSubStmt();
7866     if (CS->body_empty())
7867       return true;
7868 
7869     BlockScopeRAII Scope(Info);
7870     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7871                                            BE = CS->body_end();
7872          /**/; ++BI) {
7873       if (BI + 1 == BE) {
7874         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7875         if (!FinalExpr) {
7876           Info.FFDiag((*BI)->getBeginLoc(),
7877                       diag::note_constexpr_stmt_expr_unsupported);
7878           return false;
7879         }
7880         return this->Visit(FinalExpr) && Scope.destroy();
7881       }
7882 
7883       APValue ReturnValue;
7884       StmtResult Result = { ReturnValue, nullptr };
7885       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7886       if (ESR != ESR_Succeeded) {
7887         // FIXME: If the statement-expression terminated due to 'return',
7888         // 'break', or 'continue', it would be nice to propagate that to
7889         // the outer statement evaluation rather than bailing out.
7890         if (ESR != ESR_Failed)
7891           Info.FFDiag((*BI)->getBeginLoc(),
7892                       diag::note_constexpr_stmt_expr_unsupported);
7893         return false;
7894       }
7895     }
7896 
7897     llvm_unreachable("Return from function from the loop above.");
7898   }
7899 
7900   /// Visit a value which is evaluated, but whose value is ignored.
VisitIgnoredValue(const Expr * E)7901   void VisitIgnoredValue(const Expr *E) {
7902     EvaluateIgnoredValue(Info, E);
7903   }
7904 
7905   /// Potentially visit a MemberExpr's base expression.
VisitIgnoredBaseExpression(const Expr * E)7906   void VisitIgnoredBaseExpression(const Expr *E) {
7907     // While MSVC doesn't evaluate the base expression, it does diagnose the
7908     // presence of side-effecting behavior.
7909     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7910       return;
7911     VisitIgnoredValue(E);
7912   }
7913 };
7914 
7915 } // namespace
7916 
7917 //===----------------------------------------------------------------------===//
7918 // Common base class for lvalue and temporary evaluation.
7919 //===----------------------------------------------------------------------===//
7920 namespace {
7921 template<class Derived>
7922 class LValueExprEvaluatorBase
7923   : public ExprEvaluatorBase<Derived> {
7924 protected:
7925   LValue &Result;
7926   bool InvalidBaseOK;
7927   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7928   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7929 
Success(APValue::LValueBase B)7930   bool Success(APValue::LValueBase B) {
7931     Result.set(B);
7932     return true;
7933   }
7934 
evaluatePointer(const Expr * E,LValue & Result)7935   bool evaluatePointer(const Expr *E, LValue &Result) {
7936     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7937   }
7938 
7939 public:
LValueExprEvaluatorBase(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)7940   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7941       : ExprEvaluatorBaseTy(Info), Result(Result),
7942         InvalidBaseOK(InvalidBaseOK) {}
7943 
Success(const APValue & V,const Expr * E)7944   bool Success(const APValue &V, const Expr *E) {
7945     Result.setFrom(this->Info.Ctx, V);
7946     return true;
7947   }
7948 
VisitMemberExpr(const MemberExpr * E)7949   bool VisitMemberExpr(const MemberExpr *E) {
7950     // Handle non-static data members.
7951     QualType BaseTy;
7952     bool EvalOK;
7953     if (E->isArrow()) {
7954       EvalOK = evaluatePointer(E->getBase(), Result);
7955       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7956     } else if (E->getBase()->isPRValue()) {
7957       assert(E->getBase()->getType()->isRecordType());
7958       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7959       BaseTy = E->getBase()->getType();
7960     } else {
7961       EvalOK = this->Visit(E->getBase());
7962       BaseTy = E->getBase()->getType();
7963     }
7964     if (!EvalOK) {
7965       if (!InvalidBaseOK)
7966         return false;
7967       Result.setInvalid(E);
7968       return true;
7969     }
7970 
7971     const ValueDecl *MD = E->getMemberDecl();
7972     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7973       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7974              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7975       (void)BaseTy;
7976       if (!HandleLValueMember(this->Info, E, Result, FD))
7977         return false;
7978     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7979       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7980         return false;
7981     } else
7982       return this->Error(E);
7983 
7984     if (MD->getType()->isReferenceType()) {
7985       APValue RefValue;
7986       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7987                                           RefValue))
7988         return false;
7989       return Success(RefValue, E);
7990     }
7991     return true;
7992   }
7993 
VisitBinaryOperator(const BinaryOperator * E)7994   bool VisitBinaryOperator(const BinaryOperator *E) {
7995     switch (E->getOpcode()) {
7996     default:
7997       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7998 
7999     case BO_PtrMemD:
8000     case BO_PtrMemI:
8001       return HandleMemberPointerAccess(this->Info, E, Result);
8002     }
8003   }
8004 
VisitCastExpr(const CastExpr * E)8005   bool VisitCastExpr(const CastExpr *E) {
8006     switch (E->getCastKind()) {
8007     default:
8008       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8009 
8010     case CK_DerivedToBase:
8011     case CK_UncheckedDerivedToBase:
8012       if (!this->Visit(E->getSubExpr()))
8013         return false;
8014 
8015       // Now figure out the necessary offset to add to the base LV to get from
8016       // the derived class to the base class.
8017       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8018                                   Result);
8019     }
8020   }
8021 };
8022 }
8023 
8024 //===----------------------------------------------------------------------===//
8025 // LValue Evaluation
8026 //
8027 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8028 // function designators (in C), decl references to void objects (in C), and
8029 // temporaries (if building with -Wno-address-of-temporary).
8030 //
8031 // LValue evaluation produces values comprising a base expression of one of the
8032 // following types:
8033 // - Declarations
8034 //  * VarDecl
8035 //  * FunctionDecl
8036 // - Literals
8037 //  * CompoundLiteralExpr in C (and in global scope in C++)
8038 //  * StringLiteral
8039 //  * PredefinedExpr
8040 //  * ObjCStringLiteralExpr
8041 //  * ObjCEncodeExpr
8042 //  * AddrLabelExpr
8043 //  * BlockExpr
8044 //  * CallExpr for a MakeStringConstant builtin
8045 // - typeid(T) expressions, as TypeInfoLValues
8046 // - Locals and temporaries
8047 //  * MaterializeTemporaryExpr
8048 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8049 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8050 //    from the AST (FIXME).
8051 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8052 //    CallIndex, for a lifetime-extended temporary.
8053 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8054 //    immediate invocation.
8055 // plus an offset in bytes.
8056 //===----------------------------------------------------------------------===//
8057 namespace {
8058 class LValueExprEvaluator
8059   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8060 public:
LValueExprEvaluator(EvalInfo & Info,LValue & Result,bool InvalidBaseOK)8061   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8062     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8063 
8064   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8065   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8066 
8067   bool VisitDeclRefExpr(const DeclRefExpr *E);
VisitPredefinedExpr(const PredefinedExpr * E)8068   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8069   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8070   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8071   bool VisitMemberExpr(const MemberExpr *E);
VisitStringLiteral(const StringLiteral * E)8072   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
VisitObjCEncodeExpr(const ObjCEncodeExpr * E)8073   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8074   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8075   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8076   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8077   bool VisitUnaryDeref(const UnaryOperator *E);
8078   bool VisitUnaryReal(const UnaryOperator *E);
8079   bool VisitUnaryImag(const UnaryOperator *E);
VisitUnaryPreInc(const UnaryOperator * UO)8080   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8081     return VisitUnaryPreIncDec(UO);
8082   }
VisitUnaryPreDec(const UnaryOperator * UO)8083   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8084     return VisitUnaryPreIncDec(UO);
8085   }
8086   bool VisitBinAssign(const BinaryOperator *BO);
8087   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8088 
VisitCastExpr(const CastExpr * E)8089   bool VisitCastExpr(const CastExpr *E) {
8090     switch (E->getCastKind()) {
8091     default:
8092       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8093 
8094     case CK_LValueBitCast:
8095       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8096       if (!Visit(E->getSubExpr()))
8097         return false;
8098       Result.Designator.setInvalid();
8099       return true;
8100 
8101     case CK_BaseToDerived:
8102       if (!Visit(E->getSubExpr()))
8103         return false;
8104       return HandleBaseToDerivedCast(Info, E, Result);
8105 
8106     case CK_Dynamic:
8107       if (!Visit(E->getSubExpr()))
8108         return false;
8109       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8110     }
8111   }
8112 };
8113 } // end anonymous namespace
8114 
8115 /// Evaluate an expression as an lvalue. This can be legitimately called on
8116 /// expressions which are not glvalues, in three cases:
8117 ///  * function designators in C, and
8118 ///  * "extern void" objects
8119 ///  * @selector() expressions in Objective-C
EvaluateLValue(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)8120 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8121                            bool InvalidBaseOK) {
8122   assert(!E->isValueDependent());
8123   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8124          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8125   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8126 }
8127 
VisitDeclRefExpr(const DeclRefExpr * E)8128 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8129   const NamedDecl *D = E->getDecl();
8130   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8131     return Success(cast<ValueDecl>(D));
8132   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8133     return VisitVarDecl(E, VD);
8134   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8135     return Visit(BD->getBinding());
8136   return Error(E);
8137 }
8138 
8139 
VisitVarDecl(const Expr * E,const VarDecl * VD)8140 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8141 
8142   // If we are within a lambda's call operator, check whether the 'VD' referred
8143   // to within 'E' actually represents a lambda-capture that maps to a
8144   // data-member/field within the closure object, and if so, evaluate to the
8145   // field or what the field refers to.
8146   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8147       isa<DeclRefExpr>(E) &&
8148       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8149     // We don't always have a complete capture-map when checking or inferring if
8150     // the function call operator meets the requirements of a constexpr function
8151     // - but we don't need to evaluate the captures to determine constexprness
8152     // (dcl.constexpr C++17).
8153     if (Info.checkingPotentialConstantExpression())
8154       return false;
8155 
8156     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8157       // Start with 'Result' referring to the complete closure object...
8158       Result = *Info.CurrentCall->This;
8159       // ... then update it to refer to the field of the closure object
8160       // that represents the capture.
8161       if (!HandleLValueMember(Info, E, Result, FD))
8162         return false;
8163       // And if the field is of reference type, update 'Result' to refer to what
8164       // the field refers to.
8165       if (FD->getType()->isReferenceType()) {
8166         APValue RVal;
8167         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8168                                             RVal))
8169           return false;
8170         Result.setFrom(Info.Ctx, RVal);
8171       }
8172       return true;
8173     }
8174   }
8175 
8176   CallStackFrame *Frame = nullptr;
8177   unsigned Version = 0;
8178   if (VD->hasLocalStorage()) {
8179     // Only if a local variable was declared in the function currently being
8180     // evaluated, do we expect to be able to find its value in the current
8181     // frame. (Otherwise it was likely declared in an enclosing context and
8182     // could either have a valid evaluatable value (for e.g. a constexpr
8183     // variable) or be ill-formed (and trigger an appropriate evaluation
8184     // diagnostic)).
8185     CallStackFrame *CurrFrame = Info.CurrentCall;
8186     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8187       // Function parameters are stored in some caller's frame. (Usually the
8188       // immediate caller, but for an inherited constructor they may be more
8189       // distant.)
8190       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8191         if (CurrFrame->Arguments) {
8192           VD = CurrFrame->Arguments.getOrigParam(PVD);
8193           Frame =
8194               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8195           Version = CurrFrame->Arguments.Version;
8196         }
8197       } else {
8198         Frame = CurrFrame;
8199         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8200       }
8201     }
8202   }
8203 
8204   if (!VD->getType()->isReferenceType()) {
8205     if (Frame) {
8206       Result.set({VD, Frame->Index, Version});
8207       return true;
8208     }
8209     return Success(VD);
8210   }
8211 
8212   if (!Info.getLangOpts().CPlusPlus11) {
8213     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8214         << VD << VD->getType();
8215     Info.Note(VD->getLocation(), diag::note_declared_at);
8216   }
8217 
8218   APValue *V;
8219   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8220     return false;
8221   if (!V->hasValue()) {
8222     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8223     // adjust the diagnostic to say that.
8224     if (!Info.checkingPotentialConstantExpression())
8225       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8226     return false;
8227   }
8228   return Success(*V, E);
8229 }
8230 
VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * E)8231 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8232     const MaterializeTemporaryExpr *E) {
8233   // Walk through the expression to find the materialized temporary itself.
8234   SmallVector<const Expr *, 2> CommaLHSs;
8235   SmallVector<SubobjectAdjustment, 2> Adjustments;
8236   const Expr *Inner =
8237       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8238 
8239   // If we passed any comma operators, evaluate their LHSs.
8240   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8241     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8242       return false;
8243 
8244   // A materialized temporary with static storage duration can appear within the
8245   // result of a constant expression evaluation, so we need to preserve its
8246   // value for use outside this evaluation.
8247   APValue *Value;
8248   if (E->getStorageDuration() == SD_Static) {
8249     // FIXME: What about SD_Thread?
8250     Value = E->getOrCreateValue(true);
8251     *Value = APValue();
8252     Result.set(E);
8253   } else {
8254     Value = &Info.CurrentCall->createTemporary(
8255         E, E->getType(),
8256         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8257                                                      : ScopeKind::Block,
8258         Result);
8259   }
8260 
8261   QualType Type = Inner->getType();
8262 
8263   // Materialize the temporary itself.
8264   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8265     *Value = APValue();
8266     return false;
8267   }
8268 
8269   // Adjust our lvalue to refer to the desired subobject.
8270   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8271     --I;
8272     switch (Adjustments[I].Kind) {
8273     case SubobjectAdjustment::DerivedToBaseAdjustment:
8274       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8275                                 Type, Result))
8276         return false;
8277       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8278       break;
8279 
8280     case SubobjectAdjustment::FieldAdjustment:
8281       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8282         return false;
8283       Type = Adjustments[I].Field->getType();
8284       break;
8285 
8286     case SubobjectAdjustment::MemberPointerAdjustment:
8287       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8288                                      Adjustments[I].Ptr.RHS))
8289         return false;
8290       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8291       break;
8292     }
8293   }
8294 
8295   return true;
8296 }
8297 
8298 bool
VisitCompoundLiteralExpr(const CompoundLiteralExpr * E)8299 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8300   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8301          "lvalue compound literal in c++?");
8302   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8303   // only see this when folding in C, so there's no standard to follow here.
8304   return Success(E);
8305 }
8306 
VisitCXXTypeidExpr(const CXXTypeidExpr * E)8307 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8308   TypeInfoLValue TypeInfo;
8309 
8310   if (!E->isPotentiallyEvaluated()) {
8311     if (E->isTypeOperand())
8312       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8313     else
8314       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8315   } else {
8316     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8317       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8318         << E->getExprOperand()->getType()
8319         << E->getExprOperand()->getSourceRange();
8320     }
8321 
8322     if (!Visit(E->getExprOperand()))
8323       return false;
8324 
8325     Optional<DynamicType> DynType =
8326         ComputeDynamicType(Info, E, Result, AK_TypeId);
8327     if (!DynType)
8328       return false;
8329 
8330     TypeInfo =
8331         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8332   }
8333 
8334   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8335 }
8336 
VisitCXXUuidofExpr(const CXXUuidofExpr * E)8337 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8338   return Success(E->getGuidDecl());
8339 }
8340 
VisitMemberExpr(const MemberExpr * E)8341 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8342   // Handle static data members.
8343   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8344     VisitIgnoredBaseExpression(E->getBase());
8345     return VisitVarDecl(E, VD);
8346   }
8347 
8348   // Handle static member functions.
8349   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8350     if (MD->isStatic()) {
8351       VisitIgnoredBaseExpression(E->getBase());
8352       return Success(MD);
8353     }
8354   }
8355 
8356   // Handle non-static data members.
8357   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8358 }
8359 
VisitArraySubscriptExpr(const ArraySubscriptExpr * E)8360 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8361   // FIXME: Deal with vectors as array subscript bases.
8362   if (E->getBase()->getType()->isVectorType())
8363     return Error(E);
8364 
8365   APSInt Index;
8366   bool Success = true;
8367 
8368   // C++17's rules require us to evaluate the LHS first, regardless of which
8369   // side is the base.
8370   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8371     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8372                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8373       if (!Info.noteFailure())
8374         return false;
8375       Success = false;
8376     }
8377   }
8378 
8379   return Success &&
8380          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8381 }
8382 
VisitUnaryDeref(const UnaryOperator * E)8383 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8384   return evaluatePointer(E->getSubExpr(), Result);
8385 }
8386 
VisitUnaryReal(const UnaryOperator * E)8387 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8388   if (!Visit(E->getSubExpr()))
8389     return false;
8390   // __real is a no-op on scalar lvalues.
8391   if (E->getSubExpr()->getType()->isAnyComplexType())
8392     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8393   return true;
8394 }
8395 
VisitUnaryImag(const UnaryOperator * E)8396 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8397   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8398          "lvalue __imag__ on scalar?");
8399   if (!Visit(E->getSubExpr()))
8400     return false;
8401   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8402   return true;
8403 }
8404 
VisitUnaryPreIncDec(const UnaryOperator * UO)8405 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8406   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8407     return Error(UO);
8408 
8409   if (!this->Visit(UO->getSubExpr()))
8410     return false;
8411 
8412   return handleIncDec(
8413       this->Info, UO, Result, UO->getSubExpr()->getType(),
8414       UO->isIncrementOp(), nullptr);
8415 }
8416 
VisitCompoundAssignOperator(const CompoundAssignOperator * CAO)8417 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8418     const CompoundAssignOperator *CAO) {
8419   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8420     return Error(CAO);
8421 
8422   bool Success = true;
8423 
8424   // C++17 onwards require that we evaluate the RHS first.
8425   APValue RHS;
8426   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8427     if (!Info.noteFailure())
8428       return false;
8429     Success = false;
8430   }
8431 
8432   // The overall lvalue result is the result of evaluating the LHS.
8433   if (!this->Visit(CAO->getLHS()) || !Success)
8434     return false;
8435 
8436   return handleCompoundAssignment(
8437       this->Info, CAO,
8438       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8439       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8440 }
8441 
VisitBinAssign(const BinaryOperator * E)8442 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8443   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8444     return Error(E);
8445 
8446   bool Success = true;
8447 
8448   // C++17 onwards require that we evaluate the RHS first.
8449   APValue NewVal;
8450   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8451     if (!Info.noteFailure())
8452       return false;
8453     Success = false;
8454   }
8455 
8456   if (!this->Visit(E->getLHS()) || !Success)
8457     return false;
8458 
8459   if (Info.getLangOpts().CPlusPlus20 &&
8460       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8461     return false;
8462 
8463   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8464                           NewVal);
8465 }
8466 
8467 //===----------------------------------------------------------------------===//
8468 // Pointer Evaluation
8469 //===----------------------------------------------------------------------===//
8470 
8471 /// Attempts to compute the number of bytes available at the pointer
8472 /// returned by a function with the alloc_size attribute. Returns true if we
8473 /// were successful. Places an unsigned number into `Result`.
8474 ///
8475 /// This expects the given CallExpr to be a call to a function with an
8476 /// alloc_size attribute.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const CallExpr * Call,llvm::APInt & Result)8477 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8478                                             const CallExpr *Call,
8479                                             llvm::APInt &Result) {
8480   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8481 
8482   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8483   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8484   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8485   if (Call->getNumArgs() <= SizeArgNo)
8486     return false;
8487 
8488   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8489     Expr::EvalResult ExprResult;
8490     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8491       return false;
8492     Into = ExprResult.Val.getInt();
8493     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8494       return false;
8495     Into = Into.zextOrSelf(BitsInSizeT);
8496     return true;
8497   };
8498 
8499   APSInt SizeOfElem;
8500   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8501     return false;
8502 
8503   if (!AllocSize->getNumElemsParam().isValid()) {
8504     Result = std::move(SizeOfElem);
8505     return true;
8506   }
8507 
8508   APSInt NumberOfElems;
8509   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8510   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8511     return false;
8512 
8513   bool Overflow;
8514   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8515   if (Overflow)
8516     return false;
8517 
8518   Result = std::move(BytesAvailable);
8519   return true;
8520 }
8521 
8522 /// Convenience function. LVal's base must be a call to an alloc_size
8523 /// function.
getBytesReturnedByAllocSizeCall(const ASTContext & Ctx,const LValue & LVal,llvm::APInt & Result)8524 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8525                                             const LValue &LVal,
8526                                             llvm::APInt &Result) {
8527   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8528          "Can't get the size of a non alloc_size function");
8529   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8530   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8531   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8532 }
8533 
8534 /// Attempts to evaluate the given LValueBase as the result of a call to
8535 /// a function with the alloc_size attribute. If it was possible to do so, this
8536 /// function will return true, make Result's Base point to said function call,
8537 /// and mark Result's Base as invalid.
evaluateLValueAsAllocSize(EvalInfo & Info,APValue::LValueBase Base,LValue & Result)8538 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8539                                       LValue &Result) {
8540   if (Base.isNull())
8541     return false;
8542 
8543   // Because we do no form of static analysis, we only support const variables.
8544   //
8545   // Additionally, we can't support parameters, nor can we support static
8546   // variables (in the latter case, use-before-assign isn't UB; in the former,
8547   // we have no clue what they'll be assigned to).
8548   const auto *VD =
8549       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8550   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8551     return false;
8552 
8553   const Expr *Init = VD->getAnyInitializer();
8554   if (!Init)
8555     return false;
8556 
8557   const Expr *E = Init->IgnoreParens();
8558   if (!tryUnwrapAllocSizeCall(E))
8559     return false;
8560 
8561   // Store E instead of E unwrapped so that the type of the LValue's base is
8562   // what the user wanted.
8563   Result.setInvalid(E);
8564 
8565   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8566   Result.addUnsizedArray(Info, E, Pointee);
8567   return true;
8568 }
8569 
8570 namespace {
8571 class PointerExprEvaluator
8572   : public ExprEvaluatorBase<PointerExprEvaluator> {
8573   LValue &Result;
8574   bool InvalidBaseOK;
8575 
Success(const Expr * E)8576   bool Success(const Expr *E) {
8577     Result.set(E);
8578     return true;
8579   }
8580 
evaluateLValue(const Expr * E,LValue & Result)8581   bool evaluateLValue(const Expr *E, LValue &Result) {
8582     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8583   }
8584 
evaluatePointer(const Expr * E,LValue & Result)8585   bool evaluatePointer(const Expr *E, LValue &Result) {
8586     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8587   }
8588 
8589   bool visitNonBuiltinCallExpr(const CallExpr *E);
8590 public:
8591 
PointerExprEvaluator(EvalInfo & info,LValue & Result,bool InvalidBaseOK)8592   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8593       : ExprEvaluatorBaseTy(info), Result(Result),
8594         InvalidBaseOK(InvalidBaseOK) {}
8595 
Success(const APValue & V,const Expr * E)8596   bool Success(const APValue &V, const Expr *E) {
8597     Result.setFrom(Info.Ctx, V);
8598     return true;
8599   }
ZeroInitialization(const Expr * E)8600   bool ZeroInitialization(const Expr *E) {
8601     Result.setNull(Info.Ctx, E->getType());
8602     return true;
8603   }
8604 
8605   bool VisitBinaryOperator(const BinaryOperator *E);
8606   bool VisitCastExpr(const CastExpr* E);
8607   bool VisitUnaryAddrOf(const UnaryOperator *E);
VisitObjCStringLiteral(const ObjCStringLiteral * E)8608   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8609       { return Success(E); }
VisitObjCBoxedExpr(const ObjCBoxedExpr * E)8610   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8611     if (E->isExpressibleAsConstantInitializer())
8612       return Success(E);
8613     if (Info.noteFailure())
8614       EvaluateIgnoredValue(Info, E->getSubExpr());
8615     return Error(E);
8616   }
VisitAddrLabelExpr(const AddrLabelExpr * E)8617   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8618       { return Success(E); }
8619   bool VisitCallExpr(const CallExpr *E);
8620   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
VisitBlockExpr(const BlockExpr * E)8621   bool VisitBlockExpr(const BlockExpr *E) {
8622     if (!E->getBlockDecl()->hasCaptures())
8623       return Success(E);
8624     return Error(E);
8625   }
VisitCXXThisExpr(const CXXThisExpr * E)8626   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8627     // Can't look at 'this' when checking a potential constant expression.
8628     if (Info.checkingPotentialConstantExpression())
8629       return false;
8630     if (!Info.CurrentCall->This) {
8631       if (Info.getLangOpts().CPlusPlus11)
8632         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8633       else
8634         Info.FFDiag(E);
8635       return false;
8636     }
8637     Result = *Info.CurrentCall->This;
8638     // If we are inside a lambda's call operator, the 'this' expression refers
8639     // to the enclosing '*this' object (either by value or reference) which is
8640     // either copied into the closure object's field that represents the '*this'
8641     // or refers to '*this'.
8642     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8643       // Ensure we actually have captured 'this'. (an error will have
8644       // been previously reported if not).
8645       if (!Info.CurrentCall->LambdaThisCaptureField)
8646         return false;
8647 
8648       // Update 'Result' to refer to the data member/field of the closure object
8649       // that represents the '*this' capture.
8650       if (!HandleLValueMember(Info, E, Result,
8651                              Info.CurrentCall->LambdaThisCaptureField))
8652         return false;
8653       // If we captured '*this' by reference, replace the field with its referent.
8654       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8655               ->isPointerType()) {
8656         APValue RVal;
8657         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8658                                             RVal))
8659           return false;
8660 
8661         Result.setFrom(Info.Ctx, RVal);
8662       }
8663     }
8664     return true;
8665   }
8666 
8667   bool VisitCXXNewExpr(const CXXNewExpr *E);
8668 
VisitSourceLocExpr(const SourceLocExpr * E)8669   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8670     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8671     APValue LValResult = E->EvaluateInContext(
8672         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8673     Result.setFrom(Info.Ctx, LValResult);
8674     return true;
8675   }
8676 
VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr * E)8677   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8678     std::string ResultStr = E->ComputeName(Info.Ctx);
8679 
8680     QualType CharTy = Info.Ctx.CharTy.withConst();
8681     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8682                ResultStr.size() + 1);
8683     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8684                                                      ArrayType::Normal, 0);
8685 
8686     StringLiteral *SL =
8687         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii,
8688                               /*Pascal*/ false, ArrayTy, E->getLocation());
8689 
8690     evaluateLValue(SL, Result);
8691     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8692     return true;
8693   }
8694 
8695   // FIXME: Missing: @protocol, @selector
8696 };
8697 } // end anonymous namespace
8698 
EvaluatePointer(const Expr * E,LValue & Result,EvalInfo & Info,bool InvalidBaseOK)8699 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8700                             bool InvalidBaseOK) {
8701   assert(!E->isValueDependent());
8702   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8703   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8704 }
8705 
VisitBinaryOperator(const BinaryOperator * E)8706 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8707   if (E->getOpcode() != BO_Add &&
8708       E->getOpcode() != BO_Sub)
8709     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8710 
8711   const Expr *PExp = E->getLHS();
8712   const Expr *IExp = E->getRHS();
8713   if (IExp->getType()->isPointerType())
8714     std::swap(PExp, IExp);
8715 
8716   bool EvalPtrOK = evaluatePointer(PExp, Result);
8717   if (!EvalPtrOK && !Info.noteFailure())
8718     return false;
8719 
8720   llvm::APSInt Offset;
8721   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8722     return false;
8723 
8724   if (E->getOpcode() == BO_Sub)
8725     negateAsSigned(Offset);
8726 
8727   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8728   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8729 }
8730 
VisitUnaryAddrOf(const UnaryOperator * E)8731 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8732   return evaluateLValue(E->getSubExpr(), Result);
8733 }
8734 
VisitCastExpr(const CastExpr * E)8735 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8736   const Expr *SubExpr = E->getSubExpr();
8737 
8738   switch (E->getCastKind()) {
8739   default:
8740     break;
8741   case CK_BitCast:
8742   case CK_CPointerToObjCPointerCast:
8743   case CK_BlockPointerToObjCPointerCast:
8744   case CK_AnyPointerToBlockPointerCast:
8745   case CK_AddressSpaceConversion:
8746     if (!Visit(SubExpr))
8747       return false;
8748     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8749     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8750     // also static_casts, but we disallow them as a resolution to DR1312.
8751     if (!E->getType()->isVoidPointerType()) {
8752       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8753           !Result.IsNullPtr &&
8754           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8755                                           E->getType()->getPointeeType()) &&
8756           Info.getStdAllocatorCaller("allocate")) {
8757         // Inside a call to std::allocator::allocate and friends, we permit
8758         // casting from void* back to cv1 T* for a pointer that points to a
8759         // cv2 T.
8760       } else {
8761         Result.Designator.setInvalid();
8762         if (SubExpr->getType()->isVoidPointerType())
8763           CCEDiag(E, diag::note_constexpr_invalid_cast)
8764             << 3 << SubExpr->getType();
8765         else
8766           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8767       }
8768     }
8769     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8770       ZeroInitialization(E);
8771     return true;
8772 
8773   case CK_DerivedToBase:
8774   case CK_UncheckedDerivedToBase:
8775     if (!evaluatePointer(E->getSubExpr(), Result))
8776       return false;
8777     if (!Result.Base && Result.Offset.isZero())
8778       return true;
8779 
8780     // Now figure out the necessary offset to add to the base LV to get from
8781     // the derived class to the base class.
8782     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8783                                   castAs<PointerType>()->getPointeeType(),
8784                                 Result);
8785 
8786   case CK_BaseToDerived:
8787     if (!Visit(E->getSubExpr()))
8788       return false;
8789     if (!Result.Base && Result.Offset.isZero())
8790       return true;
8791     return HandleBaseToDerivedCast(Info, E, Result);
8792 
8793   case CK_Dynamic:
8794     if (!Visit(E->getSubExpr()))
8795       return false;
8796     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8797 
8798   case CK_NullToPointer:
8799     VisitIgnoredValue(E->getSubExpr());
8800     return ZeroInitialization(E);
8801 
8802   case CK_IntegralToPointer: {
8803     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8804 
8805     APValue Value;
8806     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8807       break;
8808 
8809     if (Value.isInt()) {
8810       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8811       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8812       Result.Base = (Expr*)nullptr;
8813       Result.InvalidBase = false;
8814       Result.Offset = CharUnits::fromQuantity(N);
8815       Result.Designator.setInvalid();
8816       Result.IsNullPtr = false;
8817       return true;
8818     } else {
8819       // Cast is of an lvalue, no need to change value.
8820       Result.setFrom(Info.Ctx, Value);
8821       return true;
8822     }
8823   }
8824 
8825   case CK_ArrayToPointerDecay: {
8826     if (SubExpr->isGLValue()) {
8827       if (!evaluateLValue(SubExpr, Result))
8828         return false;
8829     } else {
8830       APValue &Value = Info.CurrentCall->createTemporary(
8831           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8832       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8833         return false;
8834     }
8835     // The result is a pointer to the first element of the array.
8836     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8837     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8838       Result.addArray(Info, E, CAT);
8839     else
8840       Result.addUnsizedArray(Info, E, AT->getElementType());
8841     return true;
8842   }
8843 
8844   case CK_FunctionToPointerDecay:
8845     return evaluateLValue(SubExpr, Result);
8846 
8847   case CK_LValueToRValue: {
8848     LValue LVal;
8849     if (!evaluateLValue(E->getSubExpr(), LVal))
8850       return false;
8851 
8852     APValue RVal;
8853     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8854     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8855                                         LVal, RVal))
8856       return InvalidBaseOK &&
8857              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8858     return Success(RVal, E);
8859   }
8860   }
8861 
8862   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8863 }
8864 
GetAlignOfType(EvalInfo & Info,QualType T,UnaryExprOrTypeTrait ExprKind)8865 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8866                                 UnaryExprOrTypeTrait ExprKind) {
8867   // C++ [expr.alignof]p3:
8868   //     When alignof is applied to a reference type, the result is the
8869   //     alignment of the referenced type.
8870   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8871     T = Ref->getPointeeType();
8872 
8873   if (T.getQualifiers().hasUnaligned())
8874     return CharUnits::One();
8875 
8876   const bool AlignOfReturnsPreferred =
8877       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8878 
8879   // __alignof is defined to return the preferred alignment.
8880   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8881   // as well.
8882   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8883     return Info.Ctx.toCharUnitsFromBits(
8884       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8885   // alignof and _Alignof are defined to return the ABI alignment.
8886   else if (ExprKind == UETT_AlignOf)
8887     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8888   else
8889     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8890 }
8891 
GetAlignOfExpr(EvalInfo & Info,const Expr * E,UnaryExprOrTypeTrait ExprKind)8892 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8893                                 UnaryExprOrTypeTrait ExprKind) {
8894   E = E->IgnoreParens();
8895 
8896   // The kinds of expressions that we have special-case logic here for
8897   // should be kept up to date with the special checks for those
8898   // expressions in Sema.
8899 
8900   // alignof decl is always accepted, even if it doesn't make sense: we default
8901   // to 1 in those cases.
8902   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8903     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8904                                  /*RefAsPointee*/true);
8905 
8906   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8907     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8908                                  /*RefAsPointee*/true);
8909 
8910   return GetAlignOfType(Info, E->getType(), ExprKind);
8911 }
8912 
getBaseAlignment(EvalInfo & Info,const LValue & Value)8913 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8914   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8915     return Info.Ctx.getDeclAlign(VD);
8916   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8917     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8918   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8919 }
8920 
8921 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8922 /// __builtin_is_aligned and __builtin_assume_aligned.
getAlignmentArgument(const Expr * E,QualType ForType,EvalInfo & Info,APSInt & Alignment)8923 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8924                                  EvalInfo &Info, APSInt &Alignment) {
8925   if (!EvaluateInteger(E, Alignment, Info))
8926     return false;
8927   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8928     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8929     return false;
8930   }
8931   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8932   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8933   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8934     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8935         << MaxValue << ForType << Alignment;
8936     return false;
8937   }
8938   // Ensure both alignment and source value have the same bit width so that we
8939   // don't assert when computing the resulting value.
8940   APSInt ExtAlignment =
8941       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8942   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8943          "Alignment should not be changed by ext/trunc");
8944   Alignment = ExtAlignment;
8945   assert(Alignment.getBitWidth() == SrcWidth);
8946   return true;
8947 }
8948 
8949 // To be clear: this happily visits unsupported builtins. Better name welcomed.
visitNonBuiltinCallExpr(const CallExpr * E)8950 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8951   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8952     return true;
8953 
8954   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8955     return false;
8956 
8957   Result.setInvalid(E);
8958   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8959   Result.addUnsizedArray(Info, E, PointeeTy);
8960   return true;
8961 }
8962 
VisitCallExpr(const CallExpr * E)8963 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8964   if (IsStringLiteralCall(E))
8965     return Success(E);
8966 
8967   if (unsigned BuiltinOp = E->getBuiltinCallee())
8968     return VisitBuiltinCallExpr(E, BuiltinOp);
8969 
8970   return visitNonBuiltinCallExpr(E);
8971 }
8972 
8973 // Determine if T is a character type for which we guarantee that
8974 // sizeof(T) == 1.
isOneByteCharacterType(QualType T)8975 static bool isOneByteCharacterType(QualType T) {
8976   return T->isCharType() || T->isChar8Type();
8977 }
8978 
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)8979 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8980                                                 unsigned BuiltinOp) {
8981   switch (BuiltinOp) {
8982   case Builtin::BI__builtin_addressof:
8983     return evaluateLValue(E->getArg(0), Result);
8984   case Builtin::BI__builtin_assume_aligned: {
8985     // We need to be very careful here because: if the pointer does not have the
8986     // asserted alignment, then the behavior is undefined, and undefined
8987     // behavior is non-constant.
8988     if (!evaluatePointer(E->getArg(0), Result))
8989       return false;
8990 
8991     LValue OffsetResult(Result);
8992     APSInt Alignment;
8993     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8994                               Alignment))
8995       return false;
8996     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8997 
8998     if (E->getNumArgs() > 2) {
8999       APSInt Offset;
9000       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9001         return false;
9002 
9003       int64_t AdditionalOffset = -Offset.getZExtValue();
9004       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9005     }
9006 
9007     // If there is a base object, then it must have the correct alignment.
9008     if (OffsetResult.Base) {
9009       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9010 
9011       if (BaseAlignment < Align) {
9012         Result.Designator.setInvalid();
9013         // FIXME: Add support to Diagnostic for long / long long.
9014         CCEDiag(E->getArg(0),
9015                 diag::note_constexpr_baa_insufficient_alignment) << 0
9016           << (unsigned)BaseAlignment.getQuantity()
9017           << (unsigned)Align.getQuantity();
9018         return false;
9019       }
9020     }
9021 
9022     // The offset must also have the correct alignment.
9023     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9024       Result.Designator.setInvalid();
9025 
9026       (OffsetResult.Base
9027            ? CCEDiag(E->getArg(0),
9028                      diag::note_constexpr_baa_insufficient_alignment) << 1
9029            : CCEDiag(E->getArg(0),
9030                      diag::note_constexpr_baa_value_insufficient_alignment))
9031         << (int)OffsetResult.Offset.getQuantity()
9032         << (unsigned)Align.getQuantity();
9033       return false;
9034     }
9035 
9036     return true;
9037   }
9038   case Builtin::BI__builtin_align_up:
9039   case Builtin::BI__builtin_align_down: {
9040     if (!evaluatePointer(E->getArg(0), Result))
9041       return false;
9042     APSInt Alignment;
9043     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9044                               Alignment))
9045       return false;
9046     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9047     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9048     // For align_up/align_down, we can return the same value if the alignment
9049     // is known to be greater or equal to the requested value.
9050     if (PtrAlign.getQuantity() >= Alignment)
9051       return true;
9052 
9053     // The alignment could be greater than the minimum at run-time, so we cannot
9054     // infer much about the resulting pointer value. One case is possible:
9055     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9056     // can infer the correct index if the requested alignment is smaller than
9057     // the base alignment so we can perform the computation on the offset.
9058     if (BaseAlignment.getQuantity() >= Alignment) {
9059       assert(Alignment.getBitWidth() <= 64 &&
9060              "Cannot handle > 64-bit address-space");
9061       uint64_t Alignment64 = Alignment.getZExtValue();
9062       CharUnits NewOffset = CharUnits::fromQuantity(
9063           BuiltinOp == Builtin::BI__builtin_align_down
9064               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9065               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9066       Result.adjustOffset(NewOffset - Result.Offset);
9067       // TODO: diagnose out-of-bounds values/only allow for arrays?
9068       return true;
9069     }
9070     // Otherwise, we cannot constant-evaluate the result.
9071     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9072         << Alignment;
9073     return false;
9074   }
9075   case Builtin::BI__builtin_operator_new:
9076     return HandleOperatorNewCall(Info, E, Result);
9077   case Builtin::BI__builtin_launder:
9078     return evaluatePointer(E->getArg(0), Result);
9079   case Builtin::BIstrchr:
9080   case Builtin::BIwcschr:
9081   case Builtin::BImemchr:
9082   case Builtin::BIwmemchr:
9083     if (Info.getLangOpts().CPlusPlus11)
9084       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9085         << /*isConstexpr*/0 << /*isConstructor*/0
9086         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9087     else
9088       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9089     LLVM_FALLTHROUGH;
9090   case Builtin::BI__builtin_strchr:
9091   case Builtin::BI__builtin_wcschr:
9092   case Builtin::BI__builtin_memchr:
9093   case Builtin::BI__builtin_char_memchr:
9094   case Builtin::BI__builtin_wmemchr: {
9095     if (!Visit(E->getArg(0)))
9096       return false;
9097     APSInt Desired;
9098     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9099       return false;
9100     uint64_t MaxLength = uint64_t(-1);
9101     if (BuiltinOp != Builtin::BIstrchr &&
9102         BuiltinOp != Builtin::BIwcschr &&
9103         BuiltinOp != Builtin::BI__builtin_strchr &&
9104         BuiltinOp != Builtin::BI__builtin_wcschr) {
9105       APSInt N;
9106       if (!EvaluateInteger(E->getArg(2), N, Info))
9107         return false;
9108       MaxLength = N.getExtValue();
9109     }
9110     // We cannot find the value if there are no candidates to match against.
9111     if (MaxLength == 0u)
9112       return ZeroInitialization(E);
9113     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9114         Result.Designator.Invalid)
9115       return false;
9116     QualType CharTy = Result.Designator.getType(Info.Ctx);
9117     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9118                      BuiltinOp == Builtin::BI__builtin_memchr;
9119     assert(IsRawByte ||
9120            Info.Ctx.hasSameUnqualifiedType(
9121                CharTy, E->getArg(0)->getType()->getPointeeType()));
9122     // Pointers to const void may point to objects of incomplete type.
9123     if (IsRawByte && CharTy->isIncompleteType()) {
9124       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9125       return false;
9126     }
9127     // Give up on byte-oriented matching against multibyte elements.
9128     // FIXME: We can compare the bytes in the correct order.
9129     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9130       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9131           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9132           << CharTy;
9133       return false;
9134     }
9135     // Figure out what value we're actually looking for (after converting to
9136     // the corresponding unsigned type if necessary).
9137     uint64_t DesiredVal;
9138     bool StopAtNull = false;
9139     switch (BuiltinOp) {
9140     case Builtin::BIstrchr:
9141     case Builtin::BI__builtin_strchr:
9142       // strchr compares directly to the passed integer, and therefore
9143       // always fails if given an int that is not a char.
9144       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9145                                                   E->getArg(1)->getType(),
9146                                                   Desired),
9147                                Desired))
9148         return ZeroInitialization(E);
9149       StopAtNull = true;
9150       LLVM_FALLTHROUGH;
9151     case Builtin::BImemchr:
9152     case Builtin::BI__builtin_memchr:
9153     case Builtin::BI__builtin_char_memchr:
9154       // memchr compares by converting both sides to unsigned char. That's also
9155       // correct for strchr if we get this far (to cope with plain char being
9156       // unsigned in the strchr case).
9157       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9158       break;
9159 
9160     case Builtin::BIwcschr:
9161     case Builtin::BI__builtin_wcschr:
9162       StopAtNull = true;
9163       LLVM_FALLTHROUGH;
9164     case Builtin::BIwmemchr:
9165     case Builtin::BI__builtin_wmemchr:
9166       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9167       DesiredVal = Desired.getZExtValue();
9168       break;
9169     }
9170 
9171     for (; MaxLength; --MaxLength) {
9172       APValue Char;
9173       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9174           !Char.isInt())
9175         return false;
9176       if (Char.getInt().getZExtValue() == DesiredVal)
9177         return true;
9178       if (StopAtNull && !Char.getInt())
9179         break;
9180       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9181         return false;
9182     }
9183     // Not found: return nullptr.
9184     return ZeroInitialization(E);
9185   }
9186 
9187   case Builtin::BImemcpy:
9188   case Builtin::BImemmove:
9189   case Builtin::BIwmemcpy:
9190   case Builtin::BIwmemmove:
9191     if (Info.getLangOpts().CPlusPlus11)
9192       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9193         << /*isConstexpr*/0 << /*isConstructor*/0
9194         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9195     else
9196       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9197     LLVM_FALLTHROUGH;
9198   case Builtin::BI__builtin_memcpy:
9199   case Builtin::BI__builtin_memmove:
9200   case Builtin::BI__builtin_wmemcpy:
9201   case Builtin::BI__builtin_wmemmove: {
9202     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9203                  BuiltinOp == Builtin::BIwmemmove ||
9204                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9205                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9206     bool Move = BuiltinOp == Builtin::BImemmove ||
9207                 BuiltinOp == Builtin::BIwmemmove ||
9208                 BuiltinOp == Builtin::BI__builtin_memmove ||
9209                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9210 
9211     // The result of mem* is the first argument.
9212     if (!Visit(E->getArg(0)))
9213       return false;
9214     LValue Dest = Result;
9215 
9216     LValue Src;
9217     if (!EvaluatePointer(E->getArg(1), Src, Info))
9218       return false;
9219 
9220     APSInt N;
9221     if (!EvaluateInteger(E->getArg(2), N, Info))
9222       return false;
9223     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9224 
9225     // If the size is zero, we treat this as always being a valid no-op.
9226     // (Even if one of the src and dest pointers is null.)
9227     if (!N)
9228       return true;
9229 
9230     // Otherwise, if either of the operands is null, we can't proceed. Don't
9231     // try to determine the type of the copied objects, because there aren't
9232     // any.
9233     if (!Src.Base || !Dest.Base) {
9234       APValue Val;
9235       (!Src.Base ? Src : Dest).moveInto(Val);
9236       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9237           << Move << WChar << !!Src.Base
9238           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9239       return false;
9240     }
9241     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9242       return false;
9243 
9244     // We require that Src and Dest are both pointers to arrays of
9245     // trivially-copyable type. (For the wide version, the designator will be
9246     // invalid if the designated object is not a wchar_t.)
9247     QualType T = Dest.Designator.getType(Info.Ctx);
9248     QualType SrcT = Src.Designator.getType(Info.Ctx);
9249     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9250       // FIXME: Consider using our bit_cast implementation to support this.
9251       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9252       return false;
9253     }
9254     if (T->isIncompleteType()) {
9255       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9256       return false;
9257     }
9258     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9259       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9260       return false;
9261     }
9262 
9263     // Figure out how many T's we're copying.
9264     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9265     if (!WChar) {
9266       uint64_t Remainder;
9267       llvm::APInt OrigN = N;
9268       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9269       if (Remainder) {
9270         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9271             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9272             << (unsigned)TSize;
9273         return false;
9274       }
9275     }
9276 
9277     // Check that the copying will remain within the arrays, just so that we
9278     // can give a more meaningful diagnostic. This implicitly also checks that
9279     // N fits into 64 bits.
9280     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9281     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9282     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9283       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9284           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9285           << toString(N, 10, /*Signed*/false);
9286       return false;
9287     }
9288     uint64_t NElems = N.getZExtValue();
9289     uint64_t NBytes = NElems * TSize;
9290 
9291     // Check for overlap.
9292     int Direction = 1;
9293     if (HasSameBase(Src, Dest)) {
9294       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9295       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9296       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9297         // Dest is inside the source region.
9298         if (!Move) {
9299           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9300           return false;
9301         }
9302         // For memmove and friends, copy backwards.
9303         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9304             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9305           return false;
9306         Direction = -1;
9307       } else if (!Move && SrcOffset >= DestOffset &&
9308                  SrcOffset - DestOffset < NBytes) {
9309         // Src is inside the destination region for memcpy: invalid.
9310         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9311         return false;
9312       }
9313     }
9314 
9315     while (true) {
9316       APValue Val;
9317       // FIXME: Set WantObjectRepresentation to true if we're copying a
9318       // char-like type?
9319       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9320           !handleAssignment(Info, E, Dest, T, Val))
9321         return false;
9322       // Do not iterate past the last element; if we're copying backwards, that
9323       // might take us off the start of the array.
9324       if (--NElems == 0)
9325         return true;
9326       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9327           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9328         return false;
9329     }
9330   }
9331 
9332   default:
9333     break;
9334   }
9335 
9336   return visitNonBuiltinCallExpr(E);
9337 }
9338 
9339 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9340                                      APValue &Result, const InitListExpr *ILE,
9341                                      QualType AllocType);
9342 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9343                                           APValue &Result,
9344                                           const CXXConstructExpr *CCE,
9345                                           QualType AllocType);
9346 
VisitCXXNewExpr(const CXXNewExpr * E)9347 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9348   if (!Info.getLangOpts().CPlusPlus20)
9349     Info.CCEDiag(E, diag::note_constexpr_new);
9350 
9351   // We cannot speculatively evaluate a delete expression.
9352   if (Info.SpeculativeEvaluationDepth)
9353     return false;
9354 
9355   FunctionDecl *OperatorNew = E->getOperatorNew();
9356 
9357   bool IsNothrow = false;
9358   bool IsPlacement = false;
9359   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9360       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9361     // FIXME Support array placement new.
9362     assert(E->getNumPlacementArgs() == 1);
9363     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9364       return false;
9365     if (Result.Designator.Invalid)
9366       return false;
9367     IsPlacement = true;
9368   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9369     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9370         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9371     return false;
9372   } else if (E->getNumPlacementArgs()) {
9373     // The only new-placement list we support is of the form (std::nothrow).
9374     //
9375     // FIXME: There is no restriction on this, but it's not clear that any
9376     // other form makes any sense. We get here for cases such as:
9377     //
9378     //   new (std::align_val_t{N}) X(int)
9379     //
9380     // (which should presumably be valid only if N is a multiple of
9381     // alignof(int), and in any case can't be deallocated unless N is
9382     // alignof(X) and X has new-extended alignment).
9383     if (E->getNumPlacementArgs() != 1 ||
9384         !E->getPlacementArg(0)->getType()->isNothrowT())
9385       return Error(E, diag::note_constexpr_new_placement);
9386 
9387     LValue Nothrow;
9388     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9389       return false;
9390     IsNothrow = true;
9391   }
9392 
9393   const Expr *Init = E->getInitializer();
9394   const InitListExpr *ResizedArrayILE = nullptr;
9395   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9396   bool ValueInit = false;
9397 
9398   QualType AllocType = E->getAllocatedType();
9399   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9400     const Expr *Stripped = *ArraySize;
9401     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9402          Stripped = ICE->getSubExpr())
9403       if (ICE->getCastKind() != CK_NoOp &&
9404           ICE->getCastKind() != CK_IntegralCast)
9405         break;
9406 
9407     llvm::APSInt ArrayBound;
9408     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9409       return false;
9410 
9411     // C++ [expr.new]p9:
9412     //   The expression is erroneous if:
9413     //   -- [...] its value before converting to size_t [or] applying the
9414     //      second standard conversion sequence is less than zero
9415     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9416       if (IsNothrow)
9417         return ZeroInitialization(E);
9418 
9419       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9420           << ArrayBound << (*ArraySize)->getSourceRange();
9421       return false;
9422     }
9423 
9424     //   -- its value is such that the size of the allocated object would
9425     //      exceed the implementation-defined limit
9426     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9427                                                 ArrayBound) >
9428         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9429       if (IsNothrow)
9430         return ZeroInitialization(E);
9431 
9432       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9433         << ArrayBound << (*ArraySize)->getSourceRange();
9434       return false;
9435     }
9436 
9437     //   -- the new-initializer is a braced-init-list and the number of
9438     //      array elements for which initializers are provided [...]
9439     //      exceeds the number of elements to initialize
9440     if (!Init) {
9441       // No initialization is performed.
9442     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9443                isa<ImplicitValueInitExpr>(Init)) {
9444       ValueInit = true;
9445     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9446       ResizedArrayCCE = CCE;
9447     } else {
9448       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9449       assert(CAT && "unexpected type for array initializer");
9450 
9451       unsigned Bits =
9452           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9453       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9454       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9455       if (InitBound.ugt(AllocBound)) {
9456         if (IsNothrow)
9457           return ZeroInitialization(E);
9458 
9459         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9460             << toString(AllocBound, 10, /*Signed=*/false)
9461             << toString(InitBound, 10, /*Signed=*/false)
9462             << (*ArraySize)->getSourceRange();
9463         return false;
9464       }
9465 
9466       // If the sizes differ, we must have an initializer list, and we need
9467       // special handling for this case when we initialize.
9468       if (InitBound != AllocBound)
9469         ResizedArrayILE = cast<InitListExpr>(Init);
9470     }
9471 
9472     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9473                                               ArrayType::Normal, 0);
9474   } else {
9475     assert(!AllocType->isArrayType() &&
9476            "array allocation with non-array new");
9477   }
9478 
9479   APValue *Val;
9480   if (IsPlacement) {
9481     AccessKinds AK = AK_Construct;
9482     struct FindObjectHandler {
9483       EvalInfo &Info;
9484       const Expr *E;
9485       QualType AllocType;
9486       const AccessKinds AccessKind;
9487       APValue *Value;
9488 
9489       typedef bool result_type;
9490       bool failed() { return false; }
9491       bool found(APValue &Subobj, QualType SubobjType) {
9492         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9493         // old name of the object to be used to name the new object.
9494         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9495           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9496             SubobjType << AllocType;
9497           return false;
9498         }
9499         Value = &Subobj;
9500         return true;
9501       }
9502       bool found(APSInt &Value, QualType SubobjType) {
9503         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9504         return false;
9505       }
9506       bool found(APFloat &Value, QualType SubobjType) {
9507         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9508         return false;
9509       }
9510     } Handler = {Info, E, AllocType, AK, nullptr};
9511 
9512     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9513     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9514       return false;
9515 
9516     Val = Handler.Value;
9517 
9518     // [basic.life]p1:
9519     //   The lifetime of an object o of type T ends when [...] the storage
9520     //   which the object occupies is [...] reused by an object that is not
9521     //   nested within o (6.6.2).
9522     *Val = APValue();
9523   } else {
9524     // Perform the allocation and obtain a pointer to the resulting object.
9525     Val = Info.createHeapAlloc(E, AllocType, Result);
9526     if (!Val)
9527       return false;
9528   }
9529 
9530   if (ValueInit) {
9531     ImplicitValueInitExpr VIE(AllocType);
9532     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9533       return false;
9534   } else if (ResizedArrayILE) {
9535     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9536                                   AllocType))
9537       return false;
9538   } else if (ResizedArrayCCE) {
9539     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9540                                        AllocType))
9541       return false;
9542   } else if (Init) {
9543     if (!EvaluateInPlace(*Val, Info, Result, Init))
9544       return false;
9545   } else if (!getDefaultInitValue(AllocType, *Val)) {
9546     return false;
9547   }
9548 
9549   // Array new returns a pointer to the first element, not a pointer to the
9550   // array.
9551   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9552     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9553 
9554   return true;
9555 }
9556 //===----------------------------------------------------------------------===//
9557 // Member Pointer Evaluation
9558 //===----------------------------------------------------------------------===//
9559 
9560 namespace {
9561 class MemberPointerExprEvaluator
9562   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9563   MemberPtr &Result;
9564 
Success(const ValueDecl * D)9565   bool Success(const ValueDecl *D) {
9566     Result = MemberPtr(D);
9567     return true;
9568   }
9569 public:
9570 
MemberPointerExprEvaluator(EvalInfo & Info,MemberPtr & Result)9571   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9572     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9573 
Success(const APValue & V,const Expr * E)9574   bool Success(const APValue &V, const Expr *E) {
9575     Result.setFrom(V);
9576     return true;
9577   }
ZeroInitialization(const Expr * E)9578   bool ZeroInitialization(const Expr *E) {
9579     return Success((const ValueDecl*)nullptr);
9580   }
9581 
9582   bool VisitCastExpr(const CastExpr *E);
9583   bool VisitUnaryAddrOf(const UnaryOperator *E);
9584 };
9585 } // end anonymous namespace
9586 
EvaluateMemberPointer(const Expr * E,MemberPtr & Result,EvalInfo & Info)9587 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9588                                   EvalInfo &Info) {
9589   assert(!E->isValueDependent());
9590   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9591   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9592 }
9593 
VisitCastExpr(const CastExpr * E)9594 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9595   switch (E->getCastKind()) {
9596   default:
9597     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9598 
9599   case CK_NullToMemberPointer:
9600     VisitIgnoredValue(E->getSubExpr());
9601     return ZeroInitialization(E);
9602 
9603   case CK_BaseToDerivedMemberPointer: {
9604     if (!Visit(E->getSubExpr()))
9605       return false;
9606     if (E->path_empty())
9607       return true;
9608     // Base-to-derived member pointer casts store the path in derived-to-base
9609     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9610     // the wrong end of the derived->base arc, so stagger the path by one class.
9611     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9612     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9613          PathI != PathE; ++PathI) {
9614       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9615       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9616       if (!Result.castToDerived(Derived))
9617         return Error(E);
9618     }
9619     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9620     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9621       return Error(E);
9622     return true;
9623   }
9624 
9625   case CK_DerivedToBaseMemberPointer:
9626     if (!Visit(E->getSubExpr()))
9627       return false;
9628     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9629          PathE = E->path_end(); PathI != PathE; ++PathI) {
9630       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9631       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9632       if (!Result.castToBase(Base))
9633         return Error(E);
9634     }
9635     return true;
9636   }
9637 }
9638 
VisitUnaryAddrOf(const UnaryOperator * E)9639 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9640   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9641   // member can be formed.
9642   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9643 }
9644 
9645 //===----------------------------------------------------------------------===//
9646 // Record Evaluation
9647 //===----------------------------------------------------------------------===//
9648 
9649 namespace {
9650   class RecordExprEvaluator
9651   : public ExprEvaluatorBase<RecordExprEvaluator> {
9652     const LValue &This;
9653     APValue &Result;
9654   public:
9655 
RecordExprEvaluator(EvalInfo & info,const LValue & This,APValue & Result)9656     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9657       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9658 
Success(const APValue & V,const Expr * E)9659     bool Success(const APValue &V, const Expr *E) {
9660       Result = V;
9661       return true;
9662     }
ZeroInitialization(const Expr * E)9663     bool ZeroInitialization(const Expr *E) {
9664       return ZeroInitialization(E, E->getType());
9665     }
9666     bool ZeroInitialization(const Expr *E, QualType T);
9667 
VisitCallExpr(const CallExpr * E)9668     bool VisitCallExpr(const CallExpr *E) {
9669       return handleCallExpr(E, Result, &This);
9670     }
9671     bool VisitCastExpr(const CastExpr *E);
9672     bool VisitInitListExpr(const InitListExpr *E);
VisitCXXConstructExpr(const CXXConstructExpr * E)9673     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9674       return VisitCXXConstructExpr(E, E->getType());
9675     }
9676     bool VisitLambdaExpr(const LambdaExpr *E);
9677     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9678     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9679     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9680     bool VisitBinCmp(const BinaryOperator *E);
9681   };
9682 }
9683 
9684 /// Perform zero-initialization on an object of non-union class type.
9685 /// C++11 [dcl.init]p5:
9686 ///  To zero-initialize an object or reference of type T means:
9687 ///    [...]
9688 ///    -- if T is a (possibly cv-qualified) non-union class type,
9689 ///       each non-static data member and each base-class subobject is
9690 ///       zero-initialized
HandleClassZeroInitialization(EvalInfo & Info,const Expr * E,const RecordDecl * RD,const LValue & This,APValue & Result)9691 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9692                                           const RecordDecl *RD,
9693                                           const LValue &This, APValue &Result) {
9694   assert(!RD->isUnion() && "Expected non-union class type");
9695   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9696   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9697                    std::distance(RD->field_begin(), RD->field_end()));
9698 
9699   if (RD->isInvalidDecl()) return false;
9700   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9701 
9702   if (CD) {
9703     unsigned Index = 0;
9704     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9705            End = CD->bases_end(); I != End; ++I, ++Index) {
9706       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9707       LValue Subobject = This;
9708       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9709         return false;
9710       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9711                                          Result.getStructBase(Index)))
9712         return false;
9713     }
9714   }
9715 
9716   for (const auto *I : RD->fields()) {
9717     // -- if T is a reference type, no initialization is performed.
9718     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9719       continue;
9720 
9721     LValue Subobject = This;
9722     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9723       return false;
9724 
9725     ImplicitValueInitExpr VIE(I->getType());
9726     if (!EvaluateInPlace(
9727           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9728       return false;
9729   }
9730 
9731   return true;
9732 }
9733 
ZeroInitialization(const Expr * E,QualType T)9734 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9735   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9736   if (RD->isInvalidDecl()) return false;
9737   if (RD->isUnion()) {
9738     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9739     // object's first non-static named data member is zero-initialized
9740     RecordDecl::field_iterator I = RD->field_begin();
9741     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9742       ++I;
9743     if (I == RD->field_end()) {
9744       Result = APValue((const FieldDecl*)nullptr);
9745       return true;
9746     }
9747 
9748     LValue Subobject = This;
9749     if (!HandleLValueMember(Info, E, Subobject, *I))
9750       return false;
9751     Result = APValue(*I);
9752     ImplicitValueInitExpr VIE(I->getType());
9753     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9754   }
9755 
9756   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9757     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9758     return false;
9759   }
9760 
9761   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9762 }
9763 
VisitCastExpr(const CastExpr * E)9764 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9765   switch (E->getCastKind()) {
9766   default:
9767     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9768 
9769   case CK_ConstructorConversion:
9770     return Visit(E->getSubExpr());
9771 
9772   case CK_DerivedToBase:
9773   case CK_UncheckedDerivedToBase: {
9774     APValue DerivedObject;
9775     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9776       return false;
9777     if (!DerivedObject.isStruct())
9778       return Error(E->getSubExpr());
9779 
9780     // Derived-to-base rvalue conversion: just slice off the derived part.
9781     APValue *Value = &DerivedObject;
9782     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9783     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9784          PathE = E->path_end(); PathI != PathE; ++PathI) {
9785       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9786       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9787       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9788       RD = Base;
9789     }
9790     Result = *Value;
9791     return true;
9792   }
9793   }
9794 }
9795 
VisitInitListExpr(const InitListExpr * E)9796 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9797   if (E->isTransparent())
9798     return Visit(E->getInit(0));
9799 
9800   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9801   if (RD->isInvalidDecl()) return false;
9802   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9803   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9804 
9805   EvalInfo::EvaluatingConstructorRAII EvalObj(
9806       Info,
9807       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9808       CXXRD && CXXRD->getNumBases());
9809 
9810   if (RD->isUnion()) {
9811     const FieldDecl *Field = E->getInitializedFieldInUnion();
9812     Result = APValue(Field);
9813     if (!Field)
9814       return true;
9815 
9816     // If the initializer list for a union does not contain any elements, the
9817     // first element of the union is value-initialized.
9818     // FIXME: The element should be initialized from an initializer list.
9819     //        Is this difference ever observable for initializer lists which
9820     //        we don't build?
9821     ImplicitValueInitExpr VIE(Field->getType());
9822     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9823 
9824     LValue Subobject = This;
9825     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9826       return false;
9827 
9828     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9829     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9830                                   isa<CXXDefaultInitExpr>(InitExpr));
9831 
9832     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9833       if (Field->isBitField())
9834         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9835                                      Field);
9836       return true;
9837     }
9838 
9839     return false;
9840   }
9841 
9842   if (!Result.hasValue())
9843     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9844                      std::distance(RD->field_begin(), RD->field_end()));
9845   unsigned ElementNo = 0;
9846   bool Success = true;
9847 
9848   // Initialize base classes.
9849   if (CXXRD && CXXRD->getNumBases()) {
9850     for (const auto &Base : CXXRD->bases()) {
9851       assert(ElementNo < E->getNumInits() && "missing init for base class");
9852       const Expr *Init = E->getInit(ElementNo);
9853 
9854       LValue Subobject = This;
9855       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9856         return false;
9857 
9858       APValue &FieldVal = Result.getStructBase(ElementNo);
9859       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9860         if (!Info.noteFailure())
9861           return false;
9862         Success = false;
9863       }
9864       ++ElementNo;
9865     }
9866 
9867     EvalObj.finishedConstructingBases();
9868   }
9869 
9870   // Initialize members.
9871   for (const auto *Field : RD->fields()) {
9872     // Anonymous bit-fields are not considered members of the class for
9873     // purposes of aggregate initialization.
9874     if (Field->isUnnamedBitfield())
9875       continue;
9876 
9877     LValue Subobject = This;
9878 
9879     bool HaveInit = ElementNo < E->getNumInits();
9880 
9881     // FIXME: Diagnostics here should point to the end of the initializer
9882     // list, not the start.
9883     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9884                             Subobject, Field, &Layout))
9885       return false;
9886 
9887     // Perform an implicit value-initialization for members beyond the end of
9888     // the initializer list.
9889     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9890     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9891 
9892     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9893     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9894                                   isa<CXXDefaultInitExpr>(Init));
9895 
9896     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9897     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9898         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9899                                                        FieldVal, Field))) {
9900       if (!Info.noteFailure())
9901         return false;
9902       Success = false;
9903     }
9904   }
9905 
9906   EvalObj.finishedConstructingFields();
9907 
9908   return Success;
9909 }
9910 
VisitCXXConstructExpr(const CXXConstructExpr * E,QualType T)9911 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9912                                                 QualType T) {
9913   // Note that E's type is not necessarily the type of our class here; we might
9914   // be initializing an array element instead.
9915   const CXXConstructorDecl *FD = E->getConstructor();
9916   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9917 
9918   bool ZeroInit = E->requiresZeroInitialization();
9919   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9920     // If we've already performed zero-initialization, we're already done.
9921     if (Result.hasValue())
9922       return true;
9923 
9924     if (ZeroInit)
9925       return ZeroInitialization(E, T);
9926 
9927     return getDefaultInitValue(T, Result);
9928   }
9929 
9930   const FunctionDecl *Definition = nullptr;
9931   auto Body = FD->getBody(Definition);
9932 
9933   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9934     return false;
9935 
9936   // Avoid materializing a temporary for an elidable copy/move constructor.
9937   if (E->isElidable() && !ZeroInit) {
9938     // FIXME: This only handles the simplest case, where the source object
9939     //        is passed directly as the first argument to the constructor.
9940     //        This should also handle stepping though implicit casts and
9941     //        and conversion sequences which involve two steps, with a
9942     //        conversion operator followed by a converting constructor.
9943     const Expr *SrcObj = E->getArg(0);
9944     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
9945     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
9946     if (const MaterializeTemporaryExpr *ME =
9947             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
9948       return Visit(ME->getSubExpr());
9949   }
9950 
9951   if (ZeroInit && !ZeroInitialization(E, T))
9952     return false;
9953 
9954   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9955   return HandleConstructorCall(E, This, Args,
9956                                cast<CXXConstructorDecl>(Definition), Info,
9957                                Result);
9958 }
9959 
VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr * E)9960 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9961     const CXXInheritedCtorInitExpr *E) {
9962   if (!Info.CurrentCall) {
9963     assert(Info.checkingPotentialConstantExpression());
9964     return false;
9965   }
9966 
9967   const CXXConstructorDecl *FD = E->getConstructor();
9968   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9969     return false;
9970 
9971   const FunctionDecl *Definition = nullptr;
9972   auto Body = FD->getBody(Definition);
9973 
9974   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9975     return false;
9976 
9977   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9978                                cast<CXXConstructorDecl>(Definition), Info,
9979                                Result);
9980 }
9981 
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)9982 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9983     const CXXStdInitializerListExpr *E) {
9984   const ConstantArrayType *ArrayType =
9985       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9986 
9987   LValue Array;
9988   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9989     return false;
9990 
9991   // Get a pointer to the first element of the array.
9992   Array.addArray(Info, E, ArrayType);
9993 
9994   auto InvalidType = [&] {
9995     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9996       << E->getType();
9997     return false;
9998   };
9999 
10000   // FIXME: Perform the checks on the field types in SemaInit.
10001   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10002   RecordDecl::field_iterator Field = Record->field_begin();
10003   if (Field == Record->field_end())
10004     return InvalidType();
10005 
10006   // Start pointer.
10007   if (!Field->getType()->isPointerType() ||
10008       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10009                             ArrayType->getElementType()))
10010     return InvalidType();
10011 
10012   // FIXME: What if the initializer_list type has base classes, etc?
10013   Result = APValue(APValue::UninitStruct(), 0, 2);
10014   Array.moveInto(Result.getStructField(0));
10015 
10016   if (++Field == Record->field_end())
10017     return InvalidType();
10018 
10019   if (Field->getType()->isPointerType() &&
10020       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10021                            ArrayType->getElementType())) {
10022     // End pointer.
10023     if (!HandleLValueArrayAdjustment(Info, E, Array,
10024                                      ArrayType->getElementType(),
10025                                      ArrayType->getSize().getZExtValue()))
10026       return false;
10027     Array.moveInto(Result.getStructField(1));
10028   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10029     // Length.
10030     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10031   else
10032     return InvalidType();
10033 
10034   if (++Field != Record->field_end())
10035     return InvalidType();
10036 
10037   return true;
10038 }
10039 
VisitLambdaExpr(const LambdaExpr * E)10040 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10041   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10042   if (ClosureClass->isInvalidDecl())
10043     return false;
10044 
10045   const size_t NumFields =
10046       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10047 
10048   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10049                                             E->capture_init_end()) &&
10050          "The number of lambda capture initializers should equal the number of "
10051          "fields within the closure type");
10052 
10053   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10054   // Iterate through all the lambda's closure object's fields and initialize
10055   // them.
10056   auto *CaptureInitIt = E->capture_init_begin();
10057   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
10058   bool Success = true;
10059   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10060   for (const auto *Field : ClosureClass->fields()) {
10061     assert(CaptureInitIt != E->capture_init_end());
10062     // Get the initializer for this field
10063     Expr *const CurFieldInit = *CaptureInitIt++;
10064 
10065     // If there is no initializer, either this is a VLA or an error has
10066     // occurred.
10067     if (!CurFieldInit)
10068       return Error(E);
10069 
10070     LValue Subobject = This;
10071 
10072     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10073       return false;
10074 
10075     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10076     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10077       if (!Info.keepEvaluatingAfterFailure())
10078         return false;
10079       Success = false;
10080     }
10081     ++CaptureIt;
10082   }
10083   return Success;
10084 }
10085 
EvaluateRecord(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)10086 static bool EvaluateRecord(const Expr *E, const LValue &This,
10087                            APValue &Result, EvalInfo &Info) {
10088   assert(!E->isValueDependent());
10089   assert(E->isPRValue() && E->getType()->isRecordType() &&
10090          "can't evaluate expression as a record rvalue");
10091   return RecordExprEvaluator(Info, This, Result).Visit(E);
10092 }
10093 
10094 //===----------------------------------------------------------------------===//
10095 // Temporary Evaluation
10096 //
10097 // Temporaries are represented in the AST as rvalues, but generally behave like
10098 // lvalues. The full-object of which the temporary is a subobject is implicitly
10099 // materialized so that a reference can bind to it.
10100 //===----------------------------------------------------------------------===//
10101 namespace {
10102 class TemporaryExprEvaluator
10103   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10104 public:
TemporaryExprEvaluator(EvalInfo & Info,LValue & Result)10105   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10106     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10107 
10108   /// Visit an expression which constructs the value of this temporary.
VisitConstructExpr(const Expr * E)10109   bool VisitConstructExpr(const Expr *E) {
10110     APValue &Value = Info.CurrentCall->createTemporary(
10111         E, E->getType(), ScopeKind::FullExpression, Result);
10112     return EvaluateInPlace(Value, Info, Result, E);
10113   }
10114 
VisitCastExpr(const CastExpr * E)10115   bool VisitCastExpr(const CastExpr *E) {
10116     switch (E->getCastKind()) {
10117     default:
10118       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10119 
10120     case CK_ConstructorConversion:
10121       return VisitConstructExpr(E->getSubExpr());
10122     }
10123   }
VisitInitListExpr(const InitListExpr * E)10124   bool VisitInitListExpr(const InitListExpr *E) {
10125     return VisitConstructExpr(E);
10126   }
VisitCXXConstructExpr(const CXXConstructExpr * E)10127   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10128     return VisitConstructExpr(E);
10129   }
VisitCallExpr(const CallExpr * E)10130   bool VisitCallExpr(const CallExpr *E) {
10131     return VisitConstructExpr(E);
10132   }
VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr * E)10133   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10134     return VisitConstructExpr(E);
10135   }
VisitLambdaExpr(const LambdaExpr * E)10136   bool VisitLambdaExpr(const LambdaExpr *E) {
10137     return VisitConstructExpr(E);
10138   }
10139 };
10140 } // end anonymous namespace
10141 
10142 /// Evaluate an expression of record type as a temporary.
EvaluateTemporary(const Expr * E,LValue & Result,EvalInfo & Info)10143 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10144   assert(!E->isValueDependent());
10145   assert(E->isPRValue() && E->getType()->isRecordType());
10146   return TemporaryExprEvaluator(Info, Result).Visit(E);
10147 }
10148 
10149 //===----------------------------------------------------------------------===//
10150 // Vector Evaluation
10151 //===----------------------------------------------------------------------===//
10152 
10153 namespace {
10154   class VectorExprEvaluator
10155   : public ExprEvaluatorBase<VectorExprEvaluator> {
10156     APValue &Result;
10157   public:
10158 
VectorExprEvaluator(EvalInfo & info,APValue & Result)10159     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10160       : ExprEvaluatorBaseTy(info), Result(Result) {}
10161 
Success(ArrayRef<APValue> V,const Expr * E)10162     bool Success(ArrayRef<APValue> V, const Expr *E) {
10163       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10164       // FIXME: remove this APValue copy.
10165       Result = APValue(V.data(), V.size());
10166       return true;
10167     }
Success(const APValue & V,const Expr * E)10168     bool Success(const APValue &V, const Expr *E) {
10169       assert(V.isVector());
10170       Result = V;
10171       return true;
10172     }
10173     bool ZeroInitialization(const Expr *E);
10174 
VisitUnaryReal(const UnaryOperator * E)10175     bool VisitUnaryReal(const UnaryOperator *E)
10176       { return Visit(E->getSubExpr()); }
10177     bool VisitCastExpr(const CastExpr* E);
10178     bool VisitInitListExpr(const InitListExpr *E);
10179     bool VisitUnaryImag(const UnaryOperator *E);
10180     bool VisitBinaryOperator(const BinaryOperator *E);
10181     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
10182     //                 conditional select), shufflevector, ExtVectorElementExpr
10183   };
10184 } // end anonymous namespace
10185 
EvaluateVector(const Expr * E,APValue & Result,EvalInfo & Info)10186 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10187   assert(E->isPRValue() && E->getType()->isVectorType() &&
10188          "not a vector prvalue");
10189   return VectorExprEvaluator(Info, Result).Visit(E);
10190 }
10191 
VisitCastExpr(const CastExpr * E)10192 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10193   const VectorType *VTy = E->getType()->castAs<VectorType>();
10194   unsigned NElts = VTy->getNumElements();
10195 
10196   const Expr *SE = E->getSubExpr();
10197   QualType SETy = SE->getType();
10198 
10199   switch (E->getCastKind()) {
10200   case CK_VectorSplat: {
10201     APValue Val = APValue();
10202     if (SETy->isIntegerType()) {
10203       APSInt IntResult;
10204       if (!EvaluateInteger(SE, IntResult, Info))
10205         return false;
10206       Val = APValue(std::move(IntResult));
10207     } else if (SETy->isRealFloatingType()) {
10208       APFloat FloatResult(0.0);
10209       if (!EvaluateFloat(SE, FloatResult, Info))
10210         return false;
10211       Val = APValue(std::move(FloatResult));
10212     } else {
10213       return Error(E);
10214     }
10215 
10216     // Splat and create vector APValue.
10217     SmallVector<APValue, 4> Elts(NElts, Val);
10218     return Success(Elts, E);
10219   }
10220   case CK_BitCast: {
10221     // Evaluate the operand into an APInt we can extract from.
10222     llvm::APInt SValInt;
10223     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10224       return false;
10225     // Extract the elements
10226     QualType EltTy = VTy->getElementType();
10227     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10228     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10229     SmallVector<APValue, 4> Elts;
10230     if (EltTy->isRealFloatingType()) {
10231       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10232       unsigned FloatEltSize = EltSize;
10233       if (&Sem == &APFloat::x87DoubleExtended())
10234         FloatEltSize = 80;
10235       for (unsigned i = 0; i < NElts; i++) {
10236         llvm::APInt Elt;
10237         if (BigEndian)
10238           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10239         else
10240           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10241         Elts.push_back(APValue(APFloat(Sem, Elt)));
10242       }
10243     } else if (EltTy->isIntegerType()) {
10244       for (unsigned i = 0; i < NElts; i++) {
10245         llvm::APInt Elt;
10246         if (BigEndian)
10247           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10248         else
10249           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10250         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10251       }
10252     } else {
10253       return Error(E);
10254     }
10255     return Success(Elts, E);
10256   }
10257   default:
10258     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10259   }
10260 }
10261 
10262 bool
VisitInitListExpr(const InitListExpr * E)10263 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10264   const VectorType *VT = E->getType()->castAs<VectorType>();
10265   unsigned NumInits = E->getNumInits();
10266   unsigned NumElements = VT->getNumElements();
10267 
10268   QualType EltTy = VT->getElementType();
10269   SmallVector<APValue, 4> Elements;
10270 
10271   // The number of initializers can be less than the number of
10272   // vector elements. For OpenCL, this can be due to nested vector
10273   // initialization. For GCC compatibility, missing trailing elements
10274   // should be initialized with zeroes.
10275   unsigned CountInits = 0, CountElts = 0;
10276   while (CountElts < NumElements) {
10277     // Handle nested vector initialization.
10278     if (CountInits < NumInits
10279         && E->getInit(CountInits)->getType()->isVectorType()) {
10280       APValue v;
10281       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10282         return Error(E);
10283       unsigned vlen = v.getVectorLength();
10284       for (unsigned j = 0; j < vlen; j++)
10285         Elements.push_back(v.getVectorElt(j));
10286       CountElts += vlen;
10287     } else if (EltTy->isIntegerType()) {
10288       llvm::APSInt sInt(32);
10289       if (CountInits < NumInits) {
10290         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10291           return false;
10292       } else // trailing integer zero.
10293         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10294       Elements.push_back(APValue(sInt));
10295       CountElts++;
10296     } else {
10297       llvm::APFloat f(0.0);
10298       if (CountInits < NumInits) {
10299         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10300           return false;
10301       } else // trailing float zero.
10302         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10303       Elements.push_back(APValue(f));
10304       CountElts++;
10305     }
10306     CountInits++;
10307   }
10308   return Success(Elements, E);
10309 }
10310 
10311 bool
ZeroInitialization(const Expr * E)10312 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10313   const auto *VT = E->getType()->castAs<VectorType>();
10314   QualType EltTy = VT->getElementType();
10315   APValue ZeroElement;
10316   if (EltTy->isIntegerType())
10317     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10318   else
10319     ZeroElement =
10320         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10321 
10322   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10323   return Success(Elements, E);
10324 }
10325 
VisitUnaryImag(const UnaryOperator * E)10326 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10327   VisitIgnoredValue(E->getSubExpr());
10328   return ZeroInitialization(E);
10329 }
10330 
VisitBinaryOperator(const BinaryOperator * E)10331 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10332   BinaryOperatorKind Op = E->getOpcode();
10333   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10334          "Operation not supported on vector types");
10335 
10336   if (Op == BO_Comma)
10337     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10338 
10339   Expr *LHS = E->getLHS();
10340   Expr *RHS = E->getRHS();
10341 
10342   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10343          "Must both be vector types");
10344   // Checking JUST the types are the same would be fine, except shifts don't
10345   // need to have their types be the same (since you always shift by an int).
10346   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10347              E->getType()->castAs<VectorType>()->getNumElements() &&
10348          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10349              E->getType()->castAs<VectorType>()->getNumElements() &&
10350          "All operands must be the same size.");
10351 
10352   APValue LHSValue;
10353   APValue RHSValue;
10354   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10355   if (!LHSOK && !Info.noteFailure())
10356     return false;
10357   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10358     return false;
10359 
10360   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10361     return false;
10362 
10363   return Success(LHSValue, E);
10364 }
10365 
10366 //===----------------------------------------------------------------------===//
10367 // Array Evaluation
10368 //===----------------------------------------------------------------------===//
10369 
10370 namespace {
10371   class ArrayExprEvaluator
10372   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10373     const LValue &This;
10374     APValue &Result;
10375   public:
10376 
ArrayExprEvaluator(EvalInfo & Info,const LValue & This,APValue & Result)10377     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10378       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10379 
Success(const APValue & V,const Expr * E)10380     bool Success(const APValue &V, const Expr *E) {
10381       assert(V.isArray() && "expected array");
10382       Result = V;
10383       return true;
10384     }
10385 
ZeroInitialization(const Expr * E)10386     bool ZeroInitialization(const Expr *E) {
10387       const ConstantArrayType *CAT =
10388           Info.Ctx.getAsConstantArrayType(E->getType());
10389       if (!CAT) {
10390         if (E->getType()->isIncompleteArrayType()) {
10391           // We can be asked to zero-initialize a flexible array member; this
10392           // is represented as an ImplicitValueInitExpr of incomplete array
10393           // type. In this case, the array has zero elements.
10394           Result = APValue(APValue::UninitArray(), 0, 0);
10395           return true;
10396         }
10397         // FIXME: We could handle VLAs here.
10398         return Error(E);
10399       }
10400 
10401       Result = APValue(APValue::UninitArray(), 0,
10402                        CAT->getSize().getZExtValue());
10403       if (!Result.hasArrayFiller())
10404         return true;
10405 
10406       // Zero-initialize all elements.
10407       LValue Subobject = This;
10408       Subobject.addArray(Info, E, CAT);
10409       ImplicitValueInitExpr VIE(CAT->getElementType());
10410       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10411     }
10412 
VisitCallExpr(const CallExpr * E)10413     bool VisitCallExpr(const CallExpr *E) {
10414       return handleCallExpr(E, Result, &This);
10415     }
10416     bool VisitInitListExpr(const InitListExpr *E,
10417                            QualType AllocType = QualType());
10418     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10419     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10420     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10421                                const LValue &Subobject,
10422                                APValue *Value, QualType Type);
VisitStringLiteral(const StringLiteral * E,QualType AllocType=QualType ())10423     bool VisitStringLiteral(const StringLiteral *E,
10424                             QualType AllocType = QualType()) {
10425       expandStringLiteral(Info, E, Result, AllocType);
10426       return true;
10427     }
10428   };
10429 } // end anonymous namespace
10430 
EvaluateArray(const Expr * E,const LValue & This,APValue & Result,EvalInfo & Info)10431 static bool EvaluateArray(const Expr *E, const LValue &This,
10432                           APValue &Result, EvalInfo &Info) {
10433   assert(!E->isValueDependent());
10434   assert(E->isPRValue() && E->getType()->isArrayType() &&
10435          "not an array prvalue");
10436   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10437 }
10438 
EvaluateArrayNewInitList(EvalInfo & Info,LValue & This,APValue & Result,const InitListExpr * ILE,QualType AllocType)10439 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10440                                      APValue &Result, const InitListExpr *ILE,
10441                                      QualType AllocType) {
10442   assert(!ILE->isValueDependent());
10443   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10444          "not an array prvalue");
10445   return ArrayExprEvaluator(Info, This, Result)
10446       .VisitInitListExpr(ILE, AllocType);
10447 }
10448 
EvaluateArrayNewConstructExpr(EvalInfo & Info,LValue & This,APValue & Result,const CXXConstructExpr * CCE,QualType AllocType)10449 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10450                                           APValue &Result,
10451                                           const CXXConstructExpr *CCE,
10452                                           QualType AllocType) {
10453   assert(!CCE->isValueDependent());
10454   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10455          "not an array prvalue");
10456   return ArrayExprEvaluator(Info, This, Result)
10457       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10458 }
10459 
10460 // Return true iff the given array filler may depend on the element index.
MaybeElementDependentArrayFiller(const Expr * FillerExpr)10461 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10462   // For now, just allow non-class value-initialization and initialization
10463   // lists comprised of them.
10464   if (isa<ImplicitValueInitExpr>(FillerExpr))
10465     return false;
10466   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10467     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10468       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10469         return true;
10470     }
10471     return false;
10472   }
10473   return true;
10474 }
10475 
VisitInitListExpr(const InitListExpr * E,QualType AllocType)10476 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10477                                            QualType AllocType) {
10478   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10479       AllocType.isNull() ? E->getType() : AllocType);
10480   if (!CAT)
10481     return Error(E);
10482 
10483   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10484   // an appropriately-typed string literal enclosed in braces.
10485   if (E->isStringLiteralInit()) {
10486     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10487     // FIXME: Support ObjCEncodeExpr here once we support it in
10488     // ArrayExprEvaluator generally.
10489     if (!SL)
10490       return Error(E);
10491     return VisitStringLiteral(SL, AllocType);
10492   }
10493   // Any other transparent list init will need proper handling of the
10494   // AllocType; we can't just recurse to the inner initializer.
10495   assert(!E->isTransparent() &&
10496          "transparent array list initialization is not string literal init?");
10497 
10498   bool Success = true;
10499 
10500   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10501          "zero-initialized array shouldn't have any initialized elts");
10502   APValue Filler;
10503   if (Result.isArray() && Result.hasArrayFiller())
10504     Filler = Result.getArrayFiller();
10505 
10506   unsigned NumEltsToInit = E->getNumInits();
10507   unsigned NumElts = CAT->getSize().getZExtValue();
10508   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10509 
10510   // If the initializer might depend on the array index, run it for each
10511   // array element.
10512   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10513     NumEltsToInit = NumElts;
10514 
10515   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10516                           << NumEltsToInit << ".\n");
10517 
10518   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10519 
10520   // If the array was previously zero-initialized, preserve the
10521   // zero-initialized values.
10522   if (Filler.hasValue()) {
10523     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10524       Result.getArrayInitializedElt(I) = Filler;
10525     if (Result.hasArrayFiller())
10526       Result.getArrayFiller() = Filler;
10527   }
10528 
10529   LValue Subobject = This;
10530   Subobject.addArray(Info, E, CAT);
10531   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10532     const Expr *Init =
10533         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10534     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10535                          Info, Subobject, Init) ||
10536         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10537                                      CAT->getElementType(), 1)) {
10538       if (!Info.noteFailure())
10539         return false;
10540       Success = false;
10541     }
10542   }
10543 
10544   if (!Result.hasArrayFiller())
10545     return Success;
10546 
10547   // If we get here, we have a trivial filler, which we can just evaluate
10548   // once and splat over the rest of the array elements.
10549   assert(FillerExpr && "no array filler for incomplete init list");
10550   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10551                          FillerExpr) && Success;
10552 }
10553 
VisitArrayInitLoopExpr(const ArrayInitLoopExpr * E)10554 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10555   LValue CommonLV;
10556   if (E->getCommonExpr() &&
10557       !Evaluate(Info.CurrentCall->createTemporary(
10558                     E->getCommonExpr(),
10559                     getStorageType(Info.Ctx, E->getCommonExpr()),
10560                     ScopeKind::FullExpression, CommonLV),
10561                 Info, E->getCommonExpr()->getSourceExpr()))
10562     return false;
10563 
10564   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10565 
10566   uint64_t Elements = CAT->getSize().getZExtValue();
10567   Result = APValue(APValue::UninitArray(), Elements, Elements);
10568 
10569   LValue Subobject = This;
10570   Subobject.addArray(Info, E, CAT);
10571 
10572   bool Success = true;
10573   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10574     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10575                          Info, Subobject, E->getSubExpr()) ||
10576         !HandleLValueArrayAdjustment(Info, E, Subobject,
10577                                      CAT->getElementType(), 1)) {
10578       if (!Info.noteFailure())
10579         return false;
10580       Success = false;
10581     }
10582   }
10583 
10584   return Success;
10585 }
10586 
VisitCXXConstructExpr(const CXXConstructExpr * E)10587 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10588   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10589 }
10590 
VisitCXXConstructExpr(const CXXConstructExpr * E,const LValue & Subobject,APValue * Value,QualType Type)10591 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10592                                                const LValue &Subobject,
10593                                                APValue *Value,
10594                                                QualType Type) {
10595   bool HadZeroInit = Value->hasValue();
10596 
10597   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10598     unsigned N = CAT->getSize().getZExtValue();
10599 
10600     // Preserve the array filler if we had prior zero-initialization.
10601     APValue Filler =
10602       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10603                                              : APValue();
10604 
10605     *Value = APValue(APValue::UninitArray(), N, N);
10606 
10607     if (HadZeroInit)
10608       for (unsigned I = 0; I != N; ++I)
10609         Value->getArrayInitializedElt(I) = Filler;
10610 
10611     // Initialize the elements.
10612     LValue ArrayElt = Subobject;
10613     ArrayElt.addArray(Info, E, CAT);
10614     for (unsigned I = 0; I != N; ++I)
10615       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10616                                  CAT->getElementType()) ||
10617           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10618                                        CAT->getElementType(), 1))
10619         return false;
10620 
10621     return true;
10622   }
10623 
10624   if (!Type->isRecordType())
10625     return Error(E);
10626 
10627   return RecordExprEvaluator(Info, Subobject, *Value)
10628              .VisitCXXConstructExpr(E, Type);
10629 }
10630 
10631 //===----------------------------------------------------------------------===//
10632 // Integer Evaluation
10633 //
10634 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10635 // types and back in constant folding. Integer values are thus represented
10636 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10637 //===----------------------------------------------------------------------===//
10638 
10639 namespace {
10640 class IntExprEvaluator
10641         : public ExprEvaluatorBase<IntExprEvaluator> {
10642   APValue &Result;
10643 public:
IntExprEvaluator(EvalInfo & info,APValue & result)10644   IntExprEvaluator(EvalInfo &info, APValue &result)
10645       : ExprEvaluatorBaseTy(info), Result(result) {}
10646 
Success(const llvm::APSInt & SI,const Expr * E,APValue & Result)10647   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10648     assert(E->getType()->isIntegralOrEnumerationType() &&
10649            "Invalid evaluation result.");
10650     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10651            "Invalid evaluation result.");
10652     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10653            "Invalid evaluation result.");
10654     Result = APValue(SI);
10655     return true;
10656   }
Success(const llvm::APSInt & SI,const Expr * E)10657   bool Success(const llvm::APSInt &SI, const Expr *E) {
10658     return Success(SI, E, Result);
10659   }
10660 
Success(const llvm::APInt & I,const Expr * E,APValue & Result)10661   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10662     assert(E->getType()->isIntegralOrEnumerationType() &&
10663            "Invalid evaluation result.");
10664     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10665            "Invalid evaluation result.");
10666     Result = APValue(APSInt(I));
10667     Result.getInt().setIsUnsigned(
10668                             E->getType()->isUnsignedIntegerOrEnumerationType());
10669     return true;
10670   }
Success(const llvm::APInt & I,const Expr * E)10671   bool Success(const llvm::APInt &I, const Expr *E) {
10672     return Success(I, E, Result);
10673   }
10674 
Success(uint64_t Value,const Expr * E,APValue & Result)10675   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10676     assert(E->getType()->isIntegralOrEnumerationType() &&
10677            "Invalid evaluation result.");
10678     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10679     return true;
10680   }
Success(uint64_t Value,const Expr * E)10681   bool Success(uint64_t Value, const Expr *E) {
10682     return Success(Value, E, Result);
10683   }
10684 
Success(CharUnits Size,const Expr * E)10685   bool Success(CharUnits Size, const Expr *E) {
10686     return Success(Size.getQuantity(), E);
10687   }
10688 
Success(const APValue & V,const Expr * E)10689   bool Success(const APValue &V, const Expr *E) {
10690     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10691       Result = V;
10692       return true;
10693     }
10694     return Success(V.getInt(), E);
10695   }
10696 
ZeroInitialization(const Expr * E)10697   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10698 
10699   //===--------------------------------------------------------------------===//
10700   //                            Visitor Methods
10701   //===--------------------------------------------------------------------===//
10702 
VisitIntegerLiteral(const IntegerLiteral * E)10703   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10704     return Success(E->getValue(), E);
10705   }
VisitCharacterLiteral(const CharacterLiteral * E)10706   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10707     return Success(E->getValue(), E);
10708   }
10709 
10710   bool CheckReferencedDecl(const Expr *E, const Decl *D);
VisitDeclRefExpr(const DeclRefExpr * E)10711   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10712     if (CheckReferencedDecl(E, E->getDecl()))
10713       return true;
10714 
10715     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10716   }
VisitMemberExpr(const MemberExpr * E)10717   bool VisitMemberExpr(const MemberExpr *E) {
10718     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10719       VisitIgnoredBaseExpression(E->getBase());
10720       return true;
10721     }
10722 
10723     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10724   }
10725 
10726   bool VisitCallExpr(const CallExpr *E);
10727   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10728   bool VisitBinaryOperator(const BinaryOperator *E);
10729   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10730   bool VisitUnaryOperator(const UnaryOperator *E);
10731 
10732   bool VisitCastExpr(const CastExpr* E);
10733   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10734 
VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr * E)10735   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10736     return Success(E->getValue(), E);
10737   }
10738 
VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr * E)10739   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10740     return Success(E->getValue(), E);
10741   }
10742 
VisitArrayInitIndexExpr(const ArrayInitIndexExpr * E)10743   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10744     if (Info.ArrayInitIndex == uint64_t(-1)) {
10745       // We were asked to evaluate this subexpression independent of the
10746       // enclosing ArrayInitLoopExpr. We can't do that.
10747       Info.FFDiag(E);
10748       return false;
10749     }
10750     return Success(Info.ArrayInitIndex, E);
10751   }
10752 
10753   // Note, GNU defines __null as an integer, not a pointer.
VisitGNUNullExpr(const GNUNullExpr * E)10754   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10755     return ZeroInitialization(E);
10756   }
10757 
VisitTypeTraitExpr(const TypeTraitExpr * E)10758   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10759     return Success(E->getValue(), E);
10760   }
10761 
VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr * E)10762   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10763     return Success(E->getValue(), E);
10764   }
10765 
VisitExpressionTraitExpr(const ExpressionTraitExpr * E)10766   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10767     return Success(E->getValue(), E);
10768   }
10769 
10770   bool VisitUnaryReal(const UnaryOperator *E);
10771   bool VisitUnaryImag(const UnaryOperator *E);
10772 
10773   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10774   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10775   bool VisitSourceLocExpr(const SourceLocExpr *E);
10776   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10777   bool VisitRequiresExpr(const RequiresExpr *E);
10778   // FIXME: Missing: array subscript of vector, member of vector
10779 };
10780 
10781 class FixedPointExprEvaluator
10782     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10783   APValue &Result;
10784 
10785  public:
FixedPointExprEvaluator(EvalInfo & info,APValue & result)10786   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10787       : ExprEvaluatorBaseTy(info), Result(result) {}
10788 
Success(const llvm::APInt & I,const Expr * E)10789   bool Success(const llvm::APInt &I, const Expr *E) {
10790     return Success(
10791         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10792   }
10793 
Success(uint64_t Value,const Expr * E)10794   bool Success(uint64_t Value, const Expr *E) {
10795     return Success(
10796         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10797   }
10798 
Success(const APValue & V,const Expr * E)10799   bool Success(const APValue &V, const Expr *E) {
10800     return Success(V.getFixedPoint(), E);
10801   }
10802 
Success(const APFixedPoint & V,const Expr * E)10803   bool Success(const APFixedPoint &V, const Expr *E) {
10804     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10805     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10806            "Invalid evaluation result.");
10807     Result = APValue(V);
10808     return true;
10809   }
10810 
10811   //===--------------------------------------------------------------------===//
10812   //                            Visitor Methods
10813   //===--------------------------------------------------------------------===//
10814 
VisitFixedPointLiteral(const FixedPointLiteral * E)10815   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10816     return Success(E->getValue(), E);
10817   }
10818 
10819   bool VisitCastExpr(const CastExpr *E);
10820   bool VisitUnaryOperator(const UnaryOperator *E);
10821   bool VisitBinaryOperator(const BinaryOperator *E);
10822 };
10823 } // end anonymous namespace
10824 
10825 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10826 /// produce either the integer value or a pointer.
10827 ///
10828 /// GCC has a heinous extension which folds casts between pointer types and
10829 /// pointer-sized integral types. We support this by allowing the evaluation of
10830 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10831 /// Some simple arithmetic on such values is supported (they are treated much
10832 /// like char*).
EvaluateIntegerOrLValue(const Expr * E,APValue & Result,EvalInfo & Info)10833 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10834                                     EvalInfo &Info) {
10835   assert(!E->isValueDependent());
10836   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
10837   return IntExprEvaluator(Info, Result).Visit(E);
10838 }
10839 
EvaluateInteger(const Expr * E,APSInt & Result,EvalInfo & Info)10840 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10841   assert(!E->isValueDependent());
10842   APValue Val;
10843   if (!EvaluateIntegerOrLValue(E, Val, Info))
10844     return false;
10845   if (!Val.isInt()) {
10846     // FIXME: It would be better to produce the diagnostic for casting
10847     //        a pointer to an integer.
10848     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10849     return false;
10850   }
10851   Result = Val.getInt();
10852   return true;
10853 }
10854 
VisitSourceLocExpr(const SourceLocExpr * E)10855 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10856   APValue Evaluated = E->EvaluateInContext(
10857       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10858   return Success(Evaluated, E);
10859 }
10860 
EvaluateFixedPoint(const Expr * E,APFixedPoint & Result,EvalInfo & Info)10861 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10862                                EvalInfo &Info) {
10863   assert(!E->isValueDependent());
10864   if (E->getType()->isFixedPointType()) {
10865     APValue Val;
10866     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10867       return false;
10868     if (!Val.isFixedPoint())
10869       return false;
10870 
10871     Result = Val.getFixedPoint();
10872     return true;
10873   }
10874   return false;
10875 }
10876 
EvaluateFixedPointOrInteger(const Expr * E,APFixedPoint & Result,EvalInfo & Info)10877 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10878                                         EvalInfo &Info) {
10879   assert(!E->isValueDependent());
10880   if (E->getType()->isIntegerType()) {
10881     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10882     APSInt Val;
10883     if (!EvaluateInteger(E, Val, Info))
10884       return false;
10885     Result = APFixedPoint(Val, FXSema);
10886     return true;
10887   } else if (E->getType()->isFixedPointType()) {
10888     return EvaluateFixedPoint(E, Result, Info);
10889   }
10890   return false;
10891 }
10892 
10893 /// Check whether the given declaration can be directly converted to an integral
10894 /// rvalue. If not, no diagnostic is produced; there are other things we can
10895 /// try.
CheckReferencedDecl(const Expr * E,const Decl * D)10896 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10897   // Enums are integer constant exprs.
10898   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10899     // Check for signedness/width mismatches between E type and ECD value.
10900     bool SameSign = (ECD->getInitVal().isSigned()
10901                      == E->getType()->isSignedIntegerOrEnumerationType());
10902     bool SameWidth = (ECD->getInitVal().getBitWidth()
10903                       == Info.Ctx.getIntWidth(E->getType()));
10904     if (SameSign && SameWidth)
10905       return Success(ECD->getInitVal(), E);
10906     else {
10907       // Get rid of mismatch (otherwise Success assertions will fail)
10908       // by computing a new value matching the type of E.
10909       llvm::APSInt Val = ECD->getInitVal();
10910       if (!SameSign)
10911         Val.setIsSigned(!ECD->getInitVal().isSigned());
10912       if (!SameWidth)
10913         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10914       return Success(Val, E);
10915     }
10916   }
10917   return false;
10918 }
10919 
10920 /// Values returned by __builtin_classify_type, chosen to match the values
10921 /// produced by GCC's builtin.
10922 enum class GCCTypeClass {
10923   None = -1,
10924   Void = 0,
10925   Integer = 1,
10926   // GCC reserves 2 for character types, but instead classifies them as
10927   // integers.
10928   Enum = 3,
10929   Bool = 4,
10930   Pointer = 5,
10931   // GCC reserves 6 for references, but appears to never use it (because
10932   // expressions never have reference type, presumably).
10933   PointerToDataMember = 7,
10934   RealFloat = 8,
10935   Complex = 9,
10936   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10937   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10938   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10939   // uses 12 for that purpose, same as for a class or struct. Maybe it
10940   // internally implements a pointer to member as a struct?  Who knows.
10941   PointerToMemberFunction = 12, // Not a bug, see above.
10942   ClassOrStruct = 12,
10943   Union = 13,
10944   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10945   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10946   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10947   // literals.
10948 };
10949 
10950 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10951 /// as GCC.
10952 static GCCTypeClass
EvaluateBuiltinClassifyType(QualType T,const LangOptions & LangOpts)10953 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10954   assert(!T->isDependentType() && "unexpected dependent type");
10955 
10956   QualType CanTy = T.getCanonicalType();
10957   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10958 
10959   switch (CanTy->getTypeClass()) {
10960 #define TYPE(ID, BASE)
10961 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10962 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10963 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10964 #include "clang/AST/TypeNodes.inc"
10965   case Type::Auto:
10966   case Type::DeducedTemplateSpecialization:
10967       llvm_unreachable("unexpected non-canonical or dependent type");
10968 
10969   case Type::Builtin:
10970     switch (BT->getKind()) {
10971 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10972 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10973     case BuiltinType::ID: return GCCTypeClass::Integer;
10974 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10975     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10976 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10977     case BuiltinType::ID: break;
10978 #include "clang/AST/BuiltinTypes.def"
10979     case BuiltinType::Void:
10980       return GCCTypeClass::Void;
10981 
10982     case BuiltinType::Bool:
10983       return GCCTypeClass::Bool;
10984 
10985     case BuiltinType::Char_U:
10986     case BuiltinType::UChar:
10987     case BuiltinType::WChar_U:
10988     case BuiltinType::Char8:
10989     case BuiltinType::Char16:
10990     case BuiltinType::Char32:
10991     case BuiltinType::UShort:
10992     case BuiltinType::UInt:
10993     case BuiltinType::ULong:
10994     case BuiltinType::ULongLong:
10995     case BuiltinType::UInt128:
10996       return GCCTypeClass::Integer;
10997 
10998     case BuiltinType::UShortAccum:
10999     case BuiltinType::UAccum:
11000     case BuiltinType::ULongAccum:
11001     case BuiltinType::UShortFract:
11002     case BuiltinType::UFract:
11003     case BuiltinType::ULongFract:
11004     case BuiltinType::SatUShortAccum:
11005     case BuiltinType::SatUAccum:
11006     case BuiltinType::SatULongAccum:
11007     case BuiltinType::SatUShortFract:
11008     case BuiltinType::SatUFract:
11009     case BuiltinType::SatULongFract:
11010       return GCCTypeClass::None;
11011 
11012     case BuiltinType::NullPtr:
11013 
11014     case BuiltinType::ObjCId:
11015     case BuiltinType::ObjCClass:
11016     case BuiltinType::ObjCSel:
11017 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11018     case BuiltinType::Id:
11019 #include "clang/Basic/OpenCLImageTypes.def"
11020 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11021     case BuiltinType::Id:
11022 #include "clang/Basic/OpenCLExtensionTypes.def"
11023     case BuiltinType::OCLSampler:
11024     case BuiltinType::OCLEvent:
11025     case BuiltinType::OCLClkEvent:
11026     case BuiltinType::OCLQueue:
11027     case BuiltinType::OCLReserveID:
11028 #define SVE_TYPE(Name, Id, SingletonId) \
11029     case BuiltinType::Id:
11030 #include "clang/Basic/AArch64SVEACLETypes.def"
11031 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11032     case BuiltinType::Id:
11033 #include "clang/Basic/PPCTypes.def"
11034 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11035 #include "clang/Basic/RISCVVTypes.def"
11036       return GCCTypeClass::None;
11037 
11038     case BuiltinType::Dependent:
11039       llvm_unreachable("unexpected dependent type");
11040     };
11041     llvm_unreachable("unexpected placeholder type");
11042 
11043   case Type::Enum:
11044     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11045 
11046   case Type::Pointer:
11047   case Type::ConstantArray:
11048   case Type::VariableArray:
11049   case Type::IncompleteArray:
11050   case Type::FunctionNoProto:
11051   case Type::FunctionProto:
11052     return GCCTypeClass::Pointer;
11053 
11054   case Type::MemberPointer:
11055     return CanTy->isMemberDataPointerType()
11056                ? GCCTypeClass::PointerToDataMember
11057                : GCCTypeClass::PointerToMemberFunction;
11058 
11059   case Type::Complex:
11060     return GCCTypeClass::Complex;
11061 
11062   case Type::Record:
11063     return CanTy->isUnionType() ? GCCTypeClass::Union
11064                                 : GCCTypeClass::ClassOrStruct;
11065 
11066   case Type::Atomic:
11067     // GCC classifies _Atomic T the same as T.
11068     return EvaluateBuiltinClassifyType(
11069         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11070 
11071   case Type::BlockPointer:
11072   case Type::Vector:
11073   case Type::ExtVector:
11074   case Type::ConstantMatrix:
11075   case Type::ObjCObject:
11076   case Type::ObjCInterface:
11077   case Type::ObjCObjectPointer:
11078   case Type::Pipe:
11079   case Type::ExtInt:
11080     // GCC classifies vectors as None. We follow its lead and classify all
11081     // other types that don't fit into the regular classification the same way.
11082     return GCCTypeClass::None;
11083 
11084   case Type::LValueReference:
11085   case Type::RValueReference:
11086     llvm_unreachable("invalid type for expression");
11087   }
11088 
11089   llvm_unreachable("unexpected type class");
11090 }
11091 
11092 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11093 /// as GCC.
11094 static GCCTypeClass
EvaluateBuiltinClassifyType(const CallExpr * E,const LangOptions & LangOpts)11095 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11096   // If no argument was supplied, default to None. This isn't
11097   // ideal, however it is what gcc does.
11098   if (E->getNumArgs() == 0)
11099     return GCCTypeClass::None;
11100 
11101   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11102   // being an ICE, but still folds it to a constant using the type of the first
11103   // argument.
11104   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11105 }
11106 
11107 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11108 /// __builtin_constant_p when applied to the given pointer.
11109 ///
11110 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11111 /// or it points to the first character of a string literal.
EvaluateBuiltinConstantPForLValue(const APValue & LV)11112 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11113   APValue::LValueBase Base = LV.getLValueBase();
11114   if (Base.isNull()) {
11115     // A null base is acceptable.
11116     return true;
11117   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11118     if (!isa<StringLiteral>(E))
11119       return false;
11120     return LV.getLValueOffset().isZero();
11121   } else if (Base.is<TypeInfoLValue>()) {
11122     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11123     // evaluate to true.
11124     return true;
11125   } else {
11126     // Any other base is not constant enough for GCC.
11127     return false;
11128   }
11129 }
11130 
11131 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11132 /// GCC as we can manage.
EvaluateBuiltinConstantP(EvalInfo & Info,const Expr * Arg)11133 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11134   // This evaluation is not permitted to have side-effects, so evaluate it in
11135   // a speculative evaluation context.
11136   SpeculativeEvaluationRAII SpeculativeEval(Info);
11137 
11138   // Constant-folding is always enabled for the operand of __builtin_constant_p
11139   // (even when the enclosing evaluation context otherwise requires a strict
11140   // language-specific constant expression).
11141   FoldConstant Fold(Info, true);
11142 
11143   QualType ArgType = Arg->getType();
11144 
11145   // __builtin_constant_p always has one operand. The rules which gcc follows
11146   // are not precisely documented, but are as follows:
11147   //
11148   //  - If the operand is of integral, floating, complex or enumeration type,
11149   //    and can be folded to a known value of that type, it returns 1.
11150   //  - If the operand can be folded to a pointer to the first character
11151   //    of a string literal (or such a pointer cast to an integral type)
11152   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11153   //
11154   // Otherwise, it returns 0.
11155   //
11156   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11157   // its support for this did not work prior to GCC 9 and is not yet well
11158   // understood.
11159   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11160       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11161       ArgType->isNullPtrType()) {
11162     APValue V;
11163     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11164       Fold.keepDiagnostics();
11165       return false;
11166     }
11167 
11168     // For a pointer (possibly cast to integer), there are special rules.
11169     if (V.getKind() == APValue::LValue)
11170       return EvaluateBuiltinConstantPForLValue(V);
11171 
11172     // Otherwise, any constant value is good enough.
11173     return V.hasValue();
11174   }
11175 
11176   // Anything else isn't considered to be sufficiently constant.
11177   return false;
11178 }
11179 
11180 /// Retrieves the "underlying object type" of the given expression,
11181 /// as used by __builtin_object_size.
getObjectType(APValue::LValueBase B)11182 static QualType getObjectType(APValue::LValueBase B) {
11183   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11184     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11185       return VD->getType();
11186   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11187     if (isa<CompoundLiteralExpr>(E))
11188       return E->getType();
11189   } else if (B.is<TypeInfoLValue>()) {
11190     return B.getTypeInfoType();
11191   } else if (B.is<DynamicAllocLValue>()) {
11192     return B.getDynamicAllocType();
11193   }
11194 
11195   return QualType();
11196 }
11197 
11198 /// A more selective version of E->IgnoreParenCasts for
11199 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11200 /// to change the type of E.
11201 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11202 ///
11203 /// Always returns an RValue with a pointer representation.
ignorePointerCastsAndParens(const Expr * E)11204 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11205   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11206 
11207   auto *NoParens = E->IgnoreParens();
11208   auto *Cast = dyn_cast<CastExpr>(NoParens);
11209   if (Cast == nullptr)
11210     return NoParens;
11211 
11212   // We only conservatively allow a few kinds of casts, because this code is
11213   // inherently a simple solution that seeks to support the common case.
11214   auto CastKind = Cast->getCastKind();
11215   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11216       CastKind != CK_AddressSpaceConversion)
11217     return NoParens;
11218 
11219   auto *SubExpr = Cast->getSubExpr();
11220   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11221     return NoParens;
11222   return ignorePointerCastsAndParens(SubExpr);
11223 }
11224 
11225 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11226 /// record layout. e.g.
11227 ///   struct { struct { int a, b; } fst, snd; } obj;
11228 ///   obj.fst   // no
11229 ///   obj.snd   // yes
11230 ///   obj.fst.a // no
11231 ///   obj.fst.b // no
11232 ///   obj.snd.a // no
11233 ///   obj.snd.b // yes
11234 ///
11235 /// Please note: this function is specialized for how __builtin_object_size
11236 /// views "objects".
11237 ///
11238 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11239 /// correct result, it will always return true.
isDesignatorAtObjectEnd(const ASTContext & Ctx,const LValue & LVal)11240 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11241   assert(!LVal.Designator.Invalid);
11242 
11243   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11244     const RecordDecl *Parent = FD->getParent();
11245     Invalid = Parent->isInvalidDecl();
11246     if (Invalid || Parent->isUnion())
11247       return true;
11248     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11249     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11250   };
11251 
11252   auto &Base = LVal.getLValueBase();
11253   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11254     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11255       bool Invalid;
11256       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11257         return Invalid;
11258     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11259       for (auto *FD : IFD->chain()) {
11260         bool Invalid;
11261         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11262           return Invalid;
11263       }
11264     }
11265   }
11266 
11267   unsigned I = 0;
11268   QualType BaseType = getType(Base);
11269   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11270     // If we don't know the array bound, conservatively assume we're looking at
11271     // the final array element.
11272     ++I;
11273     if (BaseType->isIncompleteArrayType())
11274       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11275     else
11276       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11277   }
11278 
11279   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11280     const auto &Entry = LVal.Designator.Entries[I];
11281     if (BaseType->isArrayType()) {
11282       // Because __builtin_object_size treats arrays as objects, we can ignore
11283       // the index iff this is the last array in the Designator.
11284       if (I + 1 == E)
11285         return true;
11286       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11287       uint64_t Index = Entry.getAsArrayIndex();
11288       if (Index + 1 != CAT->getSize())
11289         return false;
11290       BaseType = CAT->getElementType();
11291     } else if (BaseType->isAnyComplexType()) {
11292       const auto *CT = BaseType->castAs<ComplexType>();
11293       uint64_t Index = Entry.getAsArrayIndex();
11294       if (Index != 1)
11295         return false;
11296       BaseType = CT->getElementType();
11297     } else if (auto *FD = getAsField(Entry)) {
11298       bool Invalid;
11299       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11300         return Invalid;
11301       BaseType = FD->getType();
11302     } else {
11303       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11304       return false;
11305     }
11306   }
11307   return true;
11308 }
11309 
11310 /// Tests to see if the LValue has a user-specified designator (that isn't
11311 /// necessarily valid). Note that this always returns 'true' if the LValue has
11312 /// an unsized array as its first designator entry, because there's currently no
11313 /// way to tell if the user typed *foo or foo[0].
refersToCompleteObject(const LValue & LVal)11314 static bool refersToCompleteObject(const LValue &LVal) {
11315   if (LVal.Designator.Invalid)
11316     return false;
11317 
11318   if (!LVal.Designator.Entries.empty())
11319     return LVal.Designator.isMostDerivedAnUnsizedArray();
11320 
11321   if (!LVal.InvalidBase)
11322     return true;
11323 
11324   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11325   // the LValueBase.
11326   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11327   return !E || !isa<MemberExpr>(E);
11328 }
11329 
11330 /// Attempts to detect a user writing into a piece of memory that's impossible
11331 /// to figure out the size of by just using types.
isUserWritingOffTheEnd(const ASTContext & Ctx,const LValue & LVal)11332 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11333   const SubobjectDesignator &Designator = LVal.Designator;
11334   // Notes:
11335   // - Users can only write off of the end when we have an invalid base. Invalid
11336   //   bases imply we don't know where the memory came from.
11337   // - We used to be a bit more aggressive here; we'd only be conservative if
11338   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11339   //   broke some common standard library extensions (PR30346), but was
11340   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11341   //   with some sort of list. OTOH, it seems that GCC is always
11342   //   conservative with the last element in structs (if it's an array), so our
11343   //   current behavior is more compatible than an explicit list approach would
11344   //   be.
11345   return LVal.InvalidBase &&
11346          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11347          Designator.MostDerivedIsArrayElement &&
11348          isDesignatorAtObjectEnd(Ctx, LVal);
11349 }
11350 
11351 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11352 /// Fails if the conversion would cause loss of precision.
convertUnsignedAPIntToCharUnits(const llvm::APInt & Int,CharUnits & Result)11353 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11354                                             CharUnits &Result) {
11355   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11356   if (Int.ugt(CharUnitsMax))
11357     return false;
11358   Result = CharUnits::fromQuantity(Int.getZExtValue());
11359   return true;
11360 }
11361 
11362 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11363 /// determine how many bytes exist from the beginning of the object to either
11364 /// the end of the current subobject, or the end of the object itself, depending
11365 /// on what the LValue looks like + the value of Type.
11366 ///
11367 /// If this returns false, the value of Result is undefined.
determineEndOffset(EvalInfo & Info,SourceLocation ExprLoc,unsigned Type,const LValue & LVal,CharUnits & EndOffset)11368 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11369                                unsigned Type, const LValue &LVal,
11370                                CharUnits &EndOffset) {
11371   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11372 
11373   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11374     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11375       return false;
11376     return HandleSizeof(Info, ExprLoc, Ty, Result);
11377   };
11378 
11379   // We want to evaluate the size of the entire object. This is a valid fallback
11380   // for when Type=1 and the designator is invalid, because we're asked for an
11381   // upper-bound.
11382   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11383     // Type=3 wants a lower bound, so we can't fall back to this.
11384     if (Type == 3 && !DetermineForCompleteObject)
11385       return false;
11386 
11387     llvm::APInt APEndOffset;
11388     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11389         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11390       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11391 
11392     if (LVal.InvalidBase)
11393       return false;
11394 
11395     QualType BaseTy = getObjectType(LVal.getLValueBase());
11396     return CheckedHandleSizeof(BaseTy, EndOffset);
11397   }
11398 
11399   // We want to evaluate the size of a subobject.
11400   const SubobjectDesignator &Designator = LVal.Designator;
11401 
11402   // The following is a moderately common idiom in C:
11403   //
11404   // struct Foo { int a; char c[1]; };
11405   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11406   // strcpy(&F->c[0], Bar);
11407   //
11408   // In order to not break too much legacy code, we need to support it.
11409   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11410     // If we can resolve this to an alloc_size call, we can hand that back,
11411     // because we know for certain how many bytes there are to write to.
11412     llvm::APInt APEndOffset;
11413     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11414         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11415       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11416 
11417     // If we cannot determine the size of the initial allocation, then we can't
11418     // given an accurate upper-bound. However, we are still able to give
11419     // conservative lower-bounds for Type=3.
11420     if (Type == 1)
11421       return false;
11422   }
11423 
11424   CharUnits BytesPerElem;
11425   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11426     return false;
11427 
11428   // According to the GCC documentation, we want the size of the subobject
11429   // denoted by the pointer. But that's not quite right -- what we actually
11430   // want is the size of the immediately-enclosing array, if there is one.
11431   int64_t ElemsRemaining;
11432   if (Designator.MostDerivedIsArrayElement &&
11433       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11434     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11435     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11436     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11437   } else {
11438     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11439   }
11440 
11441   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11442   return true;
11443 }
11444 
11445 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11446 /// returns true and stores the result in @p Size.
11447 ///
11448 /// If @p WasError is non-null, this will report whether the failure to evaluate
11449 /// is to be treated as an Error in IntExprEvaluator.
tryEvaluateBuiltinObjectSize(const Expr * E,unsigned Type,EvalInfo & Info,uint64_t & Size)11450 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11451                                          EvalInfo &Info, uint64_t &Size) {
11452   // Determine the denoted object.
11453   LValue LVal;
11454   {
11455     // The operand of __builtin_object_size is never evaluated for side-effects.
11456     // If there are any, but we can determine the pointed-to object anyway, then
11457     // ignore the side-effects.
11458     SpeculativeEvaluationRAII SpeculativeEval(Info);
11459     IgnoreSideEffectsRAII Fold(Info);
11460 
11461     if (E->isGLValue()) {
11462       // It's possible for us to be given GLValues if we're called via
11463       // Expr::tryEvaluateObjectSize.
11464       APValue RVal;
11465       if (!EvaluateAsRValue(Info, E, RVal))
11466         return false;
11467       LVal.setFrom(Info.Ctx, RVal);
11468     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11469                                 /*InvalidBaseOK=*/true))
11470       return false;
11471   }
11472 
11473   // If we point to before the start of the object, there are no accessible
11474   // bytes.
11475   if (LVal.getLValueOffset().isNegative()) {
11476     Size = 0;
11477     return true;
11478   }
11479 
11480   CharUnits EndOffset;
11481   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11482     return false;
11483 
11484   // If we've fallen outside of the end offset, just pretend there's nothing to
11485   // write to/read from.
11486   if (EndOffset <= LVal.getLValueOffset())
11487     Size = 0;
11488   else
11489     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11490   return true;
11491 }
11492 
VisitCallExpr(const CallExpr * E)11493 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11494   if (unsigned BuiltinOp = E->getBuiltinCallee())
11495     return VisitBuiltinCallExpr(E, BuiltinOp);
11496 
11497   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11498 }
11499 
getBuiltinAlignArguments(const CallExpr * E,EvalInfo & Info,APValue & Val,APSInt & Alignment)11500 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11501                                      APValue &Val, APSInt &Alignment) {
11502   QualType SrcTy = E->getArg(0)->getType();
11503   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11504     return false;
11505   // Even though we are evaluating integer expressions we could get a pointer
11506   // argument for the __builtin_is_aligned() case.
11507   if (SrcTy->isPointerType()) {
11508     LValue Ptr;
11509     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11510       return false;
11511     Ptr.moveInto(Val);
11512   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11513     Info.FFDiag(E->getArg(0));
11514     return false;
11515   } else {
11516     APSInt SrcInt;
11517     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11518       return false;
11519     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11520            "Bit widths must be the same");
11521     Val = APValue(SrcInt);
11522   }
11523   assert(Val.hasValue());
11524   return true;
11525 }
11526 
VisitBuiltinCallExpr(const CallExpr * E,unsigned BuiltinOp)11527 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11528                                             unsigned BuiltinOp) {
11529   switch (BuiltinOp) {
11530   default:
11531     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11532 
11533   case Builtin::BI__builtin_dynamic_object_size:
11534   case Builtin::BI__builtin_object_size: {
11535     // The type was checked when we built the expression.
11536     unsigned Type =
11537         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11538     assert(Type <= 3 && "unexpected type");
11539 
11540     uint64_t Size;
11541     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11542       return Success(Size, E);
11543 
11544     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11545       return Success((Type & 2) ? 0 : -1, E);
11546 
11547     // Expression had no side effects, but we couldn't statically determine the
11548     // size of the referenced object.
11549     switch (Info.EvalMode) {
11550     case EvalInfo::EM_ConstantExpression:
11551     case EvalInfo::EM_ConstantFold:
11552     case EvalInfo::EM_IgnoreSideEffects:
11553       // Leave it to IR generation.
11554       return Error(E);
11555     case EvalInfo::EM_ConstantExpressionUnevaluated:
11556       // Reduce it to a constant now.
11557       return Success((Type & 2) ? 0 : -1, E);
11558     }
11559 
11560     llvm_unreachable("unexpected EvalMode");
11561   }
11562 
11563   case Builtin::BI__builtin_os_log_format_buffer_size: {
11564     analyze_os_log::OSLogBufferLayout Layout;
11565     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11566     return Success(Layout.size().getQuantity(), E);
11567   }
11568 
11569   case Builtin::BI__builtin_is_aligned: {
11570     APValue Src;
11571     APSInt Alignment;
11572     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11573       return false;
11574     if (Src.isLValue()) {
11575       // If we evaluated a pointer, check the minimum known alignment.
11576       LValue Ptr;
11577       Ptr.setFrom(Info.Ctx, Src);
11578       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11579       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11580       // We can return true if the known alignment at the computed offset is
11581       // greater than the requested alignment.
11582       assert(PtrAlign.isPowerOfTwo());
11583       assert(Alignment.isPowerOf2());
11584       if (PtrAlign.getQuantity() >= Alignment)
11585         return Success(1, E);
11586       // If the alignment is not known to be sufficient, some cases could still
11587       // be aligned at run time. However, if the requested alignment is less or
11588       // equal to the base alignment and the offset is not aligned, we know that
11589       // the run-time value can never be aligned.
11590       if (BaseAlignment.getQuantity() >= Alignment &&
11591           PtrAlign.getQuantity() < Alignment)
11592         return Success(0, E);
11593       // Otherwise we can't infer whether the value is sufficiently aligned.
11594       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11595       //  in cases where we can't fully evaluate the pointer.
11596       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11597           << Alignment;
11598       return false;
11599     }
11600     assert(Src.isInt());
11601     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11602   }
11603   case Builtin::BI__builtin_align_up: {
11604     APValue Src;
11605     APSInt Alignment;
11606     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11607       return false;
11608     if (!Src.isInt())
11609       return Error(E);
11610     APSInt AlignedVal =
11611         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11612                Src.getInt().isUnsigned());
11613     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11614     return Success(AlignedVal, E);
11615   }
11616   case Builtin::BI__builtin_align_down: {
11617     APValue Src;
11618     APSInt Alignment;
11619     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11620       return false;
11621     if (!Src.isInt())
11622       return Error(E);
11623     APSInt AlignedVal =
11624         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11625     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11626     return Success(AlignedVal, E);
11627   }
11628 
11629   case Builtin::BI__builtin_bitreverse8:
11630   case Builtin::BI__builtin_bitreverse16:
11631   case Builtin::BI__builtin_bitreverse32:
11632   case Builtin::BI__builtin_bitreverse64: {
11633     APSInt Val;
11634     if (!EvaluateInteger(E->getArg(0), Val, Info))
11635       return false;
11636 
11637     return Success(Val.reverseBits(), E);
11638   }
11639 
11640   case Builtin::BI__builtin_bswap16:
11641   case Builtin::BI__builtin_bswap32:
11642   case Builtin::BI__builtin_bswap64: {
11643     APSInt Val;
11644     if (!EvaluateInteger(E->getArg(0), Val, Info))
11645       return false;
11646 
11647     return Success(Val.byteSwap(), E);
11648   }
11649 
11650   case Builtin::BI__builtin_classify_type:
11651     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11652 
11653   case Builtin::BI__builtin_clrsb:
11654   case Builtin::BI__builtin_clrsbl:
11655   case Builtin::BI__builtin_clrsbll: {
11656     APSInt Val;
11657     if (!EvaluateInteger(E->getArg(0), Val, Info))
11658       return false;
11659 
11660     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11661   }
11662 
11663   case Builtin::BI__builtin_clz:
11664   case Builtin::BI__builtin_clzl:
11665   case Builtin::BI__builtin_clzll:
11666   case Builtin::BI__builtin_clzs: {
11667     APSInt Val;
11668     if (!EvaluateInteger(E->getArg(0), Val, Info))
11669       return false;
11670     if (!Val)
11671       return Error(E);
11672 
11673     return Success(Val.countLeadingZeros(), E);
11674   }
11675 
11676   case Builtin::BI__builtin_constant_p: {
11677     const Expr *Arg = E->getArg(0);
11678     if (EvaluateBuiltinConstantP(Info, Arg))
11679       return Success(true, E);
11680     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11681       // Outside a constant context, eagerly evaluate to false in the presence
11682       // of side-effects in order to avoid -Wunsequenced false-positives in
11683       // a branch on __builtin_constant_p(expr).
11684       return Success(false, E);
11685     }
11686     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11687     return false;
11688   }
11689 
11690   case Builtin::BI__builtin_is_constant_evaluated: {
11691     const auto *Callee = Info.CurrentCall->getCallee();
11692     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11693         (Info.CallStackDepth == 1 ||
11694          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11695           Callee->getIdentifier() &&
11696           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11697       // FIXME: Find a better way to avoid duplicated diagnostics.
11698       if (Info.EvalStatus.Diag)
11699         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11700                                                : Info.CurrentCall->CallLoc,
11701                     diag::warn_is_constant_evaluated_always_true_constexpr)
11702             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11703                                          : "std::is_constant_evaluated");
11704     }
11705 
11706     return Success(Info.InConstantContext, E);
11707   }
11708 
11709   case Builtin::BI__builtin_ctz:
11710   case Builtin::BI__builtin_ctzl:
11711   case Builtin::BI__builtin_ctzll:
11712   case Builtin::BI__builtin_ctzs: {
11713     APSInt Val;
11714     if (!EvaluateInteger(E->getArg(0), Val, Info))
11715       return false;
11716     if (!Val)
11717       return Error(E);
11718 
11719     return Success(Val.countTrailingZeros(), E);
11720   }
11721 
11722   case Builtin::BI__builtin_eh_return_data_regno: {
11723     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11724     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11725     return Success(Operand, E);
11726   }
11727 
11728   case Builtin::BI__builtin_expect:
11729   case Builtin::BI__builtin_expect_with_probability:
11730     return Visit(E->getArg(0));
11731 
11732   case Builtin::BI__builtin_ffs:
11733   case Builtin::BI__builtin_ffsl:
11734   case Builtin::BI__builtin_ffsll: {
11735     APSInt Val;
11736     if (!EvaluateInteger(E->getArg(0), Val, Info))
11737       return false;
11738 
11739     unsigned N = Val.countTrailingZeros();
11740     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11741   }
11742 
11743   case Builtin::BI__builtin_fpclassify: {
11744     APFloat Val(0.0);
11745     if (!EvaluateFloat(E->getArg(5), Val, Info))
11746       return false;
11747     unsigned Arg;
11748     switch (Val.getCategory()) {
11749     case APFloat::fcNaN: Arg = 0; break;
11750     case APFloat::fcInfinity: Arg = 1; break;
11751     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11752     case APFloat::fcZero: Arg = 4; break;
11753     }
11754     return Visit(E->getArg(Arg));
11755   }
11756 
11757   case Builtin::BI__builtin_isinf_sign: {
11758     APFloat Val(0.0);
11759     return EvaluateFloat(E->getArg(0), Val, Info) &&
11760            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11761   }
11762 
11763   case Builtin::BI__builtin_isinf: {
11764     APFloat Val(0.0);
11765     return EvaluateFloat(E->getArg(0), Val, Info) &&
11766            Success(Val.isInfinity() ? 1 : 0, E);
11767   }
11768 
11769   case Builtin::BI__builtin_isfinite: {
11770     APFloat Val(0.0);
11771     return EvaluateFloat(E->getArg(0), Val, Info) &&
11772            Success(Val.isFinite() ? 1 : 0, E);
11773   }
11774 
11775   case Builtin::BI__builtin_isnan: {
11776     APFloat Val(0.0);
11777     return EvaluateFloat(E->getArg(0), Val, Info) &&
11778            Success(Val.isNaN() ? 1 : 0, E);
11779   }
11780 
11781   case Builtin::BI__builtin_isnormal: {
11782     APFloat Val(0.0);
11783     return EvaluateFloat(E->getArg(0), Val, Info) &&
11784            Success(Val.isNormal() ? 1 : 0, E);
11785   }
11786 
11787   case Builtin::BI__builtin_parity:
11788   case Builtin::BI__builtin_parityl:
11789   case Builtin::BI__builtin_parityll: {
11790     APSInt Val;
11791     if (!EvaluateInteger(E->getArg(0), Val, Info))
11792       return false;
11793 
11794     return Success(Val.countPopulation() % 2, E);
11795   }
11796 
11797   case Builtin::BI__builtin_popcount:
11798   case Builtin::BI__builtin_popcountl:
11799   case Builtin::BI__builtin_popcountll: {
11800     APSInt Val;
11801     if (!EvaluateInteger(E->getArg(0), Val, Info))
11802       return false;
11803 
11804     return Success(Val.countPopulation(), E);
11805   }
11806 
11807   case Builtin::BI__builtin_rotateleft8:
11808   case Builtin::BI__builtin_rotateleft16:
11809   case Builtin::BI__builtin_rotateleft32:
11810   case Builtin::BI__builtin_rotateleft64:
11811   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11812   case Builtin::BI_rotl16:
11813   case Builtin::BI_rotl:
11814   case Builtin::BI_lrotl:
11815   case Builtin::BI_rotl64: {
11816     APSInt Val, Amt;
11817     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11818         !EvaluateInteger(E->getArg(1), Amt, Info))
11819       return false;
11820 
11821     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11822   }
11823 
11824   case Builtin::BI__builtin_rotateright8:
11825   case Builtin::BI__builtin_rotateright16:
11826   case Builtin::BI__builtin_rotateright32:
11827   case Builtin::BI__builtin_rotateright64:
11828   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11829   case Builtin::BI_rotr16:
11830   case Builtin::BI_rotr:
11831   case Builtin::BI_lrotr:
11832   case Builtin::BI_rotr64: {
11833     APSInt Val, Amt;
11834     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11835         !EvaluateInteger(E->getArg(1), Amt, Info))
11836       return false;
11837 
11838     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11839   }
11840 
11841   case Builtin::BIstrlen:
11842   case Builtin::BIwcslen:
11843     // A call to strlen is not a constant expression.
11844     if (Info.getLangOpts().CPlusPlus11)
11845       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11846         << /*isConstexpr*/0 << /*isConstructor*/0
11847         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11848     else
11849       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11850     LLVM_FALLTHROUGH;
11851   case Builtin::BI__builtin_strlen:
11852   case Builtin::BI__builtin_wcslen: {
11853     // As an extension, we support __builtin_strlen() as a constant expression,
11854     // and support folding strlen() to a constant.
11855     uint64_t StrLen;
11856     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
11857       return Success(StrLen, E);
11858     return false;
11859   }
11860 
11861   case Builtin::BIstrcmp:
11862   case Builtin::BIwcscmp:
11863   case Builtin::BIstrncmp:
11864   case Builtin::BIwcsncmp:
11865   case Builtin::BImemcmp:
11866   case Builtin::BIbcmp:
11867   case Builtin::BIwmemcmp:
11868     // A call to strlen is not a constant expression.
11869     if (Info.getLangOpts().CPlusPlus11)
11870       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11871         << /*isConstexpr*/0 << /*isConstructor*/0
11872         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11873     else
11874       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11875     LLVM_FALLTHROUGH;
11876   case Builtin::BI__builtin_strcmp:
11877   case Builtin::BI__builtin_wcscmp:
11878   case Builtin::BI__builtin_strncmp:
11879   case Builtin::BI__builtin_wcsncmp:
11880   case Builtin::BI__builtin_memcmp:
11881   case Builtin::BI__builtin_bcmp:
11882   case Builtin::BI__builtin_wmemcmp: {
11883     LValue String1, String2;
11884     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11885         !EvaluatePointer(E->getArg(1), String2, Info))
11886       return false;
11887 
11888     uint64_t MaxLength = uint64_t(-1);
11889     if (BuiltinOp != Builtin::BIstrcmp &&
11890         BuiltinOp != Builtin::BIwcscmp &&
11891         BuiltinOp != Builtin::BI__builtin_strcmp &&
11892         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11893       APSInt N;
11894       if (!EvaluateInteger(E->getArg(2), N, Info))
11895         return false;
11896       MaxLength = N.getExtValue();
11897     }
11898 
11899     // Empty substrings compare equal by definition.
11900     if (MaxLength == 0u)
11901       return Success(0, E);
11902 
11903     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11904         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11905         String1.Designator.Invalid || String2.Designator.Invalid)
11906       return false;
11907 
11908     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11909     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11910 
11911     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11912                      BuiltinOp == Builtin::BIbcmp ||
11913                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11914                      BuiltinOp == Builtin::BI__builtin_bcmp;
11915 
11916     assert(IsRawByte ||
11917            (Info.Ctx.hasSameUnqualifiedType(
11918                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11919             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11920 
11921     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11922     // 'char8_t', but no other types.
11923     if (IsRawByte &&
11924         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11925       // FIXME: Consider using our bit_cast implementation to support this.
11926       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11927           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11928           << CharTy1 << CharTy2;
11929       return false;
11930     }
11931 
11932     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11933       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11934              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11935              Char1.isInt() && Char2.isInt();
11936     };
11937     const auto &AdvanceElems = [&] {
11938       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11939              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11940     };
11941 
11942     bool StopAtNull =
11943         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11944          BuiltinOp != Builtin::BIwmemcmp &&
11945          BuiltinOp != Builtin::BI__builtin_memcmp &&
11946          BuiltinOp != Builtin::BI__builtin_bcmp &&
11947          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11948     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11949                   BuiltinOp == Builtin::BIwcsncmp ||
11950                   BuiltinOp == Builtin::BIwmemcmp ||
11951                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11952                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11953                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11954 
11955     for (; MaxLength; --MaxLength) {
11956       APValue Char1, Char2;
11957       if (!ReadCurElems(Char1, Char2))
11958         return false;
11959       if (Char1.getInt().ne(Char2.getInt())) {
11960         if (IsWide) // wmemcmp compares with wchar_t signedness.
11961           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11962         // memcmp always compares unsigned chars.
11963         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11964       }
11965       if (StopAtNull && !Char1.getInt())
11966         return Success(0, E);
11967       assert(!(StopAtNull && !Char2.getInt()));
11968       if (!AdvanceElems())
11969         return false;
11970     }
11971     // We hit the strncmp / memcmp limit.
11972     return Success(0, E);
11973   }
11974 
11975   case Builtin::BI__atomic_always_lock_free:
11976   case Builtin::BI__atomic_is_lock_free:
11977   case Builtin::BI__c11_atomic_is_lock_free: {
11978     APSInt SizeVal;
11979     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11980       return false;
11981 
11982     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11983     // of two less than or equal to the maximum inline atomic width, we know it
11984     // is lock-free.  If the size isn't a power of two, or greater than the
11985     // maximum alignment where we promote atomics, we know it is not lock-free
11986     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11987     // the answer can only be determined at runtime; for example, 16-byte
11988     // atomics have lock-free implementations on some, but not all,
11989     // x86-64 processors.
11990 
11991     // Check power-of-two.
11992     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11993     if (Size.isPowerOfTwo()) {
11994       // Check against inlining width.
11995       unsigned InlineWidthBits =
11996           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11997       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11998         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11999             Size == CharUnits::One() ||
12000             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12001                                                 Expr::NPC_NeverValueDependent))
12002           // OK, we will inline appropriately-aligned operations of this size,
12003           // and _Atomic(T) is appropriately-aligned.
12004           return Success(1, E);
12005 
12006         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12007           castAs<PointerType>()->getPointeeType();
12008         if (!PointeeType->isIncompleteType() &&
12009             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12010           // OK, we will inline operations on this object.
12011           return Success(1, E);
12012         }
12013       }
12014     }
12015 
12016     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12017         Success(0, E) : Error(E);
12018   }
12019   case Builtin::BI__builtin_add_overflow:
12020   case Builtin::BI__builtin_sub_overflow:
12021   case Builtin::BI__builtin_mul_overflow:
12022   case Builtin::BI__builtin_sadd_overflow:
12023   case Builtin::BI__builtin_uadd_overflow:
12024   case Builtin::BI__builtin_uaddl_overflow:
12025   case Builtin::BI__builtin_uaddll_overflow:
12026   case Builtin::BI__builtin_usub_overflow:
12027   case Builtin::BI__builtin_usubl_overflow:
12028   case Builtin::BI__builtin_usubll_overflow:
12029   case Builtin::BI__builtin_umul_overflow:
12030   case Builtin::BI__builtin_umull_overflow:
12031   case Builtin::BI__builtin_umulll_overflow:
12032   case Builtin::BI__builtin_saddl_overflow:
12033   case Builtin::BI__builtin_saddll_overflow:
12034   case Builtin::BI__builtin_ssub_overflow:
12035   case Builtin::BI__builtin_ssubl_overflow:
12036   case Builtin::BI__builtin_ssubll_overflow:
12037   case Builtin::BI__builtin_smul_overflow:
12038   case Builtin::BI__builtin_smull_overflow:
12039   case Builtin::BI__builtin_smulll_overflow: {
12040     LValue ResultLValue;
12041     APSInt LHS, RHS;
12042 
12043     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12044     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12045         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12046         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12047       return false;
12048 
12049     APSInt Result;
12050     bool DidOverflow = false;
12051 
12052     // If the types don't have to match, enlarge all 3 to the largest of them.
12053     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12054         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12055         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12056       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12057                       ResultType->isSignedIntegerOrEnumerationType();
12058       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12059                       ResultType->isSignedIntegerOrEnumerationType();
12060       uint64_t LHSSize = LHS.getBitWidth();
12061       uint64_t RHSSize = RHS.getBitWidth();
12062       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12063       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12064 
12065       // Add an additional bit if the signedness isn't uniformly agreed to. We
12066       // could do this ONLY if there is a signed and an unsigned that both have
12067       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12068       // caught in the shrink-to-result later anyway.
12069       if (IsSigned && !AllSigned)
12070         ++MaxBits;
12071 
12072       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12073       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12074       Result = APSInt(MaxBits, !IsSigned);
12075     }
12076 
12077     // Find largest int.
12078     switch (BuiltinOp) {
12079     default:
12080       llvm_unreachable("Invalid value for BuiltinOp");
12081     case Builtin::BI__builtin_add_overflow:
12082     case Builtin::BI__builtin_sadd_overflow:
12083     case Builtin::BI__builtin_saddl_overflow:
12084     case Builtin::BI__builtin_saddll_overflow:
12085     case Builtin::BI__builtin_uadd_overflow:
12086     case Builtin::BI__builtin_uaddl_overflow:
12087     case Builtin::BI__builtin_uaddll_overflow:
12088       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12089                               : LHS.uadd_ov(RHS, DidOverflow);
12090       break;
12091     case Builtin::BI__builtin_sub_overflow:
12092     case Builtin::BI__builtin_ssub_overflow:
12093     case Builtin::BI__builtin_ssubl_overflow:
12094     case Builtin::BI__builtin_ssubll_overflow:
12095     case Builtin::BI__builtin_usub_overflow:
12096     case Builtin::BI__builtin_usubl_overflow:
12097     case Builtin::BI__builtin_usubll_overflow:
12098       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12099                               : LHS.usub_ov(RHS, DidOverflow);
12100       break;
12101     case Builtin::BI__builtin_mul_overflow:
12102     case Builtin::BI__builtin_smul_overflow:
12103     case Builtin::BI__builtin_smull_overflow:
12104     case Builtin::BI__builtin_smulll_overflow:
12105     case Builtin::BI__builtin_umul_overflow:
12106     case Builtin::BI__builtin_umull_overflow:
12107     case Builtin::BI__builtin_umulll_overflow:
12108       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12109                               : LHS.umul_ov(RHS, DidOverflow);
12110       break;
12111     }
12112 
12113     // In the case where multiple sizes are allowed, truncate and see if
12114     // the values are the same.
12115     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12116         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12117         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12118       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12119       // since it will give us the behavior of a TruncOrSelf in the case where
12120       // its parameter <= its size.  We previously set Result to be at least the
12121       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12122       // will work exactly like TruncOrSelf.
12123       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12124       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12125 
12126       if (!APSInt::isSameValue(Temp, Result))
12127         DidOverflow = true;
12128       Result = Temp;
12129     }
12130 
12131     APValue APV{Result};
12132     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12133       return false;
12134     return Success(DidOverflow, E);
12135   }
12136   }
12137 }
12138 
12139 /// Determine whether this is a pointer past the end of the complete
12140 /// object referred to by the lvalue.
isOnePastTheEndOfCompleteObject(const ASTContext & Ctx,const LValue & LV)12141 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12142                                             const LValue &LV) {
12143   // A null pointer can be viewed as being "past the end" but we don't
12144   // choose to look at it that way here.
12145   if (!LV.getLValueBase())
12146     return false;
12147 
12148   // If the designator is valid and refers to a subobject, we're not pointing
12149   // past the end.
12150   if (!LV.getLValueDesignator().Invalid &&
12151       !LV.getLValueDesignator().isOnePastTheEnd())
12152     return false;
12153 
12154   // A pointer to an incomplete type might be past-the-end if the type's size is
12155   // zero.  We cannot tell because the type is incomplete.
12156   QualType Ty = getType(LV.getLValueBase());
12157   if (Ty->isIncompleteType())
12158     return true;
12159 
12160   // We're a past-the-end pointer if we point to the byte after the object,
12161   // no matter what our type or path is.
12162   auto Size = Ctx.getTypeSizeInChars(Ty);
12163   return LV.getLValueOffset() == Size;
12164 }
12165 
12166 namespace {
12167 
12168 /// Data recursive integer evaluator of certain binary operators.
12169 ///
12170 /// We use a data recursive algorithm for binary operators so that we are able
12171 /// to handle extreme cases of chained binary operators without causing stack
12172 /// overflow.
12173 class DataRecursiveIntBinOpEvaluator {
12174   struct EvalResult {
12175     APValue Val;
12176     bool Failed;
12177 
EvalResult__anon4a4db2532811::DataRecursiveIntBinOpEvaluator::EvalResult12178     EvalResult() : Failed(false) { }
12179 
swap__anon4a4db2532811::DataRecursiveIntBinOpEvaluator::EvalResult12180     void swap(EvalResult &RHS) {
12181       Val.swap(RHS.Val);
12182       Failed = RHS.Failed;
12183       RHS.Failed = false;
12184     }
12185   };
12186 
12187   struct Job {
12188     const Expr *E;
12189     EvalResult LHSResult; // meaningful only for binary operator expression.
12190     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12191 
12192     Job() = default;
12193     Job(Job &&) = default;
12194 
startSpeculativeEval__anon4a4db2532811::DataRecursiveIntBinOpEvaluator::Job12195     void startSpeculativeEval(EvalInfo &Info) {
12196       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12197     }
12198 
12199   private:
12200     SpeculativeEvaluationRAII SpecEvalRAII;
12201   };
12202 
12203   SmallVector<Job, 16> Queue;
12204 
12205   IntExprEvaluator &IntEval;
12206   EvalInfo &Info;
12207   APValue &FinalResult;
12208 
12209 public:
DataRecursiveIntBinOpEvaluator(IntExprEvaluator & IntEval,APValue & Result)12210   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12211     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12212 
12213   /// True if \param E is a binary operator that we are going to handle
12214   /// data recursively.
12215   /// We handle binary operators that are comma, logical, or that have operands
12216   /// with integral or enumeration type.
shouldEnqueue(const BinaryOperator * E)12217   static bool shouldEnqueue(const BinaryOperator *E) {
12218     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12219            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12220             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12221             E->getRHS()->getType()->isIntegralOrEnumerationType());
12222   }
12223 
Traverse(const BinaryOperator * E)12224   bool Traverse(const BinaryOperator *E) {
12225     enqueue(E);
12226     EvalResult PrevResult;
12227     while (!Queue.empty())
12228       process(PrevResult);
12229 
12230     if (PrevResult.Failed) return false;
12231 
12232     FinalResult.swap(PrevResult.Val);
12233     return true;
12234   }
12235 
12236 private:
Success(uint64_t Value,const Expr * E,APValue & Result)12237   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12238     return IntEval.Success(Value, E, Result);
12239   }
Success(const APSInt & Value,const Expr * E,APValue & Result)12240   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12241     return IntEval.Success(Value, E, Result);
12242   }
Error(const Expr * E)12243   bool Error(const Expr *E) {
12244     return IntEval.Error(E);
12245   }
Error(const Expr * E,diag::kind D)12246   bool Error(const Expr *E, diag::kind D) {
12247     return IntEval.Error(E, D);
12248   }
12249 
CCEDiag(const Expr * E,diag::kind D)12250   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12251     return Info.CCEDiag(E, D);
12252   }
12253 
12254   // Returns true if visiting the RHS is necessary, false otherwise.
12255   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12256                          bool &SuppressRHSDiags);
12257 
12258   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12259                   const BinaryOperator *E, APValue &Result);
12260 
EvaluateExpr(const Expr * E,EvalResult & Result)12261   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12262     Result.Failed = !Evaluate(Result.Val, Info, E);
12263     if (Result.Failed)
12264       Result.Val = APValue();
12265   }
12266 
12267   void process(EvalResult &Result);
12268 
enqueue(const Expr * E)12269   void enqueue(const Expr *E) {
12270     E = E->IgnoreParens();
12271     Queue.resize(Queue.size()+1);
12272     Queue.back().E = E;
12273     Queue.back().Kind = Job::AnyExprKind;
12274   }
12275 };
12276 
12277 }
12278 
12279 bool DataRecursiveIntBinOpEvaluator::
VisitBinOpLHSOnly(EvalResult & LHSResult,const BinaryOperator * E,bool & SuppressRHSDiags)12280        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12281                          bool &SuppressRHSDiags) {
12282   if (E->getOpcode() == BO_Comma) {
12283     // Ignore LHS but note if we could not evaluate it.
12284     if (LHSResult.Failed)
12285       return Info.noteSideEffect();
12286     return true;
12287   }
12288 
12289   if (E->isLogicalOp()) {
12290     bool LHSAsBool;
12291     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12292       // We were able to evaluate the LHS, see if we can get away with not
12293       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12294       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12295         Success(LHSAsBool, E, LHSResult.Val);
12296         return false; // Ignore RHS
12297       }
12298     } else {
12299       LHSResult.Failed = true;
12300 
12301       // Since we weren't able to evaluate the left hand side, it
12302       // might have had side effects.
12303       if (!Info.noteSideEffect())
12304         return false;
12305 
12306       // We can't evaluate the LHS; however, sometimes the result
12307       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12308       // Don't ignore RHS and suppress diagnostics from this arm.
12309       SuppressRHSDiags = true;
12310     }
12311 
12312     return true;
12313   }
12314 
12315   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12316          E->getRHS()->getType()->isIntegralOrEnumerationType());
12317 
12318   if (LHSResult.Failed && !Info.noteFailure())
12319     return false; // Ignore RHS;
12320 
12321   return true;
12322 }
12323 
addOrSubLValueAsInteger(APValue & LVal,const APSInt & Index,bool IsSub)12324 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12325                                     bool IsSub) {
12326   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12327   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12328   // offsets.
12329   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12330   CharUnits &Offset = LVal.getLValueOffset();
12331   uint64_t Offset64 = Offset.getQuantity();
12332   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12333   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12334                                          : Offset64 + Index64);
12335 }
12336 
12337 bool DataRecursiveIntBinOpEvaluator::
VisitBinOp(const EvalResult & LHSResult,const EvalResult & RHSResult,const BinaryOperator * E,APValue & Result)12338        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12339                   const BinaryOperator *E, APValue &Result) {
12340   if (E->getOpcode() == BO_Comma) {
12341     if (RHSResult.Failed)
12342       return false;
12343     Result = RHSResult.Val;
12344     return true;
12345   }
12346 
12347   if (E->isLogicalOp()) {
12348     bool lhsResult, rhsResult;
12349     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12350     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12351 
12352     if (LHSIsOK) {
12353       if (RHSIsOK) {
12354         if (E->getOpcode() == BO_LOr)
12355           return Success(lhsResult || rhsResult, E, Result);
12356         else
12357           return Success(lhsResult && rhsResult, E, Result);
12358       }
12359     } else {
12360       if (RHSIsOK) {
12361         // We can't evaluate the LHS; however, sometimes the result
12362         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12363         if (rhsResult == (E->getOpcode() == BO_LOr))
12364           return Success(rhsResult, E, Result);
12365       }
12366     }
12367 
12368     return false;
12369   }
12370 
12371   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12372          E->getRHS()->getType()->isIntegralOrEnumerationType());
12373 
12374   if (LHSResult.Failed || RHSResult.Failed)
12375     return false;
12376 
12377   const APValue &LHSVal = LHSResult.Val;
12378   const APValue &RHSVal = RHSResult.Val;
12379 
12380   // Handle cases like (unsigned long)&a + 4.
12381   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12382     Result = LHSVal;
12383     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12384     return true;
12385   }
12386 
12387   // Handle cases like 4 + (unsigned long)&a
12388   if (E->getOpcode() == BO_Add &&
12389       RHSVal.isLValue() && LHSVal.isInt()) {
12390     Result = RHSVal;
12391     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12392     return true;
12393   }
12394 
12395   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12396     // Handle (intptr_t)&&A - (intptr_t)&&B.
12397     if (!LHSVal.getLValueOffset().isZero() ||
12398         !RHSVal.getLValueOffset().isZero())
12399       return false;
12400     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12401     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12402     if (!LHSExpr || !RHSExpr)
12403       return false;
12404     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12405     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12406     if (!LHSAddrExpr || !RHSAddrExpr)
12407       return false;
12408     // Make sure both labels come from the same function.
12409     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12410         RHSAddrExpr->getLabel()->getDeclContext())
12411       return false;
12412     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12413     return true;
12414   }
12415 
12416   // All the remaining cases expect both operands to be an integer
12417   if (!LHSVal.isInt() || !RHSVal.isInt())
12418     return Error(E);
12419 
12420   // Set up the width and signedness manually, in case it can't be deduced
12421   // from the operation we're performing.
12422   // FIXME: Don't do this in the cases where we can deduce it.
12423   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12424                E->getType()->isUnsignedIntegerOrEnumerationType());
12425   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12426                          RHSVal.getInt(), Value))
12427     return false;
12428   return Success(Value, E, Result);
12429 }
12430 
process(EvalResult & Result)12431 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12432   Job &job = Queue.back();
12433 
12434   switch (job.Kind) {
12435     case Job::AnyExprKind: {
12436       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12437         if (shouldEnqueue(Bop)) {
12438           job.Kind = Job::BinOpKind;
12439           enqueue(Bop->getLHS());
12440           return;
12441         }
12442       }
12443 
12444       EvaluateExpr(job.E, Result);
12445       Queue.pop_back();
12446       return;
12447     }
12448 
12449     case Job::BinOpKind: {
12450       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12451       bool SuppressRHSDiags = false;
12452       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12453         Queue.pop_back();
12454         return;
12455       }
12456       if (SuppressRHSDiags)
12457         job.startSpeculativeEval(Info);
12458       job.LHSResult.swap(Result);
12459       job.Kind = Job::BinOpVisitedLHSKind;
12460       enqueue(Bop->getRHS());
12461       return;
12462     }
12463 
12464     case Job::BinOpVisitedLHSKind: {
12465       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12466       EvalResult RHS;
12467       RHS.swap(Result);
12468       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12469       Queue.pop_back();
12470       return;
12471     }
12472   }
12473 
12474   llvm_unreachable("Invalid Job::Kind!");
12475 }
12476 
12477 namespace {
12478 enum class CmpResult {
12479   Unequal,
12480   Less,
12481   Equal,
12482   Greater,
12483   Unordered,
12484 };
12485 }
12486 
12487 template <class SuccessCB, class AfterCB>
12488 static bool
EvaluateComparisonBinaryOperator(EvalInfo & Info,const BinaryOperator * E,SuccessCB && Success,AfterCB && DoAfter)12489 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12490                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12491   assert(!E->isValueDependent());
12492   assert(E->isComparisonOp() && "expected comparison operator");
12493   assert((E->getOpcode() == BO_Cmp ||
12494           E->getType()->isIntegralOrEnumerationType()) &&
12495          "unsupported binary expression evaluation");
12496   auto Error = [&](const Expr *E) {
12497     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12498     return false;
12499   };
12500 
12501   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12502   bool IsEquality = E->isEqualityOp();
12503 
12504   QualType LHSTy = E->getLHS()->getType();
12505   QualType RHSTy = E->getRHS()->getType();
12506 
12507   if (LHSTy->isIntegralOrEnumerationType() &&
12508       RHSTy->isIntegralOrEnumerationType()) {
12509     APSInt LHS, RHS;
12510     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12511     if (!LHSOK && !Info.noteFailure())
12512       return false;
12513     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12514       return false;
12515     if (LHS < RHS)
12516       return Success(CmpResult::Less, E);
12517     if (LHS > RHS)
12518       return Success(CmpResult::Greater, E);
12519     return Success(CmpResult::Equal, E);
12520   }
12521 
12522   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12523     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12524     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12525 
12526     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12527     if (!LHSOK && !Info.noteFailure())
12528       return false;
12529     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12530       return false;
12531     if (LHSFX < RHSFX)
12532       return Success(CmpResult::Less, E);
12533     if (LHSFX > RHSFX)
12534       return Success(CmpResult::Greater, E);
12535     return Success(CmpResult::Equal, E);
12536   }
12537 
12538   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12539     ComplexValue LHS, RHS;
12540     bool LHSOK;
12541     if (E->isAssignmentOp()) {
12542       LValue LV;
12543       EvaluateLValue(E->getLHS(), LV, Info);
12544       LHSOK = false;
12545     } else if (LHSTy->isRealFloatingType()) {
12546       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12547       if (LHSOK) {
12548         LHS.makeComplexFloat();
12549         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12550       }
12551     } else {
12552       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12553     }
12554     if (!LHSOK && !Info.noteFailure())
12555       return false;
12556 
12557     if (E->getRHS()->getType()->isRealFloatingType()) {
12558       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12559         return false;
12560       RHS.makeComplexFloat();
12561       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12562     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12563       return false;
12564 
12565     if (LHS.isComplexFloat()) {
12566       APFloat::cmpResult CR_r =
12567         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12568       APFloat::cmpResult CR_i =
12569         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12570       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12571       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12572     } else {
12573       assert(IsEquality && "invalid complex comparison");
12574       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12575                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12576       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12577     }
12578   }
12579 
12580   if (LHSTy->isRealFloatingType() &&
12581       RHSTy->isRealFloatingType()) {
12582     APFloat RHS(0.0), LHS(0.0);
12583 
12584     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12585     if (!LHSOK && !Info.noteFailure())
12586       return false;
12587 
12588     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12589       return false;
12590 
12591     assert(E->isComparisonOp() && "Invalid binary operator!");
12592     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12593     if (!Info.InConstantContext &&
12594         APFloatCmpResult == APFloat::cmpUnordered &&
12595         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12596       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12597       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12598       return false;
12599     }
12600     auto GetCmpRes = [&]() {
12601       switch (APFloatCmpResult) {
12602       case APFloat::cmpEqual:
12603         return CmpResult::Equal;
12604       case APFloat::cmpLessThan:
12605         return CmpResult::Less;
12606       case APFloat::cmpGreaterThan:
12607         return CmpResult::Greater;
12608       case APFloat::cmpUnordered:
12609         return CmpResult::Unordered;
12610       }
12611       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12612     };
12613     return Success(GetCmpRes(), E);
12614   }
12615 
12616   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12617     LValue LHSValue, RHSValue;
12618 
12619     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12620     if (!LHSOK && !Info.noteFailure())
12621       return false;
12622 
12623     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12624       return false;
12625 
12626     // Reject differing bases from the normal codepath; we special-case
12627     // comparisons to null.
12628     if (!HasSameBase(LHSValue, RHSValue)) {
12629       // Inequalities and subtractions between unrelated pointers have
12630       // unspecified or undefined behavior.
12631       if (!IsEquality) {
12632         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12633         return false;
12634       }
12635       // A constant address may compare equal to the address of a symbol.
12636       // The one exception is that address of an object cannot compare equal
12637       // to a null pointer constant.
12638       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12639           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12640         return Error(E);
12641       // It's implementation-defined whether distinct literals will have
12642       // distinct addresses. In clang, the result of such a comparison is
12643       // unspecified, so it is not a constant expression. However, we do know
12644       // that the address of a literal will be non-null.
12645       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12646           LHSValue.Base && RHSValue.Base)
12647         return Error(E);
12648       // We can't tell whether weak symbols will end up pointing to the same
12649       // object.
12650       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12651         return Error(E);
12652       // We can't compare the address of the start of one object with the
12653       // past-the-end address of another object, per C++ DR1652.
12654       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12655            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12656           (RHSValue.Base && RHSValue.Offset.isZero() &&
12657            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12658         return Error(E);
12659       // We can't tell whether an object is at the same address as another
12660       // zero sized object.
12661       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12662           (LHSValue.Base && isZeroSized(RHSValue)))
12663         return Error(E);
12664       return Success(CmpResult::Unequal, E);
12665     }
12666 
12667     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12668     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12669 
12670     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12671     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12672 
12673     // C++11 [expr.rel]p3:
12674     //   Pointers to void (after pointer conversions) can be compared, with a
12675     //   result defined as follows: If both pointers represent the same
12676     //   address or are both the null pointer value, the result is true if the
12677     //   operator is <= or >= and false otherwise; otherwise the result is
12678     //   unspecified.
12679     // We interpret this as applying to pointers to *cv* void.
12680     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12681       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12682 
12683     // C++11 [expr.rel]p2:
12684     // - If two pointers point to non-static data members of the same object,
12685     //   or to subobjects or array elements fo such members, recursively, the
12686     //   pointer to the later declared member compares greater provided the
12687     //   two members have the same access control and provided their class is
12688     //   not a union.
12689     //   [...]
12690     // - Otherwise pointer comparisons are unspecified.
12691     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12692       bool WasArrayIndex;
12693       unsigned Mismatch = FindDesignatorMismatch(
12694           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12695       // At the point where the designators diverge, the comparison has a
12696       // specified value if:
12697       //  - we are comparing array indices
12698       //  - we are comparing fields of a union, or fields with the same access
12699       // Otherwise, the result is unspecified and thus the comparison is not a
12700       // constant expression.
12701       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12702           Mismatch < RHSDesignator.Entries.size()) {
12703         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12704         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12705         if (!LF && !RF)
12706           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12707         else if (!LF)
12708           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12709               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12710               << RF->getParent() << RF;
12711         else if (!RF)
12712           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12713               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12714               << LF->getParent() << LF;
12715         else if (!LF->getParent()->isUnion() &&
12716                  LF->getAccess() != RF->getAccess())
12717           Info.CCEDiag(E,
12718                        diag::note_constexpr_pointer_comparison_differing_access)
12719               << LF << LF->getAccess() << RF << RF->getAccess()
12720               << LF->getParent();
12721       }
12722     }
12723 
12724     // The comparison here must be unsigned, and performed with the same
12725     // width as the pointer.
12726     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12727     uint64_t CompareLHS = LHSOffset.getQuantity();
12728     uint64_t CompareRHS = RHSOffset.getQuantity();
12729     assert(PtrSize <= 64 && "Unexpected pointer width");
12730     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12731     CompareLHS &= Mask;
12732     CompareRHS &= Mask;
12733 
12734     // If there is a base and this is a relational operator, we can only
12735     // compare pointers within the object in question; otherwise, the result
12736     // depends on where the object is located in memory.
12737     if (!LHSValue.Base.isNull() && IsRelational) {
12738       QualType BaseTy = getType(LHSValue.Base);
12739       if (BaseTy->isIncompleteType())
12740         return Error(E);
12741       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12742       uint64_t OffsetLimit = Size.getQuantity();
12743       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12744         return Error(E);
12745     }
12746 
12747     if (CompareLHS < CompareRHS)
12748       return Success(CmpResult::Less, E);
12749     if (CompareLHS > CompareRHS)
12750       return Success(CmpResult::Greater, E);
12751     return Success(CmpResult::Equal, E);
12752   }
12753 
12754   if (LHSTy->isMemberPointerType()) {
12755     assert(IsEquality && "unexpected member pointer operation");
12756     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12757 
12758     MemberPtr LHSValue, RHSValue;
12759 
12760     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12761     if (!LHSOK && !Info.noteFailure())
12762       return false;
12763 
12764     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12765       return false;
12766 
12767     // C++11 [expr.eq]p2:
12768     //   If both operands are null, they compare equal. Otherwise if only one is
12769     //   null, they compare unequal.
12770     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12771       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12772       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12773     }
12774 
12775     //   Otherwise if either is a pointer to a virtual member function, the
12776     //   result is unspecified.
12777     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12778       if (MD->isVirtual())
12779         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12780     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12781       if (MD->isVirtual())
12782         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12783 
12784     //   Otherwise they compare equal if and only if they would refer to the
12785     //   same member of the same most derived object or the same subobject if
12786     //   they were dereferenced with a hypothetical object of the associated
12787     //   class type.
12788     bool Equal = LHSValue == RHSValue;
12789     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12790   }
12791 
12792   if (LHSTy->isNullPtrType()) {
12793     assert(E->isComparisonOp() && "unexpected nullptr operation");
12794     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12795     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12796     // are compared, the result is true of the operator is <=, >= or ==, and
12797     // false otherwise.
12798     return Success(CmpResult::Equal, E);
12799   }
12800 
12801   return DoAfter();
12802 }
12803 
VisitBinCmp(const BinaryOperator * E)12804 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12805   if (!CheckLiteralType(Info, E))
12806     return false;
12807 
12808   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12809     ComparisonCategoryResult CCR;
12810     switch (CR) {
12811     case CmpResult::Unequal:
12812       llvm_unreachable("should never produce Unequal for three-way comparison");
12813     case CmpResult::Less:
12814       CCR = ComparisonCategoryResult::Less;
12815       break;
12816     case CmpResult::Equal:
12817       CCR = ComparisonCategoryResult::Equal;
12818       break;
12819     case CmpResult::Greater:
12820       CCR = ComparisonCategoryResult::Greater;
12821       break;
12822     case CmpResult::Unordered:
12823       CCR = ComparisonCategoryResult::Unordered;
12824       break;
12825     }
12826     // Evaluation succeeded. Lookup the information for the comparison category
12827     // type and fetch the VarDecl for the result.
12828     const ComparisonCategoryInfo &CmpInfo =
12829         Info.Ctx.CompCategories.getInfoForType(E->getType());
12830     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12831     // Check and evaluate the result as a constant expression.
12832     LValue LV;
12833     LV.set(VD);
12834     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12835       return false;
12836     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12837                                    ConstantExprKind::Normal);
12838   };
12839   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12840     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12841   });
12842 }
12843 
VisitBinaryOperator(const BinaryOperator * E)12844 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12845   // We don't support assignment in C. C++ assignments don't get here because
12846   // assignment is an lvalue in C++.
12847   if (E->isAssignmentOp()) {
12848     Error(E);
12849     if (!Info.noteFailure())
12850       return false;
12851   }
12852 
12853   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12854     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12855 
12856   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12857           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12858          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12859 
12860   if (E->isComparisonOp()) {
12861     // Evaluate builtin binary comparisons by evaluating them as three-way
12862     // comparisons and then translating the result.
12863     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12864       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12865              "should only produce Unequal for equality comparisons");
12866       bool IsEqual   = CR == CmpResult::Equal,
12867            IsLess    = CR == CmpResult::Less,
12868            IsGreater = CR == CmpResult::Greater;
12869       auto Op = E->getOpcode();
12870       switch (Op) {
12871       default:
12872         llvm_unreachable("unsupported binary operator");
12873       case BO_EQ:
12874       case BO_NE:
12875         return Success(IsEqual == (Op == BO_EQ), E);
12876       case BO_LT:
12877         return Success(IsLess, E);
12878       case BO_GT:
12879         return Success(IsGreater, E);
12880       case BO_LE:
12881         return Success(IsEqual || IsLess, E);
12882       case BO_GE:
12883         return Success(IsEqual || IsGreater, E);
12884       }
12885     };
12886     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12887       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12888     });
12889   }
12890 
12891   QualType LHSTy = E->getLHS()->getType();
12892   QualType RHSTy = E->getRHS()->getType();
12893 
12894   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12895       E->getOpcode() == BO_Sub) {
12896     LValue LHSValue, RHSValue;
12897 
12898     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12899     if (!LHSOK && !Info.noteFailure())
12900       return false;
12901 
12902     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12903       return false;
12904 
12905     // Reject differing bases from the normal codepath; we special-case
12906     // comparisons to null.
12907     if (!HasSameBase(LHSValue, RHSValue)) {
12908       // Handle &&A - &&B.
12909       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12910         return Error(E);
12911       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12912       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12913       if (!LHSExpr || !RHSExpr)
12914         return Error(E);
12915       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12916       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12917       if (!LHSAddrExpr || !RHSAddrExpr)
12918         return Error(E);
12919       // Make sure both labels come from the same function.
12920       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12921           RHSAddrExpr->getLabel()->getDeclContext())
12922         return Error(E);
12923       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12924     }
12925     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12926     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12927 
12928     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12929     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12930 
12931     // C++11 [expr.add]p6:
12932     //   Unless both pointers point to elements of the same array object, or
12933     //   one past the last element of the array object, the behavior is
12934     //   undefined.
12935     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12936         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12937                                 RHSDesignator))
12938       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12939 
12940     QualType Type = E->getLHS()->getType();
12941     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12942 
12943     CharUnits ElementSize;
12944     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12945       return false;
12946 
12947     // As an extension, a type may have zero size (empty struct or union in
12948     // C, array of zero length). Pointer subtraction in such cases has
12949     // undefined behavior, so is not constant.
12950     if (ElementSize.isZero()) {
12951       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12952           << ElementType;
12953       return false;
12954     }
12955 
12956     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12957     // and produce incorrect results when it overflows. Such behavior
12958     // appears to be non-conforming, but is common, so perhaps we should
12959     // assume the standard intended for such cases to be undefined behavior
12960     // and check for them.
12961 
12962     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12963     // overflow in the final conversion to ptrdiff_t.
12964     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12965     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12966     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12967                     false);
12968     APSInt TrueResult = (LHS - RHS) / ElemSize;
12969     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12970 
12971     if (Result.extend(65) != TrueResult &&
12972         !HandleOverflow(Info, E, TrueResult, E->getType()))
12973       return false;
12974     return Success(Result, E);
12975   }
12976 
12977   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12978 }
12979 
12980 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12981 /// a result as the expression's type.
VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr * E)12982 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12983                                     const UnaryExprOrTypeTraitExpr *E) {
12984   switch(E->getKind()) {
12985   case UETT_PreferredAlignOf:
12986   case UETT_AlignOf: {
12987     if (E->isArgumentType())
12988       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12989                      E);
12990     else
12991       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12992                      E);
12993   }
12994 
12995   case UETT_VecStep: {
12996     QualType Ty = E->getTypeOfArgument();
12997 
12998     if (Ty->isVectorType()) {
12999       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13000 
13001       // The vec_step built-in functions that take a 3-component
13002       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13003       if (n == 3)
13004         n = 4;
13005 
13006       return Success(n, E);
13007     } else
13008       return Success(1, E);
13009   }
13010 
13011   case UETT_SizeOf: {
13012     QualType SrcTy = E->getTypeOfArgument();
13013     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13014     //   the result is the size of the referenced type."
13015     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13016       SrcTy = Ref->getPointeeType();
13017 
13018     CharUnits Sizeof;
13019     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13020       return false;
13021     return Success(Sizeof, E);
13022   }
13023   case UETT_OpenMPRequiredSimdAlign:
13024     assert(E->isArgumentType());
13025     return Success(
13026         Info.Ctx.toCharUnitsFromBits(
13027                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13028             .getQuantity(),
13029         E);
13030   }
13031 
13032   llvm_unreachable("unknown expr/type trait");
13033 }
13034 
VisitOffsetOfExpr(const OffsetOfExpr * OOE)13035 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13036   CharUnits Result;
13037   unsigned n = OOE->getNumComponents();
13038   if (n == 0)
13039     return Error(OOE);
13040   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13041   for (unsigned i = 0; i != n; ++i) {
13042     OffsetOfNode ON = OOE->getComponent(i);
13043     switch (ON.getKind()) {
13044     case OffsetOfNode::Array: {
13045       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13046       APSInt IdxResult;
13047       if (!EvaluateInteger(Idx, IdxResult, Info))
13048         return false;
13049       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13050       if (!AT)
13051         return Error(OOE);
13052       CurrentType = AT->getElementType();
13053       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13054       Result += IdxResult.getSExtValue() * ElementSize;
13055       break;
13056     }
13057 
13058     case OffsetOfNode::Field: {
13059       FieldDecl *MemberDecl = ON.getField();
13060       const RecordType *RT = CurrentType->getAs<RecordType>();
13061       if (!RT)
13062         return Error(OOE);
13063       RecordDecl *RD = RT->getDecl();
13064       if (RD->isInvalidDecl()) return false;
13065       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13066       unsigned i = MemberDecl->getFieldIndex();
13067       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13068       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13069       CurrentType = MemberDecl->getType().getNonReferenceType();
13070       break;
13071     }
13072 
13073     case OffsetOfNode::Identifier:
13074       llvm_unreachable("dependent __builtin_offsetof");
13075 
13076     case OffsetOfNode::Base: {
13077       CXXBaseSpecifier *BaseSpec = ON.getBase();
13078       if (BaseSpec->isVirtual())
13079         return Error(OOE);
13080 
13081       // Find the layout of the class whose base we are looking into.
13082       const RecordType *RT = CurrentType->getAs<RecordType>();
13083       if (!RT)
13084         return Error(OOE);
13085       RecordDecl *RD = RT->getDecl();
13086       if (RD->isInvalidDecl()) return false;
13087       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13088 
13089       // Find the base class itself.
13090       CurrentType = BaseSpec->getType();
13091       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13092       if (!BaseRT)
13093         return Error(OOE);
13094 
13095       // Add the offset to the base.
13096       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13097       break;
13098     }
13099     }
13100   }
13101   return Success(Result, OOE);
13102 }
13103 
VisitUnaryOperator(const UnaryOperator * E)13104 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13105   switch (E->getOpcode()) {
13106   default:
13107     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13108     // See C99 6.6p3.
13109     return Error(E);
13110   case UO_Extension:
13111     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13112     // If so, we could clear the diagnostic ID.
13113     return Visit(E->getSubExpr());
13114   case UO_Plus:
13115     // The result is just the value.
13116     return Visit(E->getSubExpr());
13117   case UO_Minus: {
13118     if (!Visit(E->getSubExpr()))
13119       return false;
13120     if (!Result.isInt()) return Error(E);
13121     const APSInt &Value = Result.getInt();
13122     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13123         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13124                         E->getType()))
13125       return false;
13126     return Success(-Value, E);
13127   }
13128   case UO_Not: {
13129     if (!Visit(E->getSubExpr()))
13130       return false;
13131     if (!Result.isInt()) return Error(E);
13132     return Success(~Result.getInt(), E);
13133   }
13134   case UO_LNot: {
13135     bool bres;
13136     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13137       return false;
13138     return Success(!bres, E);
13139   }
13140   }
13141 }
13142 
13143 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13144 /// result type is integer.
VisitCastExpr(const CastExpr * E)13145 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13146   const Expr *SubExpr = E->getSubExpr();
13147   QualType DestType = E->getType();
13148   QualType SrcType = SubExpr->getType();
13149 
13150   switch (E->getCastKind()) {
13151   case CK_BaseToDerived:
13152   case CK_DerivedToBase:
13153   case CK_UncheckedDerivedToBase:
13154   case CK_Dynamic:
13155   case CK_ToUnion:
13156   case CK_ArrayToPointerDecay:
13157   case CK_FunctionToPointerDecay:
13158   case CK_NullToPointer:
13159   case CK_NullToMemberPointer:
13160   case CK_BaseToDerivedMemberPointer:
13161   case CK_DerivedToBaseMemberPointer:
13162   case CK_ReinterpretMemberPointer:
13163   case CK_ConstructorConversion:
13164   case CK_IntegralToPointer:
13165   case CK_ToVoid:
13166   case CK_VectorSplat:
13167   case CK_IntegralToFloating:
13168   case CK_FloatingCast:
13169   case CK_CPointerToObjCPointerCast:
13170   case CK_BlockPointerToObjCPointerCast:
13171   case CK_AnyPointerToBlockPointerCast:
13172   case CK_ObjCObjectLValueCast:
13173   case CK_FloatingRealToComplex:
13174   case CK_FloatingComplexToReal:
13175   case CK_FloatingComplexCast:
13176   case CK_FloatingComplexToIntegralComplex:
13177   case CK_IntegralRealToComplex:
13178   case CK_IntegralComplexCast:
13179   case CK_IntegralComplexToFloatingComplex:
13180   case CK_BuiltinFnToFnPtr:
13181   case CK_ZeroToOCLOpaqueType:
13182   case CK_NonAtomicToAtomic:
13183   case CK_AddressSpaceConversion:
13184   case CK_IntToOCLSampler:
13185   case CK_FloatingToFixedPoint:
13186   case CK_FixedPointToFloating:
13187   case CK_FixedPointCast:
13188   case CK_IntegralToFixedPoint:
13189   case CK_MatrixCast:
13190     llvm_unreachable("invalid cast kind for integral value");
13191 
13192   case CK_BitCast:
13193   case CK_Dependent:
13194   case CK_LValueBitCast:
13195   case CK_ARCProduceObject:
13196   case CK_ARCConsumeObject:
13197   case CK_ARCReclaimReturnedObject:
13198   case CK_ARCExtendBlockObject:
13199   case CK_CopyAndAutoreleaseBlockObject:
13200     return Error(E);
13201 
13202   case CK_UserDefinedConversion:
13203   case CK_LValueToRValue:
13204   case CK_AtomicToNonAtomic:
13205   case CK_NoOp:
13206   case CK_LValueToRValueBitCast:
13207     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13208 
13209   case CK_MemberPointerToBoolean:
13210   case CK_PointerToBoolean:
13211   case CK_IntegralToBoolean:
13212   case CK_FloatingToBoolean:
13213   case CK_BooleanToSignedIntegral:
13214   case CK_FloatingComplexToBoolean:
13215   case CK_IntegralComplexToBoolean: {
13216     bool BoolResult;
13217     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13218       return false;
13219     uint64_t IntResult = BoolResult;
13220     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13221       IntResult = (uint64_t)-1;
13222     return Success(IntResult, E);
13223   }
13224 
13225   case CK_FixedPointToIntegral: {
13226     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13227     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13228       return false;
13229     bool Overflowed;
13230     llvm::APSInt Result = Src.convertToInt(
13231         Info.Ctx.getIntWidth(DestType),
13232         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13233     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13234       return false;
13235     return Success(Result, E);
13236   }
13237 
13238   case CK_FixedPointToBoolean: {
13239     // Unsigned padding does not affect this.
13240     APValue Val;
13241     if (!Evaluate(Val, Info, SubExpr))
13242       return false;
13243     return Success(Val.getFixedPoint().getBoolValue(), E);
13244   }
13245 
13246   case CK_IntegralCast: {
13247     if (!Visit(SubExpr))
13248       return false;
13249 
13250     if (!Result.isInt()) {
13251       // Allow casts of address-of-label differences if they are no-ops
13252       // or narrowing.  (The narrowing case isn't actually guaranteed to
13253       // be constant-evaluatable except in some narrow cases which are hard
13254       // to detect here.  We let it through on the assumption the user knows
13255       // what they are doing.)
13256       if (Result.isAddrLabelDiff())
13257         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13258       // Only allow casts of lvalues if they are lossless.
13259       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13260     }
13261 
13262     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13263                                       Result.getInt()), E);
13264   }
13265 
13266   case CK_PointerToIntegral: {
13267     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13268 
13269     LValue LV;
13270     if (!EvaluatePointer(SubExpr, LV, Info))
13271       return false;
13272 
13273     if (LV.getLValueBase()) {
13274       // Only allow based lvalue casts if they are lossless.
13275       // FIXME: Allow a larger integer size than the pointer size, and allow
13276       // narrowing back down to pointer width in subsequent integral casts.
13277       // FIXME: Check integer type's active bits, not its type size.
13278       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13279         return Error(E);
13280 
13281       LV.Designator.setInvalid();
13282       LV.moveInto(Result);
13283       return true;
13284     }
13285 
13286     APSInt AsInt;
13287     APValue V;
13288     LV.moveInto(V);
13289     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13290       llvm_unreachable("Can't cast this!");
13291 
13292     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13293   }
13294 
13295   case CK_IntegralComplexToReal: {
13296     ComplexValue C;
13297     if (!EvaluateComplex(SubExpr, C, Info))
13298       return false;
13299     return Success(C.getComplexIntReal(), E);
13300   }
13301 
13302   case CK_FloatingToIntegral: {
13303     APFloat F(0.0);
13304     if (!EvaluateFloat(SubExpr, F, Info))
13305       return false;
13306 
13307     APSInt Value;
13308     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13309       return false;
13310     return Success(Value, E);
13311   }
13312   }
13313 
13314   llvm_unreachable("unknown cast resulting in integral value");
13315 }
13316 
VisitUnaryReal(const UnaryOperator * E)13317 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13318   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13319     ComplexValue LV;
13320     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13321       return false;
13322     if (!LV.isComplexInt())
13323       return Error(E);
13324     return Success(LV.getComplexIntReal(), E);
13325   }
13326 
13327   return Visit(E->getSubExpr());
13328 }
13329 
VisitUnaryImag(const UnaryOperator * E)13330 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13331   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13332     ComplexValue LV;
13333     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13334       return false;
13335     if (!LV.isComplexInt())
13336       return Error(E);
13337     return Success(LV.getComplexIntImag(), E);
13338   }
13339 
13340   VisitIgnoredValue(E->getSubExpr());
13341   return Success(0, E);
13342 }
13343 
VisitSizeOfPackExpr(const SizeOfPackExpr * E)13344 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13345   return Success(E->getPackLength(), E);
13346 }
13347 
VisitCXXNoexceptExpr(const CXXNoexceptExpr * E)13348 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13349   return Success(E->getValue(), E);
13350 }
13351 
VisitConceptSpecializationExpr(const ConceptSpecializationExpr * E)13352 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13353        const ConceptSpecializationExpr *E) {
13354   return Success(E->isSatisfied(), E);
13355 }
13356 
VisitRequiresExpr(const RequiresExpr * E)13357 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13358   return Success(E->isSatisfied(), E);
13359 }
13360 
VisitUnaryOperator(const UnaryOperator * E)13361 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13362   switch (E->getOpcode()) {
13363     default:
13364       // Invalid unary operators
13365       return Error(E);
13366     case UO_Plus:
13367       // The result is just the value.
13368       return Visit(E->getSubExpr());
13369     case UO_Minus: {
13370       if (!Visit(E->getSubExpr())) return false;
13371       if (!Result.isFixedPoint())
13372         return Error(E);
13373       bool Overflowed;
13374       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13375       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13376         return false;
13377       return Success(Negated, E);
13378     }
13379     case UO_LNot: {
13380       bool bres;
13381       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13382         return false;
13383       return Success(!bres, E);
13384     }
13385   }
13386 }
13387 
VisitCastExpr(const CastExpr * E)13388 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13389   const Expr *SubExpr = E->getSubExpr();
13390   QualType DestType = E->getType();
13391   assert(DestType->isFixedPointType() &&
13392          "Expected destination type to be a fixed point type");
13393   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13394 
13395   switch (E->getCastKind()) {
13396   case CK_FixedPointCast: {
13397     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13398     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13399       return false;
13400     bool Overflowed;
13401     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13402     if (Overflowed) {
13403       if (Info.checkingForUndefinedBehavior())
13404         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13405                                          diag::warn_fixedpoint_constant_overflow)
13406           << Result.toString() << E->getType();
13407       if (!HandleOverflow(Info, E, Result, E->getType()))
13408         return false;
13409     }
13410     return Success(Result, E);
13411   }
13412   case CK_IntegralToFixedPoint: {
13413     APSInt Src;
13414     if (!EvaluateInteger(SubExpr, Src, Info))
13415       return false;
13416 
13417     bool Overflowed;
13418     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13419         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13420 
13421     if (Overflowed) {
13422       if (Info.checkingForUndefinedBehavior())
13423         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13424                                          diag::warn_fixedpoint_constant_overflow)
13425           << IntResult.toString() << E->getType();
13426       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13427         return false;
13428     }
13429 
13430     return Success(IntResult, E);
13431   }
13432   case CK_FloatingToFixedPoint: {
13433     APFloat Src(0.0);
13434     if (!EvaluateFloat(SubExpr, Src, Info))
13435       return false;
13436 
13437     bool Overflowed;
13438     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13439         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13440 
13441     if (Overflowed) {
13442       if (Info.checkingForUndefinedBehavior())
13443         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13444                                          diag::warn_fixedpoint_constant_overflow)
13445           << Result.toString() << E->getType();
13446       if (!HandleOverflow(Info, E, Result, E->getType()))
13447         return false;
13448     }
13449 
13450     return Success(Result, E);
13451   }
13452   case CK_NoOp:
13453   case CK_LValueToRValue:
13454     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13455   default:
13456     return Error(E);
13457   }
13458 }
13459 
VisitBinaryOperator(const BinaryOperator * E)13460 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13461   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13462     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13463 
13464   const Expr *LHS = E->getLHS();
13465   const Expr *RHS = E->getRHS();
13466   FixedPointSemantics ResultFXSema =
13467       Info.Ctx.getFixedPointSemantics(E->getType());
13468 
13469   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13470   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13471     return false;
13472   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13473   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13474     return false;
13475 
13476   bool OpOverflow = false, ConversionOverflow = false;
13477   APFixedPoint Result(LHSFX.getSemantics());
13478   switch (E->getOpcode()) {
13479   case BO_Add: {
13480     Result = LHSFX.add(RHSFX, &OpOverflow)
13481                   .convert(ResultFXSema, &ConversionOverflow);
13482     break;
13483   }
13484   case BO_Sub: {
13485     Result = LHSFX.sub(RHSFX, &OpOverflow)
13486                   .convert(ResultFXSema, &ConversionOverflow);
13487     break;
13488   }
13489   case BO_Mul: {
13490     Result = LHSFX.mul(RHSFX, &OpOverflow)
13491                   .convert(ResultFXSema, &ConversionOverflow);
13492     break;
13493   }
13494   case BO_Div: {
13495     if (RHSFX.getValue() == 0) {
13496       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13497       return false;
13498     }
13499     Result = LHSFX.div(RHSFX, &OpOverflow)
13500                   .convert(ResultFXSema, &ConversionOverflow);
13501     break;
13502   }
13503   case BO_Shl:
13504   case BO_Shr: {
13505     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13506     llvm::APSInt RHSVal = RHSFX.getValue();
13507 
13508     unsigned ShiftBW =
13509         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13510     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13511     // Embedded-C 4.1.6.2.2:
13512     //   The right operand must be nonnegative and less than the total number
13513     //   of (nonpadding) bits of the fixed-point operand ...
13514     if (RHSVal.isNegative())
13515       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13516     else if (Amt != RHSVal)
13517       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13518           << RHSVal << E->getType() << ShiftBW;
13519 
13520     if (E->getOpcode() == BO_Shl)
13521       Result = LHSFX.shl(Amt, &OpOverflow);
13522     else
13523       Result = LHSFX.shr(Amt, &OpOverflow);
13524     break;
13525   }
13526   default:
13527     return false;
13528   }
13529   if (OpOverflow || ConversionOverflow) {
13530     if (Info.checkingForUndefinedBehavior())
13531       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13532                                        diag::warn_fixedpoint_constant_overflow)
13533         << Result.toString() << E->getType();
13534     if (!HandleOverflow(Info, E, Result, E->getType()))
13535       return false;
13536   }
13537   return Success(Result, E);
13538 }
13539 
13540 //===----------------------------------------------------------------------===//
13541 // Float Evaluation
13542 //===----------------------------------------------------------------------===//
13543 
13544 namespace {
13545 class FloatExprEvaluator
13546   : public ExprEvaluatorBase<FloatExprEvaluator> {
13547   APFloat &Result;
13548 public:
FloatExprEvaluator(EvalInfo & info,APFloat & result)13549   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13550     : ExprEvaluatorBaseTy(info), Result(result) {}
13551 
Success(const APValue & V,const Expr * e)13552   bool Success(const APValue &V, const Expr *e) {
13553     Result = V.getFloat();
13554     return true;
13555   }
13556 
ZeroInitialization(const Expr * E)13557   bool ZeroInitialization(const Expr *E) {
13558     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13559     return true;
13560   }
13561 
13562   bool VisitCallExpr(const CallExpr *E);
13563 
13564   bool VisitUnaryOperator(const UnaryOperator *E);
13565   bool VisitBinaryOperator(const BinaryOperator *E);
13566   bool VisitFloatingLiteral(const FloatingLiteral *E);
13567   bool VisitCastExpr(const CastExpr *E);
13568 
13569   bool VisitUnaryReal(const UnaryOperator *E);
13570   bool VisitUnaryImag(const UnaryOperator *E);
13571 
13572   // FIXME: Missing: array subscript of vector, member of vector
13573 };
13574 } // end anonymous namespace
13575 
EvaluateFloat(const Expr * E,APFloat & Result,EvalInfo & Info)13576 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13577   assert(!E->isValueDependent());
13578   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13579   return FloatExprEvaluator(Info, Result).Visit(E);
13580 }
13581 
TryEvaluateBuiltinNaN(const ASTContext & Context,QualType ResultTy,const Expr * Arg,bool SNaN,llvm::APFloat & Result)13582 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13583                                   QualType ResultTy,
13584                                   const Expr *Arg,
13585                                   bool SNaN,
13586                                   llvm::APFloat &Result) {
13587   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13588   if (!S) return false;
13589 
13590   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13591 
13592   llvm::APInt fill;
13593 
13594   // Treat empty strings as if they were zero.
13595   if (S->getString().empty())
13596     fill = llvm::APInt(32, 0);
13597   else if (S->getString().getAsInteger(0, fill))
13598     return false;
13599 
13600   if (Context.getTargetInfo().isNan2008()) {
13601     if (SNaN)
13602       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13603     else
13604       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13605   } else {
13606     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13607     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13608     // a different encoding to what became a standard in 2008, and for pre-
13609     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13610     // sNaN. This is now known as "legacy NaN" encoding.
13611     if (SNaN)
13612       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13613     else
13614       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13615   }
13616 
13617   return true;
13618 }
13619 
VisitCallExpr(const CallExpr * E)13620 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13621   switch (E->getBuiltinCallee()) {
13622   default:
13623     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13624 
13625   case Builtin::BI__builtin_huge_val:
13626   case Builtin::BI__builtin_huge_valf:
13627   case Builtin::BI__builtin_huge_vall:
13628   case Builtin::BI__builtin_huge_valf128:
13629   case Builtin::BI__builtin_inf:
13630   case Builtin::BI__builtin_inff:
13631   case Builtin::BI__builtin_infl:
13632   case Builtin::BI__builtin_inff128: {
13633     const llvm::fltSemantics &Sem =
13634       Info.Ctx.getFloatTypeSemantics(E->getType());
13635     Result = llvm::APFloat::getInf(Sem);
13636     return true;
13637   }
13638 
13639   case Builtin::BI__builtin_nans:
13640   case Builtin::BI__builtin_nansf:
13641   case Builtin::BI__builtin_nansl:
13642   case Builtin::BI__builtin_nansf128:
13643     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13644                                true, Result))
13645       return Error(E);
13646     return true;
13647 
13648   case Builtin::BI__builtin_nan:
13649   case Builtin::BI__builtin_nanf:
13650   case Builtin::BI__builtin_nanl:
13651   case Builtin::BI__builtin_nanf128:
13652     // If this is __builtin_nan() turn this into a nan, otherwise we
13653     // can't constant fold it.
13654     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13655                                false, Result))
13656       return Error(E);
13657     return true;
13658 
13659   case Builtin::BI__builtin_fabs:
13660   case Builtin::BI__builtin_fabsf:
13661   case Builtin::BI__builtin_fabsl:
13662   case Builtin::BI__builtin_fabsf128:
13663     // The C standard says "fabs raises no floating-point exceptions,
13664     // even if x is a signaling NaN. The returned value is independent of
13665     // the current rounding direction mode."  Therefore constant folding can
13666     // proceed without regard to the floating point settings.
13667     // Reference, WG14 N2478 F.10.4.3
13668     if (!EvaluateFloat(E->getArg(0), Result, Info))
13669       return false;
13670 
13671     if (Result.isNegative())
13672       Result.changeSign();
13673     return true;
13674 
13675   case Builtin::BI__arithmetic_fence:
13676     return EvaluateFloat(E->getArg(0), Result, Info);
13677 
13678   // FIXME: Builtin::BI__builtin_powi
13679   // FIXME: Builtin::BI__builtin_powif
13680   // FIXME: Builtin::BI__builtin_powil
13681 
13682   case Builtin::BI__builtin_copysign:
13683   case Builtin::BI__builtin_copysignf:
13684   case Builtin::BI__builtin_copysignl:
13685   case Builtin::BI__builtin_copysignf128: {
13686     APFloat RHS(0.);
13687     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13688         !EvaluateFloat(E->getArg(1), RHS, Info))
13689       return false;
13690     Result.copySign(RHS);
13691     return true;
13692   }
13693   }
13694 }
13695 
VisitUnaryReal(const UnaryOperator * E)13696 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13697   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13698     ComplexValue CV;
13699     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13700       return false;
13701     Result = CV.FloatReal;
13702     return true;
13703   }
13704 
13705   return Visit(E->getSubExpr());
13706 }
13707 
VisitUnaryImag(const UnaryOperator * E)13708 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13709   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13710     ComplexValue CV;
13711     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13712       return false;
13713     Result = CV.FloatImag;
13714     return true;
13715   }
13716 
13717   VisitIgnoredValue(E->getSubExpr());
13718   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13719   Result = llvm::APFloat::getZero(Sem);
13720   return true;
13721 }
13722 
VisitUnaryOperator(const UnaryOperator * E)13723 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13724   switch (E->getOpcode()) {
13725   default: return Error(E);
13726   case UO_Plus:
13727     return EvaluateFloat(E->getSubExpr(), Result, Info);
13728   case UO_Minus:
13729     // In C standard, WG14 N2478 F.3 p4
13730     // "the unary - raises no floating point exceptions,
13731     // even if the operand is signalling."
13732     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13733       return false;
13734     Result.changeSign();
13735     return true;
13736   }
13737 }
13738 
VisitBinaryOperator(const BinaryOperator * E)13739 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13740   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13741     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13742 
13743   APFloat RHS(0.0);
13744   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13745   if (!LHSOK && !Info.noteFailure())
13746     return false;
13747   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13748          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13749 }
13750 
VisitFloatingLiteral(const FloatingLiteral * E)13751 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13752   Result = E->getValue();
13753   return true;
13754 }
13755 
VisitCastExpr(const CastExpr * E)13756 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13757   const Expr* SubExpr = E->getSubExpr();
13758 
13759   switch (E->getCastKind()) {
13760   default:
13761     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13762 
13763   case CK_IntegralToFloating: {
13764     APSInt IntResult;
13765     const FPOptions FPO = E->getFPFeaturesInEffect(
13766                                   Info.Ctx.getLangOpts());
13767     return EvaluateInteger(SubExpr, IntResult, Info) &&
13768            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13769                                 IntResult, E->getType(), Result);
13770   }
13771 
13772   case CK_FixedPointToFloating: {
13773     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13774     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13775       return false;
13776     Result =
13777         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13778     return true;
13779   }
13780 
13781   case CK_FloatingCast: {
13782     if (!Visit(SubExpr))
13783       return false;
13784     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13785                                   Result);
13786   }
13787 
13788   case CK_FloatingComplexToReal: {
13789     ComplexValue V;
13790     if (!EvaluateComplex(SubExpr, V, Info))
13791       return false;
13792     Result = V.getComplexFloatReal();
13793     return true;
13794   }
13795   }
13796 }
13797 
13798 //===----------------------------------------------------------------------===//
13799 // Complex Evaluation (for float and integer)
13800 //===----------------------------------------------------------------------===//
13801 
13802 namespace {
13803 class ComplexExprEvaluator
13804   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13805   ComplexValue &Result;
13806 
13807 public:
ComplexExprEvaluator(EvalInfo & info,ComplexValue & Result)13808   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13809     : ExprEvaluatorBaseTy(info), Result(Result) {}
13810 
Success(const APValue & V,const Expr * e)13811   bool Success(const APValue &V, const Expr *e) {
13812     Result.setFrom(V);
13813     return true;
13814   }
13815 
13816   bool ZeroInitialization(const Expr *E);
13817 
13818   //===--------------------------------------------------------------------===//
13819   //                            Visitor Methods
13820   //===--------------------------------------------------------------------===//
13821 
13822   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13823   bool VisitCastExpr(const CastExpr *E);
13824   bool VisitBinaryOperator(const BinaryOperator *E);
13825   bool VisitUnaryOperator(const UnaryOperator *E);
13826   bool VisitInitListExpr(const InitListExpr *E);
13827   bool VisitCallExpr(const CallExpr *E);
13828 };
13829 } // end anonymous namespace
13830 
EvaluateComplex(const Expr * E,ComplexValue & Result,EvalInfo & Info)13831 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13832                             EvalInfo &Info) {
13833   assert(!E->isValueDependent());
13834   assert(E->isPRValue() && E->getType()->isAnyComplexType());
13835   return ComplexExprEvaluator(Info, Result).Visit(E);
13836 }
13837 
ZeroInitialization(const Expr * E)13838 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13839   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13840   if (ElemTy->isRealFloatingType()) {
13841     Result.makeComplexFloat();
13842     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13843     Result.FloatReal = Zero;
13844     Result.FloatImag = Zero;
13845   } else {
13846     Result.makeComplexInt();
13847     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13848     Result.IntReal = Zero;
13849     Result.IntImag = Zero;
13850   }
13851   return true;
13852 }
13853 
VisitImaginaryLiteral(const ImaginaryLiteral * E)13854 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13855   const Expr* SubExpr = E->getSubExpr();
13856 
13857   if (SubExpr->getType()->isRealFloatingType()) {
13858     Result.makeComplexFloat();
13859     APFloat &Imag = Result.FloatImag;
13860     if (!EvaluateFloat(SubExpr, Imag, Info))
13861       return false;
13862 
13863     Result.FloatReal = APFloat(Imag.getSemantics());
13864     return true;
13865   } else {
13866     assert(SubExpr->getType()->isIntegerType() &&
13867            "Unexpected imaginary literal.");
13868 
13869     Result.makeComplexInt();
13870     APSInt &Imag = Result.IntImag;
13871     if (!EvaluateInteger(SubExpr, Imag, Info))
13872       return false;
13873 
13874     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13875     return true;
13876   }
13877 }
13878 
VisitCastExpr(const CastExpr * E)13879 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13880 
13881   switch (E->getCastKind()) {
13882   case CK_BitCast:
13883   case CK_BaseToDerived:
13884   case CK_DerivedToBase:
13885   case CK_UncheckedDerivedToBase:
13886   case CK_Dynamic:
13887   case CK_ToUnion:
13888   case CK_ArrayToPointerDecay:
13889   case CK_FunctionToPointerDecay:
13890   case CK_NullToPointer:
13891   case CK_NullToMemberPointer:
13892   case CK_BaseToDerivedMemberPointer:
13893   case CK_DerivedToBaseMemberPointer:
13894   case CK_MemberPointerToBoolean:
13895   case CK_ReinterpretMemberPointer:
13896   case CK_ConstructorConversion:
13897   case CK_IntegralToPointer:
13898   case CK_PointerToIntegral:
13899   case CK_PointerToBoolean:
13900   case CK_ToVoid:
13901   case CK_VectorSplat:
13902   case CK_IntegralCast:
13903   case CK_BooleanToSignedIntegral:
13904   case CK_IntegralToBoolean:
13905   case CK_IntegralToFloating:
13906   case CK_FloatingToIntegral:
13907   case CK_FloatingToBoolean:
13908   case CK_FloatingCast:
13909   case CK_CPointerToObjCPointerCast:
13910   case CK_BlockPointerToObjCPointerCast:
13911   case CK_AnyPointerToBlockPointerCast:
13912   case CK_ObjCObjectLValueCast:
13913   case CK_FloatingComplexToReal:
13914   case CK_FloatingComplexToBoolean:
13915   case CK_IntegralComplexToReal:
13916   case CK_IntegralComplexToBoolean:
13917   case CK_ARCProduceObject:
13918   case CK_ARCConsumeObject:
13919   case CK_ARCReclaimReturnedObject:
13920   case CK_ARCExtendBlockObject:
13921   case CK_CopyAndAutoreleaseBlockObject:
13922   case CK_BuiltinFnToFnPtr:
13923   case CK_ZeroToOCLOpaqueType:
13924   case CK_NonAtomicToAtomic:
13925   case CK_AddressSpaceConversion:
13926   case CK_IntToOCLSampler:
13927   case CK_FloatingToFixedPoint:
13928   case CK_FixedPointToFloating:
13929   case CK_FixedPointCast:
13930   case CK_FixedPointToBoolean:
13931   case CK_FixedPointToIntegral:
13932   case CK_IntegralToFixedPoint:
13933   case CK_MatrixCast:
13934     llvm_unreachable("invalid cast kind for complex value");
13935 
13936   case CK_LValueToRValue:
13937   case CK_AtomicToNonAtomic:
13938   case CK_NoOp:
13939   case CK_LValueToRValueBitCast:
13940     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13941 
13942   case CK_Dependent:
13943   case CK_LValueBitCast:
13944   case CK_UserDefinedConversion:
13945     return Error(E);
13946 
13947   case CK_FloatingRealToComplex: {
13948     APFloat &Real = Result.FloatReal;
13949     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13950       return false;
13951 
13952     Result.makeComplexFloat();
13953     Result.FloatImag = APFloat(Real.getSemantics());
13954     return true;
13955   }
13956 
13957   case CK_FloatingComplexCast: {
13958     if (!Visit(E->getSubExpr()))
13959       return false;
13960 
13961     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13962     QualType From
13963       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13964 
13965     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13966            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13967   }
13968 
13969   case CK_FloatingComplexToIntegralComplex: {
13970     if (!Visit(E->getSubExpr()))
13971       return false;
13972 
13973     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13974     QualType From
13975       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13976     Result.makeComplexInt();
13977     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13978                                 To, Result.IntReal) &&
13979            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13980                                 To, Result.IntImag);
13981   }
13982 
13983   case CK_IntegralRealToComplex: {
13984     APSInt &Real = Result.IntReal;
13985     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13986       return false;
13987 
13988     Result.makeComplexInt();
13989     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13990     return true;
13991   }
13992 
13993   case CK_IntegralComplexCast: {
13994     if (!Visit(E->getSubExpr()))
13995       return false;
13996 
13997     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13998     QualType From
13999       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14000 
14001     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14002     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14003     return true;
14004   }
14005 
14006   case CK_IntegralComplexToFloatingComplex: {
14007     if (!Visit(E->getSubExpr()))
14008       return false;
14009 
14010     const FPOptions FPO = E->getFPFeaturesInEffect(
14011                                   Info.Ctx.getLangOpts());
14012     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14013     QualType From
14014       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14015     Result.makeComplexFloat();
14016     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14017                                 To, Result.FloatReal) &&
14018            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14019                                 To, Result.FloatImag);
14020   }
14021   }
14022 
14023   llvm_unreachable("unknown cast resulting in complex value");
14024 }
14025 
VisitBinaryOperator(const BinaryOperator * E)14026 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14027   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14028     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14029 
14030   // Track whether the LHS or RHS is real at the type system level. When this is
14031   // the case we can simplify our evaluation strategy.
14032   bool LHSReal = false, RHSReal = false;
14033 
14034   bool LHSOK;
14035   if (E->getLHS()->getType()->isRealFloatingType()) {
14036     LHSReal = true;
14037     APFloat &Real = Result.FloatReal;
14038     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14039     if (LHSOK) {
14040       Result.makeComplexFloat();
14041       Result.FloatImag = APFloat(Real.getSemantics());
14042     }
14043   } else {
14044     LHSOK = Visit(E->getLHS());
14045   }
14046   if (!LHSOK && !Info.noteFailure())
14047     return false;
14048 
14049   ComplexValue RHS;
14050   if (E->getRHS()->getType()->isRealFloatingType()) {
14051     RHSReal = true;
14052     APFloat &Real = RHS.FloatReal;
14053     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14054       return false;
14055     RHS.makeComplexFloat();
14056     RHS.FloatImag = APFloat(Real.getSemantics());
14057   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14058     return false;
14059 
14060   assert(!(LHSReal && RHSReal) &&
14061          "Cannot have both operands of a complex operation be real.");
14062   switch (E->getOpcode()) {
14063   default: return Error(E);
14064   case BO_Add:
14065     if (Result.isComplexFloat()) {
14066       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14067                                        APFloat::rmNearestTiesToEven);
14068       if (LHSReal)
14069         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14070       else if (!RHSReal)
14071         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14072                                          APFloat::rmNearestTiesToEven);
14073     } else {
14074       Result.getComplexIntReal() += RHS.getComplexIntReal();
14075       Result.getComplexIntImag() += RHS.getComplexIntImag();
14076     }
14077     break;
14078   case BO_Sub:
14079     if (Result.isComplexFloat()) {
14080       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14081                                             APFloat::rmNearestTiesToEven);
14082       if (LHSReal) {
14083         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14084         Result.getComplexFloatImag().changeSign();
14085       } else if (!RHSReal) {
14086         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14087                                               APFloat::rmNearestTiesToEven);
14088       }
14089     } else {
14090       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14091       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14092     }
14093     break;
14094   case BO_Mul:
14095     if (Result.isComplexFloat()) {
14096       // This is an implementation of complex multiplication according to the
14097       // constraints laid out in C11 Annex G. The implementation uses the
14098       // following naming scheme:
14099       //   (a + ib) * (c + id)
14100       ComplexValue LHS = Result;
14101       APFloat &A = LHS.getComplexFloatReal();
14102       APFloat &B = LHS.getComplexFloatImag();
14103       APFloat &C = RHS.getComplexFloatReal();
14104       APFloat &D = RHS.getComplexFloatImag();
14105       APFloat &ResR = Result.getComplexFloatReal();
14106       APFloat &ResI = Result.getComplexFloatImag();
14107       if (LHSReal) {
14108         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14109         ResR = A * C;
14110         ResI = A * D;
14111       } else if (RHSReal) {
14112         ResR = C * A;
14113         ResI = C * B;
14114       } else {
14115         // In the fully general case, we need to handle NaNs and infinities
14116         // robustly.
14117         APFloat AC = A * C;
14118         APFloat BD = B * D;
14119         APFloat AD = A * D;
14120         APFloat BC = B * C;
14121         ResR = AC - BD;
14122         ResI = AD + BC;
14123         if (ResR.isNaN() && ResI.isNaN()) {
14124           bool Recalc = false;
14125           if (A.isInfinity() || B.isInfinity()) {
14126             A = APFloat::copySign(
14127                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14128             B = APFloat::copySign(
14129                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14130             if (C.isNaN())
14131               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14132             if (D.isNaN())
14133               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14134             Recalc = true;
14135           }
14136           if (C.isInfinity() || D.isInfinity()) {
14137             C = APFloat::copySign(
14138                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14139             D = APFloat::copySign(
14140                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14141             if (A.isNaN())
14142               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14143             if (B.isNaN())
14144               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14145             Recalc = true;
14146           }
14147           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14148                           AD.isInfinity() || BC.isInfinity())) {
14149             if (A.isNaN())
14150               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14151             if (B.isNaN())
14152               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14153             if (C.isNaN())
14154               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14155             if (D.isNaN())
14156               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14157             Recalc = true;
14158           }
14159           if (Recalc) {
14160             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14161             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14162           }
14163         }
14164       }
14165     } else {
14166       ComplexValue LHS = Result;
14167       Result.getComplexIntReal() =
14168         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14169          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14170       Result.getComplexIntImag() =
14171         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14172          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14173     }
14174     break;
14175   case BO_Div:
14176     if (Result.isComplexFloat()) {
14177       // This is an implementation of complex division according to the
14178       // constraints laid out in C11 Annex G. The implementation uses the
14179       // following naming scheme:
14180       //   (a + ib) / (c + id)
14181       ComplexValue LHS = Result;
14182       APFloat &A = LHS.getComplexFloatReal();
14183       APFloat &B = LHS.getComplexFloatImag();
14184       APFloat &C = RHS.getComplexFloatReal();
14185       APFloat &D = RHS.getComplexFloatImag();
14186       APFloat &ResR = Result.getComplexFloatReal();
14187       APFloat &ResI = Result.getComplexFloatImag();
14188       if (RHSReal) {
14189         ResR = A / C;
14190         ResI = B / C;
14191       } else {
14192         if (LHSReal) {
14193           // No real optimizations we can do here, stub out with zero.
14194           B = APFloat::getZero(A.getSemantics());
14195         }
14196         int DenomLogB = 0;
14197         APFloat MaxCD = maxnum(abs(C), abs(D));
14198         if (MaxCD.isFinite()) {
14199           DenomLogB = ilogb(MaxCD);
14200           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14201           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14202         }
14203         APFloat Denom = C * C + D * D;
14204         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14205                       APFloat::rmNearestTiesToEven);
14206         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14207                       APFloat::rmNearestTiesToEven);
14208         if (ResR.isNaN() && ResI.isNaN()) {
14209           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14210             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14211             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14212           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14213                      D.isFinite()) {
14214             A = APFloat::copySign(
14215                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14216             B = APFloat::copySign(
14217                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14218             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14219             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14220           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14221             C = APFloat::copySign(
14222                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14223             D = APFloat::copySign(
14224                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14225             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14226             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14227           }
14228         }
14229       }
14230     } else {
14231       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14232         return Error(E, diag::note_expr_divide_by_zero);
14233 
14234       ComplexValue LHS = Result;
14235       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14236         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14237       Result.getComplexIntReal() =
14238         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14239          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14240       Result.getComplexIntImag() =
14241         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14242          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14243     }
14244     break;
14245   }
14246 
14247   return true;
14248 }
14249 
VisitUnaryOperator(const UnaryOperator * E)14250 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14251   // Get the operand value into 'Result'.
14252   if (!Visit(E->getSubExpr()))
14253     return false;
14254 
14255   switch (E->getOpcode()) {
14256   default:
14257     return Error(E);
14258   case UO_Extension:
14259     return true;
14260   case UO_Plus:
14261     // The result is always just the subexpr.
14262     return true;
14263   case UO_Minus:
14264     if (Result.isComplexFloat()) {
14265       Result.getComplexFloatReal().changeSign();
14266       Result.getComplexFloatImag().changeSign();
14267     }
14268     else {
14269       Result.getComplexIntReal() = -Result.getComplexIntReal();
14270       Result.getComplexIntImag() = -Result.getComplexIntImag();
14271     }
14272     return true;
14273   case UO_Not:
14274     if (Result.isComplexFloat())
14275       Result.getComplexFloatImag().changeSign();
14276     else
14277       Result.getComplexIntImag() = -Result.getComplexIntImag();
14278     return true;
14279   }
14280 }
14281 
VisitInitListExpr(const InitListExpr * E)14282 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14283   if (E->getNumInits() == 2) {
14284     if (E->getType()->isComplexType()) {
14285       Result.makeComplexFloat();
14286       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14287         return false;
14288       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14289         return false;
14290     } else {
14291       Result.makeComplexInt();
14292       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14293         return false;
14294       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14295         return false;
14296     }
14297     return true;
14298   }
14299   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14300 }
14301 
VisitCallExpr(const CallExpr * E)14302 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14303   switch (E->getBuiltinCallee()) {
14304   case Builtin::BI__builtin_complex:
14305     Result.makeComplexFloat();
14306     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14307       return false;
14308     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14309       return false;
14310     return true;
14311 
14312   default:
14313     break;
14314   }
14315 
14316   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14317 }
14318 
14319 //===----------------------------------------------------------------------===//
14320 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14321 // implicit conversion.
14322 //===----------------------------------------------------------------------===//
14323 
14324 namespace {
14325 class AtomicExprEvaluator :
14326     public ExprEvaluatorBase<AtomicExprEvaluator> {
14327   const LValue *This;
14328   APValue &Result;
14329 public:
AtomicExprEvaluator(EvalInfo & Info,const LValue * This,APValue & Result)14330   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14331       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14332 
Success(const APValue & V,const Expr * E)14333   bool Success(const APValue &V, const Expr *E) {
14334     Result = V;
14335     return true;
14336   }
14337 
ZeroInitialization(const Expr * E)14338   bool ZeroInitialization(const Expr *E) {
14339     ImplicitValueInitExpr VIE(
14340         E->getType()->castAs<AtomicType>()->getValueType());
14341     // For atomic-qualified class (and array) types in C++, initialize the
14342     // _Atomic-wrapped subobject directly, in-place.
14343     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14344                 : Evaluate(Result, Info, &VIE);
14345   }
14346 
VisitCastExpr(const CastExpr * E)14347   bool VisitCastExpr(const CastExpr *E) {
14348     switch (E->getCastKind()) {
14349     default:
14350       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14351     case CK_NonAtomicToAtomic:
14352       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14353                   : Evaluate(Result, Info, E->getSubExpr());
14354     }
14355   }
14356 };
14357 } // end anonymous namespace
14358 
EvaluateAtomic(const Expr * E,const LValue * This,APValue & Result,EvalInfo & Info)14359 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14360                            EvalInfo &Info) {
14361   assert(!E->isValueDependent());
14362   assert(E->isPRValue() && E->getType()->isAtomicType());
14363   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14364 }
14365 
14366 //===----------------------------------------------------------------------===//
14367 // Void expression evaluation, primarily for a cast to void on the LHS of a
14368 // comma operator
14369 //===----------------------------------------------------------------------===//
14370 
14371 namespace {
14372 class VoidExprEvaluator
14373   : public ExprEvaluatorBase<VoidExprEvaluator> {
14374 public:
VoidExprEvaluator(EvalInfo & Info)14375   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14376 
Success(const APValue & V,const Expr * e)14377   bool Success(const APValue &V, const Expr *e) { return true; }
14378 
ZeroInitialization(const Expr * E)14379   bool ZeroInitialization(const Expr *E) { return true; }
14380 
VisitCastExpr(const CastExpr * E)14381   bool VisitCastExpr(const CastExpr *E) {
14382     switch (E->getCastKind()) {
14383     default:
14384       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14385     case CK_ToVoid:
14386       VisitIgnoredValue(E->getSubExpr());
14387       return true;
14388     }
14389   }
14390 
VisitCallExpr(const CallExpr * E)14391   bool VisitCallExpr(const CallExpr *E) {
14392     switch (E->getBuiltinCallee()) {
14393     case Builtin::BI__assume:
14394     case Builtin::BI__builtin_assume:
14395       // The argument is not evaluated!
14396       return true;
14397 
14398     case Builtin::BI__builtin_operator_delete:
14399       return HandleOperatorDeleteCall(Info, E);
14400 
14401     default:
14402       break;
14403     }
14404 
14405     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14406   }
14407 
14408   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14409 };
14410 } // end anonymous namespace
14411 
VisitCXXDeleteExpr(const CXXDeleteExpr * E)14412 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14413   // We cannot speculatively evaluate a delete expression.
14414   if (Info.SpeculativeEvaluationDepth)
14415     return false;
14416 
14417   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14418   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14419     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14420         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14421     return false;
14422   }
14423 
14424   const Expr *Arg = E->getArgument();
14425 
14426   LValue Pointer;
14427   if (!EvaluatePointer(Arg, Pointer, Info))
14428     return false;
14429   if (Pointer.Designator.Invalid)
14430     return false;
14431 
14432   // Deleting a null pointer has no effect.
14433   if (Pointer.isNullPointer()) {
14434     // This is the only case where we need to produce an extension warning:
14435     // the only other way we can succeed is if we find a dynamic allocation,
14436     // and we will have warned when we allocated it in that case.
14437     if (!Info.getLangOpts().CPlusPlus20)
14438       Info.CCEDiag(E, diag::note_constexpr_new);
14439     return true;
14440   }
14441 
14442   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14443       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14444   if (!Alloc)
14445     return false;
14446   QualType AllocType = Pointer.Base.getDynamicAllocType();
14447 
14448   // For the non-array case, the designator must be empty if the static type
14449   // does not have a virtual destructor.
14450   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14451       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14452     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14453         << Arg->getType()->getPointeeType() << AllocType;
14454     return false;
14455   }
14456 
14457   // For a class type with a virtual destructor, the selected operator delete
14458   // is the one looked up when building the destructor.
14459   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14460     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14461     if (VirtualDelete &&
14462         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14463       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14464           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14465       return false;
14466     }
14467   }
14468 
14469   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14470                          (*Alloc)->Value, AllocType))
14471     return false;
14472 
14473   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14474     // The element was already erased. This means the destructor call also
14475     // deleted the object.
14476     // FIXME: This probably results in undefined behavior before we get this
14477     // far, and should be diagnosed elsewhere first.
14478     Info.FFDiag(E, diag::note_constexpr_double_delete);
14479     return false;
14480   }
14481 
14482   return true;
14483 }
14484 
EvaluateVoid(const Expr * E,EvalInfo & Info)14485 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14486   assert(!E->isValueDependent());
14487   assert(E->isPRValue() && E->getType()->isVoidType());
14488   return VoidExprEvaluator(Info).Visit(E);
14489 }
14490 
14491 //===----------------------------------------------------------------------===//
14492 // Top level Expr::EvaluateAsRValue method.
14493 //===----------------------------------------------------------------------===//
14494 
Evaluate(APValue & Result,EvalInfo & Info,const Expr * E)14495 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14496   assert(!E->isValueDependent());
14497   // In C, function designators are not lvalues, but we evaluate them as if they
14498   // are.
14499   QualType T = E->getType();
14500   if (E->isGLValue() || T->isFunctionType()) {
14501     LValue LV;
14502     if (!EvaluateLValue(E, LV, Info))
14503       return false;
14504     LV.moveInto(Result);
14505   } else if (T->isVectorType()) {
14506     if (!EvaluateVector(E, Result, Info))
14507       return false;
14508   } else if (T->isIntegralOrEnumerationType()) {
14509     if (!IntExprEvaluator(Info, Result).Visit(E))
14510       return false;
14511   } else if (T->hasPointerRepresentation()) {
14512     LValue LV;
14513     if (!EvaluatePointer(E, LV, Info))
14514       return false;
14515     LV.moveInto(Result);
14516   } else if (T->isRealFloatingType()) {
14517     llvm::APFloat F(0.0);
14518     if (!EvaluateFloat(E, F, Info))
14519       return false;
14520     Result = APValue(F);
14521   } else if (T->isAnyComplexType()) {
14522     ComplexValue C;
14523     if (!EvaluateComplex(E, C, Info))
14524       return false;
14525     C.moveInto(Result);
14526   } else if (T->isFixedPointType()) {
14527     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14528   } else if (T->isMemberPointerType()) {
14529     MemberPtr P;
14530     if (!EvaluateMemberPointer(E, P, Info))
14531       return false;
14532     P.moveInto(Result);
14533     return true;
14534   } else if (T->isArrayType()) {
14535     LValue LV;
14536     APValue &Value =
14537         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14538     if (!EvaluateArray(E, LV, Value, Info))
14539       return false;
14540     Result = Value;
14541   } else if (T->isRecordType()) {
14542     LValue LV;
14543     APValue &Value =
14544         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14545     if (!EvaluateRecord(E, LV, Value, Info))
14546       return false;
14547     Result = Value;
14548   } else if (T->isVoidType()) {
14549     if (!Info.getLangOpts().CPlusPlus11)
14550       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14551         << E->getType();
14552     if (!EvaluateVoid(E, Info))
14553       return false;
14554   } else if (T->isAtomicType()) {
14555     QualType Unqual = T.getAtomicUnqualifiedType();
14556     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14557       LValue LV;
14558       APValue &Value = Info.CurrentCall->createTemporary(
14559           E, Unqual, ScopeKind::FullExpression, LV);
14560       if (!EvaluateAtomic(E, &LV, Value, Info))
14561         return false;
14562     } else {
14563       if (!EvaluateAtomic(E, nullptr, Result, Info))
14564         return false;
14565     }
14566   } else if (Info.getLangOpts().CPlusPlus11) {
14567     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14568     return false;
14569   } else {
14570     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14571     return false;
14572   }
14573 
14574   return true;
14575 }
14576 
14577 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14578 /// cases, the in-place evaluation is essential, since later initializers for
14579 /// an object can indirectly refer to subobjects which were initialized earlier.
EvaluateInPlace(APValue & Result,EvalInfo & Info,const LValue & This,const Expr * E,bool AllowNonLiteralTypes)14580 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14581                             const Expr *E, bool AllowNonLiteralTypes) {
14582   assert(!E->isValueDependent());
14583 
14584   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14585     return false;
14586 
14587   if (E->isPRValue()) {
14588     // Evaluate arrays and record types in-place, so that later initializers can
14589     // refer to earlier-initialized members of the object.
14590     QualType T = E->getType();
14591     if (T->isArrayType())
14592       return EvaluateArray(E, This, Result, Info);
14593     else if (T->isRecordType())
14594       return EvaluateRecord(E, This, Result, Info);
14595     else if (T->isAtomicType()) {
14596       QualType Unqual = T.getAtomicUnqualifiedType();
14597       if (Unqual->isArrayType() || Unqual->isRecordType())
14598         return EvaluateAtomic(E, &This, Result, Info);
14599     }
14600   }
14601 
14602   // For any other type, in-place evaluation is unimportant.
14603   return Evaluate(Result, Info, E);
14604 }
14605 
14606 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14607 /// lvalue-to-rvalue cast if it is an lvalue.
EvaluateAsRValue(EvalInfo & Info,const Expr * E,APValue & Result)14608 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14609   assert(!E->isValueDependent());
14610   if (Info.EnableNewConstInterp) {
14611     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14612       return false;
14613   } else {
14614     if (E->getType().isNull())
14615       return false;
14616 
14617     if (!CheckLiteralType(Info, E))
14618       return false;
14619 
14620     if (!::Evaluate(Result, Info, E))
14621       return false;
14622 
14623     if (E->isGLValue()) {
14624       LValue LV;
14625       LV.setFrom(Info.Ctx, Result);
14626       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14627         return false;
14628     }
14629   }
14630 
14631   // Check this core constant expression is a constant expression.
14632   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14633                                  ConstantExprKind::Normal) &&
14634          CheckMemoryLeaks(Info);
14635 }
14636 
FastEvaluateAsRValue(const Expr * Exp,Expr::EvalResult & Result,const ASTContext & Ctx,bool & IsConst)14637 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14638                                  const ASTContext &Ctx, bool &IsConst) {
14639   // Fast-path evaluations of integer literals, since we sometimes see files
14640   // containing vast quantities of these.
14641   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14642     Result.Val = APValue(APSInt(L->getValue(),
14643                                 L->getType()->isUnsignedIntegerType()));
14644     IsConst = true;
14645     return true;
14646   }
14647 
14648   // This case should be rare, but we need to check it before we check on
14649   // the type below.
14650   if (Exp->getType().isNull()) {
14651     IsConst = false;
14652     return true;
14653   }
14654 
14655   // FIXME: Evaluating values of large array and record types can cause
14656   // performance problems. Only do so in C++11 for now.
14657   if (Exp->isPRValue() &&
14658       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14659       !Ctx.getLangOpts().CPlusPlus11) {
14660     IsConst = false;
14661     return true;
14662   }
14663   return false;
14664 }
14665 
hasUnacceptableSideEffect(Expr::EvalStatus & Result,Expr::SideEffectsKind SEK)14666 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14667                                       Expr::SideEffectsKind SEK) {
14668   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14669          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14670 }
14671 
EvaluateAsRValue(const Expr * E,Expr::EvalResult & Result,const ASTContext & Ctx,EvalInfo & Info)14672 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14673                              const ASTContext &Ctx, EvalInfo &Info) {
14674   assert(!E->isValueDependent());
14675   bool IsConst;
14676   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14677     return IsConst;
14678 
14679   return EvaluateAsRValue(Info, E, Result.Val);
14680 }
14681 
EvaluateAsInt(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)14682 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14683                           const ASTContext &Ctx,
14684                           Expr::SideEffectsKind AllowSideEffects,
14685                           EvalInfo &Info) {
14686   assert(!E->isValueDependent());
14687   if (!E->getType()->isIntegralOrEnumerationType())
14688     return false;
14689 
14690   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14691       !ExprResult.Val.isInt() ||
14692       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14693     return false;
14694 
14695   return true;
14696 }
14697 
EvaluateAsFixedPoint(const Expr * E,Expr::EvalResult & ExprResult,const ASTContext & Ctx,Expr::SideEffectsKind AllowSideEffects,EvalInfo & Info)14698 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14699                                  const ASTContext &Ctx,
14700                                  Expr::SideEffectsKind AllowSideEffects,
14701                                  EvalInfo &Info) {
14702   assert(!E->isValueDependent());
14703   if (!E->getType()->isFixedPointType())
14704     return false;
14705 
14706   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14707     return false;
14708 
14709   if (!ExprResult.Val.isFixedPoint() ||
14710       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14711     return false;
14712 
14713   return true;
14714 }
14715 
14716 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14717 /// any crazy technique (that has nothing to do with language standards) that
14718 /// we want to.  If this function returns true, it returns the folded constant
14719 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14720 /// will be applied to the result.
EvaluateAsRValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const14721 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14722                             bool InConstantContext) const {
14723   assert(!isValueDependent() &&
14724          "Expression evaluator can't be called on a dependent expression.");
14725   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14726   Info.InConstantContext = InConstantContext;
14727   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14728 }
14729 
EvaluateAsBooleanCondition(bool & Result,const ASTContext & Ctx,bool InConstantContext) const14730 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14731                                       bool InConstantContext) const {
14732   assert(!isValueDependent() &&
14733          "Expression evaluator can't be called on a dependent expression.");
14734   EvalResult Scratch;
14735   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14736          HandleConversionToBool(Scratch.Val, Result);
14737 }
14738 
EvaluateAsInt(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const14739 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14740                          SideEffectsKind AllowSideEffects,
14741                          bool InConstantContext) const {
14742   assert(!isValueDependent() &&
14743          "Expression evaluator can't be called on a dependent expression.");
14744   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14745   Info.InConstantContext = InConstantContext;
14746   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14747 }
14748 
EvaluateAsFixedPoint(EvalResult & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const14749 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14750                                 SideEffectsKind AllowSideEffects,
14751                                 bool InConstantContext) const {
14752   assert(!isValueDependent() &&
14753          "Expression evaluator can't be called on a dependent expression.");
14754   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14755   Info.InConstantContext = InConstantContext;
14756   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14757 }
14758 
EvaluateAsFloat(APFloat & Result,const ASTContext & Ctx,SideEffectsKind AllowSideEffects,bool InConstantContext) const14759 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14760                            SideEffectsKind AllowSideEffects,
14761                            bool InConstantContext) const {
14762   assert(!isValueDependent() &&
14763          "Expression evaluator can't be called on a dependent expression.");
14764 
14765   if (!getType()->isRealFloatingType())
14766     return false;
14767 
14768   EvalResult ExprResult;
14769   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14770       !ExprResult.Val.isFloat() ||
14771       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14772     return false;
14773 
14774   Result = ExprResult.Val.getFloat();
14775   return true;
14776 }
14777 
EvaluateAsLValue(EvalResult & Result,const ASTContext & Ctx,bool InConstantContext) const14778 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14779                             bool InConstantContext) const {
14780   assert(!isValueDependent() &&
14781          "Expression evaluator can't be called on a dependent expression.");
14782 
14783   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14784   Info.InConstantContext = InConstantContext;
14785   LValue LV;
14786   CheckedTemporaries CheckedTemps;
14787   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14788       Result.HasSideEffects ||
14789       !CheckLValueConstantExpression(Info, getExprLoc(),
14790                                      Ctx.getLValueReferenceType(getType()), LV,
14791                                      ConstantExprKind::Normal, CheckedTemps))
14792     return false;
14793 
14794   LV.moveInto(Result.Val);
14795   return true;
14796 }
14797 
EvaluateDestruction(const ASTContext & Ctx,APValue::LValueBase Base,APValue DestroyedValue,QualType Type,SourceLocation Loc,Expr::EvalStatus & EStatus,bool IsConstantDestruction)14798 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14799                                 APValue DestroyedValue, QualType Type,
14800                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
14801                                 bool IsConstantDestruction) {
14802   EvalInfo Info(Ctx, EStatus,
14803                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
14804                                       : EvalInfo::EM_ConstantFold);
14805   Info.setEvaluatingDecl(Base, DestroyedValue,
14806                          EvalInfo::EvaluatingDeclKind::Dtor);
14807   Info.InConstantContext = IsConstantDestruction;
14808 
14809   LValue LVal;
14810   LVal.set(Base);
14811 
14812   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14813       EStatus.HasSideEffects)
14814     return false;
14815 
14816   if (!Info.discardCleanups())
14817     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14818 
14819   return true;
14820 }
14821 
EvaluateAsConstantExpr(EvalResult & Result,const ASTContext & Ctx,ConstantExprKind Kind) const14822 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14823                                   ConstantExprKind Kind) const {
14824   assert(!isValueDependent() &&
14825          "Expression evaluator can't be called on a dependent expression.");
14826 
14827   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14828   EvalInfo Info(Ctx, Result, EM);
14829   Info.InConstantContext = true;
14830 
14831   // The type of the object we're initializing is 'const T' for a class NTTP.
14832   QualType T = getType();
14833   if (Kind == ConstantExprKind::ClassTemplateArgument)
14834     T.addConst();
14835 
14836   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14837   // represent the result of the evaluation. CheckConstantExpression ensures
14838   // this doesn't escape.
14839   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14840   APValue::LValueBase Base(&BaseMTE);
14841 
14842   Info.setEvaluatingDecl(Base, Result.Val);
14843   LValue LVal;
14844   LVal.set(Base);
14845 
14846   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14847     return false;
14848 
14849   if (!Info.discardCleanups())
14850     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14851 
14852   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14853                                Result.Val, Kind))
14854     return false;
14855   if (!CheckMemoryLeaks(Info))
14856     return false;
14857 
14858   // If this is a class template argument, it's required to have constant
14859   // destruction too.
14860   if (Kind == ConstantExprKind::ClassTemplateArgument &&
14861       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
14862                             true) ||
14863        Result.HasSideEffects)) {
14864     // FIXME: Prefix a note to indicate that the problem is lack of constant
14865     // destruction.
14866     return false;
14867   }
14868 
14869   return true;
14870 }
14871 
EvaluateAsInitializer(APValue & Value,const ASTContext & Ctx,const VarDecl * VD,SmallVectorImpl<PartialDiagnosticAt> & Notes,bool IsConstantInitialization) const14872 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14873                                  const VarDecl *VD,
14874                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
14875                                  bool IsConstantInitialization) const {
14876   assert(!isValueDependent() &&
14877          "Expression evaluator can't be called on a dependent expression.");
14878 
14879   // FIXME: Evaluating initializers for large array and record types can cause
14880   // performance problems. Only do so in C++11 for now.
14881   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14882       !Ctx.getLangOpts().CPlusPlus11)
14883     return false;
14884 
14885   Expr::EvalStatus EStatus;
14886   EStatus.Diag = &Notes;
14887 
14888   EvalInfo Info(Ctx, EStatus,
14889                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
14890                     ? EvalInfo::EM_ConstantExpression
14891                     : EvalInfo::EM_ConstantFold);
14892   Info.setEvaluatingDecl(VD, Value);
14893   Info.InConstantContext = IsConstantInitialization;
14894 
14895   SourceLocation DeclLoc = VD->getLocation();
14896   QualType DeclTy = VD->getType();
14897 
14898   if (Info.EnableNewConstInterp) {
14899     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14900     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14901       return false;
14902   } else {
14903     LValue LVal;
14904     LVal.set(VD);
14905 
14906     if (!EvaluateInPlace(Value, Info, LVal, this,
14907                          /*AllowNonLiteralTypes=*/true) ||
14908         EStatus.HasSideEffects)
14909       return false;
14910 
14911     // At this point, any lifetime-extended temporaries are completely
14912     // initialized.
14913     Info.performLifetimeExtension();
14914 
14915     if (!Info.discardCleanups())
14916       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14917   }
14918   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
14919                                  ConstantExprKind::Normal) &&
14920          CheckMemoryLeaks(Info);
14921 }
14922 
evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> & Notes) const14923 bool VarDecl::evaluateDestruction(
14924     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14925   Expr::EvalStatus EStatus;
14926   EStatus.Diag = &Notes;
14927 
14928   // Only treat the destruction as constant destruction if we formally have
14929   // constant initialization (or are usable in a constant expression).
14930   bool IsConstantDestruction = hasConstantInitialization();
14931 
14932   // Make a copy of the value for the destructor to mutate, if we know it.
14933   // Otherwise, treat the value as default-initialized; if the destructor works
14934   // anyway, then the destruction is constant (and must be essentially empty).
14935   APValue DestroyedValue;
14936   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14937     DestroyedValue = *getEvaluatedValue();
14938   else if (!getDefaultInitValue(getType(), DestroyedValue))
14939     return false;
14940 
14941   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
14942                            getType(), getLocation(), EStatus,
14943                            IsConstantDestruction) ||
14944       EStatus.HasSideEffects)
14945     return false;
14946 
14947   ensureEvaluatedStmt()->HasConstantDestruction = true;
14948   return true;
14949 }
14950 
14951 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14952 /// constant folded, but discard the result.
isEvaluatable(const ASTContext & Ctx,SideEffectsKind SEK) const14953 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14954   assert(!isValueDependent() &&
14955          "Expression evaluator can't be called on a dependent expression.");
14956 
14957   EvalResult Result;
14958   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14959          !hasUnacceptableSideEffect(Result, SEK);
14960 }
14961 
EvaluateKnownConstInt(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const14962 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14963                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14964   assert(!isValueDependent() &&
14965          "Expression evaluator can't be called on a dependent expression.");
14966 
14967   EvalResult EVResult;
14968   EVResult.Diag = Diag;
14969   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14970   Info.InConstantContext = true;
14971 
14972   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14973   (void)Result;
14974   assert(Result && "Could not evaluate expression");
14975   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14976 
14977   return EVResult.Val.getInt();
14978 }
14979 
EvaluateKnownConstIntCheckOverflow(const ASTContext & Ctx,SmallVectorImpl<PartialDiagnosticAt> * Diag) const14980 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14981     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14982   assert(!isValueDependent() &&
14983          "Expression evaluator can't be called on a dependent expression.");
14984 
14985   EvalResult EVResult;
14986   EVResult.Diag = Diag;
14987   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14988   Info.InConstantContext = true;
14989   Info.CheckingForUndefinedBehavior = true;
14990 
14991   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14992   (void)Result;
14993   assert(Result && "Could not evaluate expression");
14994   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14995 
14996   return EVResult.Val.getInt();
14997 }
14998 
EvaluateForOverflow(const ASTContext & Ctx) const14999 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15000   assert(!isValueDependent() &&
15001          "Expression evaluator can't be called on a dependent expression.");
15002 
15003   bool IsConst;
15004   EvalResult EVResult;
15005   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15006     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15007     Info.CheckingForUndefinedBehavior = true;
15008     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15009   }
15010 }
15011 
isGlobalLValue() const15012 bool Expr::EvalResult::isGlobalLValue() const {
15013   assert(Val.isLValue());
15014   return IsGlobalLValue(Val.getLValueBase());
15015 }
15016 
15017 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15018 /// an integer constant expression.
15019 
15020 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15021 /// comma, etc
15022 
15023 // CheckICE - This function does the fundamental ICE checking: the returned
15024 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15025 // and a (possibly null) SourceLocation indicating the location of the problem.
15026 //
15027 // Note that to reduce code duplication, this helper does no evaluation
15028 // itself; the caller checks whether the expression is evaluatable, and
15029 // in the rare cases where CheckICE actually cares about the evaluated
15030 // value, it calls into Evaluate.
15031 
15032 namespace {
15033 
15034 enum ICEKind {
15035   /// This expression is an ICE.
15036   IK_ICE,
15037   /// This expression is not an ICE, but if it isn't evaluated, it's
15038   /// a legal subexpression for an ICE. This return value is used to handle
15039   /// the comma operator in C99 mode, and non-constant subexpressions.
15040   IK_ICEIfUnevaluated,
15041   /// This expression is not an ICE, and is not a legal subexpression for one.
15042   IK_NotICE
15043 };
15044 
15045 struct ICEDiag {
15046   ICEKind Kind;
15047   SourceLocation Loc;
15048 
ICEDiag__anon4a4db2533511::ICEDiag15049   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15050 };
15051 
15052 }
15053 
NoDiag()15054 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15055 
Worst(ICEDiag A,ICEDiag B)15056 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15057 
CheckEvalInICE(const Expr * E,const ASTContext & Ctx)15058 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15059   Expr::EvalResult EVResult;
15060   Expr::EvalStatus Status;
15061   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15062 
15063   Info.InConstantContext = true;
15064   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15065       !EVResult.Val.isInt())
15066     return ICEDiag(IK_NotICE, E->getBeginLoc());
15067 
15068   return NoDiag();
15069 }
15070 
CheckICE(const Expr * E,const ASTContext & Ctx)15071 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15072   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15073   if (!E->getType()->isIntegralOrEnumerationType())
15074     return ICEDiag(IK_NotICE, E->getBeginLoc());
15075 
15076   switch (E->getStmtClass()) {
15077 #define ABSTRACT_STMT(Node)
15078 #define STMT(Node, Base) case Expr::Node##Class:
15079 #define EXPR(Node, Base)
15080 #include "clang/AST/StmtNodes.inc"
15081   case Expr::PredefinedExprClass:
15082   case Expr::FloatingLiteralClass:
15083   case Expr::ImaginaryLiteralClass:
15084   case Expr::StringLiteralClass:
15085   case Expr::ArraySubscriptExprClass:
15086   case Expr::MatrixSubscriptExprClass:
15087   case Expr::OMPArraySectionExprClass:
15088   case Expr::OMPArrayShapingExprClass:
15089   case Expr::OMPIteratorExprClass:
15090   case Expr::MemberExprClass:
15091   case Expr::CompoundAssignOperatorClass:
15092   case Expr::CompoundLiteralExprClass:
15093   case Expr::ExtVectorElementExprClass:
15094   case Expr::DesignatedInitExprClass:
15095   case Expr::ArrayInitLoopExprClass:
15096   case Expr::ArrayInitIndexExprClass:
15097   case Expr::NoInitExprClass:
15098   case Expr::DesignatedInitUpdateExprClass:
15099   case Expr::ImplicitValueInitExprClass:
15100   case Expr::ParenListExprClass:
15101   case Expr::VAArgExprClass:
15102   case Expr::AddrLabelExprClass:
15103   case Expr::StmtExprClass:
15104   case Expr::CXXMemberCallExprClass:
15105   case Expr::CUDAKernelCallExprClass:
15106   case Expr::CXXAddrspaceCastExprClass:
15107   case Expr::CXXDynamicCastExprClass:
15108   case Expr::CXXTypeidExprClass:
15109   case Expr::CXXUuidofExprClass:
15110   case Expr::MSPropertyRefExprClass:
15111   case Expr::MSPropertySubscriptExprClass:
15112   case Expr::CXXNullPtrLiteralExprClass:
15113   case Expr::UserDefinedLiteralClass:
15114   case Expr::CXXThisExprClass:
15115   case Expr::CXXThrowExprClass:
15116   case Expr::CXXNewExprClass:
15117   case Expr::CXXDeleteExprClass:
15118   case Expr::CXXPseudoDestructorExprClass:
15119   case Expr::UnresolvedLookupExprClass:
15120   case Expr::TypoExprClass:
15121   case Expr::RecoveryExprClass:
15122   case Expr::DependentScopeDeclRefExprClass:
15123   case Expr::CXXConstructExprClass:
15124   case Expr::CXXInheritedCtorInitExprClass:
15125   case Expr::CXXStdInitializerListExprClass:
15126   case Expr::CXXBindTemporaryExprClass:
15127   case Expr::ExprWithCleanupsClass:
15128   case Expr::CXXTemporaryObjectExprClass:
15129   case Expr::CXXUnresolvedConstructExprClass:
15130   case Expr::CXXDependentScopeMemberExprClass:
15131   case Expr::UnresolvedMemberExprClass:
15132   case Expr::ObjCStringLiteralClass:
15133   case Expr::ObjCBoxedExprClass:
15134   case Expr::ObjCArrayLiteralClass:
15135   case Expr::ObjCDictionaryLiteralClass:
15136   case Expr::ObjCEncodeExprClass:
15137   case Expr::ObjCMessageExprClass:
15138   case Expr::ObjCSelectorExprClass:
15139   case Expr::ObjCProtocolExprClass:
15140   case Expr::ObjCIvarRefExprClass:
15141   case Expr::ObjCPropertyRefExprClass:
15142   case Expr::ObjCSubscriptRefExprClass:
15143   case Expr::ObjCIsaExprClass:
15144   case Expr::ObjCAvailabilityCheckExprClass:
15145   case Expr::ShuffleVectorExprClass:
15146   case Expr::ConvertVectorExprClass:
15147   case Expr::BlockExprClass:
15148   case Expr::NoStmtClass:
15149   case Expr::OpaqueValueExprClass:
15150   case Expr::PackExpansionExprClass:
15151   case Expr::SubstNonTypeTemplateParmPackExprClass:
15152   case Expr::FunctionParmPackExprClass:
15153   case Expr::AsTypeExprClass:
15154   case Expr::ObjCIndirectCopyRestoreExprClass:
15155   case Expr::MaterializeTemporaryExprClass:
15156   case Expr::PseudoObjectExprClass:
15157   case Expr::AtomicExprClass:
15158   case Expr::LambdaExprClass:
15159   case Expr::CXXFoldExprClass:
15160   case Expr::CoawaitExprClass:
15161   case Expr::DependentCoawaitExprClass:
15162   case Expr::CoyieldExprClass:
15163   case Expr::SYCLUniqueStableNameExprClass:
15164     return ICEDiag(IK_NotICE, E->getBeginLoc());
15165 
15166   case Expr::InitListExprClass: {
15167     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15168     // form "T x = { a };" is equivalent to "T x = a;".
15169     // Unless we're initializing a reference, T is a scalar as it is known to be
15170     // of integral or enumeration type.
15171     if (E->isPRValue())
15172       if (cast<InitListExpr>(E)->getNumInits() == 1)
15173         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15174     return ICEDiag(IK_NotICE, E->getBeginLoc());
15175   }
15176 
15177   case Expr::SizeOfPackExprClass:
15178   case Expr::GNUNullExprClass:
15179   case Expr::SourceLocExprClass:
15180     return NoDiag();
15181 
15182   case Expr::SubstNonTypeTemplateParmExprClass:
15183     return
15184       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15185 
15186   case Expr::ConstantExprClass:
15187     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15188 
15189   case Expr::ParenExprClass:
15190     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15191   case Expr::GenericSelectionExprClass:
15192     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15193   case Expr::IntegerLiteralClass:
15194   case Expr::FixedPointLiteralClass:
15195   case Expr::CharacterLiteralClass:
15196   case Expr::ObjCBoolLiteralExprClass:
15197   case Expr::CXXBoolLiteralExprClass:
15198   case Expr::CXXScalarValueInitExprClass:
15199   case Expr::TypeTraitExprClass:
15200   case Expr::ConceptSpecializationExprClass:
15201   case Expr::RequiresExprClass:
15202   case Expr::ArrayTypeTraitExprClass:
15203   case Expr::ExpressionTraitExprClass:
15204   case Expr::CXXNoexceptExprClass:
15205     return NoDiag();
15206   case Expr::CallExprClass:
15207   case Expr::CXXOperatorCallExprClass: {
15208     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15209     // constant expressions, but they can never be ICEs because an ICE cannot
15210     // contain an operand of (pointer to) function type.
15211     const CallExpr *CE = cast<CallExpr>(E);
15212     if (CE->getBuiltinCallee())
15213       return CheckEvalInICE(E, Ctx);
15214     return ICEDiag(IK_NotICE, E->getBeginLoc());
15215   }
15216   case Expr::CXXRewrittenBinaryOperatorClass:
15217     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15218                     Ctx);
15219   case Expr::DeclRefExprClass: {
15220     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15221     if (isa<EnumConstantDecl>(D))
15222       return NoDiag();
15223 
15224     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15225     // integer variables in constant expressions:
15226     //
15227     // C++ 7.1.5.1p2
15228     //   A variable of non-volatile const-qualified integral or enumeration
15229     //   type initialized by an ICE can be used in ICEs.
15230     //
15231     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15232     // that mode, use of reference variables should not be allowed.
15233     const VarDecl *VD = dyn_cast<VarDecl>(D);
15234     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15235         !VD->getType()->isReferenceType())
15236       return NoDiag();
15237 
15238     return ICEDiag(IK_NotICE, E->getBeginLoc());
15239   }
15240   case Expr::UnaryOperatorClass: {
15241     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15242     switch (Exp->getOpcode()) {
15243     case UO_PostInc:
15244     case UO_PostDec:
15245     case UO_PreInc:
15246     case UO_PreDec:
15247     case UO_AddrOf:
15248     case UO_Deref:
15249     case UO_Coawait:
15250       // C99 6.6/3 allows increment and decrement within unevaluated
15251       // subexpressions of constant expressions, but they can never be ICEs
15252       // because an ICE cannot contain an lvalue operand.
15253       return ICEDiag(IK_NotICE, E->getBeginLoc());
15254     case UO_Extension:
15255     case UO_LNot:
15256     case UO_Plus:
15257     case UO_Minus:
15258     case UO_Not:
15259     case UO_Real:
15260     case UO_Imag:
15261       return CheckICE(Exp->getSubExpr(), Ctx);
15262     }
15263     llvm_unreachable("invalid unary operator class");
15264   }
15265   case Expr::OffsetOfExprClass: {
15266     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15267     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15268     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15269     // compliance: we should warn earlier for offsetof expressions with
15270     // array subscripts that aren't ICEs, and if the array subscripts
15271     // are ICEs, the value of the offsetof must be an integer constant.
15272     return CheckEvalInICE(E, Ctx);
15273   }
15274   case Expr::UnaryExprOrTypeTraitExprClass: {
15275     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15276     if ((Exp->getKind() ==  UETT_SizeOf) &&
15277         Exp->getTypeOfArgument()->isVariableArrayType())
15278       return ICEDiag(IK_NotICE, E->getBeginLoc());
15279     return NoDiag();
15280   }
15281   case Expr::BinaryOperatorClass: {
15282     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15283     switch (Exp->getOpcode()) {
15284     case BO_PtrMemD:
15285     case BO_PtrMemI:
15286     case BO_Assign:
15287     case BO_MulAssign:
15288     case BO_DivAssign:
15289     case BO_RemAssign:
15290     case BO_AddAssign:
15291     case BO_SubAssign:
15292     case BO_ShlAssign:
15293     case BO_ShrAssign:
15294     case BO_AndAssign:
15295     case BO_XorAssign:
15296     case BO_OrAssign:
15297       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15298       // constant expressions, but they can never be ICEs because an ICE cannot
15299       // contain an lvalue operand.
15300       return ICEDiag(IK_NotICE, E->getBeginLoc());
15301 
15302     case BO_Mul:
15303     case BO_Div:
15304     case BO_Rem:
15305     case BO_Add:
15306     case BO_Sub:
15307     case BO_Shl:
15308     case BO_Shr:
15309     case BO_LT:
15310     case BO_GT:
15311     case BO_LE:
15312     case BO_GE:
15313     case BO_EQ:
15314     case BO_NE:
15315     case BO_And:
15316     case BO_Xor:
15317     case BO_Or:
15318     case BO_Comma:
15319     case BO_Cmp: {
15320       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15321       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15322       if (Exp->getOpcode() == BO_Div ||
15323           Exp->getOpcode() == BO_Rem) {
15324         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15325         // we don't evaluate one.
15326         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15327           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15328           if (REval == 0)
15329             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15330           if (REval.isSigned() && REval.isAllOnes()) {
15331             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15332             if (LEval.isMinSignedValue())
15333               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15334           }
15335         }
15336       }
15337       if (Exp->getOpcode() == BO_Comma) {
15338         if (Ctx.getLangOpts().C99) {
15339           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15340           // if it isn't evaluated.
15341           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15342             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15343         } else {
15344           // In both C89 and C++, commas in ICEs are illegal.
15345           return ICEDiag(IK_NotICE, E->getBeginLoc());
15346         }
15347       }
15348       return Worst(LHSResult, RHSResult);
15349     }
15350     case BO_LAnd:
15351     case BO_LOr: {
15352       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15353       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15354       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15355         // Rare case where the RHS has a comma "side-effect"; we need
15356         // to actually check the condition to see whether the side
15357         // with the comma is evaluated.
15358         if ((Exp->getOpcode() == BO_LAnd) !=
15359             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15360           return RHSResult;
15361         return NoDiag();
15362       }
15363 
15364       return Worst(LHSResult, RHSResult);
15365     }
15366     }
15367     llvm_unreachable("invalid binary operator kind");
15368   }
15369   case Expr::ImplicitCastExprClass:
15370   case Expr::CStyleCastExprClass:
15371   case Expr::CXXFunctionalCastExprClass:
15372   case Expr::CXXStaticCastExprClass:
15373   case Expr::CXXReinterpretCastExprClass:
15374   case Expr::CXXConstCastExprClass:
15375   case Expr::ObjCBridgedCastExprClass: {
15376     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15377     if (isa<ExplicitCastExpr>(E)) {
15378       if (const FloatingLiteral *FL
15379             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15380         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15381         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15382         APSInt IgnoredVal(DestWidth, !DestSigned);
15383         bool Ignored;
15384         // If the value does not fit in the destination type, the behavior is
15385         // undefined, so we are not required to treat it as a constant
15386         // expression.
15387         if (FL->getValue().convertToInteger(IgnoredVal,
15388                                             llvm::APFloat::rmTowardZero,
15389                                             &Ignored) & APFloat::opInvalidOp)
15390           return ICEDiag(IK_NotICE, E->getBeginLoc());
15391         return NoDiag();
15392       }
15393     }
15394     switch (cast<CastExpr>(E)->getCastKind()) {
15395     case CK_LValueToRValue:
15396     case CK_AtomicToNonAtomic:
15397     case CK_NonAtomicToAtomic:
15398     case CK_NoOp:
15399     case CK_IntegralToBoolean:
15400     case CK_IntegralCast:
15401       return CheckICE(SubExpr, Ctx);
15402     default:
15403       return ICEDiag(IK_NotICE, E->getBeginLoc());
15404     }
15405   }
15406   case Expr::BinaryConditionalOperatorClass: {
15407     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15408     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15409     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15410     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15411     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15412     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15413     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15414         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15415     return FalseResult;
15416   }
15417   case Expr::ConditionalOperatorClass: {
15418     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15419     // If the condition (ignoring parens) is a __builtin_constant_p call,
15420     // then only the true side is actually considered in an integer constant
15421     // expression, and it is fully evaluated.  This is an important GNU
15422     // extension.  See GCC PR38377 for discussion.
15423     if (const CallExpr *CallCE
15424         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15425       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15426         return CheckEvalInICE(E, Ctx);
15427     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15428     if (CondResult.Kind == IK_NotICE)
15429       return CondResult;
15430 
15431     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15432     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15433 
15434     if (TrueResult.Kind == IK_NotICE)
15435       return TrueResult;
15436     if (FalseResult.Kind == IK_NotICE)
15437       return FalseResult;
15438     if (CondResult.Kind == IK_ICEIfUnevaluated)
15439       return CondResult;
15440     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15441       return NoDiag();
15442     // Rare case where the diagnostics depend on which side is evaluated
15443     // Note that if we get here, CondResult is 0, and at least one of
15444     // TrueResult and FalseResult is non-zero.
15445     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15446       return FalseResult;
15447     return TrueResult;
15448   }
15449   case Expr::CXXDefaultArgExprClass:
15450     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15451   case Expr::CXXDefaultInitExprClass:
15452     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15453   case Expr::ChooseExprClass: {
15454     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15455   }
15456   case Expr::BuiltinBitCastExprClass: {
15457     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15458       return ICEDiag(IK_NotICE, E->getBeginLoc());
15459     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15460   }
15461   }
15462 
15463   llvm_unreachable("Invalid StmtClass!");
15464 }
15465 
15466 /// Evaluate an expression as a C++11 integral constant expression.
EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext & Ctx,const Expr * E,llvm::APSInt * Value,SourceLocation * Loc)15467 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15468                                                     const Expr *E,
15469                                                     llvm::APSInt *Value,
15470                                                     SourceLocation *Loc) {
15471   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15472     if (Loc) *Loc = E->getExprLoc();
15473     return false;
15474   }
15475 
15476   APValue Result;
15477   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15478     return false;
15479 
15480   if (!Result.isInt()) {
15481     if (Loc) *Loc = E->getExprLoc();
15482     return false;
15483   }
15484 
15485   if (Value) *Value = Result.getInt();
15486   return true;
15487 }
15488 
isIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc) const15489 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15490                                  SourceLocation *Loc) const {
15491   assert(!isValueDependent() &&
15492          "Expression evaluator can't be called on a dependent expression.");
15493 
15494   if (Ctx.getLangOpts().CPlusPlus11)
15495     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15496 
15497   ICEDiag D = CheckICE(this, Ctx);
15498   if (D.Kind != IK_ICE) {
15499     if (Loc) *Loc = D.Loc;
15500     return false;
15501   }
15502   return true;
15503 }
15504 
getIntegerConstantExpr(const ASTContext & Ctx,SourceLocation * Loc,bool isEvaluated) const15505 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15506                                                     SourceLocation *Loc,
15507                                                     bool isEvaluated) const {
15508   assert(!isValueDependent() &&
15509          "Expression evaluator can't be called on a dependent expression.");
15510 
15511   APSInt Value;
15512 
15513   if (Ctx.getLangOpts().CPlusPlus11) {
15514     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15515       return Value;
15516     return None;
15517   }
15518 
15519   if (!isIntegerConstantExpr(Ctx, Loc))
15520     return None;
15521 
15522   // The only possible side-effects here are due to UB discovered in the
15523   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15524   // required to treat the expression as an ICE, so we produce the folded
15525   // value.
15526   EvalResult ExprResult;
15527   Expr::EvalStatus Status;
15528   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15529   Info.InConstantContext = true;
15530 
15531   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15532     llvm_unreachable("ICE cannot be evaluated!");
15533 
15534   return ExprResult.Val.getInt();
15535 }
15536 
isCXX98IntegralConstantExpr(const ASTContext & Ctx) const15537 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15538   assert(!isValueDependent() &&
15539          "Expression evaluator can't be called on a dependent expression.");
15540 
15541   return CheckICE(this, Ctx).Kind == IK_ICE;
15542 }
15543 
isCXX11ConstantExpr(const ASTContext & Ctx,APValue * Result,SourceLocation * Loc) const15544 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15545                                SourceLocation *Loc) const {
15546   assert(!isValueDependent() &&
15547          "Expression evaluator can't be called on a dependent expression.");
15548 
15549   // We support this checking in C++98 mode in order to diagnose compatibility
15550   // issues.
15551   assert(Ctx.getLangOpts().CPlusPlus);
15552 
15553   // Build evaluation settings.
15554   Expr::EvalStatus Status;
15555   SmallVector<PartialDiagnosticAt, 8> Diags;
15556   Status.Diag = &Diags;
15557   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15558 
15559   APValue Scratch;
15560   bool IsConstExpr =
15561       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15562       // FIXME: We don't produce a diagnostic for this, but the callers that
15563       // call us on arbitrary full-expressions should generally not care.
15564       Info.discardCleanups() && !Status.HasSideEffects;
15565 
15566   if (!Diags.empty()) {
15567     IsConstExpr = false;
15568     if (Loc) *Loc = Diags[0].first;
15569   } else if (!IsConstExpr) {
15570     // FIXME: This shouldn't happen.
15571     if (Loc) *Loc = getExprLoc();
15572   }
15573 
15574   return IsConstExpr;
15575 }
15576 
EvaluateWithSubstitution(APValue & Value,ASTContext & Ctx,const FunctionDecl * Callee,ArrayRef<const Expr * > Args,const Expr * This) const15577 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15578                                     const FunctionDecl *Callee,
15579                                     ArrayRef<const Expr*> Args,
15580                                     const Expr *This) const {
15581   assert(!isValueDependent() &&
15582          "Expression evaluator can't be called on a dependent expression.");
15583 
15584   Expr::EvalStatus Status;
15585   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15586   Info.InConstantContext = true;
15587 
15588   LValue ThisVal;
15589   const LValue *ThisPtr = nullptr;
15590   if (This) {
15591 #ifndef NDEBUG
15592     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15593     assert(MD && "Don't provide `this` for non-methods.");
15594     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15595 #endif
15596     if (!This->isValueDependent() &&
15597         EvaluateObjectArgument(Info, This, ThisVal) &&
15598         !Info.EvalStatus.HasSideEffects)
15599       ThisPtr = &ThisVal;
15600 
15601     // Ignore any side-effects from a failed evaluation. This is safe because
15602     // they can't interfere with any other argument evaluation.
15603     Info.EvalStatus.HasSideEffects = false;
15604   }
15605 
15606   CallRef Call = Info.CurrentCall->createCall(Callee);
15607   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15608        I != E; ++I) {
15609     unsigned Idx = I - Args.begin();
15610     if (Idx >= Callee->getNumParams())
15611       break;
15612     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15613     if ((*I)->isValueDependent() ||
15614         !EvaluateCallArg(PVD, *I, Call, Info) ||
15615         Info.EvalStatus.HasSideEffects) {
15616       // If evaluation fails, throw away the argument entirely.
15617       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15618         *Slot = APValue();
15619     }
15620 
15621     // Ignore any side-effects from a failed evaluation. This is safe because
15622     // they can't interfere with any other argument evaluation.
15623     Info.EvalStatus.HasSideEffects = false;
15624   }
15625 
15626   // Parameter cleanups happen in the caller and are not part of this
15627   // evaluation.
15628   Info.discardCleanups();
15629   Info.EvalStatus.HasSideEffects = false;
15630 
15631   // Build fake call to Callee.
15632   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15633   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15634   FullExpressionRAII Scope(Info);
15635   return Evaluate(Value, Info, this) && Scope.destroy() &&
15636          !Info.EvalStatus.HasSideEffects;
15637 }
15638 
isPotentialConstantExpr(const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)15639 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15640                                    SmallVectorImpl<
15641                                      PartialDiagnosticAt> &Diags) {
15642   // FIXME: It would be useful to check constexpr function templates, but at the
15643   // moment the constant expression evaluator cannot cope with the non-rigorous
15644   // ASTs which we build for dependent expressions.
15645   if (FD->isDependentContext())
15646     return true;
15647 
15648   Expr::EvalStatus Status;
15649   Status.Diag = &Diags;
15650 
15651   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15652   Info.InConstantContext = true;
15653   Info.CheckingPotentialConstantExpression = true;
15654 
15655   // The constexpr VM attempts to compile all methods to bytecode here.
15656   if (Info.EnableNewConstInterp) {
15657     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15658     return Diags.empty();
15659   }
15660 
15661   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15662   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15663 
15664   // Fabricate an arbitrary expression on the stack and pretend that it
15665   // is a temporary being used as the 'this' pointer.
15666   LValue This;
15667   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15668   This.set({&VIE, Info.CurrentCall->Index});
15669 
15670   ArrayRef<const Expr*> Args;
15671 
15672   APValue Scratch;
15673   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15674     // Evaluate the call as a constant initializer, to allow the construction
15675     // of objects of non-literal types.
15676     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15677     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15678   } else {
15679     SourceLocation Loc = FD->getLocation();
15680     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15681                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15682   }
15683 
15684   return Diags.empty();
15685 }
15686 
isPotentialConstantExprUnevaluated(Expr * E,const FunctionDecl * FD,SmallVectorImpl<PartialDiagnosticAt> & Diags)15687 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15688                                               const FunctionDecl *FD,
15689                                               SmallVectorImpl<
15690                                                 PartialDiagnosticAt> &Diags) {
15691   assert(!E->isValueDependent() &&
15692          "Expression evaluator can't be called on a dependent expression.");
15693 
15694   Expr::EvalStatus Status;
15695   Status.Diag = &Diags;
15696 
15697   EvalInfo Info(FD->getASTContext(), Status,
15698                 EvalInfo::EM_ConstantExpressionUnevaluated);
15699   Info.InConstantContext = true;
15700   Info.CheckingPotentialConstantExpression = true;
15701 
15702   // Fabricate a call stack frame to give the arguments a plausible cover story.
15703   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15704 
15705   APValue ResultScratch;
15706   Evaluate(ResultScratch, Info, E);
15707   return Diags.empty();
15708 }
15709 
tryEvaluateObjectSize(uint64_t & Result,ASTContext & Ctx,unsigned Type) const15710 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15711                                  unsigned Type) const {
15712   if (!getType()->isPointerType())
15713     return false;
15714 
15715   Expr::EvalStatus Status;
15716   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15717   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15718 }
15719 
EvaluateBuiltinStrLen(const Expr * E,uint64_t & Result,EvalInfo & Info)15720 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
15721                                   EvalInfo &Info) {
15722   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
15723     return false;
15724 
15725   LValue String;
15726 
15727   if (!EvaluatePointer(E, String, Info))
15728     return false;
15729 
15730   QualType CharTy = E->getType()->getPointeeType();
15731 
15732   // Fast path: if it's a string literal, search the string value.
15733   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
15734           String.getLValueBase().dyn_cast<const Expr *>())) {
15735     StringRef Str = S->getBytes();
15736     int64_t Off = String.Offset.getQuantity();
15737     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
15738         S->getCharByteWidth() == 1 &&
15739         // FIXME: Add fast-path for wchar_t too.
15740         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
15741       Str = Str.substr(Off);
15742 
15743       StringRef::size_type Pos = Str.find(0);
15744       if (Pos != StringRef::npos)
15745         Str = Str.substr(0, Pos);
15746 
15747       Result = Str.size();
15748       return true;
15749     }
15750 
15751     // Fall through to slow path.
15752   }
15753 
15754   // Slow path: scan the bytes of the string looking for the terminating 0.
15755   for (uint64_t Strlen = 0; /**/; ++Strlen) {
15756     APValue Char;
15757     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
15758         !Char.isInt())
15759       return false;
15760     if (!Char.getInt()) {
15761       Result = Strlen;
15762       return true;
15763     }
15764     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
15765       return false;
15766   }
15767 }
15768 
tryEvaluateStrLen(uint64_t & Result,ASTContext & Ctx) const15769 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
15770   Expr::EvalStatus Status;
15771   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15772   return EvaluateBuiltinStrLen(this, Result, Info);
15773 }
15774