blob: c57b7826320fd3b5697a78b0fb93cb116745d901 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000039#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000040#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000041#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000042#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000043#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000044#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000045#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000046#include "clang/Basic/TargetInfo.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000079 // for it directly. Otherwise use the type after adjustment.
80 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000081 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
Richard Smitha8105bc2012-01-06 16:39:00 +0000112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
114 static
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
George Burgess IVa51c4072015-10-16 01:49:01 +0000117 uint64_t &ArraySize, QualType &Type,
118 bool &IsArray) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000119 unsigned MostDerivedLength = 0;
120 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000121 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000122 if (Type->isArrayType()) {
123 const ConstantArrayType *CAT =
124 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
125 Type = CAT->getElementType();
126 ArraySize = CAT->getSize().getZExtValue();
127 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000128 IsArray = true;
Richard Smith66c96992012-02-18 22:04:06 +0000129 } else if (Type->isAnyComplexType()) {
130 const ComplexType *CT = Type->castAs<ComplexType>();
131 Type = CT->getElementType();
132 ArraySize = 2;
133 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000134 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000135 } else if (const FieldDecl *FD = getAsField(Path[I])) {
136 Type = FD->getType();
137 ArraySize = 0;
138 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000139 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000140 } else {
Richard Smith80815602011-11-07 05:07:52 +0000141 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000142 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000143 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000144 }
Richard Smith80815602011-11-07 05:07:52 +0000145 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000146 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000147 }
148
Richard Smitha8105bc2012-01-06 16:39:00 +0000149 // The order of this enum is important for diagnostics.
150 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000151 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000152 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000153 };
154
Richard Smith96e0c102011-11-04 02:25:55 +0000155 /// A path from a glvalue to a subobject of that glvalue.
156 struct SubobjectDesignator {
157 /// True if the subobject was named in a manner not supported by C++11. Such
158 /// lvalues can still be folded, but they are not core constant expressions
159 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000160 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000161
Richard Smitha8105bc2012-01-06 16:39:00 +0000162 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000163 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000164
George Burgess IVa51c4072015-10-16 01:49:01 +0000165 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000166 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000167
Richard Smitha8105bc2012-01-06 16:39:00 +0000168 /// The length of the path to the most-derived object of which this is a
169 /// subobject.
George Burgess IVa51c4072015-10-16 01:49:01 +0000170 unsigned MostDerivedPathLength : 29;
Richard Smitha8105bc2012-01-06 16:39:00 +0000171
George Burgess IVa51c4072015-10-16 01:49:01 +0000172 /// The size of the array of which the most-derived object is an element.
173 /// This will always be 0 if the most-derived object is not an array
174 /// element. 0 is not an indicator of whether or not the most-derived object
175 /// is an array, however, because 0-length arrays are allowed.
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 uint64_t MostDerivedArraySize;
177
178 /// The type of the most derived object referred to by this address.
179 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000180
Richard Smith80815602011-11-07 05:07:52 +0000181 typedef APValue::LValuePathEntry PathEntry;
182
Richard Smith96e0c102011-11-04 02:25:55 +0000183 /// The entries on the path from the glvalue to the designated subobject.
184 SmallVector<PathEntry, 8> Entries;
185
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000187
Richard Smitha8105bc2012-01-06 16:39:00 +0000188 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000189 : Invalid(false), IsOnePastTheEnd(false),
190 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
191 MostDerivedArraySize(0), MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000192
193 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000194 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
195 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
196 MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000197 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000198 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000199 ArrayRef<PathEntry> VEntries = V.getLValuePath();
200 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
George Burgess IVa51c4072015-10-16 01:49:01 +0000201 if (V.getLValueBase()) {
202 bool IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000203 MostDerivedPathLength =
204 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
205 V.getLValuePath(), MostDerivedArraySize,
George Burgess IVa51c4072015-10-16 01:49:01 +0000206 MostDerivedType, IsArray);
207 MostDerivedIsArrayElement = IsArray;
208 }
Richard Smith80815602011-11-07 05:07:52 +0000209 }
210 }
211
Richard Smith96e0c102011-11-04 02:25:55 +0000212 void setInvalid() {
213 Invalid = true;
214 Entries.clear();
215 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000216
217 /// Determine whether this is a one-past-the-end pointer.
218 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000219 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 if (IsOnePastTheEnd)
221 return true;
George Burgess IVa51c4072015-10-16 01:49:01 +0000222 if (MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000223 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
224 return true;
225 return false;
226 }
227
228 /// Check that this refers to a valid subobject.
229 bool isValidSubobject() const {
230 if (Invalid)
231 return false;
232 return !isOnePastTheEnd();
233 }
234 /// Check that this refers to a valid subobject, and if not, produce a
235 /// relevant diagnostic and set the designator as invalid.
236 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
237
238 /// Update this designator to refer to the first element within this array.
239 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000240 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000241 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000242 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000243
244 // This is a most-derived object.
245 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000246 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000247 MostDerivedArraySize = CAT->getSize().getZExtValue();
248 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000249 }
250 /// Update this designator to refer to the given base or member of this
251 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000252 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000253 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000254 APValue::BaseOrMemberType Value(D, Virtual);
255 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000256 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000257
258 // If this isn't a base class, it's a new most-derived object.
259 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
260 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000261 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000262 MostDerivedArraySize = 0;
263 MostDerivedPathLength = Entries.size();
264 }
Richard Smith96e0c102011-11-04 02:25:55 +0000265 }
Richard Smith66c96992012-02-18 22:04:06 +0000266 /// Update this designator to refer to the given complex component.
267 void addComplexUnchecked(QualType EltTy, bool Imag) {
268 PathEntry Entry;
269 Entry.ArrayIndex = Imag;
270 Entries.push_back(Entry);
271
272 // This is technically a most-derived object, though in practice this
273 // is unlikely to matter.
274 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000275 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000276 MostDerivedArraySize = 2;
277 MostDerivedPathLength = Entries.size();
278 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000279 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000280 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000281 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000282 if (Invalid) return;
George Burgess IVa51c4072015-10-16 01:49:01 +0000283 if (MostDerivedPathLength == Entries.size() &&
284 MostDerivedIsArrayElement) {
Richard Smith80815602011-11-07 05:07:52 +0000285 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000286 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
287 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
288 setInvalid();
289 }
Richard Smith96e0c102011-11-04 02:25:55 +0000290 return;
291 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000292 // [expr.add]p4: For the purposes of these operators, a pointer to a
293 // nonarray object behaves the same as a pointer to the first element of
294 // an array of length one with the type of the object as its element type.
295 if (IsOnePastTheEnd && N == (uint64_t)-1)
296 IsOnePastTheEnd = false;
297 else if (!IsOnePastTheEnd && N == 1)
298 IsOnePastTheEnd = true;
299 else if (N != 0) {
300 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000301 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000302 }
Richard Smith96e0c102011-11-04 02:25:55 +0000303 }
304 };
305
Richard Smith254a73d2011-10-28 22:34:42 +0000306 /// A stack frame in the constexpr call stack.
307 struct CallStackFrame {
308 EvalInfo &Info;
309
310 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000311 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000312
Richard Smithf6f003a2011-12-16 19:06:07 +0000313 /// Callee - The function which was called.
314 const FunctionDecl *Callee;
315
Richard Smithd62306a2011-11-10 06:34:14 +0000316 /// This - The binding for the this pointer in this call, if any.
317 const LValue *This;
318
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000319 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000320 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000321 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000322
Eli Friedman4830ec82012-06-25 21:21:08 +0000323 // Note that we intentionally use std::map here so that references to
324 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000325 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000326 typedef MapTy::const_iterator temp_iterator;
327 /// Temporaries - Temporary lvalues materialized within this stack frame.
328 MapTy Temporaries;
329
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000330 /// CallLoc - The location of the call expression for this call.
331 SourceLocation CallLoc;
332
333 /// Index - The call index of this call.
334 unsigned Index;
335
Richard Smithf6f003a2011-12-16 19:06:07 +0000336 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
337 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000338 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000339 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000340
341 APValue *getTemporary(const void *Key) {
342 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000343 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000344 }
345 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000346 };
347
Richard Smith852c9db2013-04-20 22:23:05 +0000348 /// Temporarily override 'this'.
349 class ThisOverrideRAII {
350 public:
351 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
352 : Frame(Frame), OldThis(Frame.This) {
353 if (Enable)
354 Frame.This = NewThis;
355 }
356 ~ThisOverrideRAII() {
357 Frame.This = OldThis;
358 }
359 private:
360 CallStackFrame &Frame;
361 const LValue *OldThis;
362 };
363
Richard Smith92b1ce02011-12-12 09:28:41 +0000364 /// A partial diagnostic which we might know in advance that we are not going
365 /// to emit.
366 class OptionalDiagnostic {
367 PartialDiagnostic *Diag;
368
369 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000370 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
371 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000372
373 template<typename T>
374 OptionalDiagnostic &operator<<(const T &v) {
375 if (Diag)
376 *Diag << v;
377 return *this;
378 }
Richard Smithfe800032012-01-31 04:08:20 +0000379
380 OptionalDiagnostic &operator<<(const APSInt &I) {
381 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000382 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000383 I.toString(Buffer);
384 *Diag << StringRef(Buffer.data(), Buffer.size());
385 }
386 return *this;
387 }
388
389 OptionalDiagnostic &operator<<(const APFloat &F) {
390 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000391 // FIXME: Force the precision of the source value down so we don't
392 // print digits which are usually useless (we don't really care here if
393 // we truncate a digit by accident in edge cases). Ideally,
394 // APFloat::toString would automatically print the shortest
395 // representation which rounds to the correct value, but it's a bit
396 // tricky to implement.
397 unsigned precision =
398 llvm::APFloat::semanticsPrecision(F.getSemantics());
399 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000400 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000401 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000402 *Diag << StringRef(Buffer.data(), Buffer.size());
403 }
404 return *this;
405 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000406 };
407
Richard Smith08d6a2c2013-07-24 07:11:57 +0000408 /// A cleanup, and a flag indicating whether it is lifetime-extended.
409 class Cleanup {
410 llvm::PointerIntPair<APValue*, 1, bool> Value;
411
412 public:
413 Cleanup(APValue *Val, bool IsLifetimeExtended)
414 : Value(Val, IsLifetimeExtended) {}
415
416 bool isLifetimeExtended() const { return Value.getInt(); }
417 void endLifetime() {
418 *Value.getPointer() = APValue();
419 }
420 };
421
Richard Smithb228a862012-02-15 02:18:13 +0000422 /// EvalInfo - This is a private struct used by the evaluator to capture
423 /// information about a subexpression as it is folded. It retains information
424 /// about the AST context, but also maintains information about the folded
425 /// expression.
426 ///
427 /// If an expression could be evaluated, it is still possible it is not a C
428 /// "integer constant expression" or constant expression. If not, this struct
429 /// captures information about how and why not.
430 ///
431 /// One bit of information passed *into* the request for constant folding
432 /// indicates whether the subexpression is "evaluated" or not according to C
433 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
434 /// evaluate the expression regardless of what the RHS is, but C only allows
435 /// certain things in certain situations.
Reid Kleckner06df4022016-12-13 19:48:32 +0000436 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000437 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000438
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000439 /// EvalStatus - Contains information about the evaluation.
440 Expr::EvalStatus &EvalStatus;
441
442 /// CurrentCall - The top of the constexpr call stack.
443 CallStackFrame *CurrentCall;
444
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000445 /// CallStackDepth - The number of calls in the call stack right now.
446 unsigned CallStackDepth;
447
Richard Smithb228a862012-02-15 02:18:13 +0000448 /// NextCallIndex - The next call index to assign.
449 unsigned NextCallIndex;
450
Richard Smitha3d3bd22013-05-08 02:12:03 +0000451 /// StepsLeft - The remaining number of evaluation steps we're permitted
452 /// to perform. This is essentially a limit for the number of statements
453 /// we will evaluate.
454 unsigned StepsLeft;
455
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000456 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000457 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000458 CallStackFrame BottomFrame;
459
Richard Smith08d6a2c2013-07-24 07:11:57 +0000460 /// A stack of values whose lifetimes end at the end of some surrounding
461 /// evaluation frame.
462 llvm::SmallVector<Cleanup, 16> CleanupStack;
463
Richard Smithd62306a2011-11-10 06:34:14 +0000464 /// EvaluatingDecl - This is the declaration whose initializer is being
465 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000466 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000467
468 /// EvaluatingDeclValue - This is the value being constructed for the
469 /// declaration whose initializer is being evaluated, if any.
470 APValue *EvaluatingDeclValue;
471
Richard Smith410306b2016-12-12 02:53:20 +0000472 /// The current array initialization index, if we're performing array
473 /// initialization.
474 uint64_t ArrayInitIndex = -1;
475
Richard Smith357362d2011-12-13 06:39:58 +0000476 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
477 /// notes attached to it will also be stored, otherwise they will not be.
478 bool HasActiveDiagnostic;
479
Richard Smith0c6124b2015-12-03 01:36:22 +0000480 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
481 /// fold (not just why it's not strictly a constant expression)?
482 bool HasFoldFailureDiagnostic;
483
George Burgess IV8c892b52016-05-25 22:31:54 +0000484 /// \brief Whether or not we're currently speculatively evaluating.
485 bool IsSpeculativelyEvaluating;
486
Richard Smith6d4c6582013-11-05 22:18:15 +0000487 enum EvaluationMode {
488 /// Evaluate as a constant expression. Stop if we find that the expression
489 /// is not a constant expression.
490 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000491
Richard Smith6d4c6582013-11-05 22:18:15 +0000492 /// Evaluate as a potential constant expression. Keep going if we hit a
493 /// construct that we can't evaluate yet (because we don't yet know the
494 /// value of something) but stop if we hit something that could never be
495 /// a constant expression.
496 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000497
Richard Smith6d4c6582013-11-05 22:18:15 +0000498 /// Fold the expression to a constant. Stop if we hit a side-effect that
499 /// we can't model.
500 EM_ConstantFold,
501
502 /// Evaluate the expression looking for integer overflow and similar
503 /// issues. Don't worry about side-effects, and try to visit all
504 /// subexpressions.
505 EM_EvaluateForOverflow,
506
507 /// Evaluate in any way we know how. Don't worry about side-effects that
508 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000509 EM_IgnoreSideEffects,
510
511 /// Evaluate as a constant expression. Stop if we find that the expression
512 /// is not a constant expression. Some expressions can be retried in the
513 /// optimizer if we don't constant fold them here, but in an unevaluated
514 /// context we try to fold them immediately since the optimizer never
515 /// gets a chance to look at it.
516 EM_ConstantExpressionUnevaluated,
517
518 /// Evaluate as a potential constant expression. Keep going if we hit a
519 /// construct that we can't evaluate yet (because we don't yet know the
520 /// value of something) but stop if we hit something that could never be
521 /// a constant expression. Some expressions can be retried in the
522 /// optimizer if we don't constant fold them here, but in an unevaluated
523 /// context we try to fold them immediately since the optimizer never
524 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000525 EM_PotentialConstantExpressionUnevaluated,
526
527 /// Evaluate as a constant expression. Continue evaluating if we find a
528 /// MemberExpr with a base that can't be evaluated.
529 EM_DesignatorFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000530 } EvalMode;
531
532 /// Are we checking whether the expression is a potential constant
533 /// expression?
534 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000535 return EvalMode == EM_PotentialConstantExpression ||
536 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000537 }
538
539 /// Are we checking an expression for overflow?
540 // FIXME: We should check for any kind of undefined or suspicious behavior
541 // in such constructs, not just overflow.
542 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
543
544 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000545 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000546 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000547 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000548 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
549 EvaluatingDecl((const ValueDecl *)nullptr),
550 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000551 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
552 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000553
Richard Smith7525ff62013-05-09 07:14:00 +0000554 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
555 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000556 EvaluatingDeclValue = &Value;
557 }
558
David Blaikiebbafb8a2012-03-11 07:00:24 +0000559 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000560
Richard Smith357362d2011-12-13 06:39:58 +0000561 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000562 // Don't perform any constexpr calls (other than the call we're checking)
563 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000564 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000565 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000566 if (NextCallIndex == 0) {
567 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000568 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000569 return false;
570 }
Richard Smith357362d2011-12-13 06:39:58 +0000571 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
572 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000573 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000574 << getLangOpts().ConstexprCallDepth;
575 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000576 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000577
Richard Smithb228a862012-02-15 02:18:13 +0000578 CallStackFrame *getCallFrame(unsigned CallIndex) {
579 assert(CallIndex && "no call index in getCallFrame");
580 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
581 // be null in this loop.
582 CallStackFrame *Frame = CurrentCall;
583 while (Frame->Index > CallIndex)
584 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000585 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000586 }
587
Richard Smitha3d3bd22013-05-08 02:12:03 +0000588 bool nextStep(const Stmt *S) {
589 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000590 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000591 return false;
592 }
593 --StepsLeft;
594 return true;
595 }
596
Richard Smith357362d2011-12-13 06:39:58 +0000597 private:
598 /// Add a diagnostic to the diagnostics list.
599 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
600 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
601 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
602 return EvalStatus.Diag->back().second;
603 }
604
Richard Smithf6f003a2011-12-16 19:06:07 +0000605 /// Add notes containing a call stack to the current point of evaluation.
606 void addCallStack(unsigned Limit);
607
Faisal Valie690b7a2016-07-02 22:34:24 +0000608 private:
609 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
610 unsigned ExtraNotes, bool IsCCEDiag) {
611
Richard Smith92b1ce02011-12-12 09:28:41 +0000612 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000613 // If we have a prior diagnostic, it will be noting that the expression
614 // isn't a constant expression. This diagnostic is more important,
615 // unless we require this evaluation to produce a constant expression.
616 //
617 // FIXME: We might want to show both diagnostics to the user in
618 // EM_ConstantFold mode.
619 if (!EvalStatus.Diag->empty()) {
620 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000621 case EM_ConstantFold:
622 case EM_IgnoreSideEffects:
623 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000624 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000625 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000626 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000627 case EM_ConstantExpression:
628 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000629 case EM_ConstantExpressionUnevaluated:
630 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000631 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000632 HasActiveDiagnostic = false;
633 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000634 }
635 }
636
Richard Smithf6f003a2011-12-16 19:06:07 +0000637 unsigned CallStackNotes = CallStackDepth - 1;
638 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
639 if (Limit)
640 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000641 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000642 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000643
Richard Smith357362d2011-12-13 06:39:58 +0000644 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000645 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000646 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000647 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
648 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000649 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000650 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000651 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000652 }
Richard Smith357362d2011-12-13 06:39:58 +0000653 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000654 return OptionalDiagnostic();
655 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000656 public:
657 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
658 OptionalDiagnostic
659 FFDiag(SourceLocation Loc,
660 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
661 unsigned ExtraNotes = 0) {
662 return Diag(Loc, DiagId, ExtraNotes, false);
663 }
664
665 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000666 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000667 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000668 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000669 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000670 HasActiveDiagnostic = false;
671 return OptionalDiagnostic();
672 }
673
Richard Smith92b1ce02011-12-12 09:28:41 +0000674 /// Diagnose that the evaluation does not produce a C++11 core constant
675 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000676 ///
677 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
678 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000679 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000680 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000681 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000682 // Don't override a previous diagnostic. Don't bother collecting
683 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000684 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000685 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000686 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000687 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000688 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000689 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000690 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
691 = diag::note_invalid_subexpr_in_const_expr,
692 unsigned ExtraNotes = 0) {
693 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
694 }
Richard Smith357362d2011-12-13 06:39:58 +0000695 /// Add a note to a prior diagnostic.
696 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
697 if (!HasActiveDiagnostic)
698 return OptionalDiagnostic();
699 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000700 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000701
702 /// Add a stack of notes to a prior diagnostic.
703 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
704 if (HasActiveDiagnostic) {
705 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
706 Diags.begin(), Diags.end());
707 }
708 }
Richard Smith253c2a32012-01-27 01:14:48 +0000709
Richard Smith6d4c6582013-11-05 22:18:15 +0000710 /// Should we continue evaluation after encountering a side-effect that we
711 /// couldn't model?
712 bool keepEvaluatingAfterSideEffect() {
713 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000714 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000715 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000716 case EM_EvaluateForOverflow:
717 case EM_IgnoreSideEffects:
718 return true;
719
Richard Smith6d4c6582013-11-05 22:18:15 +0000720 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000721 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000722 case EM_ConstantFold:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000723 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000724 return false;
725 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000726 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000727 }
728
729 /// Note that we have had a side-effect, and determine whether we should
730 /// keep evaluating.
731 bool noteSideEffect() {
732 EvalStatus.HasSideEffects = true;
733 return keepEvaluatingAfterSideEffect();
734 }
735
Richard Smithce8eca52015-12-08 03:21:47 +0000736 /// Should we continue evaluation after encountering undefined behavior?
737 bool keepEvaluatingAfterUndefinedBehavior() {
738 switch (EvalMode) {
739 case EM_EvaluateForOverflow:
740 case EM_IgnoreSideEffects:
741 case EM_ConstantFold:
742 case EM_DesignatorFold:
743 return true;
744
745 case EM_PotentialConstantExpression:
746 case EM_PotentialConstantExpressionUnevaluated:
747 case EM_ConstantExpression:
748 case EM_ConstantExpressionUnevaluated:
749 return false;
750 }
751 llvm_unreachable("Missed EvalMode case");
752 }
753
754 /// Note that we hit something that was technically undefined behavior, but
755 /// that we can evaluate past it (such as signed overflow or floating-point
756 /// division by zero.)
757 bool noteUndefinedBehavior() {
758 EvalStatus.HasUndefinedBehavior = true;
759 return keepEvaluatingAfterUndefinedBehavior();
760 }
761
Richard Smith253c2a32012-01-27 01:14:48 +0000762 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000763 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000764 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000765 if (!StepsLeft)
766 return false;
767
768 switch (EvalMode) {
769 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000770 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000771 case EM_EvaluateForOverflow:
772 return true;
773
774 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000775 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000776 case EM_ConstantFold:
777 case EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000778 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000779 return false;
780 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000781 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000782 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000783
George Burgess IV8c892b52016-05-25 22:31:54 +0000784 /// Notes that we failed to evaluate an expression that other expressions
785 /// directly depend on, and determine if we should keep evaluating. This
786 /// should only be called if we actually intend to keep evaluating.
787 ///
788 /// Call noteSideEffect() instead if we may be able to ignore the value that
789 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
790 ///
791 /// (Foo(), 1) // use noteSideEffect
792 /// (Foo() || true) // use noteSideEffect
793 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000794 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000795 // Failure when evaluating some expression often means there is some
796 // subexpression whose evaluation was skipped. Therefore, (because we
797 // don't track whether we skipped an expression when unwinding after an
798 // evaluation failure) every evaluation failure that bubbles up from a
799 // subexpression implies that a side-effect has potentially happened. We
800 // skip setting the HasSideEffects flag to true until we decide to
801 // continue evaluating after that point, which happens here.
802 bool KeepGoing = keepEvaluatingAfterFailure();
803 EvalStatus.HasSideEffects |= KeepGoing;
804 return KeepGoing;
805 }
806
George Burgess IV3a03fab2015-09-04 21:28:13 +0000807 bool allowInvalidBaseExpr() const {
808 return EvalMode == EM_DesignatorFold;
809 }
Richard Smith410306b2016-12-12 02:53:20 +0000810
811 class ArrayInitLoopIndex {
812 EvalInfo &Info;
813 uint64_t OuterIndex;
814
815 public:
816 ArrayInitLoopIndex(EvalInfo &Info)
817 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
818 Info.ArrayInitIndex = 0;
819 }
820 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
821
822 operator uint64_t&() { return Info.ArrayInitIndex; }
823 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000824 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000825
826 /// Object used to treat all foldable expressions as constant expressions.
827 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000828 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000829 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000830 bool HadNoPriorDiags;
831 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000832
Richard Smith6d4c6582013-11-05 22:18:15 +0000833 explicit FoldConstant(EvalInfo &Info, bool Enabled)
834 : Info(Info),
835 Enabled(Enabled),
836 HadNoPriorDiags(Info.EvalStatus.Diag &&
837 Info.EvalStatus.Diag->empty() &&
838 !Info.EvalStatus.HasSideEffects),
839 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000840 if (Enabled &&
841 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
842 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000843 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000844 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000845 void keepDiagnostics() { Enabled = false; }
846 ~FoldConstant() {
847 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000848 !Info.EvalStatus.HasSideEffects)
849 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000850 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000851 }
852 };
Richard Smith17100ba2012-02-16 02:46:34 +0000853
George Burgess IV3a03fab2015-09-04 21:28:13 +0000854 /// RAII object used to treat the current evaluation as the correct pointer
855 /// offset fold for the current EvalMode
856 struct FoldOffsetRAII {
857 EvalInfo &Info;
858 EvalInfo::EvaluationMode OldMode;
859 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
860 : Info(Info), OldMode(Info.EvalMode) {
861 if (!Info.checkingPotentialConstantExpression())
862 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
863 : EvalInfo::EM_ConstantFold;
864 }
865
866 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
867 };
868
George Burgess IV8c892b52016-05-25 22:31:54 +0000869 /// RAII object used to optionally suppress diagnostics and side-effects from
870 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000871 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000872 /// Pair of EvalInfo, and a bit that stores whether or not we were
873 /// speculatively evaluating when we created this RAII.
874 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000875 Expr::EvalStatus Old;
876
George Burgess IV8c892b52016-05-25 22:31:54 +0000877 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
878 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
879 Old = Other.Old;
880 Other.InfoAndOldSpecEval.setPointer(nullptr);
881 }
882
883 void maybeRestoreState() {
884 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
885 if (!Info)
886 return;
887
888 Info->EvalStatus = Old;
889 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
890 }
891
Richard Smith17100ba2012-02-16 02:46:34 +0000892 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000893 SpeculativeEvaluationRAII() = default;
894
895 SpeculativeEvaluationRAII(
896 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
897 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
898 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000899 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000900 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000901 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000902
903 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
904 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
905 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +0000906 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000907
908 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
909 maybeRestoreState();
910 moveFromAndCancel(std::move(Other));
911 return *this;
912 }
913
914 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +0000915 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000916
917 /// RAII object wrapping a full-expression or block scope, and handling
918 /// the ending of the lifetime of temporaries created within it.
919 template<bool IsFullExpression>
920 class ScopeRAII {
921 EvalInfo &Info;
922 unsigned OldStackSize;
923 public:
924 ScopeRAII(EvalInfo &Info)
925 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
926 ~ScopeRAII() {
927 // Body moved to a static method to encourage the compiler to inline away
928 // instances of this class.
929 cleanup(Info, OldStackSize);
930 }
931 private:
932 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
933 unsigned NewEnd = OldStackSize;
934 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
935 I != N; ++I) {
936 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
937 // Full-expression cleanup of a lifetime-extended temporary: nothing
938 // to do, just move this cleanup to the right place in the stack.
939 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
940 ++NewEnd;
941 } else {
942 // End the lifetime of the object.
943 Info.CleanupStack[I].endLifetime();
944 }
945 }
946 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
947 Info.CleanupStack.end());
948 }
949 };
950 typedef ScopeRAII<false> BlockScopeRAII;
951 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000952}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000953
Richard Smitha8105bc2012-01-06 16:39:00 +0000954bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
955 CheckSubobjectKind CSK) {
956 if (Invalid)
957 return false;
958 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000959 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000960 << CSK;
961 setInvalid();
962 return false;
963 }
964 return true;
965}
966
967void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
968 const Expr *E, uint64_t N) {
George Burgess IVa51c4072015-10-16 01:49:01 +0000969 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000970 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000971 << static_cast<int>(N) << /*array*/ 0
972 << static_cast<unsigned>(MostDerivedArraySize);
973 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000974 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000975 << static_cast<int>(N) << /*non-array*/ 1;
976 setInvalid();
977}
978
Richard Smithf6f003a2011-12-16 19:06:07 +0000979CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
980 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000981 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +0000982 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
983 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000984 Info.CurrentCall = this;
985 ++Info.CallStackDepth;
986}
987
988CallStackFrame::~CallStackFrame() {
989 assert(Info.CurrentCall == this && "calls retired out of order");
990 --Info.CallStackDepth;
991 Info.CurrentCall = Caller;
992}
993
Richard Smith08d6a2c2013-07-24 07:11:57 +0000994APValue &CallStackFrame::createTemporary(const void *Key,
995 bool IsLifetimeExtended) {
996 APValue &Result = Temporaries[Key];
997 assert(Result.isUninit() && "temporary created multiple times");
998 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
999 return Result;
1000}
1001
Richard Smith84401042013-06-03 05:03:02 +00001002static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001003
1004void EvalInfo::addCallStack(unsigned Limit) {
1005 // Determine which calls to skip, if any.
1006 unsigned ActiveCalls = CallStackDepth - 1;
1007 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1008 if (Limit && Limit < ActiveCalls) {
1009 SkipStart = Limit / 2 + Limit % 2;
1010 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001011 }
1012
Richard Smithf6f003a2011-12-16 19:06:07 +00001013 // Walk the call stack and add the diagnostics.
1014 unsigned CallIdx = 0;
1015 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1016 Frame = Frame->Caller, ++CallIdx) {
1017 // Skip this call?
1018 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1019 if (CallIdx == SkipStart) {
1020 // Note that we're skipping calls.
1021 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1022 << unsigned(ActiveCalls - Limit);
1023 }
1024 continue;
1025 }
1026
Richard Smith5179eb72016-06-28 19:03:57 +00001027 // Use a different note for an inheriting constructor, because from the
1028 // user's perspective it's not really a function at all.
1029 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1030 if (CD->isInheritingConstructor()) {
1031 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1032 << CD->getParent();
1033 continue;
1034 }
1035 }
1036
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001037 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001038 llvm::raw_svector_ostream Out(Buffer);
1039 describeCall(Frame, Out);
1040 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1041 }
1042}
1043
1044namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001045 struct ComplexValue {
1046 private:
1047 bool IsInt;
1048
1049 public:
1050 APSInt IntReal, IntImag;
1051 APFloat FloatReal, FloatImag;
1052
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001053 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001054
1055 void makeComplexFloat() { IsInt = false; }
1056 bool isComplexFloat() const { return !IsInt; }
1057 APFloat &getComplexFloatReal() { return FloatReal; }
1058 APFloat &getComplexFloatImag() { return FloatImag; }
1059
1060 void makeComplexInt() { IsInt = true; }
1061 bool isComplexInt() const { return IsInt; }
1062 APSInt &getComplexIntReal() { return IntReal; }
1063 APSInt &getComplexIntImag() { return IntImag; }
1064
Richard Smith2e312c82012-03-03 22:46:17 +00001065 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001066 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001067 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001068 else
Richard Smith2e312c82012-03-03 22:46:17 +00001069 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001070 }
Richard Smith2e312c82012-03-03 22:46:17 +00001071 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001072 assert(v.isComplexFloat() || v.isComplexInt());
1073 if (v.isComplexFloat()) {
1074 makeComplexFloat();
1075 FloatReal = v.getComplexFloatReal();
1076 FloatImag = v.getComplexFloatImag();
1077 } else {
1078 makeComplexInt();
1079 IntReal = v.getComplexIntReal();
1080 IntImag = v.getComplexIntImag();
1081 }
1082 }
John McCall93d91dc2010-05-07 17:22:02 +00001083 };
John McCall45d55e42010-05-07 21:00:08 +00001084
1085 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001086 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001087 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001088 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001089 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001090 SubobjectDesignator Designator;
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00001091 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001092
Richard Smithce40ad62011-11-12 22:28:03 +00001093 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001094 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001095 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001096 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001097 SubobjectDesignator &getLValueDesignator() { return Designator; }
1098 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00001099 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001100
Richard Smith2e312c82012-03-03 22:46:17 +00001101 void moveInto(APValue &V) const {
1102 if (Designator.Invalid)
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00001103 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1104 IsNullPtr);
Richard Smith2e312c82012-03-03 22:46:17 +00001105 else
1106 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00001107 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
John McCall45d55e42010-05-07 21:00:08 +00001108 }
Richard Smith2e312c82012-03-03 22:46:17 +00001109 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001110 assert(V.isLValue());
1111 Base = V.getLValueBase();
1112 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001113 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001114 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001115 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00001116 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001117 }
1118
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00001119 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1120 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +00001121 Base = B;
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00001122 Offset = CharUnits::fromQuantity(Offset_);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001123 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001124 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001125 Designator = SubobjectDesignator(getType(B));
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00001126 IsNullPtr = IsNullPtr_;
Richard Smitha8105bc2012-01-06 16:39:00 +00001127 }
1128
George Burgess IV3a03fab2015-09-04 21:28:13 +00001129 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1130 set(B, I, true);
1131 }
1132
Richard Smitha8105bc2012-01-06 16:39:00 +00001133 // Check that this LValue is not based on a null pointer. If it is, produce
1134 // a diagnostic and mark the designator as invalid.
1135 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1136 CheckSubobjectKind CSK) {
1137 if (Designator.Invalid)
1138 return false;
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00001139 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001140 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001141 << CSK;
1142 Designator.setInvalid();
1143 return false;
1144 }
1145 return true;
1146 }
1147
1148 // Check this LValue refers to an object. If not, set the designator to be
1149 // invalid and emit a diagnostic.
1150 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001151 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001152 Designator.checkSubobject(Info, E, CSK);
1153 }
1154
1155 void addDecl(EvalInfo &Info, const Expr *E,
1156 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001157 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1158 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001159 }
1160 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001161 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1162 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001163 }
Richard Smith66c96992012-02-18 22:04:06 +00001164 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001165 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1166 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001167 }
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00001168 void clearIsNullPointer() {
1169 IsNullPtr = false;
1170 }
1171 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, uint64_t Index,
1172 CharUnits ElementSize) {
1173 // Compute the new offset in the appropriate width.
1174 Offset += Index * ElementSize;
1175 if (Index && checkNullPointer(Info, E, CSK_ArrayIndex))
1176 Designator.adjustIndex(Info, E, Index);
1177 if (Index)
1178 clearIsNullPointer();
1179 }
1180 void adjustOffset(CharUnits N) {
1181 Offset += N;
1182 if (N.getQuantity())
1183 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001184 }
John McCall45d55e42010-05-07 21:00:08 +00001185 };
Richard Smith027bf112011-11-17 22:56:20 +00001186
1187 struct MemberPtr {
1188 MemberPtr() {}
1189 explicit MemberPtr(const ValueDecl *Decl) :
1190 DeclAndIsDerivedMember(Decl, false), Path() {}
1191
1192 /// The member or (direct or indirect) field referred to by this member
1193 /// pointer, or 0 if this is a null member pointer.
1194 const ValueDecl *getDecl() const {
1195 return DeclAndIsDerivedMember.getPointer();
1196 }
1197 /// Is this actually a member of some type derived from the relevant class?
1198 bool isDerivedMember() const {
1199 return DeclAndIsDerivedMember.getInt();
1200 }
1201 /// Get the class which the declaration actually lives in.
1202 const CXXRecordDecl *getContainingRecord() const {
1203 return cast<CXXRecordDecl>(
1204 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1205 }
1206
Richard Smith2e312c82012-03-03 22:46:17 +00001207 void moveInto(APValue &V) const {
1208 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001209 }
Richard Smith2e312c82012-03-03 22:46:17 +00001210 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001211 assert(V.isMemberPointer());
1212 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1213 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1214 Path.clear();
1215 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1216 Path.insert(Path.end(), P.begin(), P.end());
1217 }
1218
1219 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1220 /// whether the member is a member of some class derived from the class type
1221 /// of the member pointer.
1222 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1223 /// Path - The path of base/derived classes from the member declaration's
1224 /// class (exclusive) to the class type of the member pointer (inclusive).
1225 SmallVector<const CXXRecordDecl*, 4> Path;
1226
1227 /// Perform a cast towards the class of the Decl (either up or down the
1228 /// hierarchy).
1229 bool castBack(const CXXRecordDecl *Class) {
1230 assert(!Path.empty());
1231 const CXXRecordDecl *Expected;
1232 if (Path.size() >= 2)
1233 Expected = Path[Path.size() - 2];
1234 else
1235 Expected = getContainingRecord();
1236 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1237 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1238 // if B does not contain the original member and is not a base or
1239 // derived class of the class containing the original member, the result
1240 // of the cast is undefined.
1241 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1242 // (D::*). We consider that to be a language defect.
1243 return false;
1244 }
1245 Path.pop_back();
1246 return true;
1247 }
1248 /// Perform a base-to-derived member pointer cast.
1249 bool castToDerived(const CXXRecordDecl *Derived) {
1250 if (!getDecl())
1251 return true;
1252 if (!isDerivedMember()) {
1253 Path.push_back(Derived);
1254 return true;
1255 }
1256 if (!castBack(Derived))
1257 return false;
1258 if (Path.empty())
1259 DeclAndIsDerivedMember.setInt(false);
1260 return true;
1261 }
1262 /// Perform a derived-to-base member pointer cast.
1263 bool castToBase(const CXXRecordDecl *Base) {
1264 if (!getDecl())
1265 return true;
1266 if (Path.empty())
1267 DeclAndIsDerivedMember.setInt(true);
1268 if (isDerivedMember()) {
1269 Path.push_back(Base);
1270 return true;
1271 }
1272 return castBack(Base);
1273 }
1274 };
Richard Smith357362d2011-12-13 06:39:58 +00001275
Richard Smith7bb00672012-02-01 01:42:44 +00001276 /// Compare two member pointers, which are assumed to be of the same type.
1277 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1278 if (!LHS.getDecl() || !RHS.getDecl())
1279 return !LHS.getDecl() && !RHS.getDecl();
1280 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1281 return false;
1282 return LHS.Path == RHS.Path;
1283 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001284}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001285
Richard Smith2e312c82012-03-03 22:46:17 +00001286static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001287static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1288 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001289 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001290static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1291static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001292static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1293 EvalInfo &Info);
1294static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001295static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001296static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001297 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001298static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001299static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001300static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001301static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001302
1303//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001304// Misc utilities
1305//===----------------------------------------------------------------------===//
1306
Richard Smith84401042013-06-03 05:03:02 +00001307/// Produce a string describing the given constexpr call.
1308static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1309 unsigned ArgIndex = 0;
1310 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1311 !isa<CXXConstructorDecl>(Frame->Callee) &&
1312 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1313
1314 if (!IsMemberCall)
1315 Out << *Frame->Callee << '(';
1316
1317 if (Frame->This && IsMemberCall) {
1318 APValue Val;
1319 Frame->This->moveInto(Val);
1320 Val.printPretty(Out, Frame->Info.Ctx,
1321 Frame->This->Designator.MostDerivedType);
1322 // FIXME: Add parens around Val if needed.
1323 Out << "->" << *Frame->Callee << '(';
1324 IsMemberCall = false;
1325 }
1326
1327 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1328 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1329 if (ArgIndex > (unsigned)IsMemberCall)
1330 Out << ", ";
1331
1332 const ParmVarDecl *Param = *I;
1333 const APValue &Arg = Frame->Arguments[ArgIndex];
1334 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1335
1336 if (ArgIndex == 0 && IsMemberCall)
1337 Out << "->" << *Frame->Callee << '(';
1338 }
1339
1340 Out << ')';
1341}
1342
Richard Smithd9f663b2013-04-22 15:31:51 +00001343/// Evaluate an expression to see if it had side-effects, and discard its
1344/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001345/// \return \c true if the caller should keep evaluating.
1346static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001347 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001348 if (!Evaluate(Scratch, Info, E))
1349 // We don't need the value, but we might have skipped a side effect here.
1350 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001351 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001352}
1353
Richard Smith861b5b52013-05-07 23:34:45 +00001354/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1355/// return its existing value.
1356static int64_t getExtValue(const APSInt &Value) {
1357 return Value.isSigned() ? Value.getSExtValue()
1358 : static_cast<int64_t>(Value.getZExtValue());
1359}
1360
Richard Smithd62306a2011-11-10 06:34:14 +00001361/// Should this call expression be treated as a string literal?
1362static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001363 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001364 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1365 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1366}
1367
Richard Smithce40ad62011-11-12 22:28:03 +00001368static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001369 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1370 // constant expression of pointer type that evaluates to...
1371
1372 // ... a null pointer value, or a prvalue core constant expression of type
1373 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001374 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001375
Richard Smithce40ad62011-11-12 22:28:03 +00001376 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1377 // ... the address of an object with static storage duration,
1378 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1379 return VD->hasGlobalStorage();
1380 // ... the address of a function,
1381 return isa<FunctionDecl>(D);
1382 }
1383
1384 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001385 switch (E->getStmtClass()) {
1386 default:
1387 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001388 case Expr::CompoundLiteralExprClass: {
1389 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1390 return CLE->isFileScope() && CLE->isLValue();
1391 }
Richard Smithe6c01442013-06-05 00:46:14 +00001392 case Expr::MaterializeTemporaryExprClass:
1393 // A materialized temporary might have been lifetime-extended to static
1394 // storage duration.
1395 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001396 // A string literal has static storage duration.
1397 case Expr::StringLiteralClass:
1398 case Expr::PredefinedExprClass:
1399 case Expr::ObjCStringLiteralClass:
1400 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001401 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001402 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001403 return true;
1404 case Expr::CallExprClass:
1405 return IsStringLiteralCall(cast<CallExpr>(E));
1406 // For GCC compatibility, &&label has static storage duration.
1407 case Expr::AddrLabelExprClass:
1408 return true;
1409 // A Block literal expression may be used as the initialization value for
1410 // Block variables at global or local static scope.
1411 case Expr::BlockExprClass:
1412 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001413 case Expr::ImplicitValueInitExprClass:
1414 // FIXME:
1415 // We can never form an lvalue with an implicit value initialization as its
1416 // base through expression evaluation, so these only appear in one case: the
1417 // implicit variable declaration we invent when checking whether a constexpr
1418 // constructor can produce a constant expression. We must assume that such
1419 // an expression might be a global lvalue.
1420 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001421 }
John McCall95007602010-05-10 23:27:23 +00001422}
1423
Richard Smithb228a862012-02-15 02:18:13 +00001424static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1425 assert(Base && "no location for a null lvalue");
1426 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1427 if (VD)
1428 Info.Note(VD->getLocation(), diag::note_declared_at);
1429 else
Ted Kremenek28831752012-08-23 20:46:57 +00001430 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001431 diag::note_constexpr_temporary_here);
1432}
1433
Richard Smith80815602011-11-07 05:07:52 +00001434/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001435/// value for an address or reference constant expression. Return true if we
1436/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001437static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1438 QualType Type, const LValue &LVal) {
1439 bool IsReferenceType = Type->isReferenceType();
1440
Richard Smith357362d2011-12-13 06:39:58 +00001441 APValue::LValueBase Base = LVal.getLValueBase();
1442 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1443
Richard Smith0dea49e2012-02-18 04:58:18 +00001444 // Check that the object is a global. Note that the fake 'this' object we
1445 // manufacture when checking potential constant expressions is conservatively
1446 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001447 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001448 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001449 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001450 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001451 << IsReferenceType << !Designator.Entries.empty()
1452 << !!VD << VD;
1453 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001454 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001455 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001456 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001457 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001458 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001459 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001460 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001461 LVal.getLValueCallIndex() == 0) &&
1462 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001463
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001464 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1465 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001466 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001467 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001468 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001469
Hans Wennborg82dd8772014-06-25 22:19:48 +00001470 // A dllimport variable never acts like a constant.
1471 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001472 return false;
1473 }
1474 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1475 // __declspec(dllimport) must be handled very carefully:
1476 // We must never initialize an expression with the thunk in C++.
1477 // Doing otherwise would allow the same id-expression to yield
1478 // different addresses for the same function in different translation
1479 // units. However, this means that we must dynamically initialize the
1480 // expression with the contents of the import address table at runtime.
1481 //
1482 // The C language has no notion of ODR; furthermore, it has no notion of
1483 // dynamic initialization. This means that we are permitted to
1484 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001485 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001486 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001487 }
1488 }
1489
Richard Smitha8105bc2012-01-06 16:39:00 +00001490 // Allow address constant expressions to be past-the-end pointers. This is
1491 // an extension: the standard requires them to point to an object.
1492 if (!IsReferenceType)
1493 return true;
1494
1495 // A reference constant expression must refer to an object.
1496 if (!Base) {
1497 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001498 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001499 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001500 }
1501
Richard Smith357362d2011-12-13 06:39:58 +00001502 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001503 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001504 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001505 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001506 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001507 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001508 }
1509
Richard Smith80815602011-11-07 05:07:52 +00001510 return true;
1511}
1512
Richard Smithfddd3842011-12-30 21:15:51 +00001513/// Check that this core constant expression is of literal type, and if not,
1514/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001515static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001516 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001517 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001518 return true;
1519
Richard Smith7525ff62013-05-09 07:14:00 +00001520 // C++1y: A constant initializer for an object o [...] may also invoke
1521 // constexpr constructors for o and its subobjects even if those objects
1522 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001523 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001524 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001525 return true;
1526
Richard Smithfddd3842011-12-30 21:15:51 +00001527 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001528 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001529 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001530 << E->getType();
1531 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001532 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001533 return false;
1534}
1535
Richard Smith0b0a0b62011-10-29 20:57:55 +00001536/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001537/// constant expression. If not, report an appropriate diagnostic. Does not
1538/// check that the expression is of literal type.
1539static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1540 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001541 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001542 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001543 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001544 return false;
1545 }
1546
Richard Smith77be48a2014-07-31 06:31:19 +00001547 // We allow _Atomic(T) to be initialized from anything that T can be
1548 // initialized from.
1549 if (const AtomicType *AT = Type->getAs<AtomicType>())
1550 Type = AT->getValueType();
1551
Richard Smithb228a862012-02-15 02:18:13 +00001552 // Core issue 1454: For a literal constant expression of array or class type,
1553 // each subobject of its value shall have been initialized by a constant
1554 // expression.
1555 if (Value.isArray()) {
1556 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1557 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1558 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1559 Value.getArrayInitializedElt(I)))
1560 return false;
1561 }
1562 if (!Value.hasArrayFiller())
1563 return true;
1564 return CheckConstantExpression(Info, DiagLoc, EltTy,
1565 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001566 }
Richard Smithb228a862012-02-15 02:18:13 +00001567 if (Value.isUnion() && Value.getUnionField()) {
1568 return CheckConstantExpression(Info, DiagLoc,
1569 Value.getUnionField()->getType(),
1570 Value.getUnionValue());
1571 }
1572 if (Value.isStruct()) {
1573 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1574 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1575 unsigned BaseIndex = 0;
1576 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1577 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1578 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1579 Value.getStructBase(BaseIndex)))
1580 return false;
1581 }
1582 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001583 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001584 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1585 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001586 return false;
1587 }
1588 }
1589
1590 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001591 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001592 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001593 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1594 }
1595
1596 // Everything else is fine.
1597 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001598}
1599
Benjamin Kramer8407df72015-03-09 16:47:52 +00001600static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001601 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001602}
1603
1604static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001605 if (Value.CallIndex)
1606 return false;
1607 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1608 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001609}
1610
Richard Smithcecf1842011-11-01 21:06:14 +00001611static bool IsWeakLValue(const LValue &Value) {
1612 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001613 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001614}
1615
David Majnemerb5116032014-12-09 23:32:34 +00001616static bool isZeroSized(const LValue &Value) {
1617 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001618 if (Decl && isa<VarDecl>(Decl)) {
1619 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001620 if (Ty->isArrayType())
1621 return Ty->isIncompleteType() ||
1622 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001623 }
1624 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001625}
1626
Richard Smith2e312c82012-03-03 22:46:17 +00001627static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001628 // A null base expression indicates a null pointer. These are always
1629 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001630 if (!Value.getLValueBase()) {
1631 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001632 return true;
1633 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001634
Richard Smith027bf112011-11-17 22:56:20 +00001635 // We have a non-null base. These are generally known to be true, but if it's
1636 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001637 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001638 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001639 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001640}
1641
Richard Smith2e312c82012-03-03 22:46:17 +00001642static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001643 switch (Val.getKind()) {
1644 case APValue::Uninitialized:
1645 return false;
1646 case APValue::Int:
1647 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001648 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001649 case APValue::Float:
1650 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001651 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001652 case APValue::ComplexInt:
1653 Result = Val.getComplexIntReal().getBoolValue() ||
1654 Val.getComplexIntImag().getBoolValue();
1655 return true;
1656 case APValue::ComplexFloat:
1657 Result = !Val.getComplexFloatReal().isZero() ||
1658 !Val.getComplexFloatImag().isZero();
1659 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001660 case APValue::LValue:
1661 return EvalPointerValueAsBool(Val, Result);
1662 case APValue::MemberPointer:
1663 Result = Val.getMemberPointerDecl();
1664 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001665 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001666 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001667 case APValue::Struct:
1668 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001669 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001670 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001671 }
1672
Richard Smith11562c52011-10-28 17:51:58 +00001673 llvm_unreachable("unknown APValue kind");
1674}
1675
1676static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1677 EvalInfo &Info) {
1678 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001679 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001680 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001681 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001682 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001683}
1684
Richard Smith357362d2011-12-13 06:39:58 +00001685template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001686static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001687 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001688 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001689 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001690 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001691}
1692
1693static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1694 QualType SrcType, const APFloat &Value,
1695 QualType DestType, APSInt &Result) {
1696 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001697 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001698 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001699
Richard Smith357362d2011-12-13 06:39:58 +00001700 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001701 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001702 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1703 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001704 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001705 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001706}
1707
Richard Smith357362d2011-12-13 06:39:58 +00001708static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1709 QualType SrcType, QualType DestType,
1710 APFloat &Result) {
1711 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001712 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001713 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1714 APFloat::rmNearestTiesToEven, &ignored)
1715 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001716 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001717 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001718}
1719
Richard Smith911e1422012-01-30 22:27:01 +00001720static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1721 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001722 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001723 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001724 APSInt Result = Value;
1725 // Figure out if this is a truncate, extend or noop cast.
1726 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001727 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001728 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001729 return Result;
1730}
1731
Richard Smith357362d2011-12-13 06:39:58 +00001732static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1733 QualType SrcType, const APSInt &Value,
1734 QualType DestType, APFloat &Result) {
1735 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1736 if (Result.convertFromAPInt(Value, Value.isSigned(),
1737 APFloat::rmNearestTiesToEven)
1738 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001739 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001740 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001741}
1742
Richard Smith49ca8aa2013-08-06 07:09:20 +00001743static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1744 APValue &Value, const FieldDecl *FD) {
1745 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1746
1747 if (!Value.isInt()) {
1748 // Trying to store a pointer-cast-to-integer into a bitfield.
1749 // FIXME: In this case, we should provide the diagnostic for casting
1750 // a pointer to an integer.
1751 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001752 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001753 return false;
1754 }
1755
1756 APSInt &Int = Value.getInt();
1757 unsigned OldBitWidth = Int.getBitWidth();
1758 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1759 if (NewBitWidth < OldBitWidth)
1760 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1761 return true;
1762}
1763
Eli Friedman803acb32011-12-22 03:51:45 +00001764static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1765 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001766 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001767 if (!Evaluate(SVal, Info, E))
1768 return false;
1769 if (SVal.isInt()) {
1770 Res = SVal.getInt();
1771 return true;
1772 }
1773 if (SVal.isFloat()) {
1774 Res = SVal.getFloat().bitcastToAPInt();
1775 return true;
1776 }
1777 if (SVal.isVector()) {
1778 QualType VecTy = E->getType();
1779 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1780 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1781 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1782 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1783 Res = llvm::APInt::getNullValue(VecSize);
1784 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1785 APValue &Elt = SVal.getVectorElt(i);
1786 llvm::APInt EltAsInt;
1787 if (Elt.isInt()) {
1788 EltAsInt = Elt.getInt();
1789 } else if (Elt.isFloat()) {
1790 EltAsInt = Elt.getFloat().bitcastToAPInt();
1791 } else {
1792 // Don't try to handle vectors of anything other than int or float
1793 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00001794 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001795 return false;
1796 }
1797 unsigned BaseEltSize = EltAsInt.getBitWidth();
1798 if (BigEndian)
1799 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1800 else
1801 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1802 }
1803 return true;
1804 }
1805 // Give up if the input isn't an int, float, or vector. For example, we
1806 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00001807 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001808 return false;
1809}
1810
Richard Smith43e77732013-05-07 04:50:00 +00001811/// Perform the given integer operation, which is known to need at most BitWidth
1812/// bits, and check for overflow in the original type (if that type was not an
1813/// unsigned type).
1814template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001815static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1816 const APSInt &LHS, const APSInt &RHS,
1817 unsigned BitWidth, Operation Op,
1818 APSInt &Result) {
1819 if (LHS.isUnsigned()) {
1820 Result = Op(LHS, RHS);
1821 return true;
1822 }
Richard Smith43e77732013-05-07 04:50:00 +00001823
1824 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001825 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001826 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001827 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001828 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001829 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001830 << Result.toString(10) << E->getType();
1831 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001832 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001833 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001834 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001835}
1836
1837/// Perform the given binary integer operation.
1838static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1839 BinaryOperatorKind Opcode, APSInt RHS,
1840 APSInt &Result) {
1841 switch (Opcode) {
1842 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001843 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00001844 return false;
1845 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001846 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1847 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001848 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001849 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1850 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001851 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001852 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1853 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001854 case BO_And: Result = LHS & RHS; return true;
1855 case BO_Xor: Result = LHS ^ RHS; return true;
1856 case BO_Or: Result = LHS | RHS; return true;
1857 case BO_Div:
1858 case BO_Rem:
1859 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001860 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00001861 return false;
1862 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001863 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1864 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1865 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001866 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1867 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001868 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1869 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001870 return true;
1871 case BO_Shl: {
1872 if (Info.getLangOpts().OpenCL)
1873 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1874 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1875 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1876 RHS.isUnsigned());
1877 else if (RHS.isSigned() && RHS.isNegative()) {
1878 // During constant-folding, a negative shift is an opposite shift. Such
1879 // a shift is not a constant expression.
1880 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1881 RHS = -RHS;
1882 goto shift_right;
1883 }
1884 shift_left:
1885 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1886 // the shifted type.
1887 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1888 if (SA != RHS) {
1889 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1890 << RHS << E->getType() << LHS.getBitWidth();
1891 } else if (LHS.isSigned()) {
1892 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1893 // operand, and must not overflow the corresponding unsigned type.
1894 if (LHS.isNegative())
1895 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1896 else if (LHS.countLeadingZeros() < SA)
1897 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1898 }
1899 Result = LHS << SA;
1900 return true;
1901 }
1902 case BO_Shr: {
1903 if (Info.getLangOpts().OpenCL)
1904 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1905 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1906 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1907 RHS.isUnsigned());
1908 else if (RHS.isSigned() && RHS.isNegative()) {
1909 // During constant-folding, a negative shift is an opposite shift. Such a
1910 // shift is not a constant expression.
1911 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1912 RHS = -RHS;
1913 goto shift_left;
1914 }
1915 shift_right:
1916 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1917 // shifted type.
1918 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1919 if (SA != RHS)
1920 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1921 << RHS << E->getType() << LHS.getBitWidth();
1922 Result = LHS >> SA;
1923 return true;
1924 }
1925
1926 case BO_LT: Result = LHS < RHS; return true;
1927 case BO_GT: Result = LHS > RHS; return true;
1928 case BO_LE: Result = LHS <= RHS; return true;
1929 case BO_GE: Result = LHS >= RHS; return true;
1930 case BO_EQ: Result = LHS == RHS; return true;
1931 case BO_NE: Result = LHS != RHS; return true;
1932 }
1933}
1934
Richard Smith861b5b52013-05-07 23:34:45 +00001935/// Perform the given binary floating-point operation, in-place, on LHS.
1936static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1937 APFloat &LHS, BinaryOperatorKind Opcode,
1938 const APFloat &RHS) {
1939 switch (Opcode) {
1940 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00001941 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00001942 return false;
1943 case BO_Mul:
1944 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1945 break;
1946 case BO_Add:
1947 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1948 break;
1949 case BO_Sub:
1950 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1951 break;
1952 case BO_Div:
1953 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1954 break;
1955 }
1956
Richard Smith0c6124b2015-12-03 01:36:22 +00001957 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00001958 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00001959 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00001960 }
Richard Smith861b5b52013-05-07 23:34:45 +00001961 return true;
1962}
1963
Richard Smitha8105bc2012-01-06 16:39:00 +00001964/// Cast an lvalue referring to a base subobject to a derived class, by
1965/// truncating the lvalue's path to the given length.
1966static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1967 const RecordDecl *TruncatedType,
1968 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001969 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001970
1971 // Check we actually point to a derived class object.
1972 if (TruncatedElements == D.Entries.size())
1973 return true;
1974 assert(TruncatedElements >= D.MostDerivedPathLength &&
1975 "not casting to a derived class");
1976 if (!Result.checkSubobject(Info, E, CSK_Derived))
1977 return false;
1978
1979 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001980 const RecordDecl *RD = TruncatedType;
1981 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001982 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001983 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1984 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001985 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001986 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001987 else
Richard Smithd62306a2011-11-10 06:34:14 +00001988 Result.Offset -= Layout.getBaseClassOffset(Base);
1989 RD = Base;
1990 }
Richard Smith027bf112011-11-17 22:56:20 +00001991 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001992 return true;
1993}
1994
John McCalld7bca762012-05-01 00:38:49 +00001995static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001996 const CXXRecordDecl *Derived,
1997 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001998 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001999 if (!RL) {
2000 if (Derived->isInvalidDecl()) return false;
2001 RL = &Info.Ctx.getASTRecordLayout(Derived);
2002 }
2003
Richard Smithd62306a2011-11-10 06:34:14 +00002004 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002005 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002006 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002007}
2008
Richard Smitha8105bc2012-01-06 16:39:00 +00002009static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002010 const CXXRecordDecl *DerivedDecl,
2011 const CXXBaseSpecifier *Base) {
2012 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2013
John McCalld7bca762012-05-01 00:38:49 +00002014 if (!Base->isVirtual())
2015 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002016
Richard Smitha8105bc2012-01-06 16:39:00 +00002017 SubobjectDesignator &D = Obj.Designator;
2018 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002019 return false;
2020
Richard Smitha8105bc2012-01-06 16:39:00 +00002021 // Extract most-derived object and corresponding type.
2022 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2023 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2024 return false;
2025
2026 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002027 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002028 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2029 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002030 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002031 return true;
2032}
2033
Richard Smith84401042013-06-03 05:03:02 +00002034static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2035 QualType Type, LValue &Result) {
2036 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2037 PathE = E->path_end();
2038 PathI != PathE; ++PathI) {
2039 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2040 *PathI))
2041 return false;
2042 Type = (*PathI)->getType();
2043 }
2044 return true;
2045}
2046
Richard Smithd62306a2011-11-10 06:34:14 +00002047/// Update LVal to refer to the given field, which must be a member of the type
2048/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002049static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002050 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002051 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002052 if (!RL) {
2053 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002054 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002055 }
Richard Smithd62306a2011-11-10 06:34:14 +00002056
2057 unsigned I = FD->getFieldIndex();
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00002058 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002059 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002060 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002061}
2062
Richard Smith1b78b3d2012-01-25 22:15:11 +00002063/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002064static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002065 LValue &LVal,
2066 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002067 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002068 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002069 return false;
2070 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002071}
2072
Richard Smithd62306a2011-11-10 06:34:14 +00002073/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002074static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2075 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002076 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2077 // extension.
2078 if (Type->isVoidType() || Type->isFunctionType()) {
2079 Size = CharUnits::One();
2080 return true;
2081 }
2082
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002083 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002084 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002085 return false;
2086 }
2087
Richard Smithd62306a2011-11-10 06:34:14 +00002088 if (!Type->isConstantSizeType()) {
2089 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002090 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002091 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002092 return false;
2093 }
2094
2095 Size = Info.Ctx.getTypeSizeInChars(Type);
2096 return true;
2097}
2098
2099/// Update a pointer value to model pointer arithmetic.
2100/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002101/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002102/// \param LVal - The pointer value to be updated.
2103/// \param EltTy - The pointee type represented by LVal.
2104/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002105static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2106 LValue &LVal, QualType EltTy,
2107 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002108 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002109 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002110 return false;
2111
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00002112 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002113 return true;
2114}
2115
Richard Smith66c96992012-02-18 22:04:06 +00002116/// Update an lvalue to refer to a component of a complex number.
2117/// \param Info - Information about the ongoing evaluation.
2118/// \param LVal - The lvalue to be updated.
2119/// \param EltTy - The complex number's component type.
2120/// \param Imag - False for the real component, true for the imaginary.
2121static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2122 LValue &LVal, QualType EltTy,
2123 bool Imag) {
2124 if (Imag) {
2125 CharUnits SizeOfComponent;
2126 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2127 return false;
2128 LVal.Offset += SizeOfComponent;
2129 }
2130 LVal.addComplex(Info, E, EltTy, Imag);
2131 return true;
2132}
2133
Richard Smith27908702011-10-24 17:54:18 +00002134/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002135///
2136/// \param Info Information about the ongoing evaluation.
2137/// \param E An expression to be used when printing diagnostics.
2138/// \param VD The variable whose initializer should be obtained.
2139/// \param Frame The frame in which the variable was created. Must be null
2140/// if this variable is not local to the evaluation.
2141/// \param Result Filled in with a pointer to the value of the variable.
2142static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2143 const VarDecl *VD, CallStackFrame *Frame,
2144 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002145 // If this is a parameter to an active constexpr function call, perform
2146 // argument substitution.
2147 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002148 // Assume arguments of a potential constant expression are unknown
2149 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002150 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002151 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002152 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002153 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002154 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002155 }
Richard Smith3229b742013-05-05 21:17:10 +00002156 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002157 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002158 }
Richard Smith27908702011-10-24 17:54:18 +00002159
Richard Smithd9f663b2013-04-22 15:31:51 +00002160 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002161 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002162 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002163 if (!Result) {
2164 // Assume variables referenced within a lambda's call operator that were
2165 // not declared within the call operator are captures and during checking
2166 // of a potential constant expression, assume they are unknown constant
2167 // expressions.
2168 assert(isLambdaCallOperator(Frame->Callee) &&
2169 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2170 "missing value for local variable");
2171 if (Info.checkingPotentialConstantExpression())
2172 return false;
2173 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002174 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002175 diag::note_unimplemented_constexpr_lambda_feature_ast)
2176 << "captures not currently allowed";
2177 return false;
2178 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002179 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002180 }
2181
Richard Smithd0b4dd62011-12-19 06:19:21 +00002182 // Dig out the initializer, and use the declaration which it's attached to.
2183 const Expr *Init = VD->getAnyInitializer(VD);
2184 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002185 // If we're checking a potential constant expression, the variable could be
2186 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002187 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002188 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002189 return false;
2190 }
2191
Richard Smithd62306a2011-11-10 06:34:14 +00002192 // If we're currently evaluating the initializer of this declaration, use that
2193 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002194 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002195 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002196 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002197 }
2198
Richard Smithcecf1842011-11-01 21:06:14 +00002199 // Never evaluate the initializer of a weak variable. We can't be sure that
2200 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002201 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002202 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002203 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002204 }
Richard Smithcecf1842011-11-01 21:06:14 +00002205
Richard Smithd0b4dd62011-12-19 06:19:21 +00002206 // Check that we can fold the initializer. In C++, we will have already done
2207 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002208 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002209 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002210 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002211 Notes.size() + 1) << VD;
2212 Info.Note(VD->getLocation(), diag::note_declared_at);
2213 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002214 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002215 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002216 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002217 Notes.size() + 1) << VD;
2218 Info.Note(VD->getLocation(), diag::note_declared_at);
2219 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002220 }
Richard Smith27908702011-10-24 17:54:18 +00002221
Richard Smith3229b742013-05-05 21:17:10 +00002222 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002223 return true;
Richard Smith27908702011-10-24 17:54:18 +00002224}
2225
Richard Smith11562c52011-10-28 17:51:58 +00002226static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002227 Qualifiers Quals = T.getQualifiers();
2228 return Quals.hasConst() && !Quals.hasVolatile();
2229}
2230
Richard Smithe97cbd72011-11-11 04:05:33 +00002231/// Get the base index of the given base class within an APValue representing
2232/// the given derived class.
2233static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2234 const CXXRecordDecl *Base) {
2235 Base = Base->getCanonicalDecl();
2236 unsigned Index = 0;
2237 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2238 E = Derived->bases_end(); I != E; ++I, ++Index) {
2239 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2240 return Index;
2241 }
2242
2243 llvm_unreachable("base class missing from derived class's bases list");
2244}
2245
Richard Smith3da88fa2013-04-26 14:36:30 +00002246/// Extract the value of a character from a string literal.
2247static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2248 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002249 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2250 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2251 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002252 const StringLiteral *S = cast<StringLiteral>(Lit);
2253 const ConstantArrayType *CAT =
2254 Info.Ctx.getAsConstantArrayType(S->getType());
2255 assert(CAT && "string literal isn't an array");
2256 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002257 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002258
2259 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002260 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002261 if (Index < S->getLength())
2262 Value = S->getCodeUnit(Index);
2263 return Value;
2264}
2265
Richard Smith3da88fa2013-04-26 14:36:30 +00002266// Expand a string literal into an array of characters.
2267static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2268 APValue &Result) {
2269 const StringLiteral *S = cast<StringLiteral>(Lit);
2270 const ConstantArrayType *CAT =
2271 Info.Ctx.getAsConstantArrayType(S->getType());
2272 assert(CAT && "string literal isn't an array");
2273 QualType CharType = CAT->getElementType();
2274 assert(CharType->isIntegerType() && "unexpected character type");
2275
2276 unsigned Elts = CAT->getSize().getZExtValue();
2277 Result = APValue(APValue::UninitArray(),
2278 std::min(S->getLength(), Elts), Elts);
2279 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2280 CharType->isUnsignedIntegerType());
2281 if (Result.hasArrayFiller())
2282 Result.getArrayFiller() = APValue(Value);
2283 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2284 Value = S->getCodeUnit(I);
2285 Result.getArrayInitializedElt(I) = APValue(Value);
2286 }
2287}
2288
2289// Expand an array so that it has more than Index filled elements.
2290static void expandArray(APValue &Array, unsigned Index) {
2291 unsigned Size = Array.getArraySize();
2292 assert(Index < Size);
2293
2294 // Always at least double the number of elements for which we store a value.
2295 unsigned OldElts = Array.getArrayInitializedElts();
2296 unsigned NewElts = std::max(Index+1, OldElts * 2);
2297 NewElts = std::min(Size, std::max(NewElts, 8u));
2298
2299 // Copy the data across.
2300 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2301 for (unsigned I = 0; I != OldElts; ++I)
2302 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2303 for (unsigned I = OldElts; I != NewElts; ++I)
2304 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2305 if (NewValue.hasArrayFiller())
2306 NewValue.getArrayFiller() = Array.getArrayFiller();
2307 Array.swap(NewValue);
2308}
2309
Richard Smithb01fe402014-09-16 01:24:02 +00002310/// Determine whether a type would actually be read by an lvalue-to-rvalue
2311/// conversion. If it's of class type, we may assume that the copy operation
2312/// is trivial. Note that this is never true for a union type with fields
2313/// (because the copy always "reads" the active member) and always true for
2314/// a non-class type.
2315static bool isReadByLvalueToRvalueConversion(QualType T) {
2316 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2317 if (!RD || (RD->isUnion() && !RD->field_empty()))
2318 return true;
2319 if (RD->isEmpty())
2320 return false;
2321
2322 for (auto *Field : RD->fields())
2323 if (isReadByLvalueToRvalueConversion(Field->getType()))
2324 return true;
2325
2326 for (auto &BaseSpec : RD->bases())
2327 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2328 return true;
2329
2330 return false;
2331}
2332
2333/// Diagnose an attempt to read from any unreadable field within the specified
2334/// type, which might be a class type.
2335static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2336 QualType T) {
2337 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2338 if (!RD)
2339 return false;
2340
2341 if (!RD->hasMutableFields())
2342 return false;
2343
2344 for (auto *Field : RD->fields()) {
2345 // If we're actually going to read this field in some way, then it can't
2346 // be mutable. If we're in a union, then assigning to a mutable field
2347 // (even an empty one) can change the active member, so that's not OK.
2348 // FIXME: Add core issue number for the union case.
2349 if (Field->isMutable() &&
2350 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002351 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002352 Info.Note(Field->getLocation(), diag::note_declared_at);
2353 return true;
2354 }
2355
2356 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2357 return true;
2358 }
2359
2360 for (auto &BaseSpec : RD->bases())
2361 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2362 return true;
2363
2364 // All mutable fields were empty, and thus not actually read.
2365 return false;
2366}
2367
Richard Smith861b5b52013-05-07 23:34:45 +00002368/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002369enum AccessKinds {
2370 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002371 AK_Assign,
2372 AK_Increment,
2373 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002374};
2375
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002376namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002377/// A handle to a complete object (an object that is not a subobject of
2378/// another object).
2379struct CompleteObject {
2380 /// The value of the complete object.
2381 APValue *Value;
2382 /// The type of the complete object.
2383 QualType Type;
2384
Craig Topper36250ad2014-05-12 05:36:57 +00002385 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002386 CompleteObject(APValue *Value, QualType Type)
2387 : Value(Value), Type(Type) {
2388 assert(Value && "missing value for complete object");
2389 }
2390
Aaron Ballman67347662015-02-15 22:00:28 +00002391 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002392};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002393} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002394
Richard Smith3da88fa2013-04-26 14:36:30 +00002395/// Find the designated sub-object of an rvalue.
2396template<typename SubobjectHandler>
2397typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002398findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002399 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002400 if (Sub.Invalid)
2401 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002402 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002403 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002404 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002405 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002406 << handler.AccessKind;
2407 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002408 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002409 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002410 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002411
Richard Smith3229b742013-05-05 21:17:10 +00002412 APValue *O = Obj.Value;
2413 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002414 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002415
Richard Smithd62306a2011-11-10 06:34:14 +00002416 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002417 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2418 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002419 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002420 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002421 return handler.failed();
2422 }
2423
Richard Smith49ca8aa2013-08-06 07:09:20 +00002424 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002425 // If we are reading an object of class type, there may still be more
2426 // things we need to check: if there are any mutable subobjects, we
2427 // cannot perform this read. (This only happens when performing a trivial
2428 // copy or assignment.)
2429 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2430 diagnoseUnreadableFields(Info, E, ObjType))
2431 return handler.failed();
2432
Richard Smith49ca8aa2013-08-06 07:09:20 +00002433 if (!handler.found(*O, ObjType))
2434 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002435
Richard Smith49ca8aa2013-08-06 07:09:20 +00002436 // If we modified a bit-field, truncate it to the right width.
2437 if (handler.AccessKind != AK_Read &&
2438 LastField && LastField->isBitField() &&
2439 !truncateBitfieldValue(Info, E, *O, LastField))
2440 return false;
2441
2442 return true;
2443 }
2444
Craig Topper36250ad2014-05-12 05:36:57 +00002445 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002446 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002447 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002448 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002449 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002450 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002451 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002452 // Note, it should not be possible to form a pointer with a valid
2453 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002454 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002455 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002456 << handler.AccessKind;
2457 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002458 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002459 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002460 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002461
2462 ObjType = CAT->getElementType();
2463
Richard Smith14a94132012-02-17 03:35:37 +00002464 // An array object is represented as either an Array APValue or as an
2465 // LValue which refers to a string literal.
2466 if (O->isLValue()) {
2467 assert(I == N - 1 && "extracting subobject of character?");
2468 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002469 if (handler.AccessKind != AK_Read)
2470 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2471 *O);
2472 else
2473 return handler.foundString(*O, ObjType, Index);
2474 }
2475
2476 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002477 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002478 else if (handler.AccessKind != AK_Read) {
2479 expandArray(*O, Index);
2480 O = &O->getArrayInitializedElt(Index);
2481 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002482 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002483 } else if (ObjType->isAnyComplexType()) {
2484 // Next subobject is a complex number.
2485 uint64_t Index = Sub.Entries[I].ArrayIndex;
2486 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002487 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002488 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002489 << handler.AccessKind;
2490 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002491 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002492 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002493 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002494
2495 bool WasConstQualified = ObjType.isConstQualified();
2496 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2497 if (WasConstQualified)
2498 ObjType.addConst();
2499
Richard Smith66c96992012-02-18 22:04:06 +00002500 assert(I == N - 1 && "extracting subobject of scalar?");
2501 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002502 return handler.found(Index ? O->getComplexIntImag()
2503 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002504 } else {
2505 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002506 return handler.found(Index ? O->getComplexFloatImag()
2507 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002508 }
Richard Smithd62306a2011-11-10 06:34:14 +00002509 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002510 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002511 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002512 << Field;
2513 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002514 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002515 }
2516
Richard Smithd62306a2011-11-10 06:34:14 +00002517 // Next subobject is a class, struct or union field.
2518 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2519 if (RD->isUnion()) {
2520 const FieldDecl *UnionField = O->getUnionField();
2521 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002522 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002523 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002524 << handler.AccessKind << Field << !UnionField << UnionField;
2525 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002526 }
Richard Smithd62306a2011-11-10 06:34:14 +00002527 O = &O->getUnionValue();
2528 } else
2529 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002530
2531 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002532 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002533 if (WasConstQualified && !Field->isMutable())
2534 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002535
2536 if (ObjType.isVolatileQualified()) {
2537 if (Info.getLangOpts().CPlusPlus) {
2538 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002539 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002540 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002541 Info.Note(Field->getLocation(), diag::note_declared_at);
2542 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002543 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002544 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002545 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002546 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002547
2548 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002549 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002550 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002551 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2552 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2553 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002554
2555 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002556 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002557 if (WasConstQualified)
2558 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002559 }
2560 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002561}
2562
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002563namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002564struct ExtractSubobjectHandler {
2565 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002566 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002567
2568 static const AccessKinds AccessKind = AK_Read;
2569
2570 typedef bool result_type;
2571 bool failed() { return false; }
2572 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002573 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002574 return true;
2575 }
2576 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002577 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002578 return true;
2579 }
2580 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002581 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002582 return true;
2583 }
2584 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002585 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002586 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2587 return true;
2588 }
2589};
Richard Smith3229b742013-05-05 21:17:10 +00002590} // end anonymous namespace
2591
Richard Smith3da88fa2013-04-26 14:36:30 +00002592const AccessKinds ExtractSubobjectHandler::AccessKind;
2593
2594/// Extract the designated sub-object of an rvalue.
2595static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002596 const CompleteObject &Obj,
2597 const SubobjectDesignator &Sub,
2598 APValue &Result) {
2599 ExtractSubobjectHandler Handler = { Info, Result };
2600 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002601}
2602
Richard Smith3229b742013-05-05 21:17:10 +00002603namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002604struct ModifySubobjectHandler {
2605 EvalInfo &Info;
2606 APValue &NewVal;
2607 const Expr *E;
2608
2609 typedef bool result_type;
2610 static const AccessKinds AccessKind = AK_Assign;
2611
2612 bool checkConst(QualType QT) {
2613 // Assigning to a const object has undefined behavior.
2614 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002615 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002616 return false;
2617 }
2618 return true;
2619 }
2620
2621 bool failed() { return false; }
2622 bool found(APValue &Subobj, QualType SubobjType) {
2623 if (!checkConst(SubobjType))
2624 return false;
2625 // We've been given ownership of NewVal, so just swap it in.
2626 Subobj.swap(NewVal);
2627 return true;
2628 }
2629 bool found(APSInt &Value, QualType SubobjType) {
2630 if (!checkConst(SubobjType))
2631 return false;
2632 if (!NewVal.isInt()) {
2633 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002634 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002635 return false;
2636 }
2637 Value = NewVal.getInt();
2638 return true;
2639 }
2640 bool found(APFloat &Value, QualType SubobjType) {
2641 if (!checkConst(SubobjType))
2642 return false;
2643 Value = NewVal.getFloat();
2644 return true;
2645 }
2646 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2647 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2648 }
2649};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002650} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002651
Richard Smith3229b742013-05-05 21:17:10 +00002652const AccessKinds ModifySubobjectHandler::AccessKind;
2653
Richard Smith3da88fa2013-04-26 14:36:30 +00002654/// Update the designated sub-object of an rvalue to the given value.
2655static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002656 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002657 const SubobjectDesignator &Sub,
2658 APValue &NewVal) {
2659 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002660 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002661}
2662
Richard Smith84f6dcf2012-02-02 01:16:57 +00002663/// Find the position where two subobject designators diverge, or equivalently
2664/// the length of the common initial subsequence.
2665static unsigned FindDesignatorMismatch(QualType ObjType,
2666 const SubobjectDesignator &A,
2667 const SubobjectDesignator &B,
2668 bool &WasArrayIndex) {
2669 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2670 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002671 if (!ObjType.isNull() &&
2672 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002673 // Next subobject is an array element.
2674 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2675 WasArrayIndex = true;
2676 return I;
2677 }
Richard Smith66c96992012-02-18 22:04:06 +00002678 if (ObjType->isAnyComplexType())
2679 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2680 else
2681 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002682 } else {
2683 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2684 WasArrayIndex = false;
2685 return I;
2686 }
2687 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2688 // Next subobject is a field.
2689 ObjType = FD->getType();
2690 else
2691 // Next subobject is a base class.
2692 ObjType = QualType();
2693 }
2694 }
2695 WasArrayIndex = false;
2696 return I;
2697}
2698
2699/// Determine whether the given subobject designators refer to elements of the
2700/// same array object.
2701static bool AreElementsOfSameArray(QualType ObjType,
2702 const SubobjectDesignator &A,
2703 const SubobjectDesignator &B) {
2704 if (A.Entries.size() != B.Entries.size())
2705 return false;
2706
George Burgess IVa51c4072015-10-16 01:49:01 +00002707 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002708 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2709 // A is a subobject of the array element.
2710 return false;
2711
2712 // If A (and B) designates an array element, the last entry will be the array
2713 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2714 // of length 1' case, and the entire path must match.
2715 bool WasArrayIndex;
2716 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2717 return CommonLength >= A.Entries.size() - IsArray;
2718}
2719
Richard Smith3229b742013-05-05 21:17:10 +00002720/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002721static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2722 AccessKinds AK, const LValue &LVal,
2723 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002724 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002725 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002726 return CompleteObject();
2727 }
2728
Craig Topper36250ad2014-05-12 05:36:57 +00002729 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002730 if (LVal.CallIndex) {
2731 Frame = Info.getCallFrame(LVal.CallIndex);
2732 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002733 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002734 << AK << LVal.Base.is<const ValueDecl*>();
2735 NoteLValueLocation(Info, LVal.Base);
2736 return CompleteObject();
2737 }
Richard Smith3229b742013-05-05 21:17:10 +00002738 }
2739
2740 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2741 // is not a constant expression (even if the object is non-volatile). We also
2742 // apply this rule to C++98, in order to conform to the expected 'volatile'
2743 // semantics.
2744 if (LValType.isVolatileQualified()) {
2745 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00002746 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00002747 << AK << LValType;
2748 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002749 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002750 return CompleteObject();
2751 }
2752
2753 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002754 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002755 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002756
2757 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2758 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2759 // In C++11, constexpr, non-volatile variables initialized with constant
2760 // expressions are constant expressions too. Inside constexpr functions,
2761 // parameters are constant expressions even if they're non-const.
2762 // In C++1y, objects local to a constant expression (those with a Frame) are
2763 // both readable and writable inside constant expressions.
2764 // In C, such things can also be folded, although they are not ICEs.
2765 const VarDecl *VD = dyn_cast<VarDecl>(D);
2766 if (VD) {
2767 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2768 VD = VDef;
2769 }
2770 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002771 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002772 return CompleteObject();
2773 }
2774
2775 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002776 if (BaseType.isVolatileQualified()) {
2777 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002778 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002779 << AK << 1 << VD;
2780 Info.Note(VD->getLocation(), diag::note_declared_at);
2781 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002782 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002783 }
2784 return CompleteObject();
2785 }
2786
2787 // Unless we're looking at a local variable or argument in a constexpr call,
2788 // the variable we're reading must be const.
2789 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002790 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002791 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2792 // OK, we can read and modify an object if we're in the process of
2793 // evaluating its initializer, because its lifetime began in this
2794 // evaluation.
2795 } else if (AK != AK_Read) {
2796 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00002797 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00002798 return CompleteObject();
2799 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002800 // OK, we can read this variable.
2801 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002802 // In OpenCL if a variable is in constant address space it is a const value.
2803 if (!(BaseType.isConstQualified() ||
2804 (Info.getLangOpts().OpenCL &&
2805 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002806 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002807 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002808 Info.Note(VD->getLocation(), diag::note_declared_at);
2809 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002810 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002811 }
2812 return CompleteObject();
2813 }
2814 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2815 // We support folding of const floating-point types, in order to make
2816 // static const data members of such types (supported as an extension)
2817 // more useful.
2818 if (Info.getLangOpts().CPlusPlus11) {
2819 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2820 Info.Note(VD->getLocation(), diag::note_declared_at);
2821 } else {
2822 Info.CCEDiag(E);
2823 }
2824 } else {
2825 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002826 if (Info.checkingPotentialConstantExpression() &&
2827 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2828 // The definition of this variable could be constexpr. We can't
2829 // access it right now, but may be able to in future.
2830 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002831 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00002832 Info.Note(VD->getLocation(), diag::note_declared_at);
2833 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002834 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002835 }
2836 return CompleteObject();
2837 }
2838 }
2839
2840 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2841 return CompleteObject();
2842 } else {
2843 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2844
2845 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002846 if (const MaterializeTemporaryExpr *MTE =
2847 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2848 assert(MTE->getStorageDuration() == SD_Static &&
2849 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002850
Richard Smithe6c01442013-06-05 00:46:14 +00002851 // Per C++1y [expr.const]p2:
2852 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2853 // - a [...] glvalue of integral or enumeration type that refers to
2854 // a non-volatile const object [...]
2855 // [...]
2856 // - a [...] glvalue of literal type that refers to a non-volatile
2857 // object whose lifetime began within the evaluation of e.
2858 //
2859 // C++11 misses the 'began within the evaluation of e' check and
2860 // instead allows all temporaries, including things like:
2861 // int &&r = 1;
2862 // int x = ++r;
2863 // constexpr int k = r;
2864 // Therefore we use the C++1y rules in C++11 too.
2865 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2866 const ValueDecl *ED = MTE->getExtendingDecl();
2867 if (!(BaseType.isConstQualified() &&
2868 BaseType->isIntegralOrEnumerationType()) &&
2869 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002870 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00002871 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2872 return CompleteObject();
2873 }
2874
2875 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2876 assert(BaseVal && "got reference to unevaluated temporary");
2877 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002878 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00002879 return CompleteObject();
2880 }
2881 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002882 BaseVal = Frame->getTemporary(Base);
2883 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002884 }
Richard Smith3229b742013-05-05 21:17:10 +00002885
2886 // Volatile temporary objects cannot be accessed in constant expressions.
2887 if (BaseType.isVolatileQualified()) {
2888 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002889 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002890 << AK << 0;
2891 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2892 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002893 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00002894 }
2895 return CompleteObject();
2896 }
2897 }
2898
Richard Smith7525ff62013-05-09 07:14:00 +00002899 // During the construction of an object, it is not yet 'const'.
2900 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2901 // and this doesn't do quite the right thing for const subobjects of the
2902 // object under construction.
2903 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2904 BaseType = Info.Ctx.getCanonicalType(BaseType);
2905 BaseType.removeLocalConst();
2906 }
2907
Richard Smith6d4c6582013-11-05 22:18:15 +00002908 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00002909 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00002910 //
2911 // FIXME: Not all local state is mutable. Allow local constant subobjects
2912 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00002913 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
2914 Info.EvalStatus.HasSideEffects) ||
2915 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00002916 return CompleteObject();
2917
2918 return CompleteObject(BaseVal, BaseType);
2919}
2920
Richard Smith243ef902013-05-05 23:31:59 +00002921/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2922/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2923/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002924///
2925/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002926/// \param Conv - The expression for which we are performing the conversion.
2927/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002928/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2929/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002930/// \param LVal - The glvalue on which we are attempting to perform this action.
2931/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002932static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002933 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002934 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002935 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002936 return false;
2937
Richard Smith3229b742013-05-05 21:17:10 +00002938 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002939 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002940 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002941 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2942 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2943 // initializer until now for such expressions. Such an expression can't be
2944 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00002945 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002946 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002947 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002948 }
Richard Smith3229b742013-05-05 21:17:10 +00002949 APValue Lit;
2950 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2951 return false;
2952 CompleteObject LitObj(&Lit, Base->getType());
2953 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002954 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002955 // We represent a string literal array as an lvalue pointing at the
2956 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002957 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002958 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2959 CompleteObject StrObj(&Str, Base->getType());
2960 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002961 }
Richard Smith11562c52011-10-28 17:51:58 +00002962 }
2963
Richard Smith3229b742013-05-05 21:17:10 +00002964 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2965 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002966}
2967
2968/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002969static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002970 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002971 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002972 return false;
2973
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002974 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002975 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002976 return false;
2977 }
2978
Richard Smith3229b742013-05-05 21:17:10 +00002979 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2980 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002981}
2982
Richard Smith243ef902013-05-05 23:31:59 +00002983static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2984 return T->isSignedIntegerType() &&
2985 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2986}
2987
2988namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002989struct CompoundAssignSubobjectHandler {
2990 EvalInfo &Info;
2991 const Expr *E;
2992 QualType PromotedLHSType;
2993 BinaryOperatorKind Opcode;
2994 const APValue &RHS;
2995
2996 static const AccessKinds AccessKind = AK_Assign;
2997
2998 typedef bool result_type;
2999
3000 bool checkConst(QualType QT) {
3001 // Assigning to a const object has undefined behavior.
3002 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003003 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003004 return false;
3005 }
3006 return true;
3007 }
3008
3009 bool failed() { return false; }
3010 bool found(APValue &Subobj, QualType SubobjType) {
3011 switch (Subobj.getKind()) {
3012 case APValue::Int:
3013 return found(Subobj.getInt(), SubobjType);
3014 case APValue::Float:
3015 return found(Subobj.getFloat(), SubobjType);
3016 case APValue::ComplexInt:
3017 case APValue::ComplexFloat:
3018 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003019 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003020 return false;
3021 case APValue::LValue:
3022 return foundPointer(Subobj, SubobjType);
3023 default:
3024 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003025 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003026 return false;
3027 }
3028 }
3029 bool found(APSInt &Value, QualType SubobjType) {
3030 if (!checkConst(SubobjType))
3031 return false;
3032
3033 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3034 // We don't support compound assignment on integer-cast-to-pointer
3035 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003036 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003037 return false;
3038 }
3039
3040 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3041 SubobjType, Value);
3042 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3043 return false;
3044 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3045 return true;
3046 }
3047 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003048 return checkConst(SubobjType) &&
3049 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3050 Value) &&
3051 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3052 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003053 }
3054 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3055 if (!checkConst(SubobjType))
3056 return false;
3057
3058 QualType PointeeType;
3059 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3060 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003061
3062 if (PointeeType.isNull() || !RHS.isInt() ||
3063 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003064 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003065 return false;
3066 }
3067
Richard Smith861b5b52013-05-07 23:34:45 +00003068 int64_t Offset = getExtValue(RHS.getInt());
3069 if (Opcode == BO_Sub)
3070 Offset = -Offset;
3071
3072 LValue LVal;
3073 LVal.setFrom(Info.Ctx, Subobj);
3074 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3075 return false;
3076 LVal.moveInto(Subobj);
3077 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003078 }
3079 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3080 llvm_unreachable("shouldn't encounter string elements here");
3081 }
3082};
3083} // end anonymous namespace
3084
3085const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3086
3087/// Perform a compound assignment of LVal <op>= RVal.
3088static bool handleCompoundAssignment(
3089 EvalInfo &Info, const Expr *E,
3090 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3091 BinaryOperatorKind Opcode, const APValue &RVal) {
3092 if (LVal.Designator.Invalid)
3093 return false;
3094
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003095 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003096 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003097 return false;
3098 }
3099
3100 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3101 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3102 RVal };
3103 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3104}
3105
3106namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003107struct IncDecSubobjectHandler {
3108 EvalInfo &Info;
3109 const Expr *E;
3110 AccessKinds AccessKind;
3111 APValue *Old;
3112
3113 typedef bool result_type;
3114
3115 bool checkConst(QualType QT) {
3116 // Assigning to a const object has undefined behavior.
3117 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003118 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003119 return false;
3120 }
3121 return true;
3122 }
3123
3124 bool failed() { return false; }
3125 bool found(APValue &Subobj, QualType SubobjType) {
3126 // Stash the old value. Also clear Old, so we don't clobber it later
3127 // if we're post-incrementing a complex.
3128 if (Old) {
3129 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003130 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003131 }
3132
3133 switch (Subobj.getKind()) {
3134 case APValue::Int:
3135 return found(Subobj.getInt(), SubobjType);
3136 case APValue::Float:
3137 return found(Subobj.getFloat(), SubobjType);
3138 case APValue::ComplexInt:
3139 return found(Subobj.getComplexIntReal(),
3140 SubobjType->castAs<ComplexType>()->getElementType()
3141 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3142 case APValue::ComplexFloat:
3143 return found(Subobj.getComplexFloatReal(),
3144 SubobjType->castAs<ComplexType>()->getElementType()
3145 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3146 case APValue::LValue:
3147 return foundPointer(Subobj, SubobjType);
3148 default:
3149 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003150 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003151 return false;
3152 }
3153 }
3154 bool found(APSInt &Value, QualType SubobjType) {
3155 if (!checkConst(SubobjType))
3156 return false;
3157
3158 if (!SubobjType->isIntegerType()) {
3159 // We don't support increment / decrement on integer-cast-to-pointer
3160 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003161 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003162 return false;
3163 }
3164
3165 if (Old) *Old = APValue(Value);
3166
3167 // bool arithmetic promotes to int, and the conversion back to bool
3168 // doesn't reduce mod 2^n, so special-case it.
3169 if (SubobjType->isBooleanType()) {
3170 if (AccessKind == AK_Increment)
3171 Value = 1;
3172 else
3173 Value = !Value;
3174 return true;
3175 }
3176
3177 bool WasNegative = Value.isNegative();
3178 if (AccessKind == AK_Increment) {
3179 ++Value;
3180
3181 if (!WasNegative && Value.isNegative() &&
3182 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3183 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003184 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003185 }
3186 } else {
3187 --Value;
3188
3189 if (WasNegative && !Value.isNegative() &&
3190 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3191 unsigned BitWidth = Value.getBitWidth();
3192 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3193 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003194 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003195 }
3196 }
3197 return true;
3198 }
3199 bool found(APFloat &Value, QualType SubobjType) {
3200 if (!checkConst(SubobjType))
3201 return false;
3202
3203 if (Old) *Old = APValue(Value);
3204
3205 APFloat One(Value.getSemantics(), 1);
3206 if (AccessKind == AK_Increment)
3207 Value.add(One, APFloat::rmNearestTiesToEven);
3208 else
3209 Value.subtract(One, APFloat::rmNearestTiesToEven);
3210 return true;
3211 }
3212 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3213 if (!checkConst(SubobjType))
3214 return false;
3215
3216 QualType PointeeType;
3217 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3218 PointeeType = PT->getPointeeType();
3219 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003220 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003221 return false;
3222 }
3223
3224 LValue LVal;
3225 LVal.setFrom(Info.Ctx, Subobj);
3226 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3227 AccessKind == AK_Increment ? 1 : -1))
3228 return false;
3229 LVal.moveInto(Subobj);
3230 return true;
3231 }
3232 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3233 llvm_unreachable("shouldn't encounter string elements here");
3234 }
3235};
3236} // end anonymous namespace
3237
3238/// Perform an increment or decrement on LVal.
3239static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3240 QualType LValType, bool IsIncrement, APValue *Old) {
3241 if (LVal.Designator.Invalid)
3242 return false;
3243
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003244 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003245 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003246 return false;
3247 }
3248
3249 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3250 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3251 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3252 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3253}
3254
Richard Smithe97cbd72011-11-11 04:05:33 +00003255/// Build an lvalue for the object argument of a member function call.
3256static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3257 LValue &This) {
3258 if (Object->getType()->isPointerType())
3259 return EvaluatePointer(Object, This, Info);
3260
3261 if (Object->isGLValue())
3262 return EvaluateLValue(Object, This, Info);
3263
Richard Smithd9f663b2013-04-22 15:31:51 +00003264 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003265 return EvaluateTemporary(Object, This, Info);
3266
Faisal Valie690b7a2016-07-02 22:34:24 +00003267 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003268 return false;
3269}
3270
3271/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3272/// lvalue referring to the result.
3273///
3274/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003275/// \param LV - An lvalue referring to the base of the member pointer.
3276/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003277/// \param IncludeMember - Specifies whether the member itself is included in
3278/// the resulting LValue subobject designator. This is not possible when
3279/// creating a bound member function.
3280/// \return The field or method declaration to which the member pointer refers,
3281/// or 0 if evaluation fails.
3282static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003283 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003284 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003285 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003286 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003287 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003288 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003289 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003290
3291 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3292 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003293 if (!MemPtr.getDecl()) {
3294 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003295 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003296 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003297 }
Richard Smith253c2a32012-01-27 01:14:48 +00003298
Richard Smith027bf112011-11-17 22:56:20 +00003299 if (MemPtr.isDerivedMember()) {
3300 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003301 // The end of the derived-to-base path for the base object must match the
3302 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003303 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003304 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003305 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003306 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003307 }
Richard Smith027bf112011-11-17 22:56:20 +00003308 unsigned PathLengthToMember =
3309 LV.Designator.Entries.size() - MemPtr.Path.size();
3310 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3311 const CXXRecordDecl *LVDecl = getAsBaseClass(
3312 LV.Designator.Entries[PathLengthToMember + I]);
3313 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003314 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003315 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003316 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003317 }
Richard Smith027bf112011-11-17 22:56:20 +00003318 }
3319
3320 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003321 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003322 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003323 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003324 } else if (!MemPtr.Path.empty()) {
3325 // Extend the LValue path with the member pointer's path.
3326 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3327 MemPtr.Path.size() + IncludeMember);
3328
3329 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003330 if (const PointerType *PT = LVType->getAs<PointerType>())
3331 LVType = PT->getPointeeType();
3332 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3333 assert(RD && "member pointer access on non-class-type expression");
3334 // The first class in the path is that of the lvalue.
3335 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3336 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003337 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003338 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003339 RD = Base;
3340 }
3341 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003342 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3343 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003344 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003345 }
3346
3347 // Add the member. Note that we cannot build bound member functions here.
3348 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003349 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003350 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003351 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003352 } else if (const IndirectFieldDecl *IFD =
3353 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003354 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003355 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003356 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003357 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003358 }
Richard Smith027bf112011-11-17 22:56:20 +00003359 }
3360
3361 return MemPtr.getDecl();
3362}
3363
Richard Smith84401042013-06-03 05:03:02 +00003364static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3365 const BinaryOperator *BO,
3366 LValue &LV,
3367 bool IncludeMember = true) {
3368 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3369
3370 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003371 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003372 MemberPtr MemPtr;
3373 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3374 }
Craig Topper36250ad2014-05-12 05:36:57 +00003375 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003376 }
3377
3378 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3379 BO->getRHS(), IncludeMember);
3380}
3381
Richard Smith027bf112011-11-17 22:56:20 +00003382/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3383/// the provided lvalue, which currently refers to the base object.
3384static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3385 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003386 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003387 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003388 return false;
3389
Richard Smitha8105bc2012-01-06 16:39:00 +00003390 QualType TargetQT = E->getType();
3391 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3392 TargetQT = PT->getPointeeType();
3393
3394 // Check this cast lands within the final derived-to-base subobject path.
3395 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003396 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003397 << D.MostDerivedType << TargetQT;
3398 return false;
3399 }
3400
Richard Smith027bf112011-11-17 22:56:20 +00003401 // Check the type of the final cast. We don't need to check the path,
3402 // since a cast can only be formed if the path is unique.
3403 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003404 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3405 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003406 if (NewEntriesSize == D.MostDerivedPathLength)
3407 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3408 else
Richard Smith027bf112011-11-17 22:56:20 +00003409 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003410 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003411 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003412 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003413 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003414 }
Richard Smith027bf112011-11-17 22:56:20 +00003415
3416 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003417 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003418}
3419
Mike Stump876387b2009-10-27 22:09:17 +00003420namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003421enum EvalStmtResult {
3422 /// Evaluation failed.
3423 ESR_Failed,
3424 /// Hit a 'return' statement.
3425 ESR_Returned,
3426 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003427 ESR_Succeeded,
3428 /// Hit a 'continue' statement.
3429 ESR_Continue,
3430 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003431 ESR_Break,
3432 /// Still scanning for 'case' or 'default' statement.
3433 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003434};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003435}
Richard Smith254a73d2011-10-28 22:34:42 +00003436
Richard Smith97fcf4b2016-08-14 23:15:52 +00003437static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3438 // We don't need to evaluate the initializer for a static local.
3439 if (!VD->hasLocalStorage())
3440 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003441
Richard Smith97fcf4b2016-08-14 23:15:52 +00003442 LValue Result;
3443 Result.set(VD, Info.CurrentCall->Index);
3444 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003445
Richard Smith97fcf4b2016-08-14 23:15:52 +00003446 const Expr *InitE = VD->getInit();
3447 if (!InitE) {
3448 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3449 << false << VD->getType();
3450 Val = APValue();
3451 return false;
3452 }
Richard Smith51f03172013-06-20 03:00:05 +00003453
Richard Smith97fcf4b2016-08-14 23:15:52 +00003454 if (InitE->isValueDependent())
3455 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003456
Richard Smith97fcf4b2016-08-14 23:15:52 +00003457 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3458 // Wipe out any partially-computed value, to allow tracking that this
3459 // evaluation failed.
3460 Val = APValue();
3461 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003462 }
3463
3464 return true;
3465}
3466
Richard Smith97fcf4b2016-08-14 23:15:52 +00003467static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3468 bool OK = true;
3469
3470 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3471 OK &= EvaluateVarDecl(Info, VD);
3472
3473 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3474 for (auto *BD : DD->bindings())
3475 if (auto *VD = BD->getHoldingVar())
3476 OK &= EvaluateDecl(Info, VD);
3477
3478 return OK;
3479}
3480
3481
Richard Smith4e18ca52013-05-06 05:56:11 +00003482/// Evaluate a condition (either a variable declaration or an expression).
3483static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3484 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003485 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003486 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3487 return false;
3488 return EvaluateAsBooleanCondition(Cond, Result, Info);
3489}
3490
Richard Smith89210072016-04-04 23:29:43 +00003491namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003492/// \brief A location where the result (returned value) of evaluating a
3493/// statement should be stored.
3494struct StmtResult {
3495 /// The APValue that should be filled in with the returned value.
3496 APValue &Value;
3497 /// The location containing the result, if any (used to support RVO).
3498 const LValue *Slot;
3499};
Richard Smith89210072016-04-04 23:29:43 +00003500}
Richard Smith52a980a2015-08-28 02:43:42 +00003501
3502static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003503 const Stmt *S,
3504 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003505
3506/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003507static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003508 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003509 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003510 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003511 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003512 case ESR_Break:
3513 return ESR_Succeeded;
3514 case ESR_Succeeded:
3515 case ESR_Continue:
3516 return ESR_Continue;
3517 case ESR_Failed:
3518 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003519 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003520 return ESR;
3521 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003522 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003523}
3524
Richard Smith496ddcf2013-05-12 17:32:42 +00003525/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003526static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003527 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003528 BlockScopeRAII Scope(Info);
3529
Richard Smith496ddcf2013-05-12 17:32:42 +00003530 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003531 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003532 {
3533 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003534 if (const Stmt *Init = SS->getInit()) {
3535 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3536 if (ESR != ESR_Succeeded)
3537 return ESR;
3538 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003539 if (SS->getConditionVariable() &&
3540 !EvaluateDecl(Info, SS->getConditionVariable()))
3541 return ESR_Failed;
3542 if (!EvaluateInteger(SS->getCond(), Value, Info))
3543 return ESR_Failed;
3544 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003545
3546 // Find the switch case corresponding to the value of the condition.
3547 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003548 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003549 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3550 SC = SC->getNextSwitchCase()) {
3551 if (isa<DefaultStmt>(SC)) {
3552 Found = SC;
3553 continue;
3554 }
3555
3556 const CaseStmt *CS = cast<CaseStmt>(SC);
3557 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3558 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3559 : LHS;
3560 if (LHS <= Value && Value <= RHS) {
3561 Found = SC;
3562 break;
3563 }
3564 }
3565
3566 if (!Found)
3567 return ESR_Succeeded;
3568
3569 // Search the switch body for the switch case and evaluate it from there.
3570 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3571 case ESR_Break:
3572 return ESR_Succeeded;
3573 case ESR_Succeeded:
3574 case ESR_Continue:
3575 case ESR_Failed:
3576 case ESR_Returned:
3577 return ESR;
3578 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003579 // This can only happen if the switch case is nested within a statement
3580 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003581 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003582 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003583 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003584 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003585}
3586
Richard Smith254a73d2011-10-28 22:34:42 +00003587// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003588static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003589 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003590 if (!Info.nextStep(S))
3591 return ESR_Failed;
3592
Richard Smith496ddcf2013-05-12 17:32:42 +00003593 // If we're hunting down a 'case' or 'default' label, recurse through
3594 // substatements until we hit the label.
3595 if (Case) {
3596 // FIXME: We don't start the lifetime of objects whose initialization we
3597 // jump over. However, such objects must be of class type with a trivial
3598 // default constructor that initialize all subobjects, so must be empty,
3599 // so this almost never matters.
3600 switch (S->getStmtClass()) {
3601 case Stmt::CompoundStmtClass:
3602 // FIXME: Precompute which substatement of a compound statement we
3603 // would jump to, and go straight there rather than performing a
3604 // linear scan each time.
3605 case Stmt::LabelStmtClass:
3606 case Stmt::AttributedStmtClass:
3607 case Stmt::DoStmtClass:
3608 break;
3609
3610 case Stmt::CaseStmtClass:
3611 case Stmt::DefaultStmtClass:
3612 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003613 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003614 break;
3615
3616 case Stmt::IfStmtClass: {
3617 // FIXME: Precompute which side of an 'if' we would jump to, and go
3618 // straight there rather than scanning both sides.
3619 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003620
3621 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3622 // preceded by our switch label.
3623 BlockScopeRAII Scope(Info);
3624
Richard Smith496ddcf2013-05-12 17:32:42 +00003625 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3626 if (ESR != ESR_CaseNotFound || !IS->getElse())
3627 return ESR;
3628 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3629 }
3630
3631 case Stmt::WhileStmtClass: {
3632 EvalStmtResult ESR =
3633 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3634 if (ESR != ESR_Continue)
3635 return ESR;
3636 break;
3637 }
3638
3639 case Stmt::ForStmtClass: {
3640 const ForStmt *FS = cast<ForStmt>(S);
3641 EvalStmtResult ESR =
3642 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3643 if (ESR != ESR_Continue)
3644 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003645 if (FS->getInc()) {
3646 FullExpressionRAII IncScope(Info);
3647 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3648 return ESR_Failed;
3649 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003650 break;
3651 }
3652
3653 case Stmt::DeclStmtClass:
3654 // FIXME: If the variable has initialization that can't be jumped over,
3655 // bail out of any immediately-surrounding compound-statement too.
3656 default:
3657 return ESR_CaseNotFound;
3658 }
3659 }
3660
Richard Smith254a73d2011-10-28 22:34:42 +00003661 switch (S->getStmtClass()) {
3662 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003663 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003664 // Don't bother evaluating beyond an expression-statement which couldn't
3665 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003666 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003667 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003668 return ESR_Failed;
3669 return ESR_Succeeded;
3670 }
3671
Faisal Valie690b7a2016-07-02 22:34:24 +00003672 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003673 return ESR_Failed;
3674
3675 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003676 return ESR_Succeeded;
3677
Richard Smithd9f663b2013-04-22 15:31:51 +00003678 case Stmt::DeclStmtClass: {
3679 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003680 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003681 // Each declaration initialization is its own full-expression.
3682 // FIXME: This isn't quite right; if we're performing aggregate
3683 // initialization, each braced subexpression is its own full-expression.
3684 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003685 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003686 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003687 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003688 return ESR_Succeeded;
3689 }
3690
Richard Smith357362d2011-12-13 06:39:58 +00003691 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003692 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003693 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003694 if (RetExpr &&
3695 !(Result.Slot
3696 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3697 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003698 return ESR_Failed;
3699 return ESR_Returned;
3700 }
Richard Smith254a73d2011-10-28 22:34:42 +00003701
3702 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003703 BlockScopeRAII Scope(Info);
3704
Richard Smith254a73d2011-10-28 22:34:42 +00003705 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003706 for (const auto *BI : CS->body()) {
3707 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003708 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003709 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003710 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003711 return ESR;
3712 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003713 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003714 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003715
3716 case Stmt::IfStmtClass: {
3717 const IfStmt *IS = cast<IfStmt>(S);
3718
3719 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003720 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003721 if (const Stmt *Init = IS->getInit()) {
3722 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3723 if (ESR != ESR_Succeeded)
3724 return ESR;
3725 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003726 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003727 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003728 return ESR_Failed;
3729
3730 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3731 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3732 if (ESR != ESR_Succeeded)
3733 return ESR;
3734 }
3735 return ESR_Succeeded;
3736 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003737
3738 case Stmt::WhileStmtClass: {
3739 const WhileStmt *WS = cast<WhileStmt>(S);
3740 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003741 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003742 bool Continue;
3743 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3744 Continue))
3745 return ESR_Failed;
3746 if (!Continue)
3747 break;
3748
3749 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3750 if (ESR != ESR_Continue)
3751 return ESR;
3752 }
3753 return ESR_Succeeded;
3754 }
3755
3756 case Stmt::DoStmtClass: {
3757 const DoStmt *DS = cast<DoStmt>(S);
3758 bool Continue;
3759 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003760 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003761 if (ESR != ESR_Continue)
3762 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003763 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003764
Richard Smith08d6a2c2013-07-24 07:11:57 +00003765 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003766 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3767 return ESR_Failed;
3768 } while (Continue);
3769 return ESR_Succeeded;
3770 }
3771
3772 case Stmt::ForStmtClass: {
3773 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003774 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003775 if (FS->getInit()) {
3776 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3777 if (ESR != ESR_Succeeded)
3778 return ESR;
3779 }
3780 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003781 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003782 bool Continue = true;
3783 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3784 FS->getCond(), Continue))
3785 return ESR_Failed;
3786 if (!Continue)
3787 break;
3788
3789 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3790 if (ESR != ESR_Continue)
3791 return ESR;
3792
Richard Smith08d6a2c2013-07-24 07:11:57 +00003793 if (FS->getInc()) {
3794 FullExpressionRAII IncScope(Info);
3795 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3796 return ESR_Failed;
3797 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003798 }
3799 return ESR_Succeeded;
3800 }
3801
Richard Smith896e0d72013-05-06 06:51:17 +00003802 case Stmt::CXXForRangeStmtClass: {
3803 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003804 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003805
3806 // Initialize the __range variable.
3807 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3808 if (ESR != ESR_Succeeded)
3809 return ESR;
3810
3811 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003812 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3813 if (ESR != ESR_Succeeded)
3814 return ESR;
3815 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003816 if (ESR != ESR_Succeeded)
3817 return ESR;
3818
3819 while (true) {
3820 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003821 {
3822 bool Continue = true;
3823 FullExpressionRAII CondExpr(Info);
3824 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3825 return ESR_Failed;
3826 if (!Continue)
3827 break;
3828 }
Richard Smith896e0d72013-05-06 06:51:17 +00003829
3830 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003831 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003832 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3833 if (ESR != ESR_Succeeded)
3834 return ESR;
3835
3836 // Loop body.
3837 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3838 if (ESR != ESR_Continue)
3839 return ESR;
3840
3841 // Increment: ++__begin
3842 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3843 return ESR_Failed;
3844 }
3845
3846 return ESR_Succeeded;
3847 }
3848
Richard Smith496ddcf2013-05-12 17:32:42 +00003849 case Stmt::SwitchStmtClass:
3850 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3851
Richard Smith4e18ca52013-05-06 05:56:11 +00003852 case Stmt::ContinueStmtClass:
3853 return ESR_Continue;
3854
3855 case Stmt::BreakStmtClass:
3856 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003857
3858 case Stmt::LabelStmtClass:
3859 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3860
3861 case Stmt::AttributedStmtClass:
3862 // As a general principle, C++11 attributes can be ignored without
3863 // any semantic impact.
3864 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3865 Case);
3866
3867 case Stmt::CaseStmtClass:
3868 case Stmt::DefaultStmtClass:
3869 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003870 }
3871}
3872
Richard Smithcc36f692011-12-22 02:22:31 +00003873/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3874/// default constructor. If so, we'll fold it whether or not it's marked as
3875/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3876/// so we need special handling.
3877static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003878 const CXXConstructorDecl *CD,
3879 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003880 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3881 return false;
3882
Richard Smith66e05fe2012-01-18 05:21:49 +00003883 // Value-initialization does not call a trivial default constructor, so such a
3884 // call is a core constant expression whether or not the constructor is
3885 // constexpr.
3886 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003887 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003888 // FIXME: If DiagDecl is an implicitly-declared special member function,
3889 // we should be much more explicit about why it's not constexpr.
3890 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3891 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3892 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003893 } else {
3894 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3895 }
3896 }
3897 return true;
3898}
3899
Richard Smith357362d2011-12-13 06:39:58 +00003900/// CheckConstexprFunction - Check that a function can be called in a constant
3901/// expression.
3902static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3903 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003904 const FunctionDecl *Definition,
3905 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00003906 // Potential constant expressions can contain calls to declared, but not yet
3907 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003908 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003909 Declaration->isConstexpr())
3910 return false;
3911
Richard Smith0838f3a2013-05-14 05:18:44 +00003912 // Bail out with no diagnostic if the function declaration itself is invalid.
3913 // We will have produced a relevant diagnostic while parsing it.
3914 if (Declaration->isInvalidDecl())
3915 return false;
3916
Richard Smith357362d2011-12-13 06:39:58 +00003917 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003918 if (Definition && Definition->isConstexpr() &&
3919 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00003920 return true;
3921
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003922 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003923 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Faisal Valie690b7a2016-07-02 22:34:24 +00003924
Richard Smith5179eb72016-06-28 19:03:57 +00003925 // If this function is not constexpr because it is an inherited
3926 // non-constexpr constructor, diagnose that directly.
3927 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
3928 if (CD && CD->isInheritingConstructor()) {
3929 auto *Inherited = CD->getInheritedConstructor().getConstructor();
3930 if (!Inherited->isConstexpr())
3931 DiagDecl = CD = Inherited;
3932 }
3933
3934 // FIXME: If DiagDecl is an implicitly-declared special member function
3935 // or an inheriting constructor, we should be much more explicit about why
3936 // it's not constexpr.
3937 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00003938 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00003939 << CD->getInheritedConstructor().getConstructor()->getParent();
3940 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003941 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00003942 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00003943 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3944 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003945 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00003946 }
3947 return false;
3948}
3949
Richard Smithbe6dd812014-11-19 21:27:17 +00003950/// Determine if a class has any fields that might need to be copied by a
3951/// trivial copy or move operation.
3952static bool hasFields(const CXXRecordDecl *RD) {
3953 if (!RD || RD->isEmpty())
3954 return false;
3955 for (auto *FD : RD->fields()) {
3956 if (FD->isUnnamedBitfield())
3957 continue;
3958 return true;
3959 }
3960 for (auto &Base : RD->bases())
3961 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3962 return true;
3963 return false;
3964}
3965
Richard Smithd62306a2011-11-10 06:34:14 +00003966namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003967typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003968}
3969
3970/// EvaluateArgs - Evaluate the arguments to a function call.
3971static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3972 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003973 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003974 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003975 I != E; ++I) {
3976 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3977 // If we're checking for a potential constant expression, evaluate all
3978 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00003979 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00003980 return false;
3981 Success = false;
3982 }
3983 }
3984 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003985}
3986
Richard Smith254a73d2011-10-28 22:34:42 +00003987/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003988static bool HandleFunctionCall(SourceLocation CallLoc,
3989 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003990 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003991 EvalInfo &Info, APValue &Result,
3992 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003993 ArgVector ArgValues(Args.size());
3994 if (!EvaluateArgs(Args, ArgValues, Info))
3995 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003996
Richard Smith253c2a32012-01-27 01:14:48 +00003997 if (!Info.CheckCallLimit(CallLoc))
3998 return false;
3999
4000 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004001
4002 // For a trivial copy or move assignment, perform an APValue copy. This is
4003 // essential for unions, where the operations performed by the assignment
4004 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004005 //
4006 // Skip this for non-union classes with no fields; in that case, the defaulted
4007 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004008 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004009 if (MD && MD->isDefaulted() &&
4010 (MD->getParent()->isUnion() ||
4011 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004012 assert(This &&
4013 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4014 LValue RHS;
4015 RHS.setFrom(Info.Ctx, ArgValues[0]);
4016 APValue RHSValue;
4017 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4018 RHS, RHSValue))
4019 return false;
4020 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4021 RHSValue))
4022 return false;
4023 This->moveInto(Result);
4024 return true;
4025 }
4026
Richard Smith52a980a2015-08-28 02:43:42 +00004027 StmtResult Ret = {Result, ResultSlot};
4028 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004029 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004030 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004031 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004032 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004033 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004034 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004035}
4036
Richard Smithd62306a2011-11-10 06:34:14 +00004037/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004038static bool HandleConstructorCall(const Expr *E, const LValue &This,
4039 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004040 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004041 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004042 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004043 if (!Info.CheckCallLimit(CallLoc))
4044 return false;
4045
Richard Smith3607ffe2012-02-13 03:54:03 +00004046 const CXXRecordDecl *RD = Definition->getParent();
4047 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004048 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004049 return false;
4050 }
4051
Richard Smith5179eb72016-06-28 19:03:57 +00004052 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004053
Richard Smith52a980a2015-08-28 02:43:42 +00004054 // FIXME: Creating an APValue just to hold a nonexistent return value is
4055 // wasteful.
4056 APValue RetVal;
4057 StmtResult Ret = {RetVal, nullptr};
4058
Richard Smith5179eb72016-06-28 19:03:57 +00004059 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004060 if (Definition->isDelegatingConstructor()) {
4061 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004062 {
4063 FullExpressionRAII InitScope(Info);
4064 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4065 return false;
4066 }
Richard Smith52a980a2015-08-28 02:43:42 +00004067 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004068 }
4069
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004070 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004071 // essential for unions (or classes with anonymous union members), where the
4072 // operations performed by the constructor cannot be represented by
4073 // ctor-initializers.
4074 //
4075 // Skip this for empty non-union classes; we should not perform an
4076 // lvalue-to-rvalue conversion on them because their copy constructor does not
4077 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004078 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004079 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004080 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004081 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004082 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004083 return handleLValueToRValueConversion(
4084 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4085 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004086 }
4087
4088 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004089 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004090 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004091 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004092
John McCalld7bca762012-05-01 00:38:49 +00004093 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004094 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4095
Richard Smith08d6a2c2013-07-24 07:11:57 +00004096 // A scope for temporaries lifetime-extended by reference members.
4097 BlockScopeRAII LifetimeExtendedScope(Info);
4098
Richard Smith253c2a32012-01-27 01:14:48 +00004099 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004100 unsigned BasesSeen = 0;
4101#ifndef NDEBUG
4102 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4103#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004104 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004105 LValue Subobject = This;
4106 APValue *Value = &Result;
4107
4108 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004109 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004110 if (I->isBaseInitializer()) {
4111 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004112#ifndef NDEBUG
4113 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004114 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004115 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4116 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4117 "base class initializers not in expected order");
4118 ++BaseIt;
4119#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004120 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004121 BaseType->getAsCXXRecordDecl(), &Layout))
4122 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004123 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004124 } else if ((FD = I->getMember())) {
4125 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004126 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004127 if (RD->isUnion()) {
4128 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004129 Value = &Result.getUnionValue();
4130 } else {
4131 Value = &Result.getStructField(FD->getFieldIndex());
4132 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004133 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004134 // Walk the indirect field decl's chain to find the object to initialize,
4135 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004136 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004137 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004138 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4139 // Switch the union field if it differs. This happens if we had
4140 // preceding zero-initialization, and we're now initializing a union
4141 // subobject other than the first.
4142 // FIXME: In this case, the values of the other subobjects are
4143 // specified, since zero-initialization sets all padding bits to zero.
4144 if (Value->isUninit() ||
4145 (Value->isUnion() && Value->getUnionField() != FD)) {
4146 if (CD->isUnion())
4147 *Value = APValue(FD);
4148 else
4149 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004150 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004151 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004152 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004153 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004154 if (CD->isUnion())
4155 Value = &Value->getUnionValue();
4156 else
4157 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004158 }
Richard Smithd62306a2011-11-10 06:34:14 +00004159 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004160 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004161 }
Richard Smith253c2a32012-01-27 01:14:48 +00004162
Richard Smith08d6a2c2013-07-24 07:11:57 +00004163 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004164 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4165 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004166 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004167 // If we're checking for a potential constant expression, evaluate all
4168 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004169 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004170 return false;
4171 Success = false;
4172 }
Richard Smithd62306a2011-11-10 06:34:14 +00004173 }
4174
Richard Smithd9f663b2013-04-22 15:31:51 +00004175 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004176 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004177}
4178
Richard Smith5179eb72016-06-28 19:03:57 +00004179static bool HandleConstructorCall(const Expr *E, const LValue &This,
4180 ArrayRef<const Expr*> Args,
4181 const CXXConstructorDecl *Definition,
4182 EvalInfo &Info, APValue &Result) {
4183 ArgVector ArgValues(Args.size());
4184 if (!EvaluateArgs(Args, ArgValues, Info))
4185 return false;
4186
4187 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4188 Info, Result);
4189}
4190
Eli Friedman9a156e52008-11-12 09:44:48 +00004191//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004192// Generic Evaluation
4193//===----------------------------------------------------------------------===//
4194namespace {
4195
Aaron Ballman68af21c2014-01-03 19:26:43 +00004196template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004197class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004198 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004199private:
Richard Smith52a980a2015-08-28 02:43:42 +00004200 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004201 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004202 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004203 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004204 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004205 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004206 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004207
Richard Smith17100ba2012-02-16 02:46:34 +00004208 // Check whether a conditional operator with a non-constant condition is a
4209 // potential constant expression. If neither arm is a potential constant
4210 // expression, then the conditional operator is not either.
4211 template<typename ConditionalOperator>
4212 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004213 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004214
4215 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004216 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004217 {
Richard Smith17100ba2012-02-16 02:46:34 +00004218 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004219 StmtVisitorTy::Visit(E->getFalseExpr());
4220 if (Diag.empty())
4221 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004222 }
Richard Smith17100ba2012-02-16 02:46:34 +00004223
George Burgess IV8c892b52016-05-25 22:31:54 +00004224 {
4225 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004226 Diag.clear();
4227 StmtVisitorTy::Visit(E->getTrueExpr());
4228 if (Diag.empty())
4229 return;
4230 }
4231
4232 Error(E, diag::note_constexpr_conditional_never_const);
4233 }
4234
4235
4236 template<typename ConditionalOperator>
4237 bool HandleConditionalOperator(const ConditionalOperator *E) {
4238 bool BoolResult;
4239 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004240 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004241 CheckPotentialConstantConditional(E);
4242 return false;
4243 }
4244
4245 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4246 return StmtVisitorTy::Visit(EvalExpr);
4247 }
4248
Peter Collingbournee9200682011-05-13 03:29:01 +00004249protected:
4250 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004251 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004252 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4253
Richard Smith92b1ce02011-12-12 09:28:41 +00004254 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004255 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004256 }
4257
Aaron Ballman68af21c2014-01-03 19:26:43 +00004258 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004259
4260public:
4261 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4262
4263 EvalInfo &getEvalInfo() { return Info; }
4264
Richard Smithf57d8cb2011-12-09 22:58:01 +00004265 /// Report an evaluation error. This should only be called when an error is
4266 /// first discovered. When propagating an error, just return false.
4267 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004268 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004269 return false;
4270 }
4271 bool Error(const Expr *E) {
4272 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4273 }
4274
Aaron Ballman68af21c2014-01-03 19:26:43 +00004275 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004276 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004277 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004278 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004279 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004280 }
4281
Aaron Ballman68af21c2014-01-03 19:26:43 +00004282 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004283 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004284 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004285 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004286 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004287 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004288 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004289 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004290 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004291 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004292 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004293 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004294 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004295 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004296 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004297 // The initializer may not have been parsed yet, or might be erroneous.
4298 if (!E->getExpr())
4299 return Error(E);
4300 return StmtVisitorTy::Visit(E->getExpr());
4301 }
Richard Smith5894a912011-12-19 22:12:41 +00004302 // We cannot create any objects for which cleanups are required, so there is
4303 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004304 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004305 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004306
Aaron Ballman68af21c2014-01-03 19:26:43 +00004307 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004308 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4309 return static_cast<Derived*>(this)->VisitCastExpr(E);
4310 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004311 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004312 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4313 return static_cast<Derived*>(this)->VisitCastExpr(E);
4314 }
4315
Aaron Ballman68af21c2014-01-03 19:26:43 +00004316 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004317 switch (E->getOpcode()) {
4318 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004319 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004320
4321 case BO_Comma:
4322 VisitIgnoredValue(E->getLHS());
4323 return StmtVisitorTy::Visit(E->getRHS());
4324
4325 case BO_PtrMemD:
4326 case BO_PtrMemI: {
4327 LValue Obj;
4328 if (!HandleMemberPointerAccess(Info, E, Obj))
4329 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004330 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004331 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004332 return false;
4333 return DerivedSuccess(Result, E);
4334 }
4335 }
4336 }
4337
Aaron Ballman68af21c2014-01-03 19:26:43 +00004338 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004339 // Evaluate and cache the common expression. We treat it as a temporary,
4340 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004341 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004342 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004343 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004344
Richard Smith17100ba2012-02-16 02:46:34 +00004345 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004346 }
4347
Aaron Ballman68af21c2014-01-03 19:26:43 +00004348 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004349 bool IsBcpCall = false;
4350 // If the condition (ignoring parens) is a __builtin_constant_p call,
4351 // the result is a constant expression if it can be folded without
4352 // side-effects. This is an important GNU extension. See GCC PR38377
4353 // for discussion.
4354 if (const CallExpr *CallCE =
4355 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004356 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004357 IsBcpCall = true;
4358
4359 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4360 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004361 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004362 return false;
4363
Richard Smith6d4c6582013-11-05 22:18:15 +00004364 FoldConstant Fold(Info, IsBcpCall);
4365 if (!HandleConditionalOperator(E)) {
4366 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004367 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004368 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004369
4370 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004371 }
4372
Aaron Ballman68af21c2014-01-03 19:26:43 +00004373 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004374 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4375 return DerivedSuccess(*Value, E);
4376
4377 const Expr *Source = E->getSourceExpr();
4378 if (!Source)
4379 return Error(E);
4380 if (Source == E) { // sanity checking.
4381 assert(0 && "OpaqueValueExpr recursively refers to itself");
4382 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004383 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004384 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004385 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004386
Aaron Ballman68af21c2014-01-03 19:26:43 +00004387 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004388 APValue Result;
4389 if (!handleCallExpr(E, Result, nullptr))
4390 return false;
4391 return DerivedSuccess(Result, E);
4392 }
4393
4394 bool handleCallExpr(const CallExpr *E, APValue &Result,
4395 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004396 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004397 QualType CalleeType = Callee->getType();
4398
Craig Topper36250ad2014-05-12 05:36:57 +00004399 const FunctionDecl *FD = nullptr;
4400 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004401 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004402 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004403
Richard Smithe97cbd72011-11-11 04:05:33 +00004404 // Extract function decl and 'this' pointer from the callee.
4405 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004406 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004407 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4408 // Explicit bound member calls, such as x.f() or p->g();
4409 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004410 return false;
4411 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004412 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004413 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004414 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4415 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004416 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4417 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004418 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004419 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004420 return Error(Callee);
4421
4422 FD = dyn_cast<FunctionDecl>(Member);
4423 if (!FD)
4424 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004425 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004426 LValue Call;
4427 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004428 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004429
Richard Smitha8105bc2012-01-06 16:39:00 +00004430 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004431 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004432 FD = dyn_cast_or_null<FunctionDecl>(
4433 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004434 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004435 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004436
4437 // Overloaded operator calls to member functions are represented as normal
4438 // calls with '*this' as the first argument.
4439 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4440 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004441 // FIXME: When selecting an implicit conversion for an overloaded
4442 // operator delete, we sometimes try to evaluate calls to conversion
4443 // operators without a 'this' parameter!
4444 if (Args.empty())
4445 return Error(E);
4446
Richard Smithe97cbd72011-11-11 04:05:33 +00004447 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4448 return false;
4449 This = &ThisVal;
4450 Args = Args.slice(1);
4451 }
4452
4453 // Don't call function pointers which have been cast to some other type.
4454 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004455 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004456 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004457 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004458
Richard Smith47b34932012-02-01 02:39:43 +00004459 if (This && !This->checkSubobject(Info, E, CSK_This))
4460 return false;
4461
Richard Smith3607ffe2012-02-13 03:54:03 +00004462 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4463 // calls to such functions in constant expressions.
4464 if (This && !HasQualifier &&
4465 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4466 return Error(E, diag::note_constexpr_virtual_call);
4467
Craig Topper36250ad2014-05-12 05:36:57 +00004468 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004469 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004470
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004471 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004472 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4473 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004474 return false;
4475
Richard Smith52a980a2015-08-28 02:43:42 +00004476 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004477 }
4478
Aaron Ballman68af21c2014-01-03 19:26:43 +00004479 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004480 return StmtVisitorTy::Visit(E->getInitializer());
4481 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004482 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004483 if (E->getNumInits() == 0)
4484 return DerivedZeroInitialization(E);
4485 if (E->getNumInits() == 1)
4486 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004487 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004488 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004489 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004490 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004491 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004492 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004493 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004494 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004495 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004496 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004497 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004498
Richard Smithd62306a2011-11-10 06:34:14 +00004499 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004500 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004501 assert(!E->isArrow() && "missing call to bound member function?");
4502
Richard Smith2e312c82012-03-03 22:46:17 +00004503 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004504 if (!Evaluate(Val, Info, E->getBase()))
4505 return false;
4506
4507 QualType BaseTy = E->getBase()->getType();
4508
4509 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004510 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004511 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004512 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004513 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4514
Richard Smith3229b742013-05-05 21:17:10 +00004515 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004516 SubobjectDesignator Designator(BaseTy);
4517 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004518
Richard Smith3229b742013-05-05 21:17:10 +00004519 APValue Result;
4520 return extractSubobject(Info, E, Obj, Designator, Result) &&
4521 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004522 }
4523
Aaron Ballman68af21c2014-01-03 19:26:43 +00004524 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004525 switch (E->getCastKind()) {
4526 default:
4527 break;
4528
Richard Smitha23ab512013-05-23 00:30:41 +00004529 case CK_AtomicToNonAtomic: {
4530 APValue AtomicVal;
4531 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4532 return false;
4533 return DerivedSuccess(AtomicVal, E);
4534 }
4535
Richard Smith11562c52011-10-28 17:51:58 +00004536 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004537 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004538 return StmtVisitorTy::Visit(E->getSubExpr());
4539
4540 case CK_LValueToRValue: {
4541 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004542 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4543 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004544 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004545 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004546 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004547 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004548 return false;
4549 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004550 }
4551 }
4552
Richard Smithf57d8cb2011-12-09 22:58:01 +00004553 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004554 }
4555
Aaron Ballman68af21c2014-01-03 19:26:43 +00004556 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004557 return VisitUnaryPostIncDec(UO);
4558 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004559 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004560 return VisitUnaryPostIncDec(UO);
4561 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004562 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004563 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004564 return Error(UO);
4565
4566 LValue LVal;
4567 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4568 return false;
4569 APValue RVal;
4570 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4571 UO->isIncrementOp(), &RVal))
4572 return false;
4573 return DerivedSuccess(RVal, UO);
4574 }
4575
Aaron Ballman68af21c2014-01-03 19:26:43 +00004576 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004577 // We will have checked the full-expressions inside the statement expression
4578 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004579 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004580 return Error(E);
4581
Richard Smith08d6a2c2013-07-24 07:11:57 +00004582 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004583 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004584 if (CS->body_empty())
4585 return true;
4586
Richard Smith51f03172013-06-20 03:00:05 +00004587 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4588 BE = CS->body_end();
4589 /**/; ++BI) {
4590 if (BI + 1 == BE) {
4591 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4592 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004593 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004594 diag::note_constexpr_stmt_expr_unsupported);
4595 return false;
4596 }
4597 return this->Visit(FinalExpr);
4598 }
4599
4600 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004601 StmtResult Result = { ReturnValue, nullptr };
4602 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004603 if (ESR != ESR_Succeeded) {
4604 // FIXME: If the statement-expression terminated due to 'return',
4605 // 'break', or 'continue', it would be nice to propagate that to
4606 // the outer statement evaluation rather than bailing out.
4607 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004608 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004609 diag::note_constexpr_stmt_expr_unsupported);
4610 return false;
4611 }
4612 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004613
4614 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004615 }
4616
Richard Smith4a678122011-10-24 18:44:57 +00004617 /// Visit a value which is evaluated, but whose value is ignored.
4618 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004619 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004620 }
David Majnemere9807b22016-02-26 04:23:19 +00004621
4622 /// Potentially visit a MemberExpr's base expression.
4623 void VisitIgnoredBaseExpression(const Expr *E) {
4624 // While MSVC doesn't evaluate the base expression, it does diagnose the
4625 // presence of side-effecting behavior.
4626 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4627 return;
4628 VisitIgnoredValue(E);
4629 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004630};
4631
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004632}
Peter Collingbournee9200682011-05-13 03:29:01 +00004633
4634//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004635// Common base class for lvalue and temporary evaluation.
4636//===----------------------------------------------------------------------===//
4637namespace {
4638template<class Derived>
4639class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004640 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004641protected:
4642 LValue &Result;
4643 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004644 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004645
4646 bool Success(APValue::LValueBase B) {
4647 Result.set(B);
4648 return true;
4649 }
4650
4651public:
4652 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4653 ExprEvaluatorBaseTy(Info), Result(Result) {}
4654
Richard Smith2e312c82012-03-03 22:46:17 +00004655 bool Success(const APValue &V, const Expr *E) {
4656 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004657 return true;
4658 }
Richard Smith027bf112011-11-17 22:56:20 +00004659
Richard Smith027bf112011-11-17 22:56:20 +00004660 bool VisitMemberExpr(const MemberExpr *E) {
4661 // Handle non-static data members.
4662 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004663 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004664 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004665 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004666 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004667 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004668 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004669 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004670 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004671 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004672 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004673 BaseTy = E->getBase()->getType();
4674 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004675 if (!EvalOK) {
4676 if (!this->Info.allowInvalidBaseExpr())
4677 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004678 Result.setInvalid(E);
4679 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004680 }
Richard Smith027bf112011-11-17 22:56:20 +00004681
Richard Smith1b78b3d2012-01-25 22:15:11 +00004682 const ValueDecl *MD = E->getMemberDecl();
4683 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4684 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4685 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4686 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004687 if (!HandleLValueMember(this->Info, E, Result, FD))
4688 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004689 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004690 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4691 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004692 } else
4693 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004694
Richard Smith1b78b3d2012-01-25 22:15:11 +00004695 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004696 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004697 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004698 RefValue))
4699 return false;
4700 return Success(RefValue, E);
4701 }
4702 return true;
4703 }
4704
4705 bool VisitBinaryOperator(const BinaryOperator *E) {
4706 switch (E->getOpcode()) {
4707 default:
4708 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4709
4710 case BO_PtrMemD:
4711 case BO_PtrMemI:
4712 return HandleMemberPointerAccess(this->Info, E, Result);
4713 }
4714 }
4715
4716 bool VisitCastExpr(const CastExpr *E) {
4717 switch (E->getCastKind()) {
4718 default:
4719 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4720
4721 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004722 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004723 if (!this->Visit(E->getSubExpr()))
4724 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004725
4726 // Now figure out the necessary offset to add to the base LV to get from
4727 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004728 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4729 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004730 }
4731 }
4732};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004733}
Richard Smith027bf112011-11-17 22:56:20 +00004734
4735//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004736// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004737//
4738// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4739// function designators (in C), decl references to void objects (in C), and
4740// temporaries (if building with -Wno-address-of-temporary).
4741//
4742// LValue evaluation produces values comprising a base expression of one of the
4743// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004744// - Declarations
4745// * VarDecl
4746// * FunctionDecl
4747// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00004748// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00004749// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004750// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004751// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004752// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004753// * ObjCEncodeExpr
4754// * AddrLabelExpr
4755// * BlockExpr
4756// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004757// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004758// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004759// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004760// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4761// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004762// * A MaterializeTemporaryExpr that has static storage duration, with no
4763// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004764// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004765//===----------------------------------------------------------------------===//
4766namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004767class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004768 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004769public:
Richard Smith027bf112011-11-17 22:56:20 +00004770 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4771 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004772
Richard Smith11562c52011-10-28 17:51:58 +00004773 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004774 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004775
Peter Collingbournee9200682011-05-13 03:29:01 +00004776 bool VisitDeclRefExpr(const DeclRefExpr *E);
4777 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004778 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004779 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4780 bool VisitMemberExpr(const MemberExpr *E);
4781 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4782 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004783 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004784 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004785 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4786 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004787 bool VisitUnaryReal(const UnaryOperator *E);
4788 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004789 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4790 return VisitUnaryPreIncDec(UO);
4791 }
4792 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4793 return VisitUnaryPreIncDec(UO);
4794 }
Richard Smith3229b742013-05-05 21:17:10 +00004795 bool VisitBinAssign(const BinaryOperator *BO);
4796 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004797
Peter Collingbournee9200682011-05-13 03:29:01 +00004798 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004799 switch (E->getCastKind()) {
4800 default:
Richard Smith027bf112011-11-17 22:56:20 +00004801 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004802
Eli Friedmance3e02a2011-10-11 00:13:24 +00004803 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004804 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004805 if (!Visit(E->getSubExpr()))
4806 return false;
4807 Result.Designator.setInvalid();
4808 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004809
Richard Smith027bf112011-11-17 22:56:20 +00004810 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004811 if (!Visit(E->getSubExpr()))
4812 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004813 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004814 }
4815 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004816};
4817} // end anonymous namespace
4818
Richard Smith11562c52011-10-28 17:51:58 +00004819/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004820/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004821/// * function designators in C, and
4822/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004823/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004824static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4825 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004826 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004827 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004828}
4829
Peter Collingbournee9200682011-05-13 03:29:01 +00004830bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004831 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004832 return Success(FD);
4833 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004834 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00004835 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00004836 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00004837 return Error(E);
4838}
Richard Smith733237d2011-10-24 23:14:33 +00004839
Faisal Vali0528a312016-11-13 06:09:16 +00004840
Richard Smith11562c52011-10-28 17:51:58 +00004841bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004842 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00004843 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
4844 // Only if a local variable was declared in the function currently being
4845 // evaluated, do we expect to be able to find its value in the current
4846 // frame. (Otherwise it was likely declared in an enclosing context and
4847 // could either have a valid evaluatable value (for e.g. a constexpr
4848 // variable) or be ill-formed (and trigger an appropriate evaluation
4849 // diagnostic)).
4850 if (Info.CurrentCall->Callee &&
4851 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
4852 Frame = Info.CurrentCall;
4853 }
4854 }
Richard Smith3229b742013-05-05 21:17:10 +00004855
Richard Smithfec09922011-11-01 16:57:24 +00004856 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004857 if (Frame) {
4858 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004859 return true;
4860 }
Richard Smithce40ad62011-11-12 22:28:03 +00004861 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004862 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004863
Richard Smith3229b742013-05-05 21:17:10 +00004864 APValue *V;
4865 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004866 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004867 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004868 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00004869 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004870 return false;
4871 }
Richard Smith3229b742013-05-05 21:17:10 +00004872 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004873}
4874
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004875bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4876 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004877 // Walk through the expression to find the materialized temporary itself.
4878 SmallVector<const Expr *, 2> CommaLHSs;
4879 SmallVector<SubobjectAdjustment, 2> Adjustments;
4880 const Expr *Inner = E->GetTemporaryExpr()->
4881 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004882
Richard Smith84401042013-06-03 05:03:02 +00004883 // If we passed any comma operators, evaluate their LHSs.
4884 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4885 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4886 return false;
4887
Richard Smithe6c01442013-06-05 00:46:14 +00004888 // A materialized temporary with static storage duration can appear within the
4889 // result of a constant expression evaluation, so we need to preserve its
4890 // value for use outside this evaluation.
4891 APValue *Value;
4892 if (E->getStorageDuration() == SD_Static) {
4893 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004894 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004895 Result.set(E);
4896 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004897 Value = &Info.CurrentCall->
4898 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004899 Result.set(E, Info.CurrentCall->Index);
4900 }
4901
Richard Smithea4ad5d2013-06-06 08:19:16 +00004902 QualType Type = Inner->getType();
4903
Richard Smith84401042013-06-03 05:03:02 +00004904 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004905 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4906 (E->getStorageDuration() == SD_Static &&
4907 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4908 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004909 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004910 }
Richard Smith84401042013-06-03 05:03:02 +00004911
4912 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004913 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4914 --I;
4915 switch (Adjustments[I].Kind) {
4916 case SubobjectAdjustment::DerivedToBaseAdjustment:
4917 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4918 Type, Result))
4919 return false;
4920 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4921 break;
4922
4923 case SubobjectAdjustment::FieldAdjustment:
4924 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4925 return false;
4926 Type = Adjustments[I].Field->getType();
4927 break;
4928
4929 case SubobjectAdjustment::MemberPointerAdjustment:
4930 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4931 Adjustments[I].Ptr.RHS))
4932 return false;
4933 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4934 break;
4935 }
4936 }
4937
4938 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004939}
4940
Peter Collingbournee9200682011-05-13 03:29:01 +00004941bool
4942LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00004943 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
4944 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00004945 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4946 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004947 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004948}
4949
Richard Smith6e525142011-12-27 12:18:28 +00004950bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004951 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004952 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004953
Faisal Valie690b7a2016-07-02 22:34:24 +00004954 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00004955 << E->getExprOperand()->getType()
4956 << E->getExprOperand()->getSourceRange();
4957 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004958}
4959
Francois Pichet0066db92012-04-16 04:08:35 +00004960bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4961 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004962}
Francois Pichet0066db92012-04-16 04:08:35 +00004963
Peter Collingbournee9200682011-05-13 03:29:01 +00004964bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004965 // Handle static data members.
4966 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00004967 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00004968 return VisitVarDecl(E, VD);
4969 }
4970
Richard Smith254a73d2011-10-28 22:34:42 +00004971 // Handle static member functions.
4972 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4973 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00004974 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004975 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004976 }
4977 }
4978
Richard Smithd62306a2011-11-10 06:34:14 +00004979 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004980 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004981}
4982
Peter Collingbournee9200682011-05-13 03:29:01 +00004983bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004984 // FIXME: Deal with vectors as array subscript bases.
4985 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004986 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004987
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004988 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004989 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004990
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004991 APSInt Index;
4992 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004993 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004994
Richard Smith861b5b52013-05-07 23:34:45 +00004995 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4996 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004997}
Eli Friedman9a156e52008-11-12 09:44:48 +00004998
Peter Collingbournee9200682011-05-13 03:29:01 +00004999bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00005000 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005001}
5002
Richard Smith66c96992012-02-18 22:04:06 +00005003bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5004 if (!Visit(E->getSubExpr()))
5005 return false;
5006 // __real is a no-op on scalar lvalues.
5007 if (E->getSubExpr()->getType()->isAnyComplexType())
5008 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5009 return true;
5010}
5011
5012bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5013 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5014 "lvalue __imag__ on scalar?");
5015 if (!Visit(E->getSubExpr()))
5016 return false;
5017 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5018 return true;
5019}
5020
Richard Smith243ef902013-05-05 23:31:59 +00005021bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005022 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005023 return Error(UO);
5024
5025 if (!this->Visit(UO->getSubExpr()))
5026 return false;
5027
Richard Smith243ef902013-05-05 23:31:59 +00005028 return handleIncDec(
5029 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005030 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005031}
5032
5033bool LValueExprEvaluator::VisitCompoundAssignOperator(
5034 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005035 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005036 return Error(CAO);
5037
Richard Smith3229b742013-05-05 21:17:10 +00005038 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005039
5040 // The overall lvalue result is the result of evaluating the LHS.
5041 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005042 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005043 Evaluate(RHS, this->Info, CAO->getRHS());
5044 return false;
5045 }
5046
Richard Smith3229b742013-05-05 21:17:10 +00005047 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5048 return false;
5049
Richard Smith43e77732013-05-07 04:50:00 +00005050 return handleCompoundAssignment(
5051 this->Info, CAO,
5052 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5053 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005054}
5055
5056bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005057 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005058 return Error(E);
5059
Richard Smith3229b742013-05-05 21:17:10 +00005060 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005061
5062 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005063 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005064 Evaluate(NewVal, this->Info, E->getRHS());
5065 return false;
5066 }
5067
Richard Smith3229b742013-05-05 21:17:10 +00005068 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5069 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005070
5071 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005072 NewVal);
5073}
5074
Eli Friedman9a156e52008-11-12 09:44:48 +00005075//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005076// Pointer Evaluation
5077//===----------------------------------------------------------------------===//
5078
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005079namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005080class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005081 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005082 LValue &Result;
5083
Peter Collingbournee9200682011-05-13 03:29:01 +00005084 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005085 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005086 return true;
5087 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005088public:
Mike Stump11289f42009-09-09 15:08:12 +00005089
John McCall45d55e42010-05-07 21:00:08 +00005090 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005091 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005092
Richard Smith2e312c82012-03-03 22:46:17 +00005093 bool Success(const APValue &V, const Expr *E) {
5094 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005095 return true;
5096 }
Richard Smithfddd3842011-12-30 21:15:51 +00005097 bool ZeroInitialization(const Expr *E) {
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00005098 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5099 Result.set((Expr*)nullptr, 0, false, true, Offset);
5100 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005101 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005102
John McCall45d55e42010-05-07 21:00:08 +00005103 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005104 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005105 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005106 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005107 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005108 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005109 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005110 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005111 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005112 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005113 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005114 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005115 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005116 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005117 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005118 }
Richard Smithd62306a2011-11-10 06:34:14 +00005119 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005120 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005121 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005122 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005123 if (!Info.CurrentCall->This) {
5124 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005125 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005126 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005127 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005128 return false;
5129 }
Richard Smithd62306a2011-11-10 06:34:14 +00005130 Result = *Info.CurrentCall->This;
5131 return true;
5132 }
John McCallc07a0c72011-02-17 10:25:35 +00005133
Eli Friedman449fe542009-03-23 04:56:01 +00005134 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005135};
Chris Lattner05706e882008-07-11 18:11:29 +00005136} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005137
John McCall45d55e42010-05-07 21:00:08 +00005138static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005139 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005140 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005141}
5142
John McCall45d55e42010-05-07 21:00:08 +00005143bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005144 if (E->getOpcode() != BO_Add &&
5145 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005146 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005147
Chris Lattner05706e882008-07-11 18:11:29 +00005148 const Expr *PExp = E->getLHS();
5149 const Expr *IExp = E->getRHS();
5150 if (IExp->getType()->isPointerType())
5151 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005152
Richard Smith253c2a32012-01-27 01:14:48 +00005153 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005154 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005155 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005156
John McCall45d55e42010-05-07 21:00:08 +00005157 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005158 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005159 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005160
5161 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00005162 if (E->getOpcode() == BO_Sub)
5163 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00005164
Ted Kremenek28831752012-08-23 20:46:57 +00005165 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00005166 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5167 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00005168}
Eli Friedman9a156e52008-11-12 09:44:48 +00005169
John McCall45d55e42010-05-07 21:00:08 +00005170bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5171 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005172}
Mike Stump11289f42009-09-09 15:08:12 +00005173
Peter Collingbournee9200682011-05-13 03:29:01 +00005174bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5175 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005176
Eli Friedman847a2bc2009-12-27 05:43:15 +00005177 switch (E->getCastKind()) {
5178 default:
5179 break;
5180
John McCalle3027922010-08-25 11:45:40 +00005181 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005182 case CK_CPointerToObjCPointerCast:
5183 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005184 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005185 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005186 if (!Visit(SubExpr))
5187 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005188 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5189 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5190 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005191 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005192 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005193 if (SubExpr->getType()->isVoidPointerType())
5194 CCEDiag(E, diag::note_constexpr_invalid_cast)
5195 << 3 << SubExpr->getType();
5196 else
5197 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5198 }
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00005199 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5200 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005201 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005202
Anders Carlsson18275092010-10-31 20:41:46 +00005203 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005204 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005205 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005206 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005207 if (!Result.Base && Result.Offset.isZero())
5208 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005209
Richard Smithd62306a2011-11-10 06:34:14 +00005210 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005211 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005212 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5213 castAs<PointerType>()->getPointeeType(),
5214 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005215
Richard Smith027bf112011-11-17 22:56:20 +00005216 case CK_BaseToDerived:
5217 if (!Visit(E->getSubExpr()))
5218 return false;
5219 if (!Result.Base && Result.Offset.isZero())
5220 return true;
5221 return HandleBaseToDerivedCast(Info, E, Result);
5222
Richard Smith0b0a0b62011-10-29 20:57:55 +00005223 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005224 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005225 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005226
John McCalle3027922010-08-25 11:45:40 +00005227 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005228 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5229
Richard Smith2e312c82012-03-03 22:46:17 +00005230 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005231 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005232 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005233
John McCall45d55e42010-05-07 21:00:08 +00005234 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005235 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5236 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005237 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005238 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005239 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005240 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005241 Result.Designator.setInvalid();
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00005242 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005243 return true;
5244 } else {
5245 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005246 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005247 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005248 }
5249 }
John McCalle3027922010-08-25 11:45:40 +00005250 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005251 if (SubExpr->isGLValue()) {
5252 if (!EvaluateLValue(SubExpr, Result, Info))
5253 return false;
5254 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005255 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005256 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005257 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005258 return false;
5259 }
Richard Smith96e0c102011-11-04 02:25:55 +00005260 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005261 if (const ConstantArrayType *CAT
5262 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5263 Result.addArray(Info, E, CAT);
5264 else
5265 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005266 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005267
John McCalle3027922010-08-25 11:45:40 +00005268 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005269 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005270 }
5271
Richard Smith11562c52011-10-28 17:51:58 +00005272 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005273}
Chris Lattner05706e882008-07-11 18:11:29 +00005274
Hal Finkel0dd05d42014-10-03 17:18:37 +00005275static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5276 // C++ [expr.alignof]p3:
5277 // When alignof is applied to a reference type, the result is the
5278 // alignment of the referenced type.
5279 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5280 T = Ref->getPointeeType();
5281
5282 // __alignof is defined to return the preferred alignment.
5283 return Info.Ctx.toCharUnitsFromBits(
5284 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5285}
5286
5287static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5288 E = E->IgnoreParens();
5289
5290 // The kinds of expressions that we have special-case logic here for
5291 // should be kept up to date with the special checks for those
5292 // expressions in Sema.
5293
5294 // alignof decl is always accepted, even if it doesn't make sense: we default
5295 // to 1 in those cases.
5296 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5297 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5298 /*RefAsPointee*/true);
5299
5300 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5301 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5302 /*RefAsPointee*/true);
5303
5304 return GetAlignOfType(Info, E->getType());
5305}
5306
Peter Collingbournee9200682011-05-13 03:29:01 +00005307bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005308 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005309 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005310
Richard Smith6328cbd2016-11-16 00:57:23 +00005311 if (unsigned BuiltinOp = E->getBuiltinCallee())
5312 return VisitBuiltinCallExpr(E, BuiltinOp);
5313
5314 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5315}
5316
5317bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5318 unsigned BuiltinOp) {
5319 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005320 case Builtin::BI__builtin_addressof:
5321 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005322 case Builtin::BI__builtin_assume_aligned: {
5323 // We need to be very careful here because: if the pointer does not have the
5324 // asserted alignment, then the behavior is undefined, and undefined
5325 // behavior is non-constant.
5326 if (!EvaluatePointer(E->getArg(0), Result, Info))
5327 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005328
Hal Finkel0dd05d42014-10-03 17:18:37 +00005329 LValue OffsetResult(Result);
5330 APSInt Alignment;
5331 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5332 return false;
5333 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5334
5335 if (E->getNumArgs() > 2) {
5336 APSInt Offset;
5337 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5338 return false;
5339
5340 int64_t AdditionalOffset = -getExtValue(Offset);
5341 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5342 }
5343
5344 // If there is a base object, then it must have the correct alignment.
5345 if (OffsetResult.Base) {
5346 CharUnits BaseAlignment;
5347 if (const ValueDecl *VD =
5348 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5349 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5350 } else {
5351 BaseAlignment =
5352 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5353 }
5354
5355 if (BaseAlignment < Align) {
5356 Result.Designator.setInvalid();
Yaron Kerene0bcdd42016-10-08 06:45:10 +00005357 // FIXME: Quantities here cast to integers because the plural modifier
5358 // does not work on APSInts yet.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005359 CCEDiag(E->getArg(0),
5360 diag::note_constexpr_baa_insufficient_alignment) << 0
5361 << (int) BaseAlignment.getQuantity()
5362 << (unsigned) getExtValue(Alignment);
5363 return false;
5364 }
5365 }
5366
5367 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005368 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005369 Result.Designator.setInvalid();
5370 APSInt Offset(64, false);
5371 Offset = OffsetResult.Offset.getQuantity();
5372
5373 if (OffsetResult.Base)
5374 CCEDiag(E->getArg(0),
5375 diag::note_constexpr_baa_insufficient_alignment) << 1
5376 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5377 else
5378 CCEDiag(E->getArg(0),
5379 diag::note_constexpr_baa_value_insufficient_alignment)
5380 << Offset << (unsigned) getExtValue(Alignment);
5381
5382 return false;
5383 }
5384
5385 return true;
5386 }
Richard Smithe9507952016-11-12 01:39:56 +00005387
5388 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005389 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005390 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005391 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005392 if (Info.getLangOpts().CPlusPlus11)
5393 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5394 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005395 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005396 else
5397 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5398 // Fall through.
5399 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005400 case Builtin::BI__builtin_wcschr:
5401 case Builtin::BI__builtin_memchr:
5402 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005403 if (!Visit(E->getArg(0)))
5404 return false;
5405 APSInt Desired;
5406 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5407 return false;
5408 uint64_t MaxLength = uint64_t(-1);
5409 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005410 BuiltinOp != Builtin::BIwcschr &&
5411 BuiltinOp != Builtin::BI__builtin_strchr &&
5412 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005413 APSInt N;
5414 if (!EvaluateInteger(E->getArg(2), N, Info))
5415 return false;
5416 MaxLength = N.getExtValue();
5417 }
5418
Richard Smith8110c9d2016-11-29 19:45:17 +00005419 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005420
Richard Smith8110c9d2016-11-29 19:45:17 +00005421 // Figure out what value we're actually looking for (after converting to
5422 // the corresponding unsigned type if necessary).
5423 uint64_t DesiredVal;
5424 bool StopAtNull = false;
5425 switch (BuiltinOp) {
5426 case Builtin::BIstrchr:
5427 case Builtin::BI__builtin_strchr:
5428 // strchr compares directly to the passed integer, and therefore
5429 // always fails if given an int that is not a char.
5430 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5431 E->getArg(1)->getType(),
5432 Desired),
5433 Desired))
5434 return ZeroInitialization(E);
5435 StopAtNull = true;
5436 // Fall through.
5437 case Builtin::BImemchr:
5438 case Builtin::BI__builtin_memchr:
5439 // memchr compares by converting both sides to unsigned char. That's also
5440 // correct for strchr if we get this far (to cope with plain char being
5441 // unsigned in the strchr case).
5442 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5443 break;
Richard Smithe9507952016-11-12 01:39:56 +00005444
Richard Smith8110c9d2016-11-29 19:45:17 +00005445 case Builtin::BIwcschr:
5446 case Builtin::BI__builtin_wcschr:
5447 StopAtNull = true;
5448 // Fall through.
5449 case Builtin::BIwmemchr:
5450 case Builtin::BI__builtin_wmemchr:
5451 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5452 DesiredVal = Desired.getZExtValue();
5453 break;
5454 }
Richard Smithe9507952016-11-12 01:39:56 +00005455
5456 for (; MaxLength; --MaxLength) {
5457 APValue Char;
5458 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5459 !Char.isInt())
5460 return false;
5461 if (Char.getInt().getZExtValue() == DesiredVal)
5462 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005463 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005464 break;
5465 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5466 return false;
5467 }
5468 // Not found: return nullptr.
5469 return ZeroInitialization(E);
5470 }
5471
Richard Smith6cbd65d2013-07-11 02:27:57 +00005472 default:
5473 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5474 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005475}
Chris Lattner05706e882008-07-11 18:11:29 +00005476
5477//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005478// Member Pointer Evaluation
5479//===----------------------------------------------------------------------===//
5480
5481namespace {
5482class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005483 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005484 MemberPtr &Result;
5485
5486 bool Success(const ValueDecl *D) {
5487 Result = MemberPtr(D);
5488 return true;
5489 }
5490public:
5491
5492 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5493 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5494
Richard Smith2e312c82012-03-03 22:46:17 +00005495 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005496 Result.setFrom(V);
5497 return true;
5498 }
Richard Smithfddd3842011-12-30 21:15:51 +00005499 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005500 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005501 }
5502
5503 bool VisitCastExpr(const CastExpr *E);
5504 bool VisitUnaryAddrOf(const UnaryOperator *E);
5505};
5506} // end anonymous namespace
5507
5508static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5509 EvalInfo &Info) {
5510 assert(E->isRValue() && E->getType()->isMemberPointerType());
5511 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5512}
5513
5514bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5515 switch (E->getCastKind()) {
5516 default:
5517 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5518
5519 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005520 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005521 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005522
5523 case CK_BaseToDerivedMemberPointer: {
5524 if (!Visit(E->getSubExpr()))
5525 return false;
5526 if (E->path_empty())
5527 return true;
5528 // Base-to-derived member pointer casts store the path in derived-to-base
5529 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5530 // the wrong end of the derived->base arc, so stagger the path by one class.
5531 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5532 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5533 PathI != PathE; ++PathI) {
5534 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5535 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5536 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005537 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005538 }
5539 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5540 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005541 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005542 return true;
5543 }
5544
5545 case CK_DerivedToBaseMemberPointer:
5546 if (!Visit(E->getSubExpr()))
5547 return false;
5548 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5549 PathE = E->path_end(); PathI != PathE; ++PathI) {
5550 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5551 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5552 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005553 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005554 }
5555 return true;
5556 }
5557}
5558
5559bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5560 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5561 // member can be formed.
5562 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5563}
5564
5565//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005566// Record Evaluation
5567//===----------------------------------------------------------------------===//
5568
5569namespace {
5570 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005571 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005572 const LValue &This;
5573 APValue &Result;
5574 public:
5575
5576 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5577 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5578
Richard Smith2e312c82012-03-03 22:46:17 +00005579 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005580 Result = V;
5581 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005582 }
Richard Smithb8348f52016-05-12 22:16:28 +00005583 bool ZeroInitialization(const Expr *E) {
5584 return ZeroInitialization(E, E->getType());
5585 }
5586 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005587
Richard Smith52a980a2015-08-28 02:43:42 +00005588 bool VisitCallExpr(const CallExpr *E) {
5589 return handleCallExpr(E, Result, &This);
5590 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005591 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005592 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005593 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5594 return VisitCXXConstructExpr(E, E->getType());
5595 }
Richard Smith5179eb72016-06-28 19:03:57 +00005596 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005597 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005598 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005599 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005600}
Richard Smithd62306a2011-11-10 06:34:14 +00005601
Richard Smithfddd3842011-12-30 21:15:51 +00005602/// Perform zero-initialization on an object of non-union class type.
5603/// C++11 [dcl.init]p5:
5604/// To zero-initialize an object or reference of type T means:
5605/// [...]
5606/// -- if T is a (possibly cv-qualified) non-union class type,
5607/// each non-static data member and each base-class subobject is
5608/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005609static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5610 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005611 const LValue &This, APValue &Result) {
5612 assert(!RD->isUnion() && "Expected non-union class type");
5613 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5614 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005615 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005616
John McCalld7bca762012-05-01 00:38:49 +00005617 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005618 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5619
5620 if (CD) {
5621 unsigned Index = 0;
5622 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005623 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005624 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5625 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005626 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5627 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005628 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005629 Result.getStructBase(Index)))
5630 return false;
5631 }
5632 }
5633
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005634 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005635 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005636 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005637 continue;
5638
5639 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005640 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005641 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005642
David Blaikie2d7c57e2012-04-30 02:36:29 +00005643 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005644 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005645 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005646 return false;
5647 }
5648
5649 return true;
5650}
5651
Richard Smithb8348f52016-05-12 22:16:28 +00005652bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5653 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005654 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005655 if (RD->isUnion()) {
5656 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5657 // object's first non-static named data member is zero-initialized
5658 RecordDecl::field_iterator I = RD->field_begin();
5659 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005660 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005661 return true;
5662 }
5663
5664 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005665 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005666 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005667 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005668 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005669 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005670 }
5671
Richard Smith5d108602012-02-17 00:44:16 +00005672 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005673 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005674 return false;
5675 }
5676
Richard Smitha8105bc2012-01-06 16:39:00 +00005677 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005678}
5679
Richard Smithe97cbd72011-11-11 04:05:33 +00005680bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5681 switch (E->getCastKind()) {
5682 default:
5683 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5684
5685 case CK_ConstructorConversion:
5686 return Visit(E->getSubExpr());
5687
5688 case CK_DerivedToBase:
5689 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005690 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005691 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005692 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005693 if (!DerivedObject.isStruct())
5694 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005695
5696 // Derived-to-base rvalue conversion: just slice off the derived part.
5697 APValue *Value = &DerivedObject;
5698 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5699 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5700 PathE = E->path_end(); PathI != PathE; ++PathI) {
5701 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5702 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5703 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5704 RD = Base;
5705 }
5706 Result = *Value;
5707 return true;
5708 }
5709 }
5710}
5711
Richard Smithd62306a2011-11-10 06:34:14 +00005712bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00005713 if (E->isTransparent())
5714 return Visit(E->getInit(0));
5715
Richard Smithd62306a2011-11-10 06:34:14 +00005716 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005717 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005718 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5719
5720 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005721 const FieldDecl *Field = E->getInitializedFieldInUnion();
5722 Result = APValue(Field);
5723 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005724 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005725
5726 // If the initializer list for a union does not contain any elements, the
5727 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005728 // FIXME: The element should be initialized from an initializer list.
5729 // Is this difference ever observable for initializer lists which
5730 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005731 ImplicitValueInitExpr VIE(Field->getType());
5732 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5733
Richard Smithd62306a2011-11-10 06:34:14 +00005734 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005735 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5736 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005737
5738 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5739 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5740 isa<CXXDefaultInitExpr>(InitExpr));
5741
Richard Smithb228a862012-02-15 02:18:13 +00005742 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005743 }
5744
Richard Smith872307e2016-03-08 22:17:41 +00005745 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00005746 if (Result.isUninit())
5747 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5748 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005749 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005750 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00005751
5752 // Initialize base classes.
5753 if (CXXRD) {
5754 for (const auto &Base : CXXRD->bases()) {
5755 assert(ElementNo < E->getNumInits() && "missing init for base class");
5756 const Expr *Init = E->getInit(ElementNo);
5757
5758 LValue Subobject = This;
5759 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5760 return false;
5761
5762 APValue &FieldVal = Result.getStructBase(ElementNo);
5763 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00005764 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00005765 return false;
5766 Success = false;
5767 }
5768 ++ElementNo;
5769 }
5770 }
5771
5772 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005773 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005774 // Anonymous bit-fields are not considered members of the class for
5775 // purposes of aggregate initialization.
5776 if (Field->isUnnamedBitfield())
5777 continue;
5778
5779 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005780
Richard Smith253c2a32012-01-27 01:14:48 +00005781 bool HaveInit = ElementNo < E->getNumInits();
5782
5783 // FIXME: Diagnostics here should point to the end of the initializer
5784 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005785 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005786 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005787 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005788
5789 // Perform an implicit value-initialization for members beyond the end of
5790 // the initializer list.
5791 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005792 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005793
Richard Smith852c9db2013-04-20 22:23:05 +00005794 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5795 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5796 isa<CXXDefaultInitExpr>(Init));
5797
Richard Smith49ca8aa2013-08-06 07:09:20 +00005798 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5799 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5800 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005801 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00005802 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005803 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005804 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005805 }
5806 }
5807
Richard Smith253c2a32012-01-27 01:14:48 +00005808 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005809}
5810
Richard Smithb8348f52016-05-12 22:16:28 +00005811bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5812 QualType T) {
5813 // Note that E's type is not necessarily the type of our class here; we might
5814 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00005815 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005816 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5817
Richard Smithfddd3842011-12-30 21:15:51 +00005818 bool ZeroInit = E->requiresZeroInitialization();
5819 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005820 // If we've already performed zero-initialization, we're already done.
5821 if (!Result.isUninit())
5822 return true;
5823
Richard Smithda3f4fd2014-03-05 23:32:50 +00005824 // We can get here in two different ways:
5825 // 1) We're performing value-initialization, and should zero-initialize
5826 // the object, or
5827 // 2) We're performing default-initialization of an object with a trivial
5828 // constexpr default constructor, in which case we should start the
5829 // lifetimes of all the base subobjects (there can be no data member
5830 // subobjects in this case) per [basic.life]p1.
5831 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00005832 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00005833 }
5834
Craig Topper36250ad2014-05-12 05:36:57 +00005835 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005836 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00005837
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005838 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00005839 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005840
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005841 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005842 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005843 if (const MaterializeTemporaryExpr *ME
5844 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5845 return Visit(ME->GetTemporaryExpr());
5846
Richard Smithb8348f52016-05-12 22:16:28 +00005847 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00005848 return false;
5849
Craig Topper5fc8fc22014-08-27 06:28:36 +00005850 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00005851 return HandleConstructorCall(E, This, Args,
5852 cast<CXXConstructorDecl>(Definition), Info,
5853 Result);
5854}
5855
5856bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
5857 const CXXInheritedCtorInitExpr *E) {
5858 if (!Info.CurrentCall) {
5859 assert(Info.checkingPotentialConstantExpression());
5860 return false;
5861 }
5862
5863 const CXXConstructorDecl *FD = E->getConstructor();
5864 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
5865 return false;
5866
5867 const FunctionDecl *Definition = nullptr;
5868 auto Body = FD->getBody(Definition);
5869
5870 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
5871 return false;
5872
5873 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005874 cast<CXXConstructorDecl>(Definition), Info,
5875 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005876}
5877
Richard Smithcc1b96d2013-06-12 22:31:48 +00005878bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5879 const CXXStdInitializerListExpr *E) {
5880 const ConstantArrayType *ArrayType =
5881 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5882
5883 LValue Array;
5884 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5885 return false;
5886
5887 // Get a pointer to the first element of the array.
5888 Array.addArray(Info, E, ArrayType);
5889
5890 // FIXME: Perform the checks on the field types in SemaInit.
5891 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5892 RecordDecl::field_iterator Field = Record->field_begin();
5893 if (Field == Record->field_end())
5894 return Error(E);
5895
5896 // Start pointer.
5897 if (!Field->getType()->isPointerType() ||
5898 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5899 ArrayType->getElementType()))
5900 return Error(E);
5901
5902 // FIXME: What if the initializer_list type has base classes, etc?
5903 Result = APValue(APValue::UninitStruct(), 0, 2);
5904 Array.moveInto(Result.getStructField(0));
5905
5906 if (++Field == Record->field_end())
5907 return Error(E);
5908
5909 if (Field->getType()->isPointerType() &&
5910 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5911 ArrayType->getElementType())) {
5912 // End pointer.
5913 if (!HandleLValueArrayAdjustment(Info, E, Array,
5914 ArrayType->getElementType(),
5915 ArrayType->getSize().getZExtValue()))
5916 return false;
5917 Array.moveInto(Result.getStructField(1));
5918 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5919 // Length.
5920 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5921 else
5922 return Error(E);
5923
5924 if (++Field != Record->field_end())
5925 return Error(E);
5926
5927 return true;
5928}
5929
Richard Smithd62306a2011-11-10 06:34:14 +00005930static bool EvaluateRecord(const Expr *E, const LValue &This,
5931 APValue &Result, EvalInfo &Info) {
5932 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005933 "can't evaluate expression as a record rvalue");
5934 return RecordExprEvaluator(Info, This, Result).Visit(E);
5935}
5936
5937//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005938// Temporary Evaluation
5939//
5940// Temporaries are represented in the AST as rvalues, but generally behave like
5941// lvalues. The full-object of which the temporary is a subobject is implicitly
5942// materialized so that a reference can bind to it.
5943//===----------------------------------------------------------------------===//
5944namespace {
5945class TemporaryExprEvaluator
5946 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5947public:
5948 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5949 LValueExprEvaluatorBaseTy(Info, Result) {}
5950
5951 /// Visit an expression which constructs the value of this temporary.
5952 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005953 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005954 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5955 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005956 }
5957
5958 bool VisitCastExpr(const CastExpr *E) {
5959 switch (E->getCastKind()) {
5960 default:
5961 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5962
5963 case CK_ConstructorConversion:
5964 return VisitConstructExpr(E->getSubExpr());
5965 }
5966 }
5967 bool VisitInitListExpr(const InitListExpr *E) {
5968 return VisitConstructExpr(E);
5969 }
5970 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5971 return VisitConstructExpr(E);
5972 }
5973 bool VisitCallExpr(const CallExpr *E) {
5974 return VisitConstructExpr(E);
5975 }
Richard Smith513955c2014-12-17 19:24:30 +00005976 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5977 return VisitConstructExpr(E);
5978 }
Richard Smith027bf112011-11-17 22:56:20 +00005979};
5980} // end anonymous namespace
5981
5982/// Evaluate an expression of record type as a temporary.
5983static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005984 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005985 return TemporaryExprEvaluator(Info, Result).Visit(E);
5986}
5987
5988//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005989// Vector Evaluation
5990//===----------------------------------------------------------------------===//
5991
5992namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005993 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005994 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005995 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005996 public:
Mike Stump11289f42009-09-09 15:08:12 +00005997
Richard Smith2d406342011-10-22 21:10:00 +00005998 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5999 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006000
Craig Topper9798b932015-09-29 04:30:05 +00006001 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006002 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6003 // FIXME: remove this APValue copy.
6004 Result = APValue(V.data(), V.size());
6005 return true;
6006 }
Richard Smith2e312c82012-03-03 22:46:17 +00006007 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006008 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006009 Result = V;
6010 return true;
6011 }
Richard Smithfddd3842011-12-30 21:15:51 +00006012 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006013
Richard Smith2d406342011-10-22 21:10:00 +00006014 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006015 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006016 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006017 bool VisitInitListExpr(const InitListExpr *E);
6018 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006019 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006020 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006021 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006022 };
6023} // end anonymous namespace
6024
6025static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006026 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006027 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006028}
6029
George Burgess IV533ff002015-12-11 00:23:35 +00006030bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006031 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006032 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006033
Richard Smith161f09a2011-12-06 22:44:34 +00006034 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006035 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006036
Eli Friedmanc757de22011-03-25 00:43:55 +00006037 switch (E->getCastKind()) {
6038 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006039 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006040 if (SETy->isIntegerType()) {
6041 APSInt IntResult;
6042 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006043 return false;
6044 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006045 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006046 APFloat FloatResult(0.0);
6047 if (!EvaluateFloat(SE, FloatResult, Info))
6048 return false;
6049 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006050 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006051 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006052 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006053
6054 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006055 SmallVector<APValue, 4> Elts(NElts, Val);
6056 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006057 }
Eli Friedman803acb32011-12-22 03:51:45 +00006058 case CK_BitCast: {
6059 // Evaluate the operand into an APInt we can extract from.
6060 llvm::APInt SValInt;
6061 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6062 return false;
6063 // Extract the elements
6064 QualType EltTy = VTy->getElementType();
6065 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6066 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6067 SmallVector<APValue, 4> Elts;
6068 if (EltTy->isRealFloatingType()) {
6069 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006070 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006071 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006072 FloatEltSize = 80;
6073 for (unsigned i = 0; i < NElts; i++) {
6074 llvm::APInt Elt;
6075 if (BigEndian)
6076 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6077 else
6078 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006079 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006080 }
6081 } else if (EltTy->isIntegerType()) {
6082 for (unsigned i = 0; i < NElts; i++) {
6083 llvm::APInt Elt;
6084 if (BigEndian)
6085 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6086 else
6087 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6088 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6089 }
6090 } else {
6091 return Error(E);
6092 }
6093 return Success(Elts, E);
6094 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006095 default:
Richard Smith11562c52011-10-28 17:51:58 +00006096 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006097 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006098}
6099
Richard Smith2d406342011-10-22 21:10:00 +00006100bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006101VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006102 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006103 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006104 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006105
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006106 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006107 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006108
Eli Friedmanb9c71292012-01-03 23:24:20 +00006109 // The number of initializers can be less than the number of
6110 // vector elements. For OpenCL, this can be due to nested vector
6111 // initialization. For GCC compatibility, missing trailing elements
6112 // should be initialized with zeroes.
6113 unsigned CountInits = 0, CountElts = 0;
6114 while (CountElts < NumElements) {
6115 // Handle nested vector initialization.
6116 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006117 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006118 APValue v;
6119 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6120 return Error(E);
6121 unsigned vlen = v.getVectorLength();
6122 for (unsigned j = 0; j < vlen; j++)
6123 Elements.push_back(v.getVectorElt(j));
6124 CountElts += vlen;
6125 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006126 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006127 if (CountInits < NumInits) {
6128 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006129 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006130 } else // trailing integer zero.
6131 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6132 Elements.push_back(APValue(sInt));
6133 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006134 } else {
6135 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006136 if (CountInits < NumInits) {
6137 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006138 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006139 } else // trailing float zero.
6140 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6141 Elements.push_back(APValue(f));
6142 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006143 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006144 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006145 }
Richard Smith2d406342011-10-22 21:10:00 +00006146 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006147}
6148
Richard Smith2d406342011-10-22 21:10:00 +00006149bool
Richard Smithfddd3842011-12-30 21:15:51 +00006150VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006151 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006152 QualType EltTy = VT->getElementType();
6153 APValue ZeroElement;
6154 if (EltTy->isIntegerType())
6155 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6156 else
6157 ZeroElement =
6158 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6159
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006160 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006161 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006162}
6163
Richard Smith2d406342011-10-22 21:10:00 +00006164bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006165 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006166 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006167}
6168
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006169//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006170// Array Evaluation
6171//===----------------------------------------------------------------------===//
6172
6173namespace {
6174 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006175 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006176 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006177 APValue &Result;
6178 public:
6179
Richard Smithd62306a2011-11-10 06:34:14 +00006180 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6181 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006182
6183 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006184 assert((V.isArray() || V.isLValue()) &&
6185 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006186 Result = V;
6187 return true;
6188 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006189
Richard Smithfddd3842011-12-30 21:15:51 +00006190 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006191 const ConstantArrayType *CAT =
6192 Info.Ctx.getAsConstantArrayType(E->getType());
6193 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006194 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006195
6196 Result = APValue(APValue::UninitArray(), 0,
6197 CAT->getSize().getZExtValue());
6198 if (!Result.hasArrayFiller()) return true;
6199
Richard Smithfddd3842011-12-30 21:15:51 +00006200 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006201 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006202 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006203 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006204 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006205 }
6206
Richard Smith52a980a2015-08-28 02:43:42 +00006207 bool VisitCallExpr(const CallExpr *E) {
6208 return handleCallExpr(E, Result, &This);
6209 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006210 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006211 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006212 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006213 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6214 const LValue &Subobject,
6215 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006216 };
6217} // end anonymous namespace
6218
Richard Smithd62306a2011-11-10 06:34:14 +00006219static bool EvaluateArray(const Expr *E, const LValue &This,
6220 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006221 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006222 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006223}
6224
6225bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6226 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6227 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006228 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006229
Richard Smithca2cfbf2011-12-22 01:07:19 +00006230 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6231 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006232 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006233 LValue LV;
6234 if (!EvaluateLValue(E->getInit(0), LV, Info))
6235 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006236 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006237 LV.moveInto(Val);
6238 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006239 }
6240
Richard Smith253c2a32012-01-27 01:14:48 +00006241 bool Success = true;
6242
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006243 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6244 "zero-initialized array shouldn't have any initialized elts");
6245 APValue Filler;
6246 if (Result.isArray() && Result.hasArrayFiller())
6247 Filler = Result.getArrayFiller();
6248
Richard Smith9543c5e2013-04-22 14:44:29 +00006249 unsigned NumEltsToInit = E->getNumInits();
6250 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006251 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006252
6253 // If the initializer might depend on the array index, run it for each
6254 // array element. For now, just whitelist non-class value-initialization.
6255 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6256 NumEltsToInit = NumElts;
6257
6258 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006259
6260 // If the array was previously zero-initialized, preserve the
6261 // zero-initialized values.
6262 if (!Filler.isUninit()) {
6263 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6264 Result.getArrayInitializedElt(I) = Filler;
6265 if (Result.hasArrayFiller())
6266 Result.getArrayFiller() = Filler;
6267 }
6268
Richard Smithd62306a2011-11-10 06:34:14 +00006269 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006270 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006271 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6272 const Expr *Init =
6273 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006274 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006275 Info, Subobject, Init) ||
6276 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006277 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006278 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006279 return false;
6280 Success = false;
6281 }
Richard Smithd62306a2011-11-10 06:34:14 +00006282 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006283
Richard Smith9543c5e2013-04-22 14:44:29 +00006284 if (!Result.hasArrayFiller())
6285 return Success;
6286
6287 // If we get here, we have a trivial filler, which we can just evaluate
6288 // once and splat over the rest of the array elements.
6289 assert(FillerExpr && "no array filler for incomplete init list");
6290 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6291 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006292}
6293
Richard Smith410306b2016-12-12 02:53:20 +00006294bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6295 if (E->getCommonExpr() &&
6296 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6297 Info, E->getCommonExpr()->getSourceExpr()))
6298 return false;
6299
6300 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6301
6302 uint64_t Elements = CAT->getSize().getZExtValue();
6303 Result = APValue(APValue::UninitArray(), Elements, Elements);
6304
6305 LValue Subobject = This;
6306 Subobject.addArray(Info, E, CAT);
6307
6308 bool Success = true;
6309 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6310 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6311 Info, Subobject, E->getSubExpr()) ||
6312 !HandleLValueArrayAdjustment(Info, E, Subobject,
6313 CAT->getElementType(), 1)) {
6314 if (!Info.noteFailure())
6315 return false;
6316 Success = false;
6317 }
6318 }
6319
6320 return Success;
6321}
6322
Richard Smith027bf112011-11-17 22:56:20 +00006323bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006324 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6325}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006326
Richard Smith9543c5e2013-04-22 14:44:29 +00006327bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6328 const LValue &Subobject,
6329 APValue *Value,
6330 QualType Type) {
6331 bool HadZeroInit = !Value->isUninit();
6332
6333 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6334 unsigned N = CAT->getSize().getZExtValue();
6335
6336 // Preserve the array filler if we had prior zero-initialization.
6337 APValue Filler =
6338 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6339 : APValue();
6340
6341 *Value = APValue(APValue::UninitArray(), N, N);
6342
6343 if (HadZeroInit)
6344 for (unsigned I = 0; I != N; ++I)
6345 Value->getArrayInitializedElt(I) = Filler;
6346
6347 // Initialize the elements.
6348 LValue ArrayElt = Subobject;
6349 ArrayElt.addArray(Info, E, CAT);
6350 for (unsigned I = 0; I != N; ++I)
6351 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6352 CAT->getElementType()) ||
6353 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6354 CAT->getElementType(), 1))
6355 return false;
6356
6357 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006358 }
Richard Smith027bf112011-11-17 22:56:20 +00006359
Richard Smith9543c5e2013-04-22 14:44:29 +00006360 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006361 return Error(E);
6362
Richard Smithb8348f52016-05-12 22:16:28 +00006363 return RecordExprEvaluator(Info, Subobject, *Value)
6364 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006365}
6366
Richard Smithf3e9e432011-11-07 09:22:26 +00006367//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006368// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006369//
6370// As a GNU extension, we support casting pointers to sufficiently-wide integer
6371// types and back in constant folding. Integer values are thus represented
6372// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006373//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006374
6375namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006376class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006377 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006378 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006379public:
Richard Smith2e312c82012-03-03 22:46:17 +00006380 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006381 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006382
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006383 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006384 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006385 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006386 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006387 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006388 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006389 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006390 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006391 return true;
6392 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006393 bool Success(const llvm::APSInt &SI, const Expr *E) {
6394 return Success(SI, E, Result);
6395 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006396
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006397 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006398 assert(E->getType()->isIntegralOrEnumerationType() &&
6399 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006400 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006401 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006402 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006403 Result.getInt().setIsUnsigned(
6404 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006405 return true;
6406 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006407 bool Success(const llvm::APInt &I, const Expr *E) {
6408 return Success(I, E, Result);
6409 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006410
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006411 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006412 assert(E->getType()->isIntegralOrEnumerationType() &&
6413 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006414 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006415 return true;
6416 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006417 bool Success(uint64_t Value, const Expr *E) {
6418 return Success(Value, E, Result);
6419 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006420
Ken Dyckdbc01912011-03-11 02:13:43 +00006421 bool Success(CharUnits Size, const Expr *E) {
6422 return Success(Size.getQuantity(), E);
6423 }
6424
Richard Smith2e312c82012-03-03 22:46:17 +00006425 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006426 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006427 Result = V;
6428 return true;
6429 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006430 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006431 }
Mike Stump11289f42009-09-09 15:08:12 +00006432
Richard Smithfddd3842011-12-30 21:15:51 +00006433 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006434
Peter Collingbournee9200682011-05-13 03:29:01 +00006435 //===--------------------------------------------------------------------===//
6436 // Visitor Methods
6437 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006438
Chris Lattner7174bf32008-07-12 00:38:25 +00006439 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006440 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006441 }
6442 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006443 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006444 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006445
6446 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6447 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006448 if (CheckReferencedDecl(E, E->getDecl()))
6449 return true;
6450
6451 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006452 }
6453 bool VisitMemberExpr(const MemberExpr *E) {
6454 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006455 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006456 return true;
6457 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006458
6459 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006460 }
6461
Peter Collingbournee9200682011-05-13 03:29:01 +00006462 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006463 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00006464 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006465 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006466 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006467
Peter Collingbournee9200682011-05-13 03:29:01 +00006468 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006469 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006470
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006471 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006472 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006473 }
Mike Stump11289f42009-09-09 15:08:12 +00006474
Ted Kremeneke65b0862012-03-06 20:05:56 +00006475 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6476 return Success(E->getValue(), E);
6477 }
Richard Smith410306b2016-12-12 02:53:20 +00006478
6479 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6480 if (Info.ArrayInitIndex == uint64_t(-1)) {
6481 // We were asked to evaluate this subexpression independent of the
6482 // enclosing ArrayInitLoopExpr. We can't do that.
6483 Info.FFDiag(E);
6484 return false;
6485 }
6486 return Success(Info.ArrayInitIndex, E);
6487 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00006488
Richard Smith4ce706a2011-10-11 21:43:33 +00006489 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006490 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006491 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006492 }
6493
Douglas Gregor29c42f22012-02-24 07:38:34 +00006494 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6495 return Success(E->getValue(), E);
6496 }
6497
John Wiegley6242b6a2011-04-28 00:16:57 +00006498 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6499 return Success(E->getValue(), E);
6500 }
6501
John Wiegleyf9f65842011-04-25 06:54:41 +00006502 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6503 return Success(E->getValue(), E);
6504 }
6505
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006506 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006507 bool VisitUnaryImag(const UnaryOperator *E);
6508
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006509 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006510 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006511
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006512private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006513 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006514 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006515};
Chris Lattner05706e882008-07-11 18:11:29 +00006516} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006517
Richard Smith11562c52011-10-28 17:51:58 +00006518/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6519/// produce either the integer value or a pointer.
6520///
6521/// GCC has a heinous extension which folds casts between pointer types and
6522/// pointer-sized integral types. We support this by allowing the evaluation of
6523/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6524/// Some simple arithmetic on such values is supported (they are treated much
6525/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006526static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006527 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006528 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006529 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006530}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006531
Richard Smithf57d8cb2011-12-09 22:58:01 +00006532static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006533 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006534 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006535 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006536 if (!Val.isInt()) {
6537 // FIXME: It would be better to produce the diagnostic for casting
6538 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00006539 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006540 return false;
6541 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006542 Result = Val.getInt();
6543 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006544}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006545
Richard Smithf57d8cb2011-12-09 22:58:01 +00006546/// Check whether the given declaration can be directly converted to an integral
6547/// rvalue. If not, no diagnostic is produced; there are other things we can
6548/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006549bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006550 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006551 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006552 // Check for signedness/width mismatches between E type and ECD value.
6553 bool SameSign = (ECD->getInitVal().isSigned()
6554 == E->getType()->isSignedIntegerOrEnumerationType());
6555 bool SameWidth = (ECD->getInitVal().getBitWidth()
6556 == Info.Ctx.getIntWidth(E->getType()));
6557 if (SameSign && SameWidth)
6558 return Success(ECD->getInitVal(), E);
6559 else {
6560 // Get rid of mismatch (otherwise Success assertions will fail)
6561 // by computing a new value matching the type of E.
6562 llvm::APSInt Val = ECD->getInitVal();
6563 if (!SameSign)
6564 Val.setIsSigned(!ECD->getInitVal().isSigned());
6565 if (!SameWidth)
6566 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6567 return Success(Val, E);
6568 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006569 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006570 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006571}
6572
Chris Lattner86ee2862008-10-06 06:40:35 +00006573/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6574/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006575static int EvaluateBuiltinClassifyType(const CallExpr *E,
6576 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006577 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006578 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006579 enum gcc_type_class {
6580 no_type_class = -1,
6581 void_type_class, integer_type_class, char_type_class,
6582 enumeral_type_class, boolean_type_class,
6583 pointer_type_class, reference_type_class, offset_type_class,
6584 real_type_class, complex_type_class,
6585 function_type_class, method_type_class,
6586 record_type_class, union_type_class,
6587 array_type_class, string_type_class,
6588 lang_type_class
6589 };
Mike Stump11289f42009-09-09 15:08:12 +00006590
6591 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006592 // ideal, however it is what gcc does.
6593 if (E->getNumArgs() == 0)
6594 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006595
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006596 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6597 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6598
6599 switch (CanTy->getTypeClass()) {
6600#define TYPE(ID, BASE)
6601#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6602#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6603#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6604#include "clang/AST/TypeNodes.def"
6605 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6606
6607 case Type::Builtin:
6608 switch (BT->getKind()) {
6609#define BUILTIN_TYPE(ID, SINGLETON_ID)
6610#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6611#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6612#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6613#include "clang/AST/BuiltinTypes.def"
6614 case BuiltinType::Void:
6615 return void_type_class;
6616
6617 case BuiltinType::Bool:
6618 return boolean_type_class;
6619
6620 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6621 case BuiltinType::UChar:
6622 case BuiltinType::UShort:
6623 case BuiltinType::UInt:
6624 case BuiltinType::ULong:
6625 case BuiltinType::ULongLong:
6626 case BuiltinType::UInt128:
6627 return integer_type_class;
6628
6629 case BuiltinType::NullPtr:
6630 return pointer_type_class;
6631
6632 case BuiltinType::WChar_U:
6633 case BuiltinType::Char16:
6634 case BuiltinType::Char32:
6635 case BuiltinType::ObjCId:
6636 case BuiltinType::ObjCClass:
6637 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006638#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6639 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006640#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006641 case BuiltinType::OCLSampler:
6642 case BuiltinType::OCLEvent:
6643 case BuiltinType::OCLClkEvent:
6644 case BuiltinType::OCLQueue:
6645 case BuiltinType::OCLNDRange:
6646 case BuiltinType::OCLReserveID:
6647 case BuiltinType::Dependent:
6648 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6649 };
6650
6651 case Type::Enum:
6652 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6653 break;
6654
6655 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006656 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006657 break;
6658
6659 case Type::MemberPointer:
6660 if (CanTy->isMemberDataPointerType())
6661 return offset_type_class;
6662 else {
6663 // We expect member pointers to be either data or function pointers,
6664 // nothing else.
6665 assert(CanTy->isMemberFunctionPointerType());
6666 return method_type_class;
6667 }
6668
6669 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006670 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006671
6672 case Type::FunctionNoProto:
6673 case Type::FunctionProto:
6674 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6675
6676 case Type::Record:
6677 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6678 switch (RT->getDecl()->getTagKind()) {
6679 case TagTypeKind::TTK_Struct:
6680 case TagTypeKind::TTK_Class:
6681 case TagTypeKind::TTK_Interface:
6682 return record_type_class;
6683
6684 case TagTypeKind::TTK_Enum:
6685 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6686
6687 case TagTypeKind::TTK_Union:
6688 return union_type_class;
6689 }
6690 }
David Blaikie83d382b2011-09-23 05:06:16 +00006691 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006692
6693 case Type::ConstantArray:
6694 case Type::VariableArray:
6695 case Type::IncompleteArray:
6696 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6697
6698 case Type::BlockPointer:
6699 case Type::LValueReference:
6700 case Type::RValueReference:
6701 case Type::Vector:
6702 case Type::ExtVector:
6703 case Type::Auto:
6704 case Type::ObjCObject:
6705 case Type::ObjCInterface:
6706 case Type::ObjCObjectPointer:
6707 case Type::Pipe:
6708 case Type::Atomic:
6709 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6710 }
6711
6712 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006713}
6714
Richard Smith5fab0c92011-12-28 19:48:30 +00006715/// EvaluateBuiltinConstantPForLValue - Determine the result of
6716/// __builtin_constant_p when applied to the given lvalue.
6717///
6718/// An lvalue is only "constant" if it is a pointer or reference to the first
6719/// character of a string literal.
6720template<typename LValue>
6721static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006722 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006723 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6724}
6725
6726/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6727/// GCC as we can manage.
6728static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6729 QualType ArgType = Arg->getType();
6730
6731 // __builtin_constant_p always has one operand. The rules which gcc follows
6732 // are not precisely documented, but are as follows:
6733 //
6734 // - If the operand is of integral, floating, complex or enumeration type,
6735 // and can be folded to a known value of that type, it returns 1.
6736 // - If the operand and can be folded to a pointer to the first character
6737 // of a string literal (or such a pointer cast to an integral type), it
6738 // returns 1.
6739 //
6740 // Otherwise, it returns 0.
6741 //
6742 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6743 // its support for this does not currently work.
6744 if (ArgType->isIntegralOrEnumerationType()) {
6745 Expr::EvalResult Result;
6746 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6747 return false;
6748
6749 APValue &V = Result.Val;
6750 if (V.getKind() == APValue::Int)
6751 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006752 if (V.getKind() == APValue::LValue)
6753 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006754 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6755 return Arg->isEvaluatable(Ctx);
6756 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6757 LValue LV;
6758 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006759 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006760 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6761 : EvaluatePointer(Arg, LV, Info)) &&
6762 !Status.HasSideEffects)
6763 return EvaluateBuiltinConstantPForLValue(LV);
6764 }
6765
6766 // Anything else isn't considered to be sufficiently constant.
6767 return false;
6768}
6769
John McCall95007602010-05-10 23:27:23 +00006770/// Retrieves the "underlying object type" of the given expression,
6771/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006772static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006773 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6774 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006775 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006776 } else if (const Expr *E = B.get<const Expr*>()) {
6777 if (isa<CompoundLiteralExpr>(E))
6778 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006779 }
6780
6781 return QualType();
6782}
6783
George Burgess IV3a03fab2015-09-04 21:28:13 +00006784/// A more selective version of E->IgnoreParenCasts for
George Burgess IVb40cd562015-09-04 22:36:18 +00006785/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6786/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006787/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6788///
6789/// Always returns an RValue with a pointer representation.
6790static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6791 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6792
6793 auto *NoParens = E->IgnoreParens();
6794 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006795 if (Cast == nullptr)
6796 return NoParens;
6797
6798 // We only conservatively allow a few kinds of casts, because this code is
6799 // inherently a simple solution that seeks to support the common case.
6800 auto CastKind = Cast->getCastKind();
6801 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6802 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006803 return NoParens;
6804
6805 auto *SubExpr = Cast->getSubExpr();
6806 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6807 return NoParens;
6808 return ignorePointerCastsAndParens(SubExpr);
6809}
6810
George Burgess IVa51c4072015-10-16 01:49:01 +00006811/// Checks to see if the given LValue's Designator is at the end of the LValue's
6812/// record layout. e.g.
6813/// struct { struct { int a, b; } fst, snd; } obj;
6814/// obj.fst // no
6815/// obj.snd // yes
6816/// obj.fst.a // no
6817/// obj.fst.b // no
6818/// obj.snd.a // no
6819/// obj.snd.b // yes
6820///
6821/// Please note: this function is specialized for how __builtin_object_size
6822/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00006823///
6824/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00006825static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6826 assert(!LVal.Designator.Invalid);
6827
George Burgess IV4168d752016-06-27 19:40:41 +00006828 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
6829 const RecordDecl *Parent = FD->getParent();
6830 Invalid = Parent->isInvalidDecl();
6831 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00006832 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00006833 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00006834 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6835 };
6836
6837 auto &Base = LVal.getLValueBase();
6838 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6839 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006840 bool Invalid;
6841 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6842 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006843 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006844 for (auto *FD : IFD->chain()) {
6845 bool Invalid;
6846 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
6847 return Invalid;
6848 }
George Burgess IVa51c4072015-10-16 01:49:01 +00006849 }
6850 }
6851
6852 QualType BaseType = getType(Base);
6853 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6854 if (BaseType->isArrayType()) {
6855 // Because __builtin_object_size treats arrays as objects, we can ignore
6856 // the index iff this is the last array in the Designator.
6857 if (I + 1 == E)
6858 return true;
6859 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6860 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6861 if (Index + 1 != CAT->getSize())
6862 return false;
6863 BaseType = CAT->getElementType();
6864 } else if (BaseType->isAnyComplexType()) {
6865 auto *CT = BaseType->castAs<ComplexType>();
6866 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6867 if (Index != 1)
6868 return false;
6869 BaseType = CT->getElementType();
6870 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
George Burgess IV4168d752016-06-27 19:40:41 +00006871 bool Invalid;
6872 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6873 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006874 BaseType = FD->getType();
6875 } else {
6876 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6877 "Expecting cast to a base class");
6878 return false;
6879 }
6880 }
6881 return true;
6882}
6883
6884/// Tests to see if the LValue has a designator (that isn't necessarily valid).
6885static bool refersToCompleteObject(const LValue &LVal) {
6886 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6887 return false;
6888
6889 if (!LVal.InvalidBase)
6890 return true;
6891
6892 auto *E = LVal.Base.dyn_cast<const Expr *>();
6893 (void)E;
6894 assert(E != nullptr && isa<MemberExpr>(E));
6895 return false;
6896}
6897
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006898/// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6899/// true and stores the result in @p Size.
6900///
6901/// If @p WasError is non-null, this will report whether the failure to evaluate
6902/// is to be treated as an Error in IntExprEvaluator.
6903static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6904 EvalInfo &Info, uint64_t &Size,
6905 bool *WasError = nullptr) {
6906 if (WasError != nullptr)
6907 *WasError = false;
6908
6909 auto Error = [&](const Expr *E) {
6910 if (WasError != nullptr)
6911 *WasError = true;
6912 return false;
6913 };
6914
6915 auto Success = [&](uint64_t S, const Expr *E) {
6916 Size = S;
6917 return true;
6918 };
6919
George Burgess IVbdb5b262015-08-19 02:19:07 +00006920 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006921 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006922 {
6923 // The operand of __builtin_object_size is never evaluated for side-effects.
6924 // If there are any, but we can determine the pointed-to object anyway, then
6925 // ignore the side-effects.
6926 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006927 FoldOffsetRAII Fold(Info, Type & 1);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006928
6929 if (E->isGLValue()) {
6930 // It's possible for us to be given GLValues if we're called via
6931 // Expr::tryEvaluateObjectSize.
6932 APValue RVal;
6933 if (!EvaluateAsRValue(Info, E, RVal))
6934 return false;
6935 Base.setFrom(Info.Ctx, RVal);
6936 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006937 return false;
6938 }
John McCall95007602010-05-10 23:27:23 +00006939
George Burgess IVbdb5b262015-08-19 02:19:07 +00006940 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006941 // If we point to before the start of the object, there are no accessible
6942 // bytes.
6943 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006944 return Success(0, E);
6945
George Burgess IV3a03fab2015-09-04 21:28:13 +00006946 // In the case where we're not dealing with a subobject, we discard the
6947 // subobject bit.
George Burgess IVa51c4072015-10-16 01:49:01 +00006948 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006949
6950 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6951 // exist. If we can't verify the base, then we can't do that.
6952 //
6953 // As a special case, we produce a valid object size for an unknown object
6954 // with a known designator if Type & 1 is 1. For instance:
6955 //
6956 // extern struct X { char buff[32]; int a, b, c; } *p;
6957 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6958 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6959 //
6960 // This matches GCC's behavior.
George Burgess IVa51c4072015-10-16 01:49:01 +00006961 if (Base.InvalidBase && !SubobjectOnly)
Nico Weber19999b42015-08-18 20:32:55 +00006962 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006963
George Burgess IVa51c4072015-10-16 01:49:01 +00006964 // If we're not examining only the subobject, then we reset to a complete
6965 // object designator
George Burgess IVbdb5b262015-08-19 02:19:07 +00006966 //
6967 // If Type is 1 and we've lost track of the subobject, just find the complete
6968 // object instead. (If Type is 3, that's not correct behavior and we should
6969 // return 0 instead.)
6970 LValue End = Base;
George Burgess IVa51c4072015-10-16 01:49:01 +00006971 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006972 QualType T = getObjectType(End.getLValueBase());
6973 if (T.isNull())
6974 End.Designator.setInvalid();
6975 else {
6976 End.Designator = SubobjectDesignator(T);
6977 End.Offset = CharUnits::Zero();
6978 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006979 }
John McCall95007602010-05-10 23:27:23 +00006980
George Burgess IVbdb5b262015-08-19 02:19:07 +00006981 // If it is not possible to determine which objects ptr points to at compile
6982 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6983 // and (size_t) 0 for type 2 or 3.
6984 if (End.Designator.Invalid)
6985 return false;
6986
6987 // According to the GCC documentation, we want the size of the subobject
6988 // denoted by the pointer. But that's not quite right -- what we actually
6989 // want is the size of the immediately-enclosing array, if there is one.
6990 int64_t AmountToAdd = 1;
George Burgess IVa51c4072015-10-16 01:49:01 +00006991 if (End.Designator.MostDerivedIsArrayElement &&
George Burgess IVbdb5b262015-08-19 02:19:07 +00006992 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6993 // We got a pointer to an array. Step to its end.
6994 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006995 End.Designator.Entries.back().ArrayIndex;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006996 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006997 // We're already pointing at the end of the object.
6998 AmountToAdd = 0;
6999 }
7000
George Burgess IV3a03fab2015-09-04 21:28:13 +00007001 QualType PointeeType = End.Designator.MostDerivedType;
7002 assert(!PointeeType.isNull());
7003 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007004 return Error(E);
John McCall95007602010-05-10 23:27:23 +00007005
George Burgess IVbdb5b262015-08-19 02:19:07 +00007006 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
7007 AmountToAdd))
7008 return false;
John McCall95007602010-05-10 23:27:23 +00007009
George Burgess IVbdb5b262015-08-19 02:19:07 +00007010 auto EndOffset = End.getLValueOffset();
George Burgess IVa51c4072015-10-16 01:49:01 +00007011
7012 // The following is a moderately common idiom in C:
7013 //
7014 // struct Foo { int a; char c[1]; };
7015 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7016 // strcpy(&F->c[0], Bar);
7017 //
George Burgess IVf8f63242016-09-12 23:50:35 +00007018 // So, if we see that we're examining an array at the end of a struct with an
7019 // unknown base, we give up instead of breaking code that behaves this way.
7020 // Note that we only do this when Type=1, because Type=3 is a lower bound, so
7021 // answering conservatively is fine.
7022 //
7023 // We used to be a bit more aggressive here; we'd only be conservative if the
7024 // array at the end was flexible, or if it had 0 or 1 elements. This broke
7025 // some common standard library extensions (PR30346), but was otherwise
7026 // seemingly fine. It may be useful to reintroduce this behavior with some
7027 // sort of whitelist. OTOH, it seems that GCC is always conservative with the
7028 // last element in structs (if it's an array), so our current behavior is more
7029 // compatible than a whitelisting approach would be.
George Burgess IVa51c4072015-10-16 01:49:01 +00007030 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
7031 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
7032 End.Designator.MostDerivedIsArrayElement &&
George Burgess IVa51c4072015-10-16 01:49:01 +00007033 isDesignatorAtObjectEnd(Info.Ctx, End))
7034 return false;
7035
George Burgess IVbdb5b262015-08-19 02:19:07 +00007036 if (BaseOffset > EndOffset)
7037 return Success(0, E);
7038
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007039 return Success((EndOffset - BaseOffset).getQuantity(), E);
7040}
7041
7042bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
7043 unsigned Type) {
7044 uint64_t Size;
7045 bool WasError;
7046 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
7047 return Success(Size, E);
7048 if (WasError)
7049 return Error(E);
7050 return false;
John McCall95007602010-05-10 23:27:23 +00007051}
7052
Peter Collingbournee9200682011-05-13 03:29:01 +00007053bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007054 if (unsigned BuiltinOp = E->getBuiltinCallee())
7055 return VisitBuiltinCallExpr(E, BuiltinOp);
7056
7057 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7058}
7059
7060bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7061 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007062 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007063 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007064 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007065
7066 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007067 // The type was checked when we built the expression.
7068 unsigned Type =
7069 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7070 assert(Type <= 3 && "unexpected type");
7071
7072 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00007073 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00007074
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007075 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007076 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007077
Richard Smith01ade172012-05-23 04:13:20 +00007078 // Expression had no side effects, but we couldn't statically determine the
7079 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007080 switch (Info.EvalMode) {
7081 case EvalInfo::EM_ConstantExpression:
7082 case EvalInfo::EM_PotentialConstantExpression:
7083 case EvalInfo::EM_ConstantFold:
7084 case EvalInfo::EM_EvaluateForOverflow:
7085 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00007086 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007087 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007088 return Error(E);
7089 case EvalInfo::EM_ConstantExpressionUnevaluated:
7090 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007091 // Reduce it to a constant now.
7092 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007093 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007094
7095 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007096 }
7097
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007098 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007099 case Builtin::BI__builtin_bswap32:
7100 case Builtin::BI__builtin_bswap64: {
7101 APSInt Val;
7102 if (!EvaluateInteger(E->getArg(0), Val, Info))
7103 return false;
7104
7105 return Success(Val.byteSwap(), E);
7106 }
7107
Richard Smith8889a3d2013-06-13 06:26:32 +00007108 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007109 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007110
7111 // FIXME: BI__builtin_clrsb
7112 // FIXME: BI__builtin_clrsbl
7113 // FIXME: BI__builtin_clrsbll
7114
Richard Smith80b3c8e2013-06-13 05:04:16 +00007115 case Builtin::BI__builtin_clz:
7116 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007117 case Builtin::BI__builtin_clzll:
7118 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007119 APSInt Val;
7120 if (!EvaluateInteger(E->getArg(0), Val, Info))
7121 return false;
7122 if (!Val)
7123 return Error(E);
7124
7125 return Success(Val.countLeadingZeros(), E);
7126 }
7127
Richard Smith8889a3d2013-06-13 06:26:32 +00007128 case Builtin::BI__builtin_constant_p:
7129 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7130
Richard Smith80b3c8e2013-06-13 05:04:16 +00007131 case Builtin::BI__builtin_ctz:
7132 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007133 case Builtin::BI__builtin_ctzll:
7134 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007135 APSInt Val;
7136 if (!EvaluateInteger(E->getArg(0), Val, Info))
7137 return false;
7138 if (!Val)
7139 return Error(E);
7140
7141 return Success(Val.countTrailingZeros(), E);
7142 }
7143
Richard Smith8889a3d2013-06-13 06:26:32 +00007144 case Builtin::BI__builtin_eh_return_data_regno: {
7145 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7146 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7147 return Success(Operand, E);
7148 }
7149
7150 case Builtin::BI__builtin_expect:
7151 return Visit(E->getArg(0));
7152
7153 case Builtin::BI__builtin_ffs:
7154 case Builtin::BI__builtin_ffsl:
7155 case Builtin::BI__builtin_ffsll: {
7156 APSInt Val;
7157 if (!EvaluateInteger(E->getArg(0), Val, Info))
7158 return false;
7159
7160 unsigned N = Val.countTrailingZeros();
7161 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7162 }
7163
7164 case Builtin::BI__builtin_fpclassify: {
7165 APFloat Val(0.0);
7166 if (!EvaluateFloat(E->getArg(5), Val, Info))
7167 return false;
7168 unsigned Arg;
7169 switch (Val.getCategory()) {
7170 case APFloat::fcNaN: Arg = 0; break;
7171 case APFloat::fcInfinity: Arg = 1; break;
7172 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7173 case APFloat::fcZero: Arg = 4; break;
7174 }
7175 return Visit(E->getArg(Arg));
7176 }
7177
7178 case Builtin::BI__builtin_isinf_sign: {
7179 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007180 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007181 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7182 }
7183
Richard Smithea3019d2013-10-15 19:07:14 +00007184 case Builtin::BI__builtin_isinf: {
7185 APFloat Val(0.0);
7186 return EvaluateFloat(E->getArg(0), Val, Info) &&
7187 Success(Val.isInfinity() ? 1 : 0, E);
7188 }
7189
7190 case Builtin::BI__builtin_isfinite: {
7191 APFloat Val(0.0);
7192 return EvaluateFloat(E->getArg(0), Val, Info) &&
7193 Success(Val.isFinite() ? 1 : 0, E);
7194 }
7195
7196 case Builtin::BI__builtin_isnan: {
7197 APFloat Val(0.0);
7198 return EvaluateFloat(E->getArg(0), Val, Info) &&
7199 Success(Val.isNaN() ? 1 : 0, E);
7200 }
7201
7202 case Builtin::BI__builtin_isnormal: {
7203 APFloat Val(0.0);
7204 return EvaluateFloat(E->getArg(0), Val, Info) &&
7205 Success(Val.isNormal() ? 1 : 0, E);
7206 }
7207
Richard Smith8889a3d2013-06-13 06:26:32 +00007208 case Builtin::BI__builtin_parity:
7209 case Builtin::BI__builtin_parityl:
7210 case Builtin::BI__builtin_parityll: {
7211 APSInt Val;
7212 if (!EvaluateInteger(E->getArg(0), Val, Info))
7213 return false;
7214
7215 return Success(Val.countPopulation() % 2, E);
7216 }
7217
Richard Smith80b3c8e2013-06-13 05:04:16 +00007218 case Builtin::BI__builtin_popcount:
7219 case Builtin::BI__builtin_popcountl:
7220 case Builtin::BI__builtin_popcountll: {
7221 APSInt Val;
7222 if (!EvaluateInteger(E->getArg(0), Val, Info))
7223 return false;
7224
7225 return Success(Val.countPopulation(), E);
7226 }
7227
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007228 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007229 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007230 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007231 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007232 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007233 << /*isConstexpr*/0 << /*isConstructor*/0
7234 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007235 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007236 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007237 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007238 case Builtin::BI__builtin_strlen:
7239 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007240 // As an extension, we support __builtin_strlen() as a constant expression,
7241 // and support folding strlen() to a constant.
7242 LValue String;
7243 if (!EvaluatePointer(E->getArg(0), String, Info))
7244 return false;
7245
Richard Smith8110c9d2016-11-29 19:45:17 +00007246 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7247
Richard Smithe6c19f22013-11-15 02:10:04 +00007248 // Fast path: if it's a string literal, search the string value.
7249 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7250 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007251 // The string literal may have embedded null characters. Find the first
7252 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007253 StringRef Str = S->getBytes();
7254 int64_t Off = String.Offset.getQuantity();
7255 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007256 S->getCharByteWidth() == 1 &&
7257 // FIXME: Add fast-path for wchar_t too.
7258 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007259 Str = Str.substr(Off);
7260
7261 StringRef::size_type Pos = Str.find(0);
7262 if (Pos != StringRef::npos)
7263 Str = Str.substr(0, Pos);
7264
7265 return Success(Str.size(), E);
7266 }
7267
7268 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007269 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007270
7271 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007272 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7273 APValue Char;
7274 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7275 !Char.isInt())
7276 return false;
7277 if (!Char.getInt())
7278 return Success(Strlen, E);
7279 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7280 return false;
7281 }
7282 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007283
Richard Smithe151bab2016-11-11 23:43:35 +00007284 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007285 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007286 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007287 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007288 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007289 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007290 // A call to strlen is not a constant expression.
7291 if (Info.getLangOpts().CPlusPlus11)
7292 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7293 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007294 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007295 else
7296 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7297 // Fall through.
7298 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007299 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007300 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007301 case Builtin::BI__builtin_wcsncmp:
7302 case Builtin::BI__builtin_memcmp:
7303 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007304 LValue String1, String2;
7305 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7306 !EvaluatePointer(E->getArg(1), String2, Info))
7307 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007308
7309 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7310
Richard Smithe151bab2016-11-11 23:43:35 +00007311 uint64_t MaxLength = uint64_t(-1);
7312 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007313 BuiltinOp != Builtin::BIwcscmp &&
7314 BuiltinOp != Builtin::BI__builtin_strcmp &&
7315 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007316 APSInt N;
7317 if (!EvaluateInteger(E->getArg(2), N, Info))
7318 return false;
7319 MaxLength = N.getExtValue();
7320 }
7321 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007322 BuiltinOp != Builtin::BIwmemcmp &&
7323 BuiltinOp != Builtin::BI__builtin_memcmp &&
7324 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007325 for (; MaxLength; --MaxLength) {
7326 APValue Char1, Char2;
7327 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7328 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7329 !Char1.isInt() || !Char2.isInt())
7330 return false;
7331 if (Char1.getInt() != Char2.getInt())
7332 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7333 if (StopAtNull && !Char1.getInt())
7334 return Success(0, E);
7335 assert(!(StopAtNull && !Char2.getInt()));
7336 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7337 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7338 return false;
7339 }
7340 // We hit the strncmp / memcmp limit.
7341 return Success(0, E);
7342 }
7343
Richard Smith01ba47d2012-04-13 00:45:38 +00007344 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007345 case Builtin::BI__atomic_is_lock_free:
7346 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007347 APSInt SizeVal;
7348 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7349 return false;
7350
7351 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7352 // of two less than the maximum inline atomic width, we know it is
7353 // lock-free. If the size isn't a power of two, or greater than the
7354 // maximum alignment where we promote atomics, we know it is not lock-free
7355 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7356 // the answer can only be determined at runtime; for example, 16-byte
7357 // atomics have lock-free implementations on some, but not all,
7358 // x86-64 processors.
7359
7360 // Check power-of-two.
7361 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007362 if (Size.isPowerOfTwo()) {
7363 // Check against inlining width.
7364 unsigned InlineWidthBits =
7365 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7366 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7367 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7368 Size == CharUnits::One() ||
7369 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7370 Expr::NPC_NeverValueDependent))
7371 // OK, we will inline appropriately-aligned operations of this size,
7372 // and _Atomic(T) is appropriately-aligned.
7373 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007374
Richard Smith01ba47d2012-04-13 00:45:38 +00007375 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7376 castAs<PointerType>()->getPointeeType();
7377 if (!PointeeType->isIncompleteType() &&
7378 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7379 // OK, we will inline operations on this object.
7380 return Success(1, E);
7381 }
7382 }
7383 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007384
Richard Smith01ba47d2012-04-13 00:45:38 +00007385 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7386 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007387 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007388 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007389}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007390
Richard Smith8b3497e2011-10-31 01:37:14 +00007391static bool HasSameBase(const LValue &A, const LValue &B) {
7392 if (!A.getLValueBase())
7393 return !B.getLValueBase();
7394 if (!B.getLValueBase())
7395 return false;
7396
Richard Smithce40ad62011-11-12 22:28:03 +00007397 if (A.getLValueBase().getOpaqueValue() !=
7398 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007399 const Decl *ADecl = GetLValueBaseDecl(A);
7400 if (!ADecl)
7401 return false;
7402 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007403 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007404 return false;
7405 }
7406
7407 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007408 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007409}
7410
Richard Smithd20f1e62014-10-21 23:01:04 +00007411/// \brief Determine whether this is a pointer past the end of the complete
7412/// object referred to by the lvalue.
7413static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7414 const LValue &LV) {
7415 // A null pointer can be viewed as being "past the end" but we don't
7416 // choose to look at it that way here.
7417 if (!LV.getLValueBase())
7418 return false;
7419
7420 // If the designator is valid and refers to a subobject, we're not pointing
7421 // past the end.
7422 if (!LV.getLValueDesignator().Invalid &&
7423 !LV.getLValueDesignator().isOnePastTheEnd())
7424 return false;
7425
David Majnemerc378ca52015-08-29 08:32:55 +00007426 // A pointer to an incomplete type might be past-the-end if the type's size is
7427 // zero. We cannot tell because the type is incomplete.
7428 QualType Ty = getType(LV.getLValueBase());
7429 if (Ty->isIncompleteType())
7430 return true;
7431
Richard Smithd20f1e62014-10-21 23:01:04 +00007432 // We're a past-the-end pointer if we point to the byte after the object,
7433 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007434 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007435 return LV.getLValueOffset() == Size;
7436}
7437
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007438namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007439
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007440/// \brief Data recursive integer evaluator of certain binary operators.
7441///
7442/// We use a data recursive algorithm for binary operators so that we are able
7443/// to handle extreme cases of chained binary operators without causing stack
7444/// overflow.
7445class DataRecursiveIntBinOpEvaluator {
7446 struct EvalResult {
7447 APValue Val;
7448 bool Failed;
7449
7450 EvalResult() : Failed(false) { }
7451
7452 void swap(EvalResult &RHS) {
7453 Val.swap(RHS.Val);
7454 Failed = RHS.Failed;
7455 RHS.Failed = false;
7456 }
7457 };
7458
7459 struct Job {
7460 const Expr *E;
7461 EvalResult LHSResult; // meaningful only for binary operator expression.
7462 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007463
David Blaikie73726062015-08-12 23:09:24 +00007464 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00007465 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00007466
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007467 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007468 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007469 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007470
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007471 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007472 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007473 };
7474
7475 SmallVector<Job, 16> Queue;
7476
7477 IntExprEvaluator &IntEval;
7478 EvalInfo &Info;
7479 APValue &FinalResult;
7480
7481public:
7482 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7483 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7484
7485 /// \brief True if \param E is a binary operator that we are going to handle
7486 /// data recursively.
7487 /// We handle binary operators that are comma, logical, or that have operands
7488 /// with integral or enumeration type.
7489 static bool shouldEnqueue(const BinaryOperator *E) {
7490 return E->getOpcode() == BO_Comma ||
7491 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007492 (E->isRValue() &&
7493 E->getType()->isIntegralOrEnumerationType() &&
7494 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007495 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007496 }
7497
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007498 bool Traverse(const BinaryOperator *E) {
7499 enqueue(E);
7500 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007501 while (!Queue.empty())
7502 process(PrevResult);
7503
7504 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007505
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007506 FinalResult.swap(PrevResult.Val);
7507 return true;
7508 }
7509
7510private:
7511 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7512 return IntEval.Success(Value, E, Result);
7513 }
7514 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7515 return IntEval.Success(Value, E, Result);
7516 }
7517 bool Error(const Expr *E) {
7518 return IntEval.Error(E);
7519 }
7520 bool Error(const Expr *E, diag::kind D) {
7521 return IntEval.Error(E, D);
7522 }
7523
7524 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7525 return Info.CCEDiag(E, D);
7526 }
7527
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007528 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7529 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007530 bool &SuppressRHSDiags);
7531
7532 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7533 const BinaryOperator *E, APValue &Result);
7534
7535 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7536 Result.Failed = !Evaluate(Result.Val, Info, E);
7537 if (Result.Failed)
7538 Result.Val = APValue();
7539 }
7540
Richard Trieuba4d0872012-03-21 23:30:30 +00007541 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007542
7543 void enqueue(const Expr *E) {
7544 E = E->IgnoreParens();
7545 Queue.resize(Queue.size()+1);
7546 Queue.back().E = E;
7547 Queue.back().Kind = Job::AnyExprKind;
7548 }
7549};
7550
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007551}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007552
7553bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007554 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007555 bool &SuppressRHSDiags) {
7556 if (E->getOpcode() == BO_Comma) {
7557 // Ignore LHS but note if we could not evaluate it.
7558 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007559 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007560 return true;
7561 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007562
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007563 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007564 bool LHSAsBool;
7565 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007566 // We were able to evaluate the LHS, see if we can get away with not
7567 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007568 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7569 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007570 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007571 }
7572 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007573 LHSResult.Failed = true;
7574
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007575 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007576 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007577 if (!Info.noteSideEffect())
7578 return false;
7579
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007580 // We can't evaluate the LHS; however, sometimes the result
7581 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7582 // Don't ignore RHS and suppress diagnostics from this arm.
7583 SuppressRHSDiags = true;
7584 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007585
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007586 return true;
7587 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007588
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007589 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7590 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007591
George Burgess IVa145e252016-05-25 22:38:36 +00007592 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007593 return false; // Ignore RHS;
7594
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007595 return true;
7596}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007597
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007598bool DataRecursiveIntBinOpEvaluator::
7599 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7600 const BinaryOperator *E, APValue &Result) {
7601 if (E->getOpcode() == BO_Comma) {
7602 if (RHSResult.Failed)
7603 return false;
7604 Result = RHSResult.Val;
7605 return true;
7606 }
7607
7608 if (E->isLogicalOp()) {
7609 bool lhsResult, rhsResult;
7610 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7611 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7612
7613 if (LHSIsOK) {
7614 if (RHSIsOK) {
7615 if (E->getOpcode() == BO_LOr)
7616 return Success(lhsResult || rhsResult, E, Result);
7617 else
7618 return Success(lhsResult && rhsResult, E, Result);
7619 }
7620 } else {
7621 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007622 // We can't evaluate the LHS; however, sometimes the result
7623 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7624 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007625 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007626 }
7627 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007628
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007629 return false;
7630 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007631
7632 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7633 E->getRHS()->getType()->isIntegralOrEnumerationType());
7634
7635 if (LHSResult.Failed || RHSResult.Failed)
7636 return false;
7637
7638 const APValue &LHSVal = LHSResult.Val;
7639 const APValue &RHSVal = RHSResult.Val;
7640
7641 // Handle cases like (unsigned long)&a + 4.
7642 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7643 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007644 CharUnits AdditionalOffset =
7645 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007646 if (E->getOpcode() == BO_Add)
7647 Result.getLValueOffset() += AdditionalOffset;
7648 else
7649 Result.getLValueOffset() -= AdditionalOffset;
7650 return true;
7651 }
7652
7653 // Handle cases like 4 + (unsigned long)&a
7654 if (E->getOpcode() == BO_Add &&
7655 RHSVal.isLValue() && LHSVal.isInt()) {
7656 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007657 Result.getLValueOffset() +=
7658 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007659 return true;
7660 }
7661
7662 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7663 // Handle (intptr_t)&&A - (intptr_t)&&B.
7664 if (!LHSVal.getLValueOffset().isZero() ||
7665 !RHSVal.getLValueOffset().isZero())
7666 return false;
7667 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7668 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7669 if (!LHSExpr || !RHSExpr)
7670 return false;
7671 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7672 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7673 if (!LHSAddrExpr || !RHSAddrExpr)
7674 return false;
7675 // Make sure both labels come from the same function.
7676 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7677 RHSAddrExpr->getLabel()->getDeclContext())
7678 return false;
7679 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7680 return true;
7681 }
Richard Smith43e77732013-05-07 04:50:00 +00007682
7683 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007684 if (!LHSVal.isInt() || !RHSVal.isInt())
7685 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007686
7687 // Set up the width and signedness manually, in case it can't be deduced
7688 // from the operation we're performing.
7689 // FIXME: Don't do this in the cases where we can deduce it.
7690 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7691 E->getType()->isUnsignedIntegerOrEnumerationType());
7692 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7693 RHSVal.getInt(), Value))
7694 return false;
7695 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007696}
7697
Richard Trieuba4d0872012-03-21 23:30:30 +00007698void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007699 Job &job = Queue.back();
7700
7701 switch (job.Kind) {
7702 case Job::AnyExprKind: {
7703 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7704 if (shouldEnqueue(Bop)) {
7705 job.Kind = Job::BinOpKind;
7706 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007707 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007708 }
7709 }
7710
7711 EvaluateExpr(job.E, Result);
7712 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007713 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007714 }
7715
7716 case Job::BinOpKind: {
7717 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007718 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007719 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007720 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007721 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007722 }
7723 if (SuppressRHSDiags)
7724 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007725 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007726 job.Kind = Job::BinOpVisitedLHSKind;
7727 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007728 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007729 }
7730
7731 case Job::BinOpVisitedLHSKind: {
7732 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7733 EvalResult RHS;
7734 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007735 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007736 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007737 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007738 }
7739 }
7740
7741 llvm_unreachable("Invalid Job::Kind!");
7742}
7743
George Burgess IV8c892b52016-05-25 22:31:54 +00007744namespace {
7745/// Used when we determine that we should fail, but can keep evaluating prior to
7746/// noting that we had a failure.
7747class DelayedNoteFailureRAII {
7748 EvalInfo &Info;
7749 bool NoteFailure;
7750
7751public:
7752 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
7753 : Info(Info), NoteFailure(NoteFailure) {}
7754 ~DelayedNoteFailureRAII() {
7755 if (NoteFailure) {
7756 bool ContinueAfterFailure = Info.noteFailure();
7757 (void)ContinueAfterFailure;
7758 assert(ContinueAfterFailure &&
7759 "Shouldn't have kept evaluating on failure.");
7760 }
7761 }
7762};
7763}
7764
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007765bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007766 // We don't call noteFailure immediately because the assignment happens after
7767 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00007768 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007769 return Error(E);
7770
George Burgess IV8c892b52016-05-25 22:31:54 +00007771 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007772 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7773 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007774
Anders Carlssonacc79812008-11-16 07:17:21 +00007775 QualType LHSTy = E->getLHS()->getType();
7776 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007777
Chandler Carruthb29a7432014-10-11 11:03:30 +00007778 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007779 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007780 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007781 if (E->isAssignmentOp()) {
7782 LValue LV;
7783 EvaluateLValue(E->getLHS(), LV, Info);
7784 LHSOK = false;
7785 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007786 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7787 if (LHSOK) {
7788 LHS.makeComplexFloat();
7789 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7790 }
7791 } else {
7792 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7793 }
George Burgess IVa145e252016-05-25 22:38:36 +00007794 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007795 return false;
7796
Chandler Carruthb29a7432014-10-11 11:03:30 +00007797 if (E->getRHS()->getType()->isRealFloatingType()) {
7798 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7799 return false;
7800 RHS.makeComplexFloat();
7801 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7802 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007803 return false;
7804
7805 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007806 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007807 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007808 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007809 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7810
John McCalle3027922010-08-25 11:45:40 +00007811 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007812 return Success((CR_r == APFloat::cmpEqual &&
7813 CR_i == APFloat::cmpEqual), E);
7814 else {
John McCalle3027922010-08-25 11:45:40 +00007815 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007816 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007817 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007818 CR_r == APFloat::cmpLessThan ||
7819 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007820 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007821 CR_i == APFloat::cmpLessThan ||
7822 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007823 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007824 } else {
John McCalle3027922010-08-25 11:45:40 +00007825 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007826 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7827 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7828 else {
John McCalle3027922010-08-25 11:45:40 +00007829 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007830 "Invalid compex comparison.");
7831 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7832 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7833 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007834 }
7835 }
Mike Stump11289f42009-09-09 15:08:12 +00007836
Anders Carlssonacc79812008-11-16 07:17:21 +00007837 if (LHSTy->isRealFloatingType() &&
7838 RHSTy->isRealFloatingType()) {
7839 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007840
Richard Smith253c2a32012-01-27 01:14:48 +00007841 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007842 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007843 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007844
Richard Smith253c2a32012-01-27 01:14:48 +00007845 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007846 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007847
Anders Carlssonacc79812008-11-16 07:17:21 +00007848 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007849
Anders Carlssonacc79812008-11-16 07:17:21 +00007850 switch (E->getOpcode()) {
7851 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007852 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007853 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007854 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007855 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007856 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007857 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007858 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007859 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007860 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007861 E);
John McCalle3027922010-08-25 11:45:40 +00007862 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007863 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007864 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007865 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007866 || CR == APFloat::cmpLessThan
7867 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007868 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007869 }
Mike Stump11289f42009-09-09 15:08:12 +00007870
Eli Friedmana38da572009-04-28 19:17:36 +00007871 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007872 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007873 LValue LHSValue, RHSValue;
7874
7875 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007876 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007877 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007878
Richard Smith253c2a32012-01-27 01:14:48 +00007879 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007880 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007881
Richard Smith8b3497e2011-10-31 01:37:14 +00007882 // Reject differing bases from the normal codepath; we special-case
7883 // comparisons to null.
7884 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007885 if (E->getOpcode() == BO_Sub) {
7886 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007887 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00007888 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007889 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007890 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007891 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007892 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007893 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7894 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7895 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007896 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007897 // Make sure both labels come from the same function.
7898 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7899 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00007900 return Error(E);
7901 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007902 }
Richard Smith83c68212011-10-31 05:11:32 +00007903 // Inequalities and subtractions between unrelated pointers have
7904 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007905 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007906 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007907 // A constant address may compare equal to the address of a symbol.
7908 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007909 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007910 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7911 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007912 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007913 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007914 // distinct addresses. In clang, the result of such a comparison is
7915 // unspecified, so it is not a constant expression. However, we do know
7916 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007917 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7918 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007919 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007920 // We can't tell whether weak symbols will end up pointing to the same
7921 // object.
7922 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007923 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007924 // We can't compare the address of the start of one object with the
7925 // past-the-end address of another object, per C++ DR1652.
7926 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7927 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7928 (RHSValue.Base && RHSValue.Offset.isZero() &&
7929 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7930 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007931 // We can't tell whether an object is at the same address as another
7932 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007933 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7934 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007935 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007936 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007937 // (Note that clang defaults to -fmerge-all-constants, which can
7938 // lead to inconsistent results for comparisons involving the address
7939 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007940 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007941 }
Eli Friedman64004332009-03-23 04:38:34 +00007942
Richard Smith1b470412012-02-01 08:10:20 +00007943 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7944 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7945
Richard Smith84f6dcf2012-02-02 01:16:57 +00007946 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7947 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7948
John McCalle3027922010-08-25 11:45:40 +00007949 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007950 // C++11 [expr.add]p6:
7951 // Unless both pointers point to elements of the same array object, or
7952 // one past the last element of the array object, the behavior is
7953 // undefined.
7954 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7955 !AreElementsOfSameArray(getType(LHSValue.Base),
7956 LHSDesignator, RHSDesignator))
7957 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7958
Chris Lattner882bdf22010-04-20 17:13:14 +00007959 QualType Type = E->getLHS()->getType();
7960 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007961
Richard Smithd62306a2011-11-10 06:34:14 +00007962 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007963 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007964 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007965
Richard Smith84c6b3d2013-09-10 21:34:14 +00007966 // As an extension, a type may have zero size (empty struct or union in
7967 // C, array of zero length). Pointer subtraction in such cases has
7968 // undefined behavior, so is not constant.
7969 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00007970 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00007971 << ElementType;
7972 return false;
7973 }
7974
Richard Smith1b470412012-02-01 08:10:20 +00007975 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7976 // and produce incorrect results when it overflows. Such behavior
7977 // appears to be non-conforming, but is common, so perhaps we should
7978 // assume the standard intended for such cases to be undefined behavior
7979 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007980
Richard Smith1b470412012-02-01 08:10:20 +00007981 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7982 // overflow in the final conversion to ptrdiff_t.
7983 APSInt LHS(
7984 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7985 APSInt RHS(
7986 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7987 APSInt ElemSize(
7988 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7989 APSInt TrueResult = (LHS - RHS) / ElemSize;
7990 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7991
Richard Smith0c6124b2015-12-03 01:36:22 +00007992 if (Result.extend(65) != TrueResult &&
7993 !HandleOverflow(Info, E, TrueResult, E->getType()))
7994 return false;
Richard Smith1b470412012-02-01 08:10:20 +00007995 return Success(Result, E);
7996 }
Richard Smithde21b242012-01-31 06:41:30 +00007997
7998 // C++11 [expr.rel]p3:
7999 // Pointers to void (after pointer conversions) can be compared, with a
8000 // result defined as follows: If both pointers represent the same
8001 // address or are both the null pointer value, the result is true if the
8002 // operator is <= or >= and false otherwise; otherwise the result is
8003 // unspecified.
8004 // We interpret this as applying to pointers to *cv* void.
8005 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008006 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008007 CCEDiag(E, diag::note_constexpr_void_comparison);
8008
Richard Smith84f6dcf2012-02-02 01:16:57 +00008009 // C++11 [expr.rel]p2:
8010 // - If two pointers point to non-static data members of the same object,
8011 // or to subobjects or array elements fo such members, recursively, the
8012 // pointer to the later declared member compares greater provided the
8013 // two members have the same access control and provided their class is
8014 // not a union.
8015 // [...]
8016 // - Otherwise pointer comparisons are unspecified.
8017 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8018 E->isRelationalOp()) {
8019 bool WasArrayIndex;
8020 unsigned Mismatch =
8021 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8022 RHSDesignator, WasArrayIndex);
8023 // At the point where the designators diverge, the comparison has a
8024 // specified value if:
8025 // - we are comparing array indices
8026 // - we are comparing fields of a union, or fields with the same access
8027 // Otherwise, the result is unspecified and thus the comparison is not a
8028 // constant expression.
8029 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8030 Mismatch < RHSDesignator.Entries.size()) {
8031 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8032 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8033 if (!LF && !RF)
8034 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8035 else if (!LF)
8036 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8037 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8038 << RF->getParent() << RF;
8039 else if (!RF)
8040 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8041 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8042 << LF->getParent() << LF;
8043 else if (!LF->getParent()->isUnion() &&
8044 LF->getAccess() != RF->getAccess())
8045 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8046 << LF << LF->getAccess() << RF << RF->getAccess()
8047 << LF->getParent();
8048 }
8049 }
8050
Eli Friedman6c31cb42012-04-16 04:30:08 +00008051 // The comparison here must be unsigned, and performed with the same
8052 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008053 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8054 uint64_t CompareLHS = LHSOffset.getQuantity();
8055 uint64_t CompareRHS = RHSOffset.getQuantity();
8056 assert(PtrSize <= 64 && "Unexpected pointer width");
8057 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8058 CompareLHS &= Mask;
8059 CompareRHS &= Mask;
8060
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008061 // If there is a base and this is a relational operator, we can only
8062 // compare pointers within the object in question; otherwise, the result
8063 // depends on where the object is located in memory.
8064 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8065 QualType BaseTy = getType(LHSValue.Base);
8066 if (BaseTy->isIncompleteType())
8067 return Error(E);
8068 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8069 uint64_t OffsetLimit = Size.getQuantity();
8070 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8071 return Error(E);
8072 }
8073
Richard Smith8b3497e2011-10-31 01:37:14 +00008074 switch (E->getOpcode()) {
8075 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008076 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8077 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8078 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8079 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8080 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8081 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008082 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008083 }
8084 }
Richard Smith7bb00672012-02-01 01:42:44 +00008085
8086 if (LHSTy->isMemberPointerType()) {
8087 assert(E->isEqualityOp() && "unexpected member pointer operation");
8088 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8089
8090 MemberPtr LHSValue, RHSValue;
8091
8092 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008093 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008094 return false;
8095
8096 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8097 return false;
8098
8099 // C++11 [expr.eq]p2:
8100 // If both operands are null, they compare equal. Otherwise if only one is
8101 // null, they compare unequal.
8102 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8103 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8104 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8105 }
8106
8107 // Otherwise if either is a pointer to a virtual member function, the
8108 // result is unspecified.
8109 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8110 if (MD->isVirtual())
8111 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8112 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8113 if (MD->isVirtual())
8114 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8115
8116 // Otherwise they compare equal if and only if they would refer to the
8117 // same member of the same most derived object or the same subobject if
8118 // they were dereferenced with a hypothetical object of the associated
8119 // class type.
8120 bool Equal = LHSValue == RHSValue;
8121 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8122 }
8123
Richard Smithab44d9b2012-02-14 22:35:28 +00008124 if (LHSTy->isNullPtrType()) {
8125 assert(E->isComparisonOp() && "unexpected nullptr operation");
8126 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8127 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8128 // are compared, the result is true of the operator is <=, >= or ==, and
8129 // false otherwise.
8130 BinaryOperator::Opcode Opcode = E->getOpcode();
8131 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8132 }
8133
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008134 assert((!LHSTy->isIntegralOrEnumerationType() ||
8135 !RHSTy->isIntegralOrEnumerationType()) &&
8136 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8137 // We can't continue from here for non-integral types.
8138 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008139}
8140
Peter Collingbournee190dee2011-03-11 19:24:49 +00008141/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8142/// a result as the expression's type.
8143bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8144 const UnaryExprOrTypeTraitExpr *E) {
8145 switch(E->getKind()) {
8146 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008147 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008148 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008149 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008150 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008151 }
Eli Friedman64004332009-03-23 04:38:34 +00008152
Peter Collingbournee190dee2011-03-11 19:24:49 +00008153 case UETT_VecStep: {
8154 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008155
Peter Collingbournee190dee2011-03-11 19:24:49 +00008156 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008157 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008158
Peter Collingbournee190dee2011-03-11 19:24:49 +00008159 // The vec_step built-in functions that take a 3-component
8160 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8161 if (n == 3)
8162 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008163
Peter Collingbournee190dee2011-03-11 19:24:49 +00008164 return Success(n, E);
8165 } else
8166 return Success(1, E);
8167 }
8168
8169 case UETT_SizeOf: {
8170 QualType SrcTy = E->getTypeOfArgument();
8171 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8172 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008173 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8174 SrcTy = Ref->getPointeeType();
8175
Richard Smithd62306a2011-11-10 06:34:14 +00008176 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008177 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008178 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008179 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008180 }
Alexey Bataev00396512015-07-02 03:40:19 +00008181 case UETT_OpenMPRequiredSimdAlign:
8182 assert(E->isArgumentType());
8183 return Success(
8184 Info.Ctx.toCharUnitsFromBits(
8185 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8186 .getQuantity(),
8187 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008188 }
8189
8190 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008191}
8192
Peter Collingbournee9200682011-05-13 03:29:01 +00008193bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008194 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008195 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008196 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008197 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008198 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008199 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008200 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008201 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008202 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008203 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008204 APSInt IdxResult;
8205 if (!EvaluateInteger(Idx, IdxResult, Info))
8206 return false;
8207 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8208 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008209 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008210 CurrentType = AT->getElementType();
8211 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8212 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008213 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008214 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008215
James Y Knight7281c352015-12-29 22:31:18 +00008216 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008217 FieldDecl *MemberDecl = ON.getField();
8218 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008219 if (!RT)
8220 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008221 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008222 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008223 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008224 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008225 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008226 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008227 CurrentType = MemberDecl->getType().getNonReferenceType();
8228 break;
8229 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008230
James Y Knight7281c352015-12-29 22:31:18 +00008231 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008232 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008233
James Y Knight7281c352015-12-29 22:31:18 +00008234 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008235 CXXBaseSpecifier *BaseSpec = ON.getBase();
8236 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008237 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008238
8239 // Find the layout of the class whose base we are looking into.
8240 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008241 if (!RT)
8242 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008243 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008244 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008245 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8246
8247 // Find the base class itself.
8248 CurrentType = BaseSpec->getType();
8249 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8250 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008251 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008252
8253 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008254 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008255 break;
8256 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008257 }
8258 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008259 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008260}
8261
Chris Lattnere13042c2008-07-11 19:10:17 +00008262bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008263 switch (E->getOpcode()) {
8264 default:
8265 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8266 // See C99 6.6p3.
8267 return Error(E);
8268 case UO_Extension:
8269 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8270 // If so, we could clear the diagnostic ID.
8271 return Visit(E->getSubExpr());
8272 case UO_Plus:
8273 // The result is just the value.
8274 return Visit(E->getSubExpr());
8275 case UO_Minus: {
8276 if (!Visit(E->getSubExpr()))
8277 return false;
8278 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008279 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008280 if (Value.isSigned() && Value.isMinSignedValue() &&
8281 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8282 E->getType()))
8283 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008284 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008285 }
8286 case UO_Not: {
8287 if (!Visit(E->getSubExpr()))
8288 return false;
8289 if (!Result.isInt()) return Error(E);
8290 return Success(~Result.getInt(), E);
8291 }
8292 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008293 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008294 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008295 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008296 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008297 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008298 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008299}
Mike Stump11289f42009-09-09 15:08:12 +00008300
Chris Lattner477c4be2008-07-12 01:15:53 +00008301/// HandleCast - This is used to evaluate implicit or explicit casts where the
8302/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008303bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8304 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008305 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008306 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008307
Eli Friedmanc757de22011-03-25 00:43:55 +00008308 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008309 case CK_BaseToDerived:
8310 case CK_DerivedToBase:
8311 case CK_UncheckedDerivedToBase:
8312 case CK_Dynamic:
8313 case CK_ToUnion:
8314 case CK_ArrayToPointerDecay:
8315 case CK_FunctionToPointerDecay:
8316 case CK_NullToPointer:
8317 case CK_NullToMemberPointer:
8318 case CK_BaseToDerivedMemberPointer:
8319 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008320 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008321 case CK_ConstructorConversion:
8322 case CK_IntegralToPointer:
8323 case CK_ToVoid:
8324 case CK_VectorSplat:
8325 case CK_IntegralToFloating:
8326 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008327 case CK_CPointerToObjCPointerCast:
8328 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008329 case CK_AnyPointerToBlockPointerCast:
8330 case CK_ObjCObjectLValueCast:
8331 case CK_FloatingRealToComplex:
8332 case CK_FloatingComplexToReal:
8333 case CK_FloatingComplexCast:
8334 case CK_FloatingComplexToIntegralComplex:
8335 case CK_IntegralRealToComplex:
8336 case CK_IntegralComplexCast:
8337 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008338 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008339 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008340 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008341 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008342 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008343 llvm_unreachable("invalid cast kind for integral value");
8344
Eli Friedman9faf2f92011-03-25 19:07:11 +00008345 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008346 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008347 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008348 case CK_ARCProduceObject:
8349 case CK_ARCConsumeObject:
8350 case CK_ARCReclaimReturnedObject:
8351 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008352 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008353 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008354
Richard Smith4ef685b2012-01-17 21:17:26 +00008355 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008356 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008357 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008358 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008359 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008360
8361 case CK_MemberPointerToBoolean:
8362 case CK_PointerToBoolean:
8363 case CK_IntegralToBoolean:
8364 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008365 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008366 case CK_FloatingComplexToBoolean:
8367 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008368 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008369 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008370 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008371 uint64_t IntResult = BoolResult;
8372 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8373 IntResult = (uint64_t)-1;
8374 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008375 }
8376
Eli Friedmanc757de22011-03-25 00:43:55 +00008377 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008378 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008379 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008380
Eli Friedman742421e2009-02-20 01:15:07 +00008381 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008382 // Allow casts of address-of-label differences if they are no-ops
8383 // or narrowing. (The narrowing case isn't actually guaranteed to
8384 // be constant-evaluatable except in some narrow cases which are hard
8385 // to detect here. We let it through on the assumption the user knows
8386 // what they are doing.)
8387 if (Result.isAddrLabelDiff())
8388 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008389 // Only allow casts of lvalues if they are lossless.
8390 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8391 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008392
Richard Smith911e1422012-01-30 22:27:01 +00008393 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8394 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008395 }
Mike Stump11289f42009-09-09 15:08:12 +00008396
Eli Friedmanc757de22011-03-25 00:43:55 +00008397 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008398 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8399
John McCall45d55e42010-05-07 21:00:08 +00008400 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008401 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008402 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008403
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008404 if (LV.getLValueBase()) {
8405 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008406 // FIXME: Allow a larger integer size than the pointer size, and allow
8407 // narrowing back down to pointer width in subsequent integral casts.
8408 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008409 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008410 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008411
Richard Smithcf74da72011-11-16 07:18:12 +00008412 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008413 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008414 return true;
8415 }
8416
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00008417 uint64_t V;
8418 if (LV.isNullPointer())
8419 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8420 else
8421 V = LV.getLValueOffset().getQuantity();
8422
8423 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008424 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008425 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008426
Eli Friedmanc757de22011-03-25 00:43:55 +00008427 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008428 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008429 if (!EvaluateComplex(SubExpr, C, Info))
8430 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008431 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008432 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008433
Eli Friedmanc757de22011-03-25 00:43:55 +00008434 case CK_FloatingToIntegral: {
8435 APFloat F(0.0);
8436 if (!EvaluateFloat(SubExpr, F, Info))
8437 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008438
Richard Smith357362d2011-12-13 06:39:58 +00008439 APSInt Value;
8440 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8441 return false;
8442 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008443 }
8444 }
Mike Stump11289f42009-09-09 15:08:12 +00008445
Eli Friedmanc757de22011-03-25 00:43:55 +00008446 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008447}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008448
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008449bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8450 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008451 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008452 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8453 return false;
8454 if (!LV.isComplexInt())
8455 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008456 return Success(LV.getComplexIntReal(), E);
8457 }
8458
8459 return Visit(E->getSubExpr());
8460}
8461
Eli Friedman4e7a2412009-02-27 04:45:43 +00008462bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008463 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008464 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008465 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8466 return false;
8467 if (!LV.isComplexInt())
8468 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008469 return Success(LV.getComplexIntImag(), E);
8470 }
8471
Richard Smith4a678122011-10-24 18:44:57 +00008472 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008473 return Success(0, E);
8474}
8475
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008476bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8477 return Success(E->getPackLength(), E);
8478}
8479
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008480bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8481 return Success(E->getValue(), E);
8482}
8483
Chris Lattner05706e882008-07-11 18:11:29 +00008484//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008485// Float Evaluation
8486//===----------------------------------------------------------------------===//
8487
8488namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008489class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008490 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008491 APFloat &Result;
8492public:
8493 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008494 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008495
Richard Smith2e312c82012-03-03 22:46:17 +00008496 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008497 Result = V.getFloat();
8498 return true;
8499 }
Eli Friedman24c01542008-08-22 00:06:13 +00008500
Richard Smithfddd3842011-12-30 21:15:51 +00008501 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008502 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8503 return true;
8504 }
8505
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008506 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008507
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008508 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008509 bool VisitBinaryOperator(const BinaryOperator *E);
8510 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008511 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008512
John McCallb1fb0d32010-05-07 22:08:54 +00008513 bool VisitUnaryReal(const UnaryOperator *E);
8514 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008515
Richard Smithfddd3842011-12-30 21:15:51 +00008516 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008517};
8518} // end anonymous namespace
8519
8520static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008521 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008522 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008523}
8524
Jay Foad39c79802011-01-12 09:06:06 +00008525static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008526 QualType ResultTy,
8527 const Expr *Arg,
8528 bool SNaN,
8529 llvm::APFloat &Result) {
8530 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8531 if (!S) return false;
8532
8533 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8534
8535 llvm::APInt fill;
8536
8537 // Treat empty strings as if they were zero.
8538 if (S->getString().empty())
8539 fill = llvm::APInt(32, 0);
8540 else if (S->getString().getAsInteger(0, fill))
8541 return false;
8542
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008543 if (Context.getTargetInfo().isNan2008()) {
8544 if (SNaN)
8545 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8546 else
8547 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8548 } else {
8549 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8550 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8551 // a different encoding to what became a standard in 2008, and for pre-
8552 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8553 // sNaN. This is now known as "legacy NaN" encoding.
8554 if (SNaN)
8555 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8556 else
8557 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8558 }
8559
John McCall16291492010-02-28 13:00:19 +00008560 return true;
8561}
8562
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008563bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008564 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008565 default:
8566 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8567
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008568 case Builtin::BI__builtin_huge_val:
8569 case Builtin::BI__builtin_huge_valf:
8570 case Builtin::BI__builtin_huge_vall:
8571 case Builtin::BI__builtin_inf:
8572 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008573 case Builtin::BI__builtin_infl: {
8574 const llvm::fltSemantics &Sem =
8575 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008576 Result = llvm::APFloat::getInf(Sem);
8577 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008578 }
Mike Stump11289f42009-09-09 15:08:12 +00008579
John McCall16291492010-02-28 13:00:19 +00008580 case Builtin::BI__builtin_nans:
8581 case Builtin::BI__builtin_nansf:
8582 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008583 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8584 true, Result))
8585 return Error(E);
8586 return true;
John McCall16291492010-02-28 13:00:19 +00008587
Chris Lattner0b7282e2008-10-06 06:31:58 +00008588 case Builtin::BI__builtin_nan:
8589 case Builtin::BI__builtin_nanf:
8590 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008591 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008592 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008593 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8594 false, Result))
8595 return Error(E);
8596 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008597
8598 case Builtin::BI__builtin_fabs:
8599 case Builtin::BI__builtin_fabsf:
8600 case Builtin::BI__builtin_fabsl:
8601 if (!EvaluateFloat(E->getArg(0), Result, Info))
8602 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008603
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008604 if (Result.isNegative())
8605 Result.changeSign();
8606 return true;
8607
Richard Smith8889a3d2013-06-13 06:26:32 +00008608 // FIXME: Builtin::BI__builtin_powi
8609 // FIXME: Builtin::BI__builtin_powif
8610 // FIXME: Builtin::BI__builtin_powil
8611
Mike Stump11289f42009-09-09 15:08:12 +00008612 case Builtin::BI__builtin_copysign:
8613 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008614 case Builtin::BI__builtin_copysignl: {
8615 APFloat RHS(0.);
8616 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8617 !EvaluateFloat(E->getArg(1), RHS, Info))
8618 return false;
8619 Result.copySign(RHS);
8620 return true;
8621 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008622 }
8623}
8624
John McCallb1fb0d32010-05-07 22:08:54 +00008625bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008626 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8627 ComplexValue CV;
8628 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8629 return false;
8630 Result = CV.FloatReal;
8631 return true;
8632 }
8633
8634 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008635}
8636
8637bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008638 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8639 ComplexValue CV;
8640 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8641 return false;
8642 Result = CV.FloatImag;
8643 return true;
8644 }
8645
Richard Smith4a678122011-10-24 18:44:57 +00008646 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008647 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8648 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008649 return true;
8650}
8651
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008652bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008653 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008654 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008655 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008656 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008657 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008658 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8659 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008660 Result.changeSign();
8661 return true;
8662 }
8663}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008664
Eli Friedman24c01542008-08-22 00:06:13 +00008665bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008666 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8667 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008668
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008669 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008670 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008671 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008672 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008673 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8674 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008675}
8676
8677bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8678 Result = E->getValue();
8679 return true;
8680}
8681
Peter Collingbournee9200682011-05-13 03:29:01 +00008682bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8683 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008684
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008685 switch (E->getCastKind()) {
8686 default:
Richard Smith11562c52011-10-28 17:51:58 +00008687 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008688
8689 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008690 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008691 return EvaluateInteger(SubExpr, IntResult, Info) &&
8692 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8693 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008694 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008695
8696 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008697 if (!Visit(SubExpr))
8698 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008699 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8700 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008701 }
John McCalld7646252010-11-14 08:17:51 +00008702
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008703 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008704 ComplexValue V;
8705 if (!EvaluateComplex(SubExpr, V, Info))
8706 return false;
8707 Result = V.getComplexFloatReal();
8708 return true;
8709 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008710 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008711}
8712
Eli Friedman24c01542008-08-22 00:06:13 +00008713//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008714// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008715//===----------------------------------------------------------------------===//
8716
8717namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008718class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008719 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008720 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008721
Anders Carlsson537969c2008-11-16 20:27:53 +00008722public:
John McCall93d91dc2010-05-07 17:22:02 +00008723 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008724 : ExprEvaluatorBaseTy(info), Result(Result) {}
8725
Richard Smith2e312c82012-03-03 22:46:17 +00008726 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008727 Result.setFrom(V);
8728 return true;
8729 }
Mike Stump11289f42009-09-09 15:08:12 +00008730
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008731 bool ZeroInitialization(const Expr *E);
8732
Anders Carlsson537969c2008-11-16 20:27:53 +00008733 //===--------------------------------------------------------------------===//
8734 // Visitor Methods
8735 //===--------------------------------------------------------------------===//
8736
Peter Collingbournee9200682011-05-13 03:29:01 +00008737 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008738 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008739 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008740 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008741 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008742};
8743} // end anonymous namespace
8744
John McCall93d91dc2010-05-07 17:22:02 +00008745static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8746 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008747 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008748 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008749}
8750
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008751bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00008752 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008753 if (ElemTy->isRealFloatingType()) {
8754 Result.makeComplexFloat();
8755 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8756 Result.FloatReal = Zero;
8757 Result.FloatImag = Zero;
8758 } else {
8759 Result.makeComplexInt();
8760 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8761 Result.IntReal = Zero;
8762 Result.IntImag = Zero;
8763 }
8764 return true;
8765}
8766
Peter Collingbournee9200682011-05-13 03:29:01 +00008767bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8768 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008769
8770 if (SubExpr->getType()->isRealFloatingType()) {
8771 Result.makeComplexFloat();
8772 APFloat &Imag = Result.FloatImag;
8773 if (!EvaluateFloat(SubExpr, Imag, Info))
8774 return false;
8775
8776 Result.FloatReal = APFloat(Imag.getSemantics());
8777 return true;
8778 } else {
8779 assert(SubExpr->getType()->isIntegerType() &&
8780 "Unexpected imaginary literal.");
8781
8782 Result.makeComplexInt();
8783 APSInt &Imag = Result.IntImag;
8784 if (!EvaluateInteger(SubExpr, Imag, Info))
8785 return false;
8786
8787 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8788 return true;
8789 }
8790}
8791
Peter Collingbournee9200682011-05-13 03:29:01 +00008792bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008793
John McCallfcef3cf2010-12-14 17:51:41 +00008794 switch (E->getCastKind()) {
8795 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008796 case CK_BaseToDerived:
8797 case CK_DerivedToBase:
8798 case CK_UncheckedDerivedToBase:
8799 case CK_Dynamic:
8800 case CK_ToUnion:
8801 case CK_ArrayToPointerDecay:
8802 case CK_FunctionToPointerDecay:
8803 case CK_NullToPointer:
8804 case CK_NullToMemberPointer:
8805 case CK_BaseToDerivedMemberPointer:
8806 case CK_DerivedToBaseMemberPointer:
8807 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008808 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008809 case CK_ConstructorConversion:
8810 case CK_IntegralToPointer:
8811 case CK_PointerToIntegral:
8812 case CK_PointerToBoolean:
8813 case CK_ToVoid:
8814 case CK_VectorSplat:
8815 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008816 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00008817 case CK_IntegralToBoolean:
8818 case CK_IntegralToFloating:
8819 case CK_FloatingToIntegral:
8820 case CK_FloatingToBoolean:
8821 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008822 case CK_CPointerToObjCPointerCast:
8823 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008824 case CK_AnyPointerToBlockPointerCast:
8825 case CK_ObjCObjectLValueCast:
8826 case CK_FloatingComplexToReal:
8827 case CK_FloatingComplexToBoolean:
8828 case CK_IntegralComplexToReal:
8829 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008830 case CK_ARCProduceObject:
8831 case CK_ARCConsumeObject:
8832 case CK_ARCReclaimReturnedObject:
8833 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008834 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008835 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008836 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008837 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008838 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008839 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00008840 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008841
John McCallfcef3cf2010-12-14 17:51:41 +00008842 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008843 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008844 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008845 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008846
8847 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008848 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008849 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008850 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008851
8852 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008853 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008854 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008855 return false;
8856
John McCallfcef3cf2010-12-14 17:51:41 +00008857 Result.makeComplexFloat();
8858 Result.FloatImag = APFloat(Real.getSemantics());
8859 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008860 }
8861
John McCallfcef3cf2010-12-14 17:51:41 +00008862 case CK_FloatingComplexCast: {
8863 if (!Visit(E->getSubExpr()))
8864 return false;
8865
8866 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8867 QualType From
8868 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8869
Richard Smith357362d2011-12-13 06:39:58 +00008870 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8871 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008872 }
8873
8874 case CK_FloatingComplexToIntegralComplex: {
8875 if (!Visit(E->getSubExpr()))
8876 return false;
8877
8878 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8879 QualType From
8880 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8881 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008882 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8883 To, Result.IntReal) &&
8884 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8885 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008886 }
8887
8888 case CK_IntegralRealToComplex: {
8889 APSInt &Real = Result.IntReal;
8890 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8891 return false;
8892
8893 Result.makeComplexInt();
8894 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8895 return true;
8896 }
8897
8898 case CK_IntegralComplexCast: {
8899 if (!Visit(E->getSubExpr()))
8900 return false;
8901
8902 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8903 QualType From
8904 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8905
Richard Smith911e1422012-01-30 22:27:01 +00008906 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8907 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008908 return true;
8909 }
8910
8911 case CK_IntegralComplexToFloatingComplex: {
8912 if (!Visit(E->getSubExpr()))
8913 return false;
8914
Ted Kremenek28831752012-08-23 20:46:57 +00008915 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008916 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008917 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008918 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008919 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8920 To, Result.FloatReal) &&
8921 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8922 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008923 }
8924 }
8925
8926 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008927}
8928
John McCall93d91dc2010-05-07 17:22:02 +00008929bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008930 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008931 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8932
Chandler Carrutha216cad2014-10-11 00:57:18 +00008933 // Track whether the LHS or RHS is real at the type system level. When this is
8934 // the case we can simplify our evaluation strategy.
8935 bool LHSReal = false, RHSReal = false;
8936
8937 bool LHSOK;
8938 if (E->getLHS()->getType()->isRealFloatingType()) {
8939 LHSReal = true;
8940 APFloat &Real = Result.FloatReal;
8941 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8942 if (LHSOK) {
8943 Result.makeComplexFloat();
8944 Result.FloatImag = APFloat(Real.getSemantics());
8945 }
8946 } else {
8947 LHSOK = Visit(E->getLHS());
8948 }
George Burgess IVa145e252016-05-25 22:38:36 +00008949 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008950 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008951
John McCall93d91dc2010-05-07 17:22:02 +00008952 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008953 if (E->getRHS()->getType()->isRealFloatingType()) {
8954 RHSReal = true;
8955 APFloat &Real = RHS.FloatReal;
8956 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8957 return false;
8958 RHS.makeComplexFloat();
8959 RHS.FloatImag = APFloat(Real.getSemantics());
8960 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008961 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008962
Chandler Carrutha216cad2014-10-11 00:57:18 +00008963 assert(!(LHSReal && RHSReal) &&
8964 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008965 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008966 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008967 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008968 if (Result.isComplexFloat()) {
8969 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8970 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008971 if (LHSReal)
8972 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8973 else if (!RHSReal)
8974 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8975 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008976 } else {
8977 Result.getComplexIntReal() += RHS.getComplexIntReal();
8978 Result.getComplexIntImag() += RHS.getComplexIntImag();
8979 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008980 break;
John McCalle3027922010-08-25 11:45:40 +00008981 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008982 if (Result.isComplexFloat()) {
8983 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8984 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008985 if (LHSReal) {
8986 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8987 Result.getComplexFloatImag().changeSign();
8988 } else if (!RHSReal) {
8989 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8990 APFloat::rmNearestTiesToEven);
8991 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008992 } else {
8993 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8994 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8995 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008996 break;
John McCalle3027922010-08-25 11:45:40 +00008997 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008998 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008999 // This is an implementation of complex multiplication according to the
9000 // constraints laid out in C11 Annex G. The implemantion uses the
9001 // following naming scheme:
9002 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009003 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009004 APFloat &A = LHS.getComplexFloatReal();
9005 APFloat &B = LHS.getComplexFloatImag();
9006 APFloat &C = RHS.getComplexFloatReal();
9007 APFloat &D = RHS.getComplexFloatImag();
9008 APFloat &ResR = Result.getComplexFloatReal();
9009 APFloat &ResI = Result.getComplexFloatImag();
9010 if (LHSReal) {
9011 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9012 ResR = A * C;
9013 ResI = A * D;
9014 } else if (RHSReal) {
9015 ResR = C * A;
9016 ResI = C * B;
9017 } else {
9018 // In the fully general case, we need to handle NaNs and infinities
9019 // robustly.
9020 APFloat AC = A * C;
9021 APFloat BD = B * D;
9022 APFloat AD = A * D;
9023 APFloat BC = B * C;
9024 ResR = AC - BD;
9025 ResI = AD + BC;
9026 if (ResR.isNaN() && ResI.isNaN()) {
9027 bool Recalc = false;
9028 if (A.isInfinity() || B.isInfinity()) {
9029 A = APFloat::copySign(
9030 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9031 B = APFloat::copySign(
9032 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9033 if (C.isNaN())
9034 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9035 if (D.isNaN())
9036 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9037 Recalc = true;
9038 }
9039 if (C.isInfinity() || D.isInfinity()) {
9040 C = APFloat::copySign(
9041 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9042 D = APFloat::copySign(
9043 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9044 if (A.isNaN())
9045 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9046 if (B.isNaN())
9047 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9048 Recalc = true;
9049 }
9050 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9051 AD.isInfinity() || BC.isInfinity())) {
9052 if (A.isNaN())
9053 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9054 if (B.isNaN())
9055 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9056 if (C.isNaN())
9057 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9058 if (D.isNaN())
9059 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9060 Recalc = true;
9061 }
9062 if (Recalc) {
9063 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9064 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9065 }
9066 }
9067 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009068 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009069 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009070 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009071 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9072 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009073 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009074 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9075 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9076 }
9077 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009078 case BO_Div:
9079 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009080 // This is an implementation of complex division according to the
9081 // constraints laid out in C11 Annex G. The implemantion uses the
9082 // following naming scheme:
9083 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009084 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009085 APFloat &A = LHS.getComplexFloatReal();
9086 APFloat &B = LHS.getComplexFloatImag();
9087 APFloat &C = RHS.getComplexFloatReal();
9088 APFloat &D = RHS.getComplexFloatImag();
9089 APFloat &ResR = Result.getComplexFloatReal();
9090 APFloat &ResI = Result.getComplexFloatImag();
9091 if (RHSReal) {
9092 ResR = A / C;
9093 ResI = B / C;
9094 } else {
9095 if (LHSReal) {
9096 // No real optimizations we can do here, stub out with zero.
9097 B = APFloat::getZero(A.getSemantics());
9098 }
9099 int DenomLogB = 0;
9100 APFloat MaxCD = maxnum(abs(C), abs(D));
9101 if (MaxCD.isFinite()) {
9102 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009103 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9104 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009105 }
9106 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009107 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9108 APFloat::rmNearestTiesToEven);
9109 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9110 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009111 if (ResR.isNaN() && ResI.isNaN()) {
9112 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9113 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9114 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9115 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9116 D.isFinite()) {
9117 A = APFloat::copySign(
9118 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9119 B = APFloat::copySign(
9120 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9121 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9122 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9123 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9124 C = APFloat::copySign(
9125 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9126 D = APFloat::copySign(
9127 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9128 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9129 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9130 }
9131 }
9132 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009133 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009134 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9135 return Error(E, diag::note_expr_divide_by_zero);
9136
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009137 ComplexValue LHS = Result;
9138 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9139 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9140 Result.getComplexIntReal() =
9141 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9142 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9143 Result.getComplexIntImag() =
9144 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9145 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9146 }
9147 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009148 }
9149
John McCall93d91dc2010-05-07 17:22:02 +00009150 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009151}
9152
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009153bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9154 // Get the operand value into 'Result'.
9155 if (!Visit(E->getSubExpr()))
9156 return false;
9157
9158 switch (E->getOpcode()) {
9159 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009160 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009161 case UO_Extension:
9162 return true;
9163 case UO_Plus:
9164 // The result is always just the subexpr.
9165 return true;
9166 case UO_Minus:
9167 if (Result.isComplexFloat()) {
9168 Result.getComplexFloatReal().changeSign();
9169 Result.getComplexFloatImag().changeSign();
9170 }
9171 else {
9172 Result.getComplexIntReal() = -Result.getComplexIntReal();
9173 Result.getComplexIntImag() = -Result.getComplexIntImag();
9174 }
9175 return true;
9176 case UO_Not:
9177 if (Result.isComplexFloat())
9178 Result.getComplexFloatImag().changeSign();
9179 else
9180 Result.getComplexIntImag() = -Result.getComplexIntImag();
9181 return true;
9182 }
9183}
9184
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009185bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9186 if (E->getNumInits() == 2) {
9187 if (E->getType()->isComplexType()) {
9188 Result.makeComplexFloat();
9189 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9190 return false;
9191 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9192 return false;
9193 } else {
9194 Result.makeComplexInt();
9195 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9196 return false;
9197 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9198 return false;
9199 }
9200 return true;
9201 }
9202 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9203}
9204
Anders Carlsson537969c2008-11-16 20:27:53 +00009205//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009206// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9207// implicit conversion.
9208//===----------------------------------------------------------------------===//
9209
9210namespace {
9211class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009212 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00009213 APValue &Result;
9214public:
9215 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9216 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9217
9218 bool Success(const APValue &V, const Expr *E) {
9219 Result = V;
9220 return true;
9221 }
9222
9223 bool ZeroInitialization(const Expr *E) {
9224 ImplicitValueInitExpr VIE(
9225 E->getType()->castAs<AtomicType>()->getValueType());
9226 return Evaluate(Result, Info, &VIE);
9227 }
9228
9229 bool VisitCastExpr(const CastExpr *E) {
9230 switch (E->getCastKind()) {
9231 default:
9232 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9233 case CK_NonAtomicToAtomic:
9234 return Evaluate(Result, Info, E->getSubExpr());
9235 }
9236 }
9237};
9238} // end anonymous namespace
9239
9240static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9241 assert(E->isRValue() && E->getType()->isAtomicType());
9242 return AtomicExprEvaluator(Info, Result).Visit(E);
9243}
9244
9245//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009246// Void expression evaluation, primarily for a cast to void on the LHS of a
9247// comma operator
9248//===----------------------------------------------------------------------===//
9249
9250namespace {
9251class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009252 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009253public:
9254 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9255
Richard Smith2e312c82012-03-03 22:46:17 +00009256 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009257
9258 bool VisitCastExpr(const CastExpr *E) {
9259 switch (E->getCastKind()) {
9260 default:
9261 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9262 case CK_ToVoid:
9263 VisitIgnoredValue(E->getSubExpr());
9264 return true;
9265 }
9266 }
Hal Finkela8443c32014-07-17 14:49:58 +00009267
9268 bool VisitCallExpr(const CallExpr *E) {
9269 switch (E->getBuiltinCallee()) {
9270 default:
9271 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9272 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009273 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009274 // The argument is not evaluated!
9275 return true;
9276 }
9277 }
Richard Smith42d3af92011-12-07 00:43:50 +00009278};
9279} // end anonymous namespace
9280
9281static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9282 assert(E->isRValue() && E->getType()->isVoidType());
9283 return VoidExprEvaluator(Info).Visit(E);
9284}
9285
9286//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009287// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009288//===----------------------------------------------------------------------===//
9289
Richard Smith2e312c82012-03-03 22:46:17 +00009290static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009291 // In C, function designators are not lvalues, but we evaluate them as if they
9292 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009293 QualType T = E->getType();
9294 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009295 LValue LV;
9296 if (!EvaluateLValue(E, LV, Info))
9297 return false;
9298 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009299 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009300 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009301 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009302 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009303 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009304 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009305 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009306 LValue LV;
9307 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009308 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009309 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009310 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009311 llvm::APFloat F(0.0);
9312 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009313 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009314 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009315 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009316 ComplexValue C;
9317 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009318 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009319 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009320 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009321 MemberPtr P;
9322 if (!EvaluateMemberPointer(E, P, Info))
9323 return false;
9324 P.moveInto(Result);
9325 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009326 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009327 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009328 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009329 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9330 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009331 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009332 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009333 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009334 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009335 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009336 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9337 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009338 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009339 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009340 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009341 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009342 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009343 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009344 if (!EvaluateVoid(E, Info))
9345 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009346 } else if (T->isAtomicType()) {
9347 if (!EvaluateAtomic(E, Result, Info))
9348 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009349 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009350 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009351 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009352 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009353 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009354 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009355 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009356
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009357 return true;
9358}
9359
Richard Smithb228a862012-02-15 02:18:13 +00009360/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9361/// cases, the in-place evaluation is essential, since later initializers for
9362/// an object can indirectly refer to subobjects which were initialized earlier.
9363static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009364 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009365 assert(!E->isValueDependent());
9366
Richard Smith7525ff62013-05-09 07:14:00 +00009367 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009368 return false;
9369
9370 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009371 // Evaluate arrays and record types in-place, so that later initializers can
9372 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009373 if (E->getType()->isArrayType())
9374 return EvaluateArray(E, This, Result, Info);
9375 else if (E->getType()->isRecordType())
9376 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009377 }
9378
9379 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009380 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009381}
9382
Richard Smithf57d8cb2011-12-09 22:58:01 +00009383/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9384/// lvalue-to-rvalue cast if it is an lvalue.
9385static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009386 if (E->getType().isNull())
9387 return false;
9388
Richard Smithfddd3842011-12-30 21:15:51 +00009389 if (!CheckLiteralType(Info, E))
9390 return false;
9391
Richard Smith2e312c82012-03-03 22:46:17 +00009392 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009393 return false;
9394
9395 if (E->isGLValue()) {
9396 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009397 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009398 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009399 return false;
9400 }
9401
Richard Smith2e312c82012-03-03 22:46:17 +00009402 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009403 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009404}
Richard Smith11562c52011-10-28 17:51:58 +00009405
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009406static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9407 const ASTContext &Ctx, bool &IsConst) {
9408 // Fast-path evaluations of integer literals, since we sometimes see files
9409 // containing vast quantities of these.
9410 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9411 Result.Val = APValue(APSInt(L->getValue(),
9412 L->getType()->isUnsignedIntegerType()));
9413 IsConst = true;
9414 return true;
9415 }
James Dennett0492ef02014-03-14 17:44:10 +00009416
9417 // This case should be rare, but we need to check it before we check on
9418 // the type below.
9419 if (Exp->getType().isNull()) {
9420 IsConst = false;
9421 return true;
9422 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009423
9424 // FIXME: Evaluating values of large array and record types can cause
9425 // performance problems. Only do so in C++11 for now.
9426 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9427 Exp->getType()->isRecordType()) &&
9428 !Ctx.getLangOpts().CPlusPlus11) {
9429 IsConst = false;
9430 return true;
9431 }
9432 return false;
9433}
9434
9435
Richard Smith7b553f12011-10-29 00:50:52 +00009436/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009437/// any crazy technique (that has nothing to do with language standards) that
9438/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009439/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9440/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009441bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009442 bool IsConst;
9443 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9444 return IsConst;
9445
Richard Smith6d4c6582013-11-05 22:18:15 +00009446 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009447 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009448}
9449
Jay Foad39c79802011-01-12 09:06:06 +00009450bool Expr::EvaluateAsBooleanCondition(bool &Result,
9451 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009452 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009453 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009454 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009455}
9456
Richard Smithce8eca52015-12-08 03:21:47 +00009457static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9458 Expr::SideEffectsKind SEK) {
9459 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9460 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9461}
9462
Richard Smith5fab0c92011-12-28 19:48:30 +00009463bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9464 SideEffectsKind AllowSideEffects) const {
9465 if (!getType()->isIntegralOrEnumerationType())
9466 return false;
9467
Richard Smith11562c52011-10-28 17:51:58 +00009468 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009469 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009470 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009471 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009472
Richard Smith11562c52011-10-28 17:51:58 +00009473 Result = ExprResult.Val.getInt();
9474 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009475}
9476
Richard Trieube234c32016-04-21 21:04:55 +00009477bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9478 SideEffectsKind AllowSideEffects) const {
9479 if (!getType()->isRealFloatingType())
9480 return false;
9481
9482 EvalResult ExprResult;
9483 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9484 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9485 return false;
9486
9487 Result = ExprResult.Val.getFloat();
9488 return true;
9489}
9490
Jay Foad39c79802011-01-12 09:06:06 +00009491bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009492 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009493
John McCall45d55e42010-05-07 21:00:08 +00009494 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009495 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9496 !CheckLValueConstantExpression(Info, getExprLoc(),
9497 Ctx.getLValueReferenceType(getType()), LV))
9498 return false;
9499
Richard Smith2e312c82012-03-03 22:46:17 +00009500 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009501 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009502}
9503
Richard Smithd0b4dd62011-12-19 06:19:21 +00009504bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9505 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009506 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009507 // FIXME: Evaluating initializers for large array and record types can cause
9508 // performance problems. Only do so in C++11 for now.
9509 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009510 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009511 return false;
9512
Richard Smithd0b4dd62011-12-19 06:19:21 +00009513 Expr::EvalStatus EStatus;
9514 EStatus.Diag = &Notes;
9515
Richard Smith0c6124b2015-12-03 01:36:22 +00009516 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9517 ? EvalInfo::EM_ConstantExpression
9518 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009519 InitInfo.setEvaluatingDecl(VD, Value);
9520
9521 LValue LVal;
9522 LVal.set(VD);
9523
Richard Smithfddd3842011-12-30 21:15:51 +00009524 // C++11 [basic.start.init]p2:
9525 // Variables with static storage duration or thread storage duration shall be
9526 // zero-initialized before any other initialization takes place.
9527 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009528 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009529 !VD->getType()->isReferenceType()) {
9530 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009531 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009532 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009533 return false;
9534 }
9535
Richard Smith7525ff62013-05-09 07:14:00 +00009536 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9537 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009538 EStatus.HasSideEffects)
9539 return false;
9540
9541 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9542 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009543}
9544
Richard Smith7b553f12011-10-29 00:50:52 +00009545/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9546/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009547bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009548 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009549 return EvaluateAsRValue(Result, Ctx) &&
9550 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009551}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009552
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009553APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009554 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009555 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009556 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009557 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009558 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009559 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009560 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009561
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009562 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009563}
John McCall864e3962010-05-07 05:32:02 +00009564
Richard Smithe9ff7702013-11-05 22:23:30 +00009565void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009566 bool IsConst;
9567 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009568 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009569 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009570 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9571 }
9572}
9573
Richard Smithe6c01442013-06-05 00:46:14 +00009574bool Expr::EvalResult::isGlobalLValue() const {
9575 assert(Val.isLValue());
9576 return IsGlobalLValue(Val.getLValueBase());
9577}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009578
9579
John McCall864e3962010-05-07 05:32:02 +00009580/// isIntegerConstantExpr - this recursive routine will test if an expression is
9581/// an integer constant expression.
9582
9583/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9584/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009585
9586// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009587// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9588// and a (possibly null) SourceLocation indicating the location of the problem.
9589//
John McCall864e3962010-05-07 05:32:02 +00009590// Note that to reduce code duplication, this helper does no evaluation
9591// itself; the caller checks whether the expression is evaluatable, and
9592// in the rare cases where CheckICE actually cares about the evaluated
9593// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009594
Dan Gohman28ade552010-07-26 21:25:24 +00009595namespace {
9596
Richard Smith9e575da2012-12-28 13:25:52 +00009597enum ICEKind {
9598 /// This expression is an ICE.
9599 IK_ICE,
9600 /// This expression is not an ICE, but if it isn't evaluated, it's
9601 /// a legal subexpression for an ICE. This return value is used to handle
9602 /// the comma operator in C99 mode, and non-constant subexpressions.
9603 IK_ICEIfUnevaluated,
9604 /// This expression is not an ICE, and is not a legal subexpression for one.
9605 IK_NotICE
9606};
9607
John McCall864e3962010-05-07 05:32:02 +00009608struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009609 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009610 SourceLocation Loc;
9611
Richard Smith9e575da2012-12-28 13:25:52 +00009612 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009613};
9614
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009615}
Dan Gohman28ade552010-07-26 21:25:24 +00009616
Richard Smith9e575da2012-12-28 13:25:52 +00009617static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9618
9619static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009620
Craig Toppera31a8822013-08-22 07:09:37 +00009621static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009622 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009623 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009624 !EVResult.Val.isInt())
9625 return ICEDiag(IK_NotICE, E->getLocStart());
9626
John McCall864e3962010-05-07 05:32:02 +00009627 return NoDiag();
9628}
9629
Craig Toppera31a8822013-08-22 07:09:37 +00009630static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009631 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009632 if (!E->getType()->isIntegralOrEnumerationType())
9633 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009634
9635 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009636#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009637#define STMT(Node, Base) case Expr::Node##Class:
9638#define EXPR(Node, Base)
9639#include "clang/AST/StmtNodes.inc"
9640 case Expr::PredefinedExprClass:
9641 case Expr::FloatingLiteralClass:
9642 case Expr::ImaginaryLiteralClass:
9643 case Expr::StringLiteralClass:
9644 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009645 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009646 case Expr::MemberExprClass:
9647 case Expr::CompoundAssignOperatorClass:
9648 case Expr::CompoundLiteralExprClass:
9649 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009650 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00009651 case Expr::ArrayInitLoopExprClass:
9652 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009653 case Expr::NoInitExprClass:
9654 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009655 case Expr::ImplicitValueInitExprClass:
9656 case Expr::ParenListExprClass:
9657 case Expr::VAArgExprClass:
9658 case Expr::AddrLabelExprClass:
9659 case Expr::StmtExprClass:
9660 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009661 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009662 case Expr::CXXDynamicCastExprClass:
9663 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009664 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009665 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009666 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009667 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009668 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009669 case Expr::CXXThisExprClass:
9670 case Expr::CXXThrowExprClass:
9671 case Expr::CXXNewExprClass:
9672 case Expr::CXXDeleteExprClass:
9673 case Expr::CXXPseudoDestructorExprClass:
9674 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009675 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009676 case Expr::DependentScopeDeclRefExprClass:
9677 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00009678 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009679 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009680 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009681 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009682 case Expr::CXXTemporaryObjectExprClass:
9683 case Expr::CXXUnresolvedConstructExprClass:
9684 case Expr::CXXDependentScopeMemberExprClass:
9685 case Expr::UnresolvedMemberExprClass:
9686 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009687 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009688 case Expr::ObjCArrayLiteralClass:
9689 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009690 case Expr::ObjCEncodeExprClass:
9691 case Expr::ObjCMessageExprClass:
9692 case Expr::ObjCSelectorExprClass:
9693 case Expr::ObjCProtocolExprClass:
9694 case Expr::ObjCIvarRefExprClass:
9695 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009696 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009697 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00009698 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +00009699 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009700 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009701 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009702 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009703 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009704 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009705 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009706 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009707 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009708 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009709 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009710 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009711 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009712 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009713 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009714 case Expr::CoawaitExprClass:
9715 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009716 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009717
Richard Smithf137f932014-01-25 20:50:08 +00009718 case Expr::InitListExprClass: {
9719 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9720 // form "T x = { a };" is equivalent to "T x = a;".
9721 // Unless we're initializing a reference, T is a scalar as it is known to be
9722 // of integral or enumeration type.
9723 if (E->isRValue())
9724 if (cast<InitListExpr>(E)->getNumInits() == 1)
9725 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9726 return ICEDiag(IK_NotICE, E->getLocStart());
9727 }
9728
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009729 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009730 case Expr::GNUNullExprClass:
9731 // GCC considers the GNU __null value to be an integral constant expression.
9732 return NoDiag();
9733
John McCall7c454bb2011-07-15 05:09:51 +00009734 case Expr::SubstNonTypeTemplateParmExprClass:
9735 return
9736 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9737
John McCall864e3962010-05-07 05:32:02 +00009738 case Expr::ParenExprClass:
9739 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009740 case Expr::GenericSelectionExprClass:
9741 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009742 case Expr::IntegerLiteralClass:
9743 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009744 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00009745 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00009746 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00009747 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00009748 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00009749 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00009750 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009751 return NoDiag();
9752 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00009753 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00009754 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9755 // constant expressions, but they can never be ICEs because an ICE cannot
9756 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00009757 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00009758 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00009759 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009760 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009761 }
Richard Smith6365c912012-02-24 22:12:32 +00009762 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009763 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9764 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00009765 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00009766 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00009767 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00009768 // Parameter variables are never constants. Without this check,
9769 // getAnyInitializer() can find a default argument, which leads
9770 // to chaos.
9771 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00009772 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009773
9774 // C++ 7.1.5.1p2
9775 // A variable of non-volatile const-qualified integral or enumeration
9776 // type initialized by an ICE can be used in ICEs.
9777 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00009778 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00009779 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00009780
Richard Smithd0b4dd62011-12-19 06:19:21 +00009781 const VarDecl *VD;
9782 // Look for a declaration of this variable that has an initializer, and
9783 // check whether it is an ICE.
9784 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9785 return NoDiag();
9786 else
Richard Smith9e575da2012-12-28 13:25:52 +00009787 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009788 }
9789 }
Richard Smith9e575da2012-12-28 13:25:52 +00009790 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00009791 }
John McCall864e3962010-05-07 05:32:02 +00009792 case Expr::UnaryOperatorClass: {
9793 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9794 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009795 case UO_PostInc:
9796 case UO_PostDec:
9797 case UO_PreInc:
9798 case UO_PreDec:
9799 case UO_AddrOf:
9800 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +00009801 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +00009802 // C99 6.6/3 allows increment and decrement within unevaluated
9803 // subexpressions of constant expressions, but they can never be ICEs
9804 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009805 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00009806 case UO_Extension:
9807 case UO_LNot:
9808 case UO_Plus:
9809 case UO_Minus:
9810 case UO_Not:
9811 case UO_Real:
9812 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009813 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009814 }
Richard Smith9e575da2012-12-28 13:25:52 +00009815
John McCall864e3962010-05-07 05:32:02 +00009816 // OffsetOf falls through here.
9817 }
9818 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009819 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9820 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9821 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9822 // compliance: we should warn earlier for offsetof expressions with
9823 // array subscripts that aren't ICEs, and if the array subscripts
9824 // are ICEs, the value of the offsetof must be an integer constant.
9825 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009826 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009827 case Expr::UnaryExprOrTypeTraitExprClass: {
9828 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9829 if ((Exp->getKind() == UETT_SizeOf) &&
9830 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009831 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009832 return NoDiag();
9833 }
9834 case Expr::BinaryOperatorClass: {
9835 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9836 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009837 case BO_PtrMemD:
9838 case BO_PtrMemI:
9839 case BO_Assign:
9840 case BO_MulAssign:
9841 case BO_DivAssign:
9842 case BO_RemAssign:
9843 case BO_AddAssign:
9844 case BO_SubAssign:
9845 case BO_ShlAssign:
9846 case BO_ShrAssign:
9847 case BO_AndAssign:
9848 case BO_XorAssign:
9849 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009850 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9851 // constant expressions, but they can never be ICEs because an ICE cannot
9852 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009853 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009854
John McCalle3027922010-08-25 11:45:40 +00009855 case BO_Mul:
9856 case BO_Div:
9857 case BO_Rem:
9858 case BO_Add:
9859 case BO_Sub:
9860 case BO_Shl:
9861 case BO_Shr:
9862 case BO_LT:
9863 case BO_GT:
9864 case BO_LE:
9865 case BO_GE:
9866 case BO_EQ:
9867 case BO_NE:
9868 case BO_And:
9869 case BO_Xor:
9870 case BO_Or:
9871 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009872 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9873 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009874 if (Exp->getOpcode() == BO_Div ||
9875 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009876 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009877 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009878 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009879 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009880 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009881 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009882 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009883 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009884 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009885 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009886 }
9887 }
9888 }
John McCalle3027922010-08-25 11:45:40 +00009889 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009890 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009891 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9892 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009893 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9894 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009895 } else {
9896 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009897 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009898 }
9899 }
Richard Smith9e575da2012-12-28 13:25:52 +00009900 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009901 }
John McCalle3027922010-08-25 11:45:40 +00009902 case BO_LAnd:
9903 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009904 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9905 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009906 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009907 // Rare case where the RHS has a comma "side-effect"; we need
9908 // to actually check the condition to see whether the side
9909 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009910 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009911 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009912 return RHSResult;
9913 return NoDiag();
9914 }
9915
Richard Smith9e575da2012-12-28 13:25:52 +00009916 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009917 }
9918 }
9919 }
9920 case Expr::ImplicitCastExprClass:
9921 case Expr::CStyleCastExprClass:
9922 case Expr::CXXFunctionalCastExprClass:
9923 case Expr::CXXStaticCastExprClass:
9924 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009925 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009926 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009927 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009928 if (isa<ExplicitCastExpr>(E)) {
9929 if (const FloatingLiteral *FL
9930 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9931 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9932 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9933 APSInt IgnoredVal(DestWidth, !DestSigned);
9934 bool Ignored;
9935 // If the value does not fit in the destination type, the behavior is
9936 // undefined, so we are not required to treat it as a constant
9937 // expression.
9938 if (FL->getValue().convertToInteger(IgnoredVal,
9939 llvm::APFloat::rmTowardZero,
9940 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009941 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009942 return NoDiag();
9943 }
9944 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009945 switch (cast<CastExpr>(E)->getCastKind()) {
9946 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009947 case CK_AtomicToNonAtomic:
9948 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009949 case CK_NoOp:
9950 case CK_IntegralToBoolean:
9951 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009952 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009953 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009954 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009955 }
John McCall864e3962010-05-07 05:32:02 +00009956 }
John McCallc07a0c72011-02-17 10:25:35 +00009957 case Expr::BinaryConditionalOperatorClass: {
9958 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9959 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009960 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009961 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009962 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9963 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9964 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009965 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009966 return FalseResult;
9967 }
John McCall864e3962010-05-07 05:32:02 +00009968 case Expr::ConditionalOperatorClass: {
9969 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9970 // If the condition (ignoring parens) is a __builtin_constant_p call,
9971 // then only the true side is actually considered in an integer constant
9972 // expression, and it is fully evaluated. This is an important GNU
9973 // extension. See GCC PR38377 for discussion.
9974 if (const CallExpr *CallCE
9975 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009976 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009977 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009978 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009979 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009980 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009981
Richard Smithf57d8cb2011-12-09 22:58:01 +00009982 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9983 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009984
Richard Smith9e575da2012-12-28 13:25:52 +00009985 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009986 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009987 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009988 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009989 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009990 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009991 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009992 return NoDiag();
9993 // Rare case where the diagnostics depend on which side is evaluated
9994 // Note that if we get here, CondResult is 0, and at least one of
9995 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009996 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009997 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009998 return TrueResult;
9999 }
10000 case Expr::CXXDefaultArgExprClass:
10001 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010002 case Expr::CXXDefaultInitExprClass:
10003 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010004 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010005 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010006 }
10007 }
10008
David Blaikiee4d798f2012-01-20 21:50:17 +000010009 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010010}
10011
Richard Smithf57d8cb2011-12-09 22:58:01 +000010012/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010013static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010014 const Expr *E,
10015 llvm::APSInt *Value,
10016 SourceLocation *Loc) {
10017 if (!E->getType()->isIntegralOrEnumerationType()) {
10018 if (Loc) *Loc = E->getExprLoc();
10019 return false;
10020 }
10021
Richard Smith66e05fe2012-01-18 05:21:49 +000010022 APValue Result;
10023 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010024 return false;
10025
Richard Smith98710fc2014-11-13 23:03:19 +000010026 if (!Result.isInt()) {
10027 if (Loc) *Loc = E->getExprLoc();
10028 return false;
10029 }
10030
Richard Smith66e05fe2012-01-18 05:21:49 +000010031 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010032 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010033}
10034
Craig Toppera31a8822013-08-22 07:09:37 +000010035bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10036 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010037 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010038 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010039
Richard Smith9e575da2012-12-28 13:25:52 +000010040 ICEDiag D = CheckICE(this, Ctx);
10041 if (D.Kind != IK_ICE) {
10042 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010043 return false;
10044 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010045 return true;
10046}
10047
Craig Toppera31a8822013-08-22 07:09:37 +000010048bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010049 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010050 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010051 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10052
10053 if (!isIntegerConstantExpr(Ctx, Loc))
10054 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010055 // The only possible side-effects here are due to UB discovered in the
10056 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10057 // required to treat the expression as an ICE, so we produce the folded
10058 // value.
10059 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010060 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010061 return true;
10062}
Richard Smith66e05fe2012-01-18 05:21:49 +000010063
Craig Toppera31a8822013-08-22 07:09:37 +000010064bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010065 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010066}
10067
Craig Toppera31a8822013-08-22 07:09:37 +000010068bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010069 SourceLocation *Loc) const {
10070 // We support this checking in C++98 mode in order to diagnose compatibility
10071 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010072 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010073
Richard Smith98a0a492012-02-14 21:38:30 +000010074 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010075 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010076 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010077 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010078 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010079
10080 APValue Scratch;
10081 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10082
10083 if (!Diags.empty()) {
10084 IsConstExpr = false;
10085 if (Loc) *Loc = Diags[0].first;
10086 } else if (!IsConstExpr) {
10087 // FIXME: This shouldn't happen.
10088 if (Loc) *Loc = getExprLoc();
10089 }
10090
10091 return IsConstExpr;
10092}
Richard Smith253c2a32012-01-27 01:14:48 +000010093
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010094bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10095 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +000010096 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010097 Expr::EvalStatus Status;
10098 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10099
10100 ArgVector ArgValues(Args.size());
10101 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10102 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010103 if ((*I)->isValueDependent() ||
10104 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010105 // If evaluation fails, throw away the argument entirely.
10106 ArgValues[I - Args.begin()] = APValue();
10107 if (Info.EvalStatus.HasSideEffects)
10108 return false;
10109 }
10110
10111 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +000010112 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010113 ArgValues.data());
10114 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10115}
10116
Richard Smith253c2a32012-01-27 01:14:48 +000010117bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010118 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010119 PartialDiagnosticAt> &Diags) {
10120 // FIXME: It would be useful to check constexpr function templates, but at the
10121 // moment the constant expression evaluator cannot cope with the non-rigorous
10122 // ASTs which we build for dependent expressions.
10123 if (FD->isDependentContext())
10124 return true;
10125
10126 Expr::EvalStatus Status;
10127 Status.Diag = &Diags;
10128
Richard Smith6d4c6582013-11-05 22:18:15 +000010129 EvalInfo Info(FD->getASTContext(), Status,
10130 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010131
10132 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010133 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010134
Richard Smith7525ff62013-05-09 07:14:00 +000010135 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010136 // is a temporary being used as the 'this' pointer.
10137 LValue This;
10138 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010139 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010140
Richard Smith253c2a32012-01-27 01:14:48 +000010141 ArrayRef<const Expr*> Args;
10142
Richard Smith2e312c82012-03-03 22:46:17 +000010143 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010144 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10145 // Evaluate the call as a constant initializer, to allow the construction
10146 // of objects of non-literal types.
10147 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010148 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10149 } else {
10150 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010151 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010152 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010153 }
Richard Smith253c2a32012-01-27 01:14:48 +000010154
10155 return Diags.empty();
10156}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010157
10158bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10159 const FunctionDecl *FD,
10160 SmallVectorImpl<
10161 PartialDiagnosticAt> &Diags) {
10162 Expr::EvalStatus Status;
10163 Status.Diag = &Diags;
10164
10165 EvalInfo Info(FD->getASTContext(), Status,
10166 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10167
10168 // Fabricate a call stack frame to give the arguments a plausible cover story.
10169 ArrayRef<const Expr*> Args;
10170 ArgVector ArgValues(0);
10171 bool Success = EvaluateArgs(Args, ArgValues, Info);
10172 (void)Success;
10173 assert(Success &&
10174 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010175 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010176
10177 APValue ResultScratch;
10178 Evaluate(ResultScratch, Info, E);
10179 return Diags.empty();
10180}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010181
10182bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10183 unsigned Type) const {
10184 if (!getType()->isPointerType())
10185 return false;
10186
10187 Expr::EvalStatus Status;
10188 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
10189 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
10190}