blob: 95bfd63f4dccf5e5386663a0cf6f22b4d6911dc8 [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
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
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"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.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();
66 return B.get<const Expr*>()->getType();
67 }
68
Richard Smithd62306a2011-11-10 06:34:14 +000069 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000070 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000071 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000072 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000073 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000075 return Value;
76 }
77
78 /// Get an LValue path entry, which is known to not be an array index, as a
79 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000080 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000081 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +000082 }
83 /// Get an LValue path entry, which is known to not be an array index, as a
84 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +000085 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000086 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +000087 }
88 /// Determine whether this LValue path entry for a base class names a virtual
89 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +000090 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000091 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +000092 }
93
Richard Smitha8105bc2012-01-06 16:39:00 +000094 /// Find the path length and type of the most-derived subobject in the given
95 /// path, and find the size of the containing array, if any.
96 static
97 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
98 ArrayRef<APValue::LValuePathEntry> Path,
99 uint64_t &ArraySize, QualType &Type) {
100 unsigned MostDerivedLength = 0;
101 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000103 if (Type->isArrayType()) {
104 const ConstantArrayType *CAT =
105 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
106 Type = CAT->getElementType();
107 ArraySize = CAT->getSize().getZExtValue();
108 MostDerivedLength = I + 1;
Richard Smith66c96992012-02-18 22:04:06 +0000109 } else if (Type->isAnyComplexType()) {
110 const ComplexType *CT = Type->castAs<ComplexType>();
111 Type = CT->getElementType();
112 ArraySize = 2;
113 MostDerivedLength = I + 1;
Richard Smitha8105bc2012-01-06 16:39:00 +0000114 } else if (const FieldDecl *FD = getAsField(Path[I])) {
115 Type = FD->getType();
116 ArraySize = 0;
117 MostDerivedLength = I + 1;
118 } else {
Richard Smith80815602011-11-07 05:07:52 +0000119 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000120 ArraySize = 0;
121 }
Richard Smith80815602011-11-07 05:07:52 +0000122 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000123 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000124 }
125
Richard Smitha8105bc2012-01-06 16:39:00 +0000126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000129 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000130 };
131
Richard Smith96e0c102011-11-04 02:25:55 +0000132 /// A path from a glvalue to a subobject of that glvalue.
133 struct SubobjectDesignator {
134 /// True if the subobject was named in a manner not supported by C++11. Such
135 /// lvalues can still be folded, but they are not core constant expressions
136 /// and we cannot perform lvalue-to-rvalue conversions on them.
137 bool Invalid : 1;
138
Richard Smitha8105bc2012-01-06 16:39:00 +0000139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000141
Richard Smitha8105bc2012-01-06 16:39:00 +0000142 /// The length of the path to the most-derived object of which this is a
143 /// subobject.
144 unsigned MostDerivedPathLength : 30;
145
146 /// The size of the array of which the most-derived object is an element, or
147 /// 0 if the most-derived object is not an array element.
148 uint64_t MostDerivedArraySize;
149
150 /// The type of the most derived object referred to by this address.
151 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000152
Richard Smith80815602011-11-07 05:07:52 +0000153 typedef APValue::LValuePathEntry PathEntry;
154
Richard Smith96e0c102011-11-04 02:25:55 +0000155 /// The entries on the path from the glvalue to the designated subobject.
156 SmallVector<PathEntry, 8> Entries;
157
Richard Smitha8105bc2012-01-06 16:39:00 +0000158 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000159
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 explicit SubobjectDesignator(QualType T)
161 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
162 MostDerivedArraySize(0), MostDerivedType(T) {}
163
164 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
165 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
166 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000167 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000169 ArrayRef<PathEntry> VEntries = V.getLValuePath();
170 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
175 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000176 }
177 }
178
Richard Smith96e0c102011-11-04 02:25:55 +0000179 void setInvalid() {
180 Invalid = true;
181 Entries.clear();
182 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000183
184 /// Determine whether this is a one-past-the-end pointer.
185 bool isOnePastTheEnd() const {
186 if (IsOnePastTheEnd)
187 return true;
188 if (MostDerivedArraySize &&
189 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
190 return true;
191 return false;
192 }
193
194 /// Check that this refers to a valid subobject.
195 bool isValidSubobject() const {
196 if (Invalid)
197 return false;
198 return !isOnePastTheEnd();
199 }
200 /// Check that this refers to a valid subobject, and if not, produce a
201 /// relevant diagnostic and set the designator as invalid.
202 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
203
204 /// Update this designator to refer to the first element within this array.
205 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000206 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000207 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000208 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000209
210 // This is a most-derived object.
211 MostDerivedType = CAT->getElementType();
212 MostDerivedArraySize = CAT->getSize().getZExtValue();
213 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000214 }
215 /// Update this designator to refer to the given base or member of this
216 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000218 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000221 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000222
223 // If this isn't a base class, it's a new most-derived object.
224 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
225 MostDerivedType = FD->getType();
226 MostDerivedArraySize = 0;
227 MostDerivedPathLength = Entries.size();
228 }
Richard Smith96e0c102011-11-04 02:25:55 +0000229 }
Richard Smith66c96992012-02-18 22:04:06 +0000230 /// Update this designator to refer to the given complex component.
231 void addComplexUnchecked(QualType EltTy, bool Imag) {
232 PathEntry Entry;
233 Entry.ArrayIndex = Imag;
234 Entries.push_back(Entry);
235
236 // This is technically a most-derived object, though in practice this
237 // is unlikely to matter.
238 MostDerivedType = EltTy;
239 MostDerivedArraySize = 2;
240 MostDerivedPathLength = Entries.size();
241 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000243 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000245 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000247 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250 setInvalid();
251 }
Richard Smith96e0c102011-11-04 02:25:55 +0000252 return;
253 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000254 // [expr.add]p4: For the purposes of these operators, a pointer to a
255 // nonarray object behaves the same as a pointer to the first element of
256 // an array of length one with the type of the object as its element type.
257 if (IsOnePastTheEnd && N == (uint64_t)-1)
258 IsOnePastTheEnd = false;
259 else if (!IsOnePastTheEnd && N == 1)
260 IsOnePastTheEnd = true;
261 else if (N != 0) {
262 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000263 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 }
Richard Smith96e0c102011-11-04 02:25:55 +0000265 }
266 };
267
Richard Smith254a73d2011-10-28 22:34:42 +0000268 /// A stack frame in the constexpr call stack.
269 struct CallStackFrame {
270 EvalInfo &Info;
271
272 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000273 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000274
Richard Smithf6f003a2011-12-16 19:06:07 +0000275 /// CallLoc - The location of the call expression for this call.
276 SourceLocation CallLoc;
277
278 /// Callee - The function which was called.
279 const FunctionDecl *Callee;
280
Richard Smithb228a862012-02-15 02:18:13 +0000281 /// Index - The call index of this call.
282 unsigned Index;
283
Richard Smithd62306a2011-11-10 06:34:14 +0000284 /// This - The binding for the this pointer in this call, if any.
285 const LValue *This;
286
Richard Smith254a73d2011-10-28 22:34:42 +0000287 /// ParmBindings - Parameter bindings for this function call, indexed by
288 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000289 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000290
Eli Friedman4830ec82012-06-25 21:21:08 +0000291 // Note that we intentionally use std::map here so that references to
292 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000293 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000294 typedef MapTy::const_iterator temp_iterator;
295 /// Temporaries - Temporary lvalues materialized within this stack frame.
296 MapTy Temporaries;
297
Richard Smithf6f003a2011-12-16 19:06:07 +0000298 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
299 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000300 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000301 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000302 };
303
Richard Smith852c9db2013-04-20 22:23:05 +0000304 /// Temporarily override 'this'.
305 class ThisOverrideRAII {
306 public:
307 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
308 : Frame(Frame), OldThis(Frame.This) {
309 if (Enable)
310 Frame.This = NewThis;
311 }
312 ~ThisOverrideRAII() {
313 Frame.This = OldThis;
314 }
315 private:
316 CallStackFrame &Frame;
317 const LValue *OldThis;
318 };
319
Richard Smith92b1ce02011-12-12 09:28:41 +0000320 /// A partial diagnostic which we might know in advance that we are not going
321 /// to emit.
322 class OptionalDiagnostic {
323 PartialDiagnostic *Diag;
324
325 public:
326 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
327
328 template<typename T>
329 OptionalDiagnostic &operator<<(const T &v) {
330 if (Diag)
331 *Diag << v;
332 return *this;
333 }
Richard Smithfe800032012-01-31 04:08:20 +0000334
335 OptionalDiagnostic &operator<<(const APSInt &I) {
336 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000337 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000338 I.toString(Buffer);
339 *Diag << StringRef(Buffer.data(), Buffer.size());
340 }
341 return *this;
342 }
343
344 OptionalDiagnostic &operator<<(const APFloat &F) {
345 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000346 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000347 F.toString(Buffer);
348 *Diag << StringRef(Buffer.data(), Buffer.size());
349 }
350 return *this;
351 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000352 };
353
Richard Smithb228a862012-02-15 02:18:13 +0000354 /// EvalInfo - This is a private struct used by the evaluator to capture
355 /// information about a subexpression as it is folded. It retains information
356 /// about the AST context, but also maintains information about the folded
357 /// expression.
358 ///
359 /// If an expression could be evaluated, it is still possible it is not a C
360 /// "integer constant expression" or constant expression. If not, this struct
361 /// captures information about how and why not.
362 ///
363 /// One bit of information passed *into* the request for constant folding
364 /// indicates whether the subexpression is "evaluated" or not according to C
365 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
366 /// evaluate the expression regardless of what the RHS is, but C only allows
367 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000368 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000369 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000370
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000371 /// EvalStatus - Contains information about the evaluation.
372 Expr::EvalStatus &EvalStatus;
373
374 /// CurrentCall - The top of the constexpr call stack.
375 CallStackFrame *CurrentCall;
376
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000377 /// CallStackDepth - The number of calls in the call stack right now.
378 unsigned CallStackDepth;
379
Richard Smithb228a862012-02-15 02:18:13 +0000380 /// NextCallIndex - The next call index to assign.
381 unsigned NextCallIndex;
382
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000383 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000384 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000385 CallStackFrame BottomFrame;
386
Richard Smithd62306a2011-11-10 06:34:14 +0000387 /// EvaluatingDecl - This is the declaration whose initializer is being
388 /// evaluated, if any.
389 const VarDecl *EvaluatingDecl;
390
391 /// EvaluatingDeclValue - This is the value being constructed for the
392 /// declaration whose initializer is being evaluated, if any.
393 APValue *EvaluatingDeclValue;
394
Richard Smith357362d2011-12-13 06:39:58 +0000395 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
396 /// notes attached to it will also be stored, otherwise they will not be.
397 bool HasActiveDiagnostic;
398
Richard Smith253c2a32012-01-27 01:14:48 +0000399 /// CheckingPotentialConstantExpression - Are we checking whether the
400 /// expression is a potential constant expression? If so, some diagnostics
401 /// are suppressed.
402 bool CheckingPotentialConstantExpression;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000403
404 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000405
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000406 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
407 bool OverflowCheckMode=false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000408 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000409 CallStackDepth(0), NextCallIndex(1),
410 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith253c2a32012-01-27 01:14:48 +0000411 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000412 CheckingPotentialConstantExpression(false),
413 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000414
Richard Smithd62306a2011-11-10 06:34:14 +0000415 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
416 EvaluatingDecl = VD;
417 EvaluatingDeclValue = &Value;
418 }
419
David Blaikiebbafb8a2012-03-11 07:00:24 +0000420 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000421
Richard Smith357362d2011-12-13 06:39:58 +0000422 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000423 // Don't perform any constexpr calls (other than the call we're checking)
424 // when checking a potential constant expression.
425 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
426 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000427 if (NextCallIndex == 0) {
428 // NextCallIndex has wrapped around.
429 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
430 return false;
431 }
Richard Smith357362d2011-12-13 06:39:58 +0000432 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
433 return true;
434 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
435 << getLangOpts().ConstexprCallDepth;
436 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000437 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000438
Richard Smithb228a862012-02-15 02:18:13 +0000439 CallStackFrame *getCallFrame(unsigned CallIndex) {
440 assert(CallIndex && "no call index in getCallFrame");
441 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
442 // be null in this loop.
443 CallStackFrame *Frame = CurrentCall;
444 while (Frame->Index > CallIndex)
445 Frame = Frame->Caller;
446 return (Frame->Index == CallIndex) ? Frame : 0;
447 }
448
Richard Smith357362d2011-12-13 06:39:58 +0000449 private:
450 /// Add a diagnostic to the diagnostics list.
451 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
452 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
453 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
454 return EvalStatus.Diag->back().second;
455 }
456
Richard Smithf6f003a2011-12-16 19:06:07 +0000457 /// Add notes containing a call stack to the current point of evaluation.
458 void addCallStack(unsigned Limit);
459
Richard Smith357362d2011-12-13 06:39:58 +0000460 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000461 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000462 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
463 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000464 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000465 // If we have a prior diagnostic, it will be noting that the expression
466 // isn't a constant expression. This diagnostic is more important.
467 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000468 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000469 unsigned CallStackNotes = CallStackDepth - 1;
470 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
471 if (Limit)
472 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith253c2a32012-01-27 01:14:48 +0000473 if (CheckingPotentialConstantExpression)
474 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000475
Richard Smith357362d2011-12-13 06:39:58 +0000476 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000477 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000478 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
479 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000480 if (!CheckingPotentialConstantExpression)
481 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000482 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000483 }
Richard Smith357362d2011-12-13 06:39:58 +0000484 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000485 return OptionalDiagnostic();
486 }
487
Richard Smithce1ec5e2012-03-15 04:53:45 +0000488 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
489 = diag::note_invalid_subexpr_in_const_expr,
490 unsigned ExtraNotes = 0) {
491 if (EvalStatus.Diag)
492 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
493 HasActiveDiagnostic = false;
494 return OptionalDiagnostic();
495 }
496
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000497 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
498
Richard Smith92b1ce02011-12-12 09:28:41 +0000499 /// Diagnose that the evaluation does not produce a C++11 core constant
500 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000501 template<typename LocArg>
502 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000503 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000504 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000505 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000506 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
507 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000508 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000509 }
Richard Smith357362d2011-12-13 06:39:58 +0000510 return Diag(Loc, DiagId, ExtraNotes);
511 }
512
513 /// Add a note to a prior diagnostic.
514 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
515 if (!HasActiveDiagnostic)
516 return OptionalDiagnostic();
517 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000518 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000519
520 /// Add a stack of notes to a prior diagnostic.
521 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
522 if (HasActiveDiagnostic) {
523 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
524 Diags.begin(), Diags.end());
525 }
526 }
Richard Smith253c2a32012-01-27 01:14:48 +0000527
528 /// Should we continue evaluation as much as possible after encountering a
529 /// construct which can't be folded?
530 bool keepEvaluatingAfterFailure() {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000531 // Should return true in IntOverflowCheckMode, so that we check for
532 // overflow even if some subexpressions can't be evaluated as constants.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000533 return IntOverflowCheckMode ||
534 (CheckingPotentialConstantExpression &&
535 EvalStatus.Diag && EvalStatus.Diag->empty());
Richard Smith253c2a32012-01-27 01:14:48 +0000536 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000537 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000538
539 /// Object used to treat all foldable expressions as constant expressions.
540 struct FoldConstant {
541 bool Enabled;
542
543 explicit FoldConstant(EvalInfo &Info)
544 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
545 !Info.EvalStatus.HasSideEffects) {
546 }
547 // Treat the value we've computed since this object was created as constant.
548 void Fold(EvalInfo &Info) {
549 if (Enabled && !Info.EvalStatus.Diag->empty() &&
550 !Info.EvalStatus.HasSideEffects)
551 Info.EvalStatus.Diag->clear();
552 }
553 };
Richard Smith17100ba2012-02-16 02:46:34 +0000554
555 /// RAII object used to suppress diagnostics and side-effects from a
556 /// speculative evaluation.
557 class SpeculativeEvaluationRAII {
558 EvalInfo &Info;
559 Expr::EvalStatus Old;
560
561 public:
562 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000563 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000564 : Info(Info), Old(Info.EvalStatus) {
565 Info.EvalStatus.Diag = NewDiag;
566 }
567 ~SpeculativeEvaluationRAII() {
568 Info.EvalStatus = Old;
569 }
570 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000571}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000572
Richard Smitha8105bc2012-01-06 16:39:00 +0000573bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
574 CheckSubobjectKind CSK) {
575 if (Invalid)
576 return false;
577 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000578 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000579 << CSK;
580 setInvalid();
581 return false;
582 }
583 return true;
584}
585
586void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
587 const Expr *E, uint64_t N) {
588 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000589 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000590 << static_cast<int>(N) << /*array*/ 0
591 << static_cast<unsigned>(MostDerivedArraySize);
592 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000593 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000594 << static_cast<int>(N) << /*non-array*/ 1;
595 setInvalid();
596}
597
Richard Smithf6f003a2011-12-16 19:06:07 +0000598CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
599 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000600 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000601 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000602 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000603 Info.CurrentCall = this;
604 ++Info.CallStackDepth;
605}
606
607CallStackFrame::~CallStackFrame() {
608 assert(Info.CurrentCall == this && "calls retired out of order");
609 --Info.CallStackDepth;
610 Info.CurrentCall = Caller;
611}
612
613/// Produce a string describing the given constexpr call.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000614static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000615 unsigned ArgIndex = 0;
616 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith74388b42012-02-04 00:33:54 +0000617 !isa<CXXConstructorDecl>(Frame->Callee) &&
618 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smithf6f003a2011-12-16 19:06:07 +0000619
620 if (!IsMemberCall)
621 Out << *Frame->Callee << '(';
622
623 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
624 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumib8efa1e2012-01-26 09:37:36 +0000625 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smithf6f003a2011-12-16 19:06:07 +0000626 Out << ", ";
627
628 const ParmVarDecl *Param = *I;
Richard Smith2e312c82012-03-03 22:46:17 +0000629 const APValue &Arg = Frame->Arguments[ArgIndex];
630 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smithf6f003a2011-12-16 19:06:07 +0000631
632 if (ArgIndex == 0 && IsMemberCall)
633 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000634 }
635
Richard Smithf6f003a2011-12-16 19:06:07 +0000636 Out << ')';
637}
638
639void EvalInfo::addCallStack(unsigned Limit) {
640 // Determine which calls to skip, if any.
641 unsigned ActiveCalls = CallStackDepth - 1;
642 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
643 if (Limit && Limit < ActiveCalls) {
644 SkipStart = Limit / 2 + Limit % 2;
645 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000646 }
647
Richard Smithf6f003a2011-12-16 19:06:07 +0000648 // Walk the call stack and add the diagnostics.
649 unsigned CallIdx = 0;
650 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
651 Frame = Frame->Caller, ++CallIdx) {
652 // Skip this call?
653 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
654 if (CallIdx == SkipStart) {
655 // Note that we're skipping calls.
656 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
657 << unsigned(ActiveCalls - Limit);
658 }
659 continue;
660 }
661
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000662 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000663 llvm::raw_svector_ostream Out(Buffer);
664 describeCall(Frame, Out);
665 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
666 }
667}
668
669namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000670 struct ComplexValue {
671 private:
672 bool IsInt;
673
674 public:
675 APSInt IntReal, IntImag;
676 APFloat FloatReal, FloatImag;
677
678 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
679
680 void makeComplexFloat() { IsInt = false; }
681 bool isComplexFloat() const { return !IsInt; }
682 APFloat &getComplexFloatReal() { return FloatReal; }
683 APFloat &getComplexFloatImag() { return FloatImag; }
684
685 void makeComplexInt() { IsInt = true; }
686 bool isComplexInt() const { return IsInt; }
687 APSInt &getComplexIntReal() { return IntReal; }
688 APSInt &getComplexIntImag() { return IntImag; }
689
Richard Smith2e312c82012-03-03 22:46:17 +0000690 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000691 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000692 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000693 else
Richard Smith2e312c82012-03-03 22:46:17 +0000694 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000695 }
Richard Smith2e312c82012-03-03 22:46:17 +0000696 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000697 assert(v.isComplexFloat() || v.isComplexInt());
698 if (v.isComplexFloat()) {
699 makeComplexFloat();
700 FloatReal = v.getComplexFloatReal();
701 FloatImag = v.getComplexFloatImag();
702 } else {
703 makeComplexInt();
704 IntReal = v.getComplexIntReal();
705 IntImag = v.getComplexIntImag();
706 }
707 }
John McCall93d91dc2010-05-07 17:22:02 +0000708 };
John McCall45d55e42010-05-07 21:00:08 +0000709
710 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000711 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000712 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000713 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000714 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000715
Richard Smithce40ad62011-11-12 22:28:03 +0000716 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000717 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000718 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000719 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000720 SubobjectDesignator &getLValueDesignator() { return Designator; }
721 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000722
Richard Smith2e312c82012-03-03 22:46:17 +0000723 void moveInto(APValue &V) const {
724 if (Designator.Invalid)
725 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
726 else
727 V = APValue(Base, Offset, Designator.Entries,
728 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000729 }
Richard Smith2e312c82012-03-03 22:46:17 +0000730 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000731 assert(V.isLValue());
732 Base = V.getLValueBase();
733 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000734 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000735 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000736 }
737
Richard Smithb228a862012-02-15 02:18:13 +0000738 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000739 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000740 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000741 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000742 Designator = SubobjectDesignator(getType(B));
743 }
744
745 // Check that this LValue is not based on a null pointer. If it is, produce
746 // a diagnostic and mark the designator as invalid.
747 bool checkNullPointer(EvalInfo &Info, const Expr *E,
748 CheckSubobjectKind CSK) {
749 if (Designator.Invalid)
750 return false;
751 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000752 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000753 << CSK;
754 Designator.setInvalid();
755 return false;
756 }
757 return true;
758 }
759
760 // Check this LValue refers to an object. If not, set the designator to be
761 // invalid and emit a diagnostic.
762 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000763 // Outside C++11, do not build a designator referring to a subobject of
764 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000765 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000766 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000767 return checkNullPointer(Info, E, CSK) &&
768 Designator.checkSubobject(Info, E, CSK);
769 }
770
771 void addDecl(EvalInfo &Info, const Expr *E,
772 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000773 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
774 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000775 }
776 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000777 if (checkSubobject(Info, E, CSK_ArrayToPointer))
778 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000779 }
Richard Smith66c96992012-02-18 22:04:06 +0000780 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000781 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
782 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000783 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000784 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000785 if (checkNullPointer(Info, E, CSK_ArrayIndex))
786 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000787 }
John McCall45d55e42010-05-07 21:00:08 +0000788 };
Richard Smith027bf112011-11-17 22:56:20 +0000789
790 struct MemberPtr {
791 MemberPtr() {}
792 explicit MemberPtr(const ValueDecl *Decl) :
793 DeclAndIsDerivedMember(Decl, false), Path() {}
794
795 /// The member or (direct or indirect) field referred to by this member
796 /// pointer, or 0 if this is a null member pointer.
797 const ValueDecl *getDecl() const {
798 return DeclAndIsDerivedMember.getPointer();
799 }
800 /// Is this actually a member of some type derived from the relevant class?
801 bool isDerivedMember() const {
802 return DeclAndIsDerivedMember.getInt();
803 }
804 /// Get the class which the declaration actually lives in.
805 const CXXRecordDecl *getContainingRecord() const {
806 return cast<CXXRecordDecl>(
807 DeclAndIsDerivedMember.getPointer()->getDeclContext());
808 }
809
Richard Smith2e312c82012-03-03 22:46:17 +0000810 void moveInto(APValue &V) const {
811 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000812 }
Richard Smith2e312c82012-03-03 22:46:17 +0000813 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000814 assert(V.isMemberPointer());
815 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
816 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
817 Path.clear();
818 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
819 Path.insert(Path.end(), P.begin(), P.end());
820 }
821
822 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
823 /// whether the member is a member of some class derived from the class type
824 /// of the member pointer.
825 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
826 /// Path - The path of base/derived classes from the member declaration's
827 /// class (exclusive) to the class type of the member pointer (inclusive).
828 SmallVector<const CXXRecordDecl*, 4> Path;
829
830 /// Perform a cast towards the class of the Decl (either up or down the
831 /// hierarchy).
832 bool castBack(const CXXRecordDecl *Class) {
833 assert(!Path.empty());
834 const CXXRecordDecl *Expected;
835 if (Path.size() >= 2)
836 Expected = Path[Path.size() - 2];
837 else
838 Expected = getContainingRecord();
839 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
840 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
841 // if B does not contain the original member and is not a base or
842 // derived class of the class containing the original member, the result
843 // of the cast is undefined.
844 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
845 // (D::*). We consider that to be a language defect.
846 return false;
847 }
848 Path.pop_back();
849 return true;
850 }
851 /// Perform a base-to-derived member pointer cast.
852 bool castToDerived(const CXXRecordDecl *Derived) {
853 if (!getDecl())
854 return true;
855 if (!isDerivedMember()) {
856 Path.push_back(Derived);
857 return true;
858 }
859 if (!castBack(Derived))
860 return false;
861 if (Path.empty())
862 DeclAndIsDerivedMember.setInt(false);
863 return true;
864 }
865 /// Perform a derived-to-base member pointer cast.
866 bool castToBase(const CXXRecordDecl *Base) {
867 if (!getDecl())
868 return true;
869 if (Path.empty())
870 DeclAndIsDerivedMember.setInt(true);
871 if (isDerivedMember()) {
872 Path.push_back(Base);
873 return true;
874 }
875 return castBack(Base);
876 }
877 };
Richard Smith357362d2011-12-13 06:39:58 +0000878
Richard Smith7bb00672012-02-01 01:42:44 +0000879 /// Compare two member pointers, which are assumed to be of the same type.
880 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
881 if (!LHS.getDecl() || !RHS.getDecl())
882 return !LHS.getDecl() && !RHS.getDecl();
883 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
884 return false;
885 return LHS.Path == RHS.Path;
886 }
887
Richard Smith357362d2011-12-13 06:39:58 +0000888 /// Kinds of constant expression checking, for diagnostics.
889 enum CheckConstantExpressionKind {
890 CCEK_Constant, ///< A normal constant.
891 CCEK_ReturnValue, ///< A constexpr function return value.
892 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
893 };
John McCall93d91dc2010-05-07 17:22:02 +0000894}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000895
Richard Smith2e312c82012-03-03 22:46:17 +0000896static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000897static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
898 const LValue &This, const Expr *E,
899 CheckConstantExpressionKind CCEK = CCEK_Constant,
900 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000901static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
902static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000903static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
904 EvalInfo &Info);
905static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000906static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000907static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000908 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000909static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000910static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000911
912//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000913// Misc utilities
914//===----------------------------------------------------------------------===//
915
Richard Smithd9f663b2013-04-22 15:31:51 +0000916/// Evaluate an expression to see if it had side-effects, and discard its
917/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +0000918/// \return \c true if the caller should keep evaluating.
919static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000920 APValue Scratch;
Richard Smith4e18ca52013-05-06 05:56:11 +0000921 if (!Evaluate(Scratch, Info, E)) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000922 Info.EvalStatus.HasSideEffects = true;
Richard Smith4e18ca52013-05-06 05:56:11 +0000923 return Info.keepEvaluatingAfterFailure();
924 }
925 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +0000926}
927
Richard Smithd62306a2011-11-10 06:34:14 +0000928/// Should this call expression be treated as a string literal?
929static bool IsStringLiteralCall(const CallExpr *E) {
930 unsigned Builtin = E->isBuiltinCall();
931 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
932 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
933}
934
Richard Smithce40ad62011-11-12 22:28:03 +0000935static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000936 // C++11 [expr.const]p3 An address constant expression is a prvalue core
937 // constant expression of pointer type that evaluates to...
938
939 // ... a null pointer value, or a prvalue core constant expression of type
940 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000941 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000942
Richard Smithce40ad62011-11-12 22:28:03 +0000943 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
944 // ... the address of an object with static storage duration,
945 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
946 return VD->hasGlobalStorage();
947 // ... the address of a function,
948 return isa<FunctionDecl>(D);
949 }
950
951 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000952 switch (E->getStmtClass()) {
953 default:
954 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000955 case Expr::CompoundLiteralExprClass: {
956 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
957 return CLE->isFileScope() && CLE->isLValue();
958 }
Richard Smithd62306a2011-11-10 06:34:14 +0000959 // A string literal has static storage duration.
960 case Expr::StringLiteralClass:
961 case Expr::PredefinedExprClass:
962 case Expr::ObjCStringLiteralClass:
963 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000964 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000965 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000966 return true;
967 case Expr::CallExprClass:
968 return IsStringLiteralCall(cast<CallExpr>(E));
969 // For GCC compatibility, &&label has static storage duration.
970 case Expr::AddrLabelExprClass:
971 return true;
972 // A Block literal expression may be used as the initialization value for
973 // Block variables at global or local static scope.
974 case Expr::BlockExprClass:
975 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000976 case Expr::ImplicitValueInitExprClass:
977 // FIXME:
978 // We can never form an lvalue with an implicit value initialization as its
979 // base through expression evaluation, so these only appear in one case: the
980 // implicit variable declaration we invent when checking whether a constexpr
981 // constructor can produce a constant expression. We must assume that such
982 // an expression might be a global lvalue.
983 return true;
Richard Smithd62306a2011-11-10 06:34:14 +0000984 }
John McCall95007602010-05-10 23:27:23 +0000985}
986
Richard Smithb228a862012-02-15 02:18:13 +0000987static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
988 assert(Base && "no location for a null lvalue");
989 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
990 if (VD)
991 Info.Note(VD->getLocation(), diag::note_declared_at);
992 else
Ted Kremenek28831752012-08-23 20:46:57 +0000993 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +0000994 diag::note_constexpr_temporary_here);
995}
996
Richard Smith80815602011-11-07 05:07:52 +0000997/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +0000998/// value for an address or reference constant expression. Return true if we
999/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001000static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1001 QualType Type, const LValue &LVal) {
1002 bool IsReferenceType = Type->isReferenceType();
1003
Richard Smith357362d2011-12-13 06:39:58 +00001004 APValue::LValueBase Base = LVal.getLValueBase();
1005 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1006
Richard Smith0dea49e2012-02-18 04:58:18 +00001007 // Check that the object is a global. Note that the fake 'this' object we
1008 // manufacture when checking potential constant expressions is conservatively
1009 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001010 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001011 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001012 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001013 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1014 << IsReferenceType << !Designator.Entries.empty()
1015 << !!VD << VD;
1016 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001017 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001018 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001019 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001020 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001021 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001022 }
Richard Smithb228a862012-02-15 02:18:13 +00001023 assert((Info.CheckingPotentialConstantExpression ||
1024 LVal.getLValueCallIndex() == 0) &&
1025 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001026
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001027 // Check if this is a thread-local variable.
1028 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1029 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001030 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001031 return false;
1032 }
1033 }
1034
Richard Smitha8105bc2012-01-06 16:39:00 +00001035 // Allow address constant expressions to be past-the-end pointers. This is
1036 // an extension: the standard requires them to point to an object.
1037 if (!IsReferenceType)
1038 return true;
1039
1040 // A reference constant expression must refer to an object.
1041 if (!Base) {
1042 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001043 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001044 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001045 }
1046
Richard Smith357362d2011-12-13 06:39:58 +00001047 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001048 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001049 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001050 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001051 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001052 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001053 }
1054
Richard Smith80815602011-11-07 05:07:52 +00001055 return true;
1056}
1057
Richard Smithfddd3842011-12-30 21:15:51 +00001058/// Check that this core constant expression is of literal type, and if not,
1059/// produce an appropriate diagnostic.
1060static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001061 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001062 return true;
1063
1064 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001065 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001066 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001067 << E->getType();
1068 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001069 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001070 return false;
1071}
1072
Richard Smith0b0a0b62011-10-29 20:57:55 +00001073/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001074/// constant expression. If not, report an appropriate diagnostic. Does not
1075/// check that the expression is of literal type.
1076static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1077 QualType Type, const APValue &Value) {
1078 // Core issue 1454: For a literal constant expression of array or class type,
1079 // each subobject of its value shall have been initialized by a constant
1080 // expression.
1081 if (Value.isArray()) {
1082 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1083 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1084 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1085 Value.getArrayInitializedElt(I)))
1086 return false;
1087 }
1088 if (!Value.hasArrayFiller())
1089 return true;
1090 return CheckConstantExpression(Info, DiagLoc, EltTy,
1091 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001092 }
Richard Smithb228a862012-02-15 02:18:13 +00001093 if (Value.isUnion() && Value.getUnionField()) {
1094 return CheckConstantExpression(Info, DiagLoc,
1095 Value.getUnionField()->getType(),
1096 Value.getUnionValue());
1097 }
1098 if (Value.isStruct()) {
1099 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1100 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1101 unsigned BaseIndex = 0;
1102 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1103 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1104 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1105 Value.getStructBase(BaseIndex)))
1106 return false;
1107 }
1108 }
1109 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1110 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001111 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1112 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001113 return false;
1114 }
1115 }
1116
1117 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001118 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001119 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001120 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1121 }
1122
1123 // Everything else is fine.
1124 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001125}
1126
Richard Smith83c68212011-10-31 05:11:32 +00001127const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001128 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001129}
1130
1131static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001132 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001133}
1134
Richard Smithcecf1842011-11-01 21:06:14 +00001135static bool IsWeakLValue(const LValue &Value) {
1136 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001137 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001138}
1139
Richard Smith2e312c82012-03-03 22:46:17 +00001140static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001141 // A null base expression indicates a null pointer. These are always
1142 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001143 if (!Value.getLValueBase()) {
1144 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001145 return true;
1146 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001147
Richard Smith027bf112011-11-17 22:56:20 +00001148 // We have a non-null base. These are generally known to be true, but if it's
1149 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001150 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001151 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001152 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001153}
1154
Richard Smith2e312c82012-03-03 22:46:17 +00001155static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001156 switch (Val.getKind()) {
1157 case APValue::Uninitialized:
1158 return false;
1159 case APValue::Int:
1160 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001161 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001162 case APValue::Float:
1163 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001164 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001165 case APValue::ComplexInt:
1166 Result = Val.getComplexIntReal().getBoolValue() ||
1167 Val.getComplexIntImag().getBoolValue();
1168 return true;
1169 case APValue::ComplexFloat:
1170 Result = !Val.getComplexFloatReal().isZero() ||
1171 !Val.getComplexFloatImag().isZero();
1172 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001173 case APValue::LValue:
1174 return EvalPointerValueAsBool(Val, Result);
1175 case APValue::MemberPointer:
1176 Result = Val.getMemberPointerDecl();
1177 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001178 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001179 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001180 case APValue::Struct:
1181 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001182 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001183 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001184 }
1185
Richard Smith11562c52011-10-28 17:51:58 +00001186 llvm_unreachable("unknown APValue kind");
1187}
1188
1189static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1190 EvalInfo &Info) {
1191 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001192 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001193 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001194 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001195 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001196}
1197
Richard Smith357362d2011-12-13 06:39:58 +00001198template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001199static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001200 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001201 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001202 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001203}
1204
1205static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1206 QualType SrcType, const APFloat &Value,
1207 QualType DestType, APSInt &Result) {
1208 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001209 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001210 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001211
Richard Smith357362d2011-12-13 06:39:58 +00001212 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001213 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001214 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1215 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001216 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001217 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001218}
1219
Richard Smith357362d2011-12-13 06:39:58 +00001220static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1221 QualType SrcType, QualType DestType,
1222 APFloat &Result) {
1223 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001224 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001225 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1226 APFloat::rmNearestTiesToEven, &ignored)
1227 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001228 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001229 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001230}
1231
Richard Smith911e1422012-01-30 22:27:01 +00001232static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1233 QualType DestType, QualType SrcType,
1234 APSInt &Value) {
1235 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001236 APSInt Result = Value;
1237 // Figure out if this is a truncate, extend or noop cast.
1238 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001239 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001240 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001241 return Result;
1242}
1243
Richard Smith357362d2011-12-13 06:39:58 +00001244static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1245 QualType SrcType, const APSInt &Value,
1246 QualType DestType, APFloat &Result) {
1247 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1248 if (Result.convertFromAPInt(Value, Value.isSigned(),
1249 APFloat::rmNearestTiesToEven)
1250 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001251 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001252 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001253}
1254
Eli Friedman803acb32011-12-22 03:51:45 +00001255static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1256 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001257 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001258 if (!Evaluate(SVal, Info, E))
1259 return false;
1260 if (SVal.isInt()) {
1261 Res = SVal.getInt();
1262 return true;
1263 }
1264 if (SVal.isFloat()) {
1265 Res = SVal.getFloat().bitcastToAPInt();
1266 return true;
1267 }
1268 if (SVal.isVector()) {
1269 QualType VecTy = E->getType();
1270 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1271 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1272 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1273 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1274 Res = llvm::APInt::getNullValue(VecSize);
1275 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1276 APValue &Elt = SVal.getVectorElt(i);
1277 llvm::APInt EltAsInt;
1278 if (Elt.isInt()) {
1279 EltAsInt = Elt.getInt();
1280 } else if (Elt.isFloat()) {
1281 EltAsInt = Elt.getFloat().bitcastToAPInt();
1282 } else {
1283 // Don't try to handle vectors of anything other than int or float
1284 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001285 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001286 return false;
1287 }
1288 unsigned BaseEltSize = EltAsInt.getBitWidth();
1289 if (BigEndian)
1290 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1291 else
1292 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1293 }
1294 return true;
1295 }
1296 // Give up if the input isn't an int, float, or vector. For example, we
1297 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001298 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001299 return false;
1300}
1301
Richard Smitha8105bc2012-01-06 16:39:00 +00001302/// Cast an lvalue referring to a base subobject to a derived class, by
1303/// truncating the lvalue's path to the given length.
1304static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1305 const RecordDecl *TruncatedType,
1306 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001307 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001308
1309 // Check we actually point to a derived class object.
1310 if (TruncatedElements == D.Entries.size())
1311 return true;
1312 assert(TruncatedElements >= D.MostDerivedPathLength &&
1313 "not casting to a derived class");
1314 if (!Result.checkSubobject(Info, E, CSK_Derived))
1315 return false;
1316
1317 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001318 const RecordDecl *RD = TruncatedType;
1319 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001320 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001321 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1322 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001323 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001324 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001325 else
Richard Smithd62306a2011-11-10 06:34:14 +00001326 Result.Offset -= Layout.getBaseClassOffset(Base);
1327 RD = Base;
1328 }
Richard Smith027bf112011-11-17 22:56:20 +00001329 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001330 return true;
1331}
1332
John McCalld7bca762012-05-01 00:38:49 +00001333static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001334 const CXXRecordDecl *Derived,
1335 const CXXRecordDecl *Base,
1336 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001337 if (!RL) {
1338 if (Derived->isInvalidDecl()) return false;
1339 RL = &Info.Ctx.getASTRecordLayout(Derived);
1340 }
1341
Richard Smithd62306a2011-11-10 06:34:14 +00001342 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001343 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001344 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001345}
1346
Richard Smitha8105bc2012-01-06 16:39:00 +00001347static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001348 const CXXRecordDecl *DerivedDecl,
1349 const CXXBaseSpecifier *Base) {
1350 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1351
John McCalld7bca762012-05-01 00:38:49 +00001352 if (!Base->isVirtual())
1353 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001354
Richard Smitha8105bc2012-01-06 16:39:00 +00001355 SubobjectDesignator &D = Obj.Designator;
1356 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001357 return false;
1358
Richard Smitha8105bc2012-01-06 16:39:00 +00001359 // Extract most-derived object and corresponding type.
1360 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1361 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1362 return false;
1363
1364 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001365 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001366 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1367 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001368 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001369 return true;
1370}
1371
1372/// Update LVal to refer to the given field, which must be a member of the type
1373/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001374static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001375 const FieldDecl *FD,
1376 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001377 if (!RL) {
1378 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001379 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001380 }
Richard Smithd62306a2011-11-10 06:34:14 +00001381
1382 unsigned I = FD->getFieldIndex();
1383 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001384 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001385 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001386}
1387
Richard Smith1b78b3d2012-01-25 22:15:11 +00001388/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001389static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001390 LValue &LVal,
1391 const IndirectFieldDecl *IFD) {
1392 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1393 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001394 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1395 return false;
1396 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001397}
1398
Richard Smithd62306a2011-11-10 06:34:14 +00001399/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001400static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1401 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001402 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1403 // extension.
1404 if (Type->isVoidType() || Type->isFunctionType()) {
1405 Size = CharUnits::One();
1406 return true;
1407 }
1408
1409 if (!Type->isConstantSizeType()) {
1410 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001411 // FIXME: Better diagnostic.
1412 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001413 return false;
1414 }
1415
1416 Size = Info.Ctx.getTypeSizeInChars(Type);
1417 return true;
1418}
1419
1420/// Update a pointer value to model pointer arithmetic.
1421/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001422/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001423/// \param LVal - The pointer value to be updated.
1424/// \param EltTy - The pointee type represented by LVal.
1425/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001426static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1427 LValue &LVal, QualType EltTy,
1428 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001429 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001430 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001431 return false;
1432
1433 // Compute the new offset in the appropriate width.
1434 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001435 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001436 return true;
1437}
1438
Richard Smith66c96992012-02-18 22:04:06 +00001439/// Update an lvalue to refer to a component of a complex number.
1440/// \param Info - Information about the ongoing evaluation.
1441/// \param LVal - The lvalue to be updated.
1442/// \param EltTy - The complex number's component type.
1443/// \param Imag - False for the real component, true for the imaginary.
1444static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1445 LValue &LVal, QualType EltTy,
1446 bool Imag) {
1447 if (Imag) {
1448 CharUnits SizeOfComponent;
1449 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1450 return false;
1451 LVal.Offset += SizeOfComponent;
1452 }
1453 LVal.addComplex(Info, E, EltTy, Imag);
1454 return true;
1455}
1456
Richard Smith27908702011-10-24 17:54:18 +00001457/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001458///
1459/// \param Info Information about the ongoing evaluation.
1460/// \param E An expression to be used when printing diagnostics.
1461/// \param VD The variable whose initializer should be obtained.
1462/// \param Frame The frame in which the variable was created. Must be null
1463/// if this variable is not local to the evaluation.
1464/// \param Result Filled in with a pointer to the value of the variable.
1465static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1466 const VarDecl *VD, CallStackFrame *Frame,
1467 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001468 // If this is a parameter to an active constexpr function call, perform
1469 // argument substitution.
1470 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001471 // Assume arguments of a potential constant expression are unknown
1472 // constant expressions.
1473 if (Info.CheckingPotentialConstantExpression)
1474 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001475 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001476 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001477 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001478 }
Richard Smith3229b742013-05-05 21:17:10 +00001479 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001480 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001481 }
Richard Smith27908702011-10-24 17:54:18 +00001482
Richard Smithd9f663b2013-04-22 15:31:51 +00001483 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001484 if (Frame) {
1485 Result = &Frame->Temporaries[VD];
Richard Smithd9f663b2013-04-22 15:31:51 +00001486 // If we've carried on past an unevaluatable local variable initializer,
1487 // we can't go any further. This can happen during potential constant
1488 // expression checking.
Richard Smith3229b742013-05-05 21:17:10 +00001489 return !Result->isUninit();
Richard Smithd9f663b2013-04-22 15:31:51 +00001490 }
1491
Richard Smithd0b4dd62011-12-19 06:19:21 +00001492 // Dig out the initializer, and use the declaration which it's attached to.
1493 const Expr *Init = VD->getAnyInitializer(VD);
1494 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001495 // If we're checking a potential constant expression, the variable could be
1496 // initialized later.
1497 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001498 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001499 return false;
1500 }
1501
Richard Smithd62306a2011-11-10 06:34:14 +00001502 // If we're currently evaluating the initializer of this declaration, use that
1503 // in-flight value.
1504 if (Info.EvaluatingDecl == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001505 Result = Info.EvaluatingDeclValue;
1506 return !Result->isUninit();
Richard Smithd62306a2011-11-10 06:34:14 +00001507 }
1508
Richard Smithcecf1842011-11-01 21:06:14 +00001509 // Never evaluate the initializer of a weak variable. We can't be sure that
1510 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001511 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001512 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001513 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001514 }
Richard Smithcecf1842011-11-01 21:06:14 +00001515
Richard Smithd0b4dd62011-12-19 06:19:21 +00001516 // Check that we can fold the initializer. In C++, we will have already done
1517 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001518 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001519 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001520 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001521 Notes.size() + 1) << VD;
1522 Info.Note(VD->getLocation(), diag::note_declared_at);
1523 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001524 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001525 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001526 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001527 Notes.size() + 1) << VD;
1528 Info.Note(VD->getLocation(), diag::note_declared_at);
1529 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001530 }
Richard Smith27908702011-10-24 17:54:18 +00001531
Richard Smith3229b742013-05-05 21:17:10 +00001532 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001533 return true;
Richard Smith27908702011-10-24 17:54:18 +00001534}
1535
Richard Smith11562c52011-10-28 17:51:58 +00001536static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001537 Qualifiers Quals = T.getQualifiers();
1538 return Quals.hasConst() && !Quals.hasVolatile();
1539}
1540
Richard Smithe97cbd72011-11-11 04:05:33 +00001541/// Get the base index of the given base class within an APValue representing
1542/// the given derived class.
1543static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1544 const CXXRecordDecl *Base) {
1545 Base = Base->getCanonicalDecl();
1546 unsigned Index = 0;
1547 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1548 E = Derived->bases_end(); I != E; ++I, ++Index) {
1549 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1550 return Index;
1551 }
1552
1553 llvm_unreachable("base class missing from derived class's bases list");
1554}
1555
Richard Smith3da88fa2013-04-26 14:36:30 +00001556/// Extract the value of a character from a string literal.
1557static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1558 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001559 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001560 const StringLiteral *S = cast<StringLiteral>(Lit);
1561 const ConstantArrayType *CAT =
1562 Info.Ctx.getAsConstantArrayType(S->getType());
1563 assert(CAT && "string literal isn't an array");
1564 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001565 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001566
1567 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001568 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001569 if (Index < S->getLength())
1570 Value = S->getCodeUnit(Index);
1571 return Value;
1572}
1573
Richard Smith3da88fa2013-04-26 14:36:30 +00001574// Expand a string literal into an array of characters.
1575static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1576 APValue &Result) {
1577 const StringLiteral *S = cast<StringLiteral>(Lit);
1578 const ConstantArrayType *CAT =
1579 Info.Ctx.getAsConstantArrayType(S->getType());
1580 assert(CAT && "string literal isn't an array");
1581 QualType CharType = CAT->getElementType();
1582 assert(CharType->isIntegerType() && "unexpected character type");
1583
1584 unsigned Elts = CAT->getSize().getZExtValue();
1585 Result = APValue(APValue::UninitArray(),
1586 std::min(S->getLength(), Elts), Elts);
1587 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1588 CharType->isUnsignedIntegerType());
1589 if (Result.hasArrayFiller())
1590 Result.getArrayFiller() = APValue(Value);
1591 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1592 Value = S->getCodeUnit(I);
1593 Result.getArrayInitializedElt(I) = APValue(Value);
1594 }
1595}
1596
1597// Expand an array so that it has more than Index filled elements.
1598static void expandArray(APValue &Array, unsigned Index) {
1599 unsigned Size = Array.getArraySize();
1600 assert(Index < Size);
1601
1602 // Always at least double the number of elements for which we store a value.
1603 unsigned OldElts = Array.getArrayInitializedElts();
1604 unsigned NewElts = std::max(Index+1, OldElts * 2);
1605 NewElts = std::min(Size, std::max(NewElts, 8u));
1606
1607 // Copy the data across.
1608 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1609 for (unsigned I = 0; I != OldElts; ++I)
1610 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1611 for (unsigned I = OldElts; I != NewElts; ++I)
1612 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1613 if (NewValue.hasArrayFiller())
1614 NewValue.getArrayFiller() = Array.getArrayFiller();
1615 Array.swap(NewValue);
1616}
1617
1618/// Kinds of access we can perform on an object.
1619enum AccessKinds {
1620 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001621 AK_Assign,
1622 AK_Increment,
1623 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001624};
1625
Richard Smith3229b742013-05-05 21:17:10 +00001626/// A handle to a complete object (an object that is not a subobject of
1627/// another object).
1628struct CompleteObject {
1629 /// The value of the complete object.
1630 APValue *Value;
1631 /// The type of the complete object.
1632 QualType Type;
1633
1634 CompleteObject() : Value(0) {}
1635 CompleteObject(APValue *Value, QualType Type)
1636 : Value(Value), Type(Type) {
1637 assert(Value && "missing value for complete object");
1638 }
1639
1640 operator bool() const { return Value; }
1641};
1642
Richard Smith3da88fa2013-04-26 14:36:30 +00001643/// Find the designated sub-object of an rvalue.
1644template<typename SubobjectHandler>
1645typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001646findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001647 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001648 if (Sub.Invalid)
1649 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001650 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001651 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001652 if (Info.getLangOpts().CPlusPlus11)
1653 Info.Diag(E, diag::note_constexpr_access_past_end)
1654 << handler.AccessKind;
1655 else
1656 Info.Diag(E);
1657 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001658 }
Richard Smith6804be52011-11-11 08:28:03 +00001659 if (Sub.Entries.empty())
Richard Smith3229b742013-05-05 21:17:10 +00001660 return handler.found(*Obj.Value, Obj.Type);
1661 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
Richard Smith253c2a32012-01-27 01:14:48 +00001662 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001663 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001664
Richard Smith3229b742013-05-05 21:17:10 +00001665 APValue *O = Obj.Value;
1666 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001667 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001668 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001669 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001670 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001671 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001672 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001673 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001674 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001675 // Note, it should not be possible to form a pointer with a valid
1676 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001677 if (Info.getLangOpts().CPlusPlus11)
1678 Info.Diag(E, diag::note_constexpr_access_past_end)
1679 << handler.AccessKind;
1680 else
1681 Info.Diag(E);
1682 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001683 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001684
1685 ObjType = CAT->getElementType();
1686
Richard Smith14a94132012-02-17 03:35:37 +00001687 // An array object is represented as either an Array APValue or as an
1688 // LValue which refers to a string literal.
1689 if (O->isLValue()) {
1690 assert(I == N - 1 && "extracting subobject of character?");
1691 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001692 if (handler.AccessKind != AK_Read)
1693 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1694 *O);
1695 else
1696 return handler.foundString(*O, ObjType, Index);
1697 }
1698
1699 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001700 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001701 else if (handler.AccessKind != AK_Read) {
1702 expandArray(*O, Index);
1703 O = &O->getArrayInitializedElt(Index);
1704 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001705 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001706 } else if (ObjType->isAnyComplexType()) {
1707 // Next subobject is a complex number.
1708 uint64_t Index = Sub.Entries[I].ArrayIndex;
1709 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001710 if (Info.getLangOpts().CPlusPlus11)
1711 Info.Diag(E, diag::note_constexpr_access_past_end)
1712 << handler.AccessKind;
1713 else
1714 Info.Diag(E);
1715 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001716 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001717
1718 bool WasConstQualified = ObjType.isConstQualified();
1719 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1720 if (WasConstQualified)
1721 ObjType.addConst();
1722
Richard Smith66c96992012-02-18 22:04:06 +00001723 assert(I == N - 1 && "extracting subobject of scalar?");
1724 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001725 return handler.found(Index ? O->getComplexIntImag()
1726 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001727 } else {
1728 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001729 return handler.found(Index ? O->getComplexFloatImag()
1730 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001731 }
Richard Smithd62306a2011-11-10 06:34:14 +00001732 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001733 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001734 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001735 << Field;
1736 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001737 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001738 }
1739
Richard Smithd62306a2011-11-10 06:34:14 +00001740 // Next subobject is a class, struct or union field.
1741 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1742 if (RD->isUnion()) {
1743 const FieldDecl *UnionField = O->getUnionField();
1744 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001745 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001746 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1747 << handler.AccessKind << Field << !UnionField << UnionField;
1748 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001749 }
Richard Smithd62306a2011-11-10 06:34:14 +00001750 O = &O->getUnionValue();
1751 } else
1752 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001753
1754 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001755 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001756 if (WasConstQualified && !Field->isMutable())
1757 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001758
1759 if (ObjType.isVolatileQualified()) {
1760 if (Info.getLangOpts().CPlusPlus) {
1761 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001762 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1763 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001764 Info.Note(Field->getLocation(), diag::note_declared_at);
1765 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001766 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001767 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001768 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001769 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001770 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001771 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001772 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1773 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1774 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00001775
1776 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00001777 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00001778 if (WasConstQualified)
1779 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00001780 }
Richard Smithd62306a2011-11-10 06:34:14 +00001781
Richard Smithf57d8cb2011-12-09 22:58:01 +00001782 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001783 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00001784 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1785 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001786 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001787 }
1788
Richard Smith3da88fa2013-04-26 14:36:30 +00001789 return handler.found(*O, ObjType);
1790}
1791
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001792namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001793struct ExtractSubobjectHandler {
1794 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00001795 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00001796
1797 static const AccessKinds AccessKind = AK_Read;
1798
1799 typedef bool result_type;
1800 bool failed() { return false; }
1801 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001802 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00001803 return true;
1804 }
1805 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001806 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001807 return true;
1808 }
1809 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001810 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001811 return true;
1812 }
1813 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00001814 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00001815 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
1816 return true;
1817 }
1818};
Richard Smith3229b742013-05-05 21:17:10 +00001819} // end anonymous namespace
1820
Richard Smith3da88fa2013-04-26 14:36:30 +00001821const AccessKinds ExtractSubobjectHandler::AccessKind;
1822
1823/// Extract the designated sub-object of an rvalue.
1824static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00001825 const CompleteObject &Obj,
1826 const SubobjectDesignator &Sub,
1827 APValue &Result) {
1828 ExtractSubobjectHandler Handler = { Info, Result };
1829 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00001830}
1831
Richard Smith3229b742013-05-05 21:17:10 +00001832namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001833struct ModifySubobjectHandler {
1834 EvalInfo &Info;
1835 APValue &NewVal;
1836 const Expr *E;
1837
1838 typedef bool result_type;
1839 static const AccessKinds AccessKind = AK_Assign;
1840
1841 bool checkConst(QualType QT) {
1842 // Assigning to a const object has undefined behavior.
1843 if (QT.isConstQualified()) {
1844 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
1845 return false;
1846 }
1847 return true;
1848 }
1849
1850 bool failed() { return false; }
1851 bool found(APValue &Subobj, QualType SubobjType) {
1852 if (!checkConst(SubobjType))
1853 return false;
1854 // We've been given ownership of NewVal, so just swap it in.
1855 Subobj.swap(NewVal);
1856 return true;
1857 }
1858 bool found(APSInt &Value, QualType SubobjType) {
1859 if (!checkConst(SubobjType))
1860 return false;
1861 if (!NewVal.isInt()) {
1862 // Maybe trying to write a cast pointer value into a complex?
1863 Info.Diag(E);
1864 return false;
1865 }
1866 Value = NewVal.getInt();
1867 return true;
1868 }
1869 bool found(APFloat &Value, QualType SubobjType) {
1870 if (!checkConst(SubobjType))
1871 return false;
1872 Value = NewVal.getFloat();
1873 return true;
1874 }
1875 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
1876 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
1877 }
1878};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001879} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00001880
Richard Smith3229b742013-05-05 21:17:10 +00001881const AccessKinds ModifySubobjectHandler::AccessKind;
1882
Richard Smith3da88fa2013-04-26 14:36:30 +00001883/// Update the designated sub-object of an rvalue to the given value.
1884static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00001885 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001886 const SubobjectDesignator &Sub,
1887 APValue &NewVal) {
1888 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00001889 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00001890}
1891
Richard Smith84f6dcf2012-02-02 01:16:57 +00001892/// Find the position where two subobject designators diverge, or equivalently
1893/// the length of the common initial subsequence.
1894static unsigned FindDesignatorMismatch(QualType ObjType,
1895 const SubobjectDesignator &A,
1896 const SubobjectDesignator &B,
1897 bool &WasArrayIndex) {
1898 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1899 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00001900 if (!ObjType.isNull() &&
1901 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00001902 // Next subobject is an array element.
1903 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1904 WasArrayIndex = true;
1905 return I;
1906 }
Richard Smith66c96992012-02-18 22:04:06 +00001907 if (ObjType->isAnyComplexType())
1908 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1909 else
1910 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00001911 } else {
1912 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1913 WasArrayIndex = false;
1914 return I;
1915 }
1916 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1917 // Next subobject is a field.
1918 ObjType = FD->getType();
1919 else
1920 // Next subobject is a base class.
1921 ObjType = QualType();
1922 }
1923 }
1924 WasArrayIndex = false;
1925 return I;
1926}
1927
1928/// Determine whether the given subobject designators refer to elements of the
1929/// same array object.
1930static bool AreElementsOfSameArray(QualType ObjType,
1931 const SubobjectDesignator &A,
1932 const SubobjectDesignator &B) {
1933 if (A.Entries.size() != B.Entries.size())
1934 return false;
1935
1936 bool IsArray = A.MostDerivedArraySize != 0;
1937 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1938 // A is a subobject of the array element.
1939 return false;
1940
1941 // If A (and B) designates an array element, the last entry will be the array
1942 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1943 // of length 1' case, and the entire path must match.
1944 bool WasArrayIndex;
1945 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1946 return CommonLength >= A.Entries.size() - IsArray;
1947}
1948
Richard Smith3229b742013-05-05 21:17:10 +00001949/// Find the complete object to which an LValue refers.
1950CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
1951 const LValue &LVal, QualType LValType) {
1952 if (!LVal.Base) {
1953 Info.Diag(E, diag::note_constexpr_access_null) << AK;
1954 return CompleteObject();
1955 }
1956
1957 CallStackFrame *Frame = 0;
1958 if (LVal.CallIndex) {
1959 Frame = Info.getCallFrame(LVal.CallIndex);
1960 if (!Frame) {
1961 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
1962 << AK << LVal.Base.is<const ValueDecl*>();
1963 NoteLValueLocation(Info, LVal.Base);
1964 return CompleteObject();
1965 }
1966 } else if (AK != AK_Read) {
1967 Info.Diag(E, diag::note_constexpr_modify_global);
1968 return CompleteObject();
1969 }
1970
1971 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1972 // is not a constant expression (even if the object is non-volatile). We also
1973 // apply this rule to C++98, in order to conform to the expected 'volatile'
1974 // semantics.
1975 if (LValType.isVolatileQualified()) {
1976 if (Info.getLangOpts().CPlusPlus)
1977 Info.Diag(E, diag::note_constexpr_access_volatile_type)
1978 << AK << LValType;
1979 else
1980 Info.Diag(E);
1981 return CompleteObject();
1982 }
1983
1984 // Compute value storage location and type of base object.
1985 APValue *BaseVal = 0;
1986 QualType BaseType;
1987
1988 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
1989 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1990 // In C++11, constexpr, non-volatile variables initialized with constant
1991 // expressions are constant expressions too. Inside constexpr functions,
1992 // parameters are constant expressions even if they're non-const.
1993 // In C++1y, objects local to a constant expression (those with a Frame) are
1994 // both readable and writable inside constant expressions.
1995 // In C, such things can also be folded, although they are not ICEs.
1996 const VarDecl *VD = dyn_cast<VarDecl>(D);
1997 if (VD) {
1998 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1999 VD = VDef;
2000 }
2001 if (!VD || VD->isInvalidDecl()) {
2002 Info.Diag(E);
2003 return CompleteObject();
2004 }
2005
2006 // Accesses of volatile-qualified objects are not allowed.
2007 BaseType = VD->getType();
2008 if (BaseType.isVolatileQualified()) {
2009 if (Info.getLangOpts().CPlusPlus) {
2010 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2011 << AK << 1 << VD;
2012 Info.Note(VD->getLocation(), diag::note_declared_at);
2013 } else {
2014 Info.Diag(E);
2015 }
2016 return CompleteObject();
2017 }
2018
2019 // Unless we're looking at a local variable or argument in a constexpr call,
2020 // the variable we're reading must be const.
2021 if (!Frame) {
2022 assert(AK == AK_Read && "can't modify non-local");
2023 if (VD->isConstexpr()) {
2024 // OK, we can read this variable.
2025 } else if (BaseType->isIntegralOrEnumerationType()) {
2026 if (!BaseType.isConstQualified()) {
2027 if (Info.getLangOpts().CPlusPlus) {
2028 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2029 Info.Note(VD->getLocation(), diag::note_declared_at);
2030 } else {
2031 Info.Diag(E);
2032 }
2033 return CompleteObject();
2034 }
2035 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2036 // We support folding of const floating-point types, in order to make
2037 // static const data members of such types (supported as an extension)
2038 // more useful.
2039 if (Info.getLangOpts().CPlusPlus11) {
2040 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2041 Info.Note(VD->getLocation(), diag::note_declared_at);
2042 } else {
2043 Info.CCEDiag(E);
2044 }
2045 } else {
2046 // FIXME: Allow folding of values of any literal type in all languages.
2047 if (Info.getLangOpts().CPlusPlus11) {
2048 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2049 Info.Note(VD->getLocation(), diag::note_declared_at);
2050 } else {
2051 Info.Diag(E);
2052 }
2053 return CompleteObject();
2054 }
2055 }
2056
2057 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2058 return CompleteObject();
2059 } else {
2060 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2061
2062 if (!Frame) {
2063 Info.Diag(E);
2064 return CompleteObject();
2065 }
2066
2067 BaseType = Base->getType();
2068 BaseVal = &Frame->Temporaries[Base];
2069
2070 // Volatile temporary objects cannot be accessed in constant expressions.
2071 if (BaseType.isVolatileQualified()) {
2072 if (Info.getLangOpts().CPlusPlus) {
2073 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2074 << AK << 0;
2075 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2076 } else {
2077 Info.Diag(E);
2078 }
2079 return CompleteObject();
2080 }
2081 }
2082
2083 // In C++1y, we can't safely access any mutable state when checking a
2084 // potential constant expression.
2085 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2086 Info.CheckingPotentialConstantExpression)
2087 return CompleteObject();
2088
2089 return CompleteObject(BaseVal, BaseType);
2090}
2091
Richard Smith243ef902013-05-05 23:31:59 +00002092/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2093/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2094/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002095///
2096/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002097/// \param Conv - The expression for which we are performing the conversion.
2098/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002099/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2100/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002101/// \param LVal - The glvalue on which we are attempting to perform this action.
2102/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002103static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002104 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002105 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002106 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002107 return false;
2108
Richard Smith3229b742013-05-05 21:17:10 +00002109 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002110 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002111 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2112 !Type.isVolatileQualified()) {
2113 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2114 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2115 // initializer until now for such expressions. Such an expression can't be
2116 // an ICE in C, so this only matters for fold.
2117 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2118 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002119 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002120 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002121 }
Richard Smith3229b742013-05-05 21:17:10 +00002122 APValue Lit;
2123 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2124 return false;
2125 CompleteObject LitObj(&Lit, Base->getType());
2126 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2127 } else if (isa<StringLiteral>(Base)) {
2128 // We represent a string literal array as an lvalue pointing at the
2129 // corresponding expression, rather than building an array of chars.
2130 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2131 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2132 CompleteObject StrObj(&Str, Base->getType());
2133 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002134 }
Richard Smith11562c52011-10-28 17:51:58 +00002135 }
2136
Richard Smith3229b742013-05-05 21:17:10 +00002137 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2138 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002139}
2140
2141/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002142static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002143 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002144 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002145 return false;
2146
Richard Smith3229b742013-05-05 21:17:10 +00002147 if (!Info.getLangOpts().CPlusPlus1y) {
2148 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002149 return false;
2150 }
2151
Richard Smith3229b742013-05-05 21:17:10 +00002152 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2153 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002154}
2155
Richard Smith243ef902013-05-05 23:31:59 +00002156static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2157 return T->isSignedIntegerType() &&
2158 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2159}
2160
2161namespace {
2162struct IncDecSubobjectHandler {
2163 EvalInfo &Info;
2164 const Expr *E;
2165 AccessKinds AccessKind;
2166 APValue *Old;
2167
2168 typedef bool result_type;
2169
2170 bool checkConst(QualType QT) {
2171 // Assigning to a const object has undefined behavior.
2172 if (QT.isConstQualified()) {
2173 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2174 return false;
2175 }
2176 return true;
2177 }
2178
2179 bool failed() { return false; }
2180 bool found(APValue &Subobj, QualType SubobjType) {
2181 // Stash the old value. Also clear Old, so we don't clobber it later
2182 // if we're post-incrementing a complex.
2183 if (Old) {
2184 *Old = Subobj;
2185 Old = 0;
2186 }
2187
2188 switch (Subobj.getKind()) {
2189 case APValue::Int:
2190 return found(Subobj.getInt(), SubobjType);
2191 case APValue::Float:
2192 return found(Subobj.getFloat(), SubobjType);
2193 case APValue::ComplexInt:
2194 return found(Subobj.getComplexIntReal(),
2195 SubobjType->castAs<ComplexType>()->getElementType()
2196 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2197 case APValue::ComplexFloat:
2198 return found(Subobj.getComplexFloatReal(),
2199 SubobjType->castAs<ComplexType>()->getElementType()
2200 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2201 case APValue::LValue:
2202 return foundPointer(Subobj, SubobjType);
2203 default:
2204 // FIXME: can this happen?
2205 Info.Diag(E);
2206 return false;
2207 }
2208 }
2209 bool found(APSInt &Value, QualType SubobjType) {
2210 if (!checkConst(SubobjType))
2211 return false;
2212
2213 if (!SubobjType->isIntegerType()) {
2214 // We don't support increment / decrement on integer-cast-to-pointer
2215 // values.
2216 Info.Diag(E);
2217 return false;
2218 }
2219
2220 if (Old) *Old = APValue(Value);
2221
2222 // bool arithmetic promotes to int, and the conversion back to bool
2223 // doesn't reduce mod 2^n, so special-case it.
2224 if (SubobjType->isBooleanType()) {
2225 if (AccessKind == AK_Increment)
2226 Value = 1;
2227 else
2228 Value = !Value;
2229 return true;
2230 }
2231
2232 bool WasNegative = Value.isNegative();
2233 if (AccessKind == AK_Increment) {
2234 ++Value;
2235
2236 if (!WasNegative && Value.isNegative() &&
2237 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2238 APSInt ActualValue(Value, /*IsUnsigned*/true);
2239 HandleOverflow(Info, E, ActualValue, SubobjType);
2240 }
2241 } else {
2242 --Value;
2243
2244 if (WasNegative && !Value.isNegative() &&
2245 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2246 unsigned BitWidth = Value.getBitWidth();
2247 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2248 ActualValue.setBit(BitWidth);
2249 HandleOverflow(Info, E, ActualValue, SubobjType);
2250 }
2251 }
2252 return true;
2253 }
2254 bool found(APFloat &Value, QualType SubobjType) {
2255 if (!checkConst(SubobjType))
2256 return false;
2257
2258 if (Old) *Old = APValue(Value);
2259
2260 APFloat One(Value.getSemantics(), 1);
2261 if (AccessKind == AK_Increment)
2262 Value.add(One, APFloat::rmNearestTiesToEven);
2263 else
2264 Value.subtract(One, APFloat::rmNearestTiesToEven);
2265 return true;
2266 }
2267 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2268 if (!checkConst(SubobjType))
2269 return false;
2270
2271 QualType PointeeType;
2272 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2273 PointeeType = PT->getPointeeType();
2274 else {
2275 Info.Diag(E);
2276 return false;
2277 }
2278
2279 LValue LVal;
2280 LVal.setFrom(Info.Ctx, Subobj);
2281 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2282 AccessKind == AK_Increment ? 1 : -1))
2283 return false;
2284 LVal.moveInto(Subobj);
2285 return true;
2286 }
2287 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2288 llvm_unreachable("shouldn't encounter string elements here");
2289 }
2290};
2291} // end anonymous namespace
2292
2293/// Perform an increment or decrement on LVal.
2294static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2295 QualType LValType, bool IsIncrement, APValue *Old) {
2296 if (LVal.Designator.Invalid)
2297 return false;
2298
2299 if (!Info.getLangOpts().CPlusPlus1y) {
2300 Info.Diag(E);
2301 return false;
2302 }
2303
2304 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2305 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2306 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2307 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2308}
2309
Richard Smithe97cbd72011-11-11 04:05:33 +00002310/// Build an lvalue for the object argument of a member function call.
2311static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2312 LValue &This) {
2313 if (Object->getType()->isPointerType())
2314 return EvaluatePointer(Object, This, Info);
2315
2316 if (Object->isGLValue())
2317 return EvaluateLValue(Object, This, Info);
2318
Richard Smithd9f663b2013-04-22 15:31:51 +00002319 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002320 return EvaluateTemporary(Object, This, Info);
2321
2322 return false;
2323}
2324
2325/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2326/// lvalue referring to the result.
2327///
2328/// \param Info - Information about the ongoing evaluation.
2329/// \param BO - The member pointer access operation.
2330/// \param LV - Filled in with a reference to the resulting object.
2331/// \param IncludeMember - Specifies whether the member itself is included in
2332/// the resulting LValue subobject designator. This is not possible when
2333/// creating a bound member function.
2334/// \return The field or method declaration to which the member pointer refers,
2335/// or 0 if evaluation fails.
2336static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2337 const BinaryOperator *BO,
2338 LValue &LV,
2339 bool IncludeMember = true) {
2340 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2341
Richard Smith253c2a32012-01-27 01:14:48 +00002342 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
2343 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00002344 return 0;
2345
2346 MemberPtr MemPtr;
2347 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
2348 return 0;
2349
2350 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2351 // member value, the behavior is undefined.
2352 if (!MemPtr.getDecl())
2353 return 0;
2354
Richard Smith253c2a32012-01-27 01:14:48 +00002355 if (!EvalObjOK)
2356 return 0;
2357
Richard Smith027bf112011-11-17 22:56:20 +00002358 if (MemPtr.isDerivedMember()) {
2359 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002360 // The end of the derived-to-base path for the base object must match the
2361 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002362 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00002363 LV.Designator.Entries.size())
2364 return 0;
2365 unsigned PathLengthToMember =
2366 LV.Designator.Entries.size() - MemPtr.Path.size();
2367 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2368 const CXXRecordDecl *LVDecl = getAsBaseClass(
2369 LV.Designator.Entries[PathLengthToMember + I]);
2370 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2371 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
2372 return 0;
2373 }
2374
2375 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002376 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
2377 PathLengthToMember))
2378 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002379 } else if (!MemPtr.Path.empty()) {
2380 // Extend the LValue path with the member pointer's path.
2381 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2382 MemPtr.Path.size() + IncludeMember);
2383
2384 // Walk down to the appropriate base class.
2385 QualType LVType = BO->getLHS()->getType();
2386 if (const PointerType *PT = LVType->getAs<PointerType>())
2387 LVType = PT->getPointeeType();
2388 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2389 assert(RD && "member pointer access on non-class-type expression");
2390 // The first class in the path is that of the lvalue.
2391 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2392 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00002393 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
2394 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002395 RD = Base;
2396 }
2397 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00002398 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
2399 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002400 }
2401
2402 // Add the member. Note that we cannot build bound member functions here.
2403 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002404 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2405 if (!HandleLValueMember(Info, BO, LV, FD))
2406 return 0;
2407 } else if (const IndirectFieldDecl *IFD =
2408 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2409 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2410 return 0;
2411 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002412 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002413 }
Richard Smith027bf112011-11-17 22:56:20 +00002414 }
2415
2416 return MemPtr.getDecl();
2417}
2418
2419/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2420/// the provided lvalue, which currently refers to the base object.
2421static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2422 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002423 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002424 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002425 return false;
2426
Richard Smitha8105bc2012-01-06 16:39:00 +00002427 QualType TargetQT = E->getType();
2428 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2429 TargetQT = PT->getPointeeType();
2430
2431 // Check this cast lands within the final derived-to-base subobject path.
2432 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002433 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002434 << D.MostDerivedType << TargetQT;
2435 return false;
2436 }
2437
Richard Smith027bf112011-11-17 22:56:20 +00002438 // Check the type of the final cast. We don't need to check the path,
2439 // since a cast can only be formed if the path is unique.
2440 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002441 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2442 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002443 if (NewEntriesSize == D.MostDerivedPathLength)
2444 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2445 else
Richard Smith027bf112011-11-17 22:56:20 +00002446 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002447 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002448 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002449 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002450 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002451 }
Richard Smith027bf112011-11-17 22:56:20 +00002452
2453 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002454 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002455}
2456
Mike Stump876387b2009-10-27 22:09:17 +00002457namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002458enum EvalStmtResult {
2459 /// Evaluation failed.
2460 ESR_Failed,
2461 /// Hit a 'return' statement.
2462 ESR_Returned,
2463 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002464 ESR_Succeeded,
2465 /// Hit a 'continue' statement.
2466 ESR_Continue,
2467 /// Hit a 'break' statement.
2468 ESR_Break
Richard Smith254a73d2011-10-28 22:34:42 +00002469};
2470}
2471
Richard Smithd9f663b2013-04-22 15:31:51 +00002472static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2473 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2474 // We don't need to evaluate the initializer for a static local.
2475 if (!VD->hasLocalStorage())
2476 return true;
2477
2478 LValue Result;
2479 Result.set(VD, Info.CurrentCall->Index);
2480 APValue &Val = Info.CurrentCall->Temporaries[VD];
2481
2482 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2483 // Wipe out any partially-computed value, to allow tracking that this
2484 // evaluation failed.
2485 Val = APValue();
2486 return false;
2487 }
2488 }
2489
2490 return true;
2491}
2492
Richard Smith4e18ca52013-05-06 05:56:11 +00002493/// Evaluate a condition (either a variable declaration or an expression).
2494static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2495 const Expr *Cond, bool &Result) {
2496 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2497 return false;
2498 return EvaluateAsBooleanCondition(Cond, Result, Info);
2499}
2500
2501static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
2502 const Stmt *S);
2503
2504/// Evaluate the body of a loop, and translate the result as appropriate.
2505static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
2506 const Stmt *Body) {
2507 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body)) {
2508 case ESR_Break:
2509 return ESR_Succeeded;
2510 case ESR_Succeeded:
2511 case ESR_Continue:
2512 return ESR_Continue;
2513 case ESR_Failed:
2514 case ESR_Returned:
2515 return ESR;
2516 }
2517}
2518
Richard Smith254a73d2011-10-28 22:34:42 +00002519// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002520static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00002521 const Stmt *S) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002522 // FIXME: Mark all temporaries in the current frame as destroyed at
2523 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00002524 switch (S->getStmtClass()) {
2525 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00002526 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002527 // Don't bother evaluating beyond an expression-statement which couldn't
2528 // be evaluated.
Richard Smith4e18ca52013-05-06 05:56:11 +00002529 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00002530 return ESR_Failed;
2531 return ESR_Succeeded;
2532 }
2533
2534 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00002535 return ESR_Failed;
2536
2537 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00002538 return ESR_Succeeded;
2539
Richard Smithd9f663b2013-04-22 15:31:51 +00002540 case Stmt::DeclStmtClass: {
2541 const DeclStmt *DS = cast<DeclStmt>(S);
2542 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
2543 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
2544 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
2545 return ESR_Failed;
2546 return ESR_Succeeded;
2547 }
2548
Richard Smith357362d2011-12-13 06:39:58 +00002549 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002550 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00002551 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002552 return ESR_Failed;
2553 return ESR_Returned;
2554 }
Richard Smith254a73d2011-10-28 22:34:42 +00002555
2556 case Stmt::CompoundStmtClass: {
2557 const CompoundStmt *CS = cast<CompoundStmt>(S);
2558 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2559 BE = CS->body_end(); BI != BE; ++BI) {
2560 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2561 if (ESR != ESR_Succeeded)
2562 return ESR;
2563 }
2564 return ESR_Succeeded;
2565 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002566
2567 case Stmt::IfStmtClass: {
2568 const IfStmt *IS = cast<IfStmt>(S);
2569
2570 // Evaluate the condition, as either a var decl or as an expression.
2571 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00002572 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00002573 return ESR_Failed;
2574
2575 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
2576 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
2577 if (ESR != ESR_Succeeded)
2578 return ESR;
2579 }
2580 return ESR_Succeeded;
2581 }
Richard Smith4e18ca52013-05-06 05:56:11 +00002582
2583 case Stmt::WhileStmtClass: {
2584 const WhileStmt *WS = cast<WhileStmt>(S);
2585 while (true) {
2586 bool Continue;
2587 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
2588 Continue))
2589 return ESR_Failed;
2590 if (!Continue)
2591 break;
2592
2593 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
2594 if (ESR != ESR_Continue)
2595 return ESR;
2596 }
2597 return ESR_Succeeded;
2598 }
2599
2600 case Stmt::DoStmtClass: {
2601 const DoStmt *DS = cast<DoStmt>(S);
2602 bool Continue;
2603 do {
2604 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody());
2605 if (ESR != ESR_Continue)
2606 return ESR;
2607
2608 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
2609 return ESR_Failed;
2610 } while (Continue);
2611 return ESR_Succeeded;
2612 }
2613
2614 case Stmt::ForStmtClass: {
2615 const ForStmt *FS = cast<ForStmt>(S);
2616 if (FS->getInit()) {
2617 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
2618 if (ESR != ESR_Succeeded)
2619 return ESR;
2620 }
2621 while (true) {
2622 bool Continue = true;
2623 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
2624 FS->getCond(), Continue))
2625 return ESR_Failed;
2626 if (!Continue)
2627 break;
2628
2629 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
2630 if (ESR != ESR_Continue)
2631 return ESR;
2632
2633 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
2634 return ESR_Failed;
2635 }
2636 return ESR_Succeeded;
2637 }
2638
Richard Smith896e0d72013-05-06 06:51:17 +00002639 case Stmt::CXXForRangeStmtClass: {
2640 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
2641
2642 // Initialize the __range variable.
2643 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
2644 if (ESR != ESR_Succeeded)
2645 return ESR;
2646
2647 // Create the __begin and __end iterators.
2648 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
2649 if (ESR != ESR_Succeeded)
2650 return ESR;
2651
2652 while (true) {
2653 // Condition: __begin != __end.
2654 bool Continue = true;
2655 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
2656 return ESR_Failed;
2657 if (!Continue)
2658 break;
2659
2660 // User's variable declaration, initialized by *__begin.
2661 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
2662 if (ESR != ESR_Succeeded)
2663 return ESR;
2664
2665 // Loop body.
2666 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
2667 if (ESR != ESR_Continue)
2668 return ESR;
2669
2670 // Increment: ++__begin
2671 if (!EvaluateIgnoredValue(Info, FS->getInc()))
2672 return ESR_Failed;
2673 }
2674
2675 return ESR_Succeeded;
2676 }
2677
Richard Smith4e18ca52013-05-06 05:56:11 +00002678 case Stmt::ContinueStmtClass:
2679 return ESR_Continue;
2680
2681 case Stmt::BreakStmtClass:
2682 return ESR_Break;
Richard Smith254a73d2011-10-28 22:34:42 +00002683 }
2684}
2685
Richard Smithcc36f692011-12-22 02:22:31 +00002686/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2687/// default constructor. If so, we'll fold it whether or not it's marked as
2688/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2689/// so we need special handling.
2690static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00002691 const CXXConstructorDecl *CD,
2692 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00002693 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2694 return false;
2695
Richard Smith66e05fe2012-01-18 05:21:49 +00002696 // Value-initialization does not call a trivial default constructor, so such a
2697 // call is a core constant expression whether or not the constructor is
2698 // constexpr.
2699 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002700 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00002701 // FIXME: If DiagDecl is an implicitly-declared special member function,
2702 // we should be much more explicit about why it's not constexpr.
2703 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2704 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2705 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00002706 } else {
2707 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2708 }
2709 }
2710 return true;
2711}
2712
Richard Smith357362d2011-12-13 06:39:58 +00002713/// CheckConstexprFunction - Check that a function can be called in a constant
2714/// expression.
2715static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2716 const FunctionDecl *Declaration,
2717 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00002718 // Potential constant expressions can contain calls to declared, but not yet
2719 // defined, constexpr functions.
2720 if (Info.CheckingPotentialConstantExpression && !Definition &&
2721 Declaration->isConstexpr())
2722 return false;
2723
Richard Smith357362d2011-12-13 06:39:58 +00002724 // Can we evaluate this function call?
2725 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2726 return true;
2727
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002728 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00002729 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002730 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2731 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00002732 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2733 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2734 << DiagDecl;
2735 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2736 } else {
2737 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2738 }
2739 return false;
2740}
2741
Richard Smithd62306a2011-11-10 06:34:14 +00002742namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00002743typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00002744}
2745
2746/// EvaluateArgs - Evaluate the arguments to a function call.
2747static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2748 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00002749 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002750 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00002751 I != E; ++I) {
2752 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2753 // If we're checking for a potential constant expression, evaluate all
2754 // initializers even if some of them fail.
2755 if (!Info.keepEvaluatingAfterFailure())
2756 return false;
2757 Success = false;
2758 }
2759 }
2760 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00002761}
2762
Richard Smith254a73d2011-10-28 22:34:42 +00002763/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00002764static bool HandleFunctionCall(SourceLocation CallLoc,
2765 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002766 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00002767 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002768 ArgVector ArgValues(Args.size());
2769 if (!EvaluateArgs(Args, ArgValues, Info))
2770 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00002771
Richard Smith253c2a32012-01-27 01:14:48 +00002772 if (!Info.CheckCallLimit(CallLoc))
2773 return false;
2774
2775 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd9f663b2013-04-22 15:31:51 +00002776 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00002777 if (ESR == ESR_Succeeded) {
2778 if (Callee->getResultType()->isVoidType())
2779 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002780 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00002781 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002782 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00002783}
2784
Richard Smithd62306a2011-11-10 06:34:14 +00002785/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00002786static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00002787 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00002788 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00002789 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002790 ArgVector ArgValues(Args.size());
2791 if (!EvaluateArgs(Args, ArgValues, Info))
2792 return false;
2793
Richard Smith253c2a32012-01-27 01:14:48 +00002794 if (!Info.CheckCallLimit(CallLoc))
2795 return false;
2796
Richard Smith3607ffe2012-02-13 03:54:03 +00002797 const CXXRecordDecl *RD = Definition->getParent();
2798 if (RD->getNumVBases()) {
2799 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2800 return false;
2801 }
2802
Richard Smith253c2a32012-01-27 01:14:48 +00002803 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00002804
2805 // If it's a delegating constructor, just delegate.
2806 if (Definition->isDelegatingConstructor()) {
2807 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00002808 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
2809 return false;
2810 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00002811 }
2812
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002813 // For a trivial copy or move constructor, perform an APValue copy. This is
2814 // essential for unions, where the operations performed by the constructor
2815 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002816 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00002817 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2818 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002819 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00002820 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00002821 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00002822 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002823 }
2824
2825 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00002826 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00002827 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2828 std::distance(RD->field_begin(), RD->field_end()));
2829
John McCalld7bca762012-05-01 00:38:49 +00002830 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002831 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2832
Richard Smith253c2a32012-01-27 01:14:48 +00002833 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002834 unsigned BasesSeen = 0;
2835#ifndef NDEBUG
2836 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2837#endif
2838 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2839 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00002840 LValue Subobject = This;
2841 APValue *Value = &Result;
2842
2843 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00002844 if ((*I)->isBaseInitializer()) {
2845 QualType BaseType((*I)->getBaseClass(), 0);
2846#ifndef NDEBUG
2847 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00002848 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00002849 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2850 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2851 "base class initializers not in expected order");
2852 ++BaseIt;
2853#endif
John McCalld7bca762012-05-01 00:38:49 +00002854 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2855 BaseType->getAsCXXRecordDecl(), &Layout))
2856 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00002857 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00002858 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00002859 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2860 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002861 if (RD->isUnion()) {
2862 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00002863 Value = &Result.getUnionValue();
2864 } else {
2865 Value = &Result.getStructField(FD->getFieldIndex());
2866 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00002867 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002868 // Walk the indirect field decl's chain to find the object to initialize,
2869 // and make sure we've initialized every step along it.
2870 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2871 CE = IFD->chain_end();
2872 C != CE; ++C) {
2873 FieldDecl *FD = cast<FieldDecl>(*C);
2874 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2875 // Switch the union field if it differs. This happens if we had
2876 // preceding zero-initialization, and we're now initializing a union
2877 // subobject other than the first.
2878 // FIXME: In this case, the values of the other subobjects are
2879 // specified, since zero-initialization sets all padding bits to zero.
2880 if (Value->isUninit() ||
2881 (Value->isUnion() && Value->getUnionField() != FD)) {
2882 if (CD->isUnion())
2883 *Value = APValue(FD);
2884 else
2885 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2886 std::distance(CD->field_begin(), CD->field_end()));
2887 }
John McCalld7bca762012-05-01 00:38:49 +00002888 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2889 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002890 if (CD->isUnion())
2891 Value = &Value->getUnionValue();
2892 else
2893 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00002894 }
Richard Smithd62306a2011-11-10 06:34:14 +00002895 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002896 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00002897 }
Richard Smith253c2a32012-01-27 01:14:48 +00002898
Richard Smithb228a862012-02-15 02:18:13 +00002899 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2900 (*I)->isBaseInitializer()
Richard Smith253c2a32012-01-27 01:14:48 +00002901 ? CCEK_Constant : CCEK_MemberInit)) {
2902 // If we're checking for a potential constant expression, evaluate all
2903 // initializers even if some of them fail.
2904 if (!Info.keepEvaluatingAfterFailure())
2905 return false;
2906 Success = false;
2907 }
Richard Smithd62306a2011-11-10 06:34:14 +00002908 }
2909
Richard Smithd9f663b2013-04-22 15:31:51 +00002910 return Success &&
2911 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00002912}
2913
Eli Friedman9a156e52008-11-12 09:44:48 +00002914//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00002915// Generic Evaluation
2916//===----------------------------------------------------------------------===//
2917namespace {
2918
Richard Smithf57d8cb2011-12-09 22:58:01 +00002919// FIXME: RetTy is always bool. Remove it.
2920template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00002921class ExprEvaluatorBase
2922 : public ConstStmtVisitor<Derived, RetTy> {
2923private:
Richard Smith2e312c82012-03-03 22:46:17 +00002924 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002925 return static_cast<Derived*>(this)->Success(V, E);
2926 }
Richard Smithfddd3842011-12-30 21:15:51 +00002927 RetTy DerivedZeroInitialization(const Expr *E) {
2928 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002929 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002930
Richard Smith17100ba2012-02-16 02:46:34 +00002931 // Check whether a conditional operator with a non-constant condition is a
2932 // potential constant expression. If neither arm is a potential constant
2933 // expression, then the conditional operator is not either.
2934 template<typename ConditionalOperator>
2935 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2936 assert(Info.CheckingPotentialConstantExpression);
2937
2938 // Speculatively evaluate both arms.
2939 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002940 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00002941 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2942
2943 StmtVisitorTy::Visit(E->getFalseExpr());
2944 if (Diag.empty())
2945 return;
2946
2947 Diag.clear();
2948 StmtVisitorTy::Visit(E->getTrueExpr());
2949 if (Diag.empty())
2950 return;
2951 }
2952
2953 Error(E, diag::note_constexpr_conditional_never_const);
2954 }
2955
2956
2957 template<typename ConditionalOperator>
2958 bool HandleConditionalOperator(const ConditionalOperator *E) {
2959 bool BoolResult;
2960 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2961 if (Info.CheckingPotentialConstantExpression)
2962 CheckPotentialConstantConditional(E);
2963 return false;
2964 }
2965
2966 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2967 return StmtVisitorTy::Visit(EvalExpr);
2968 }
2969
Peter Collingbournee9200682011-05-13 03:29:01 +00002970protected:
2971 EvalInfo &Info;
2972 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2973 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2974
Richard Smith92b1ce02011-12-12 09:28:41 +00002975 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002976 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002977 }
2978
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00002979 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2980
2981public:
2982 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2983
2984 EvalInfo &getEvalInfo() { return Info; }
2985
Richard Smithf57d8cb2011-12-09 22:58:01 +00002986 /// Report an evaluation error. This should only be called when an error is
2987 /// first discovered. When propagating an error, just return false.
2988 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002989 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002990 return false;
2991 }
2992 bool Error(const Expr *E) {
2993 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2994 }
2995
Peter Collingbournee9200682011-05-13 03:29:01 +00002996 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00002997 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00002998 }
2999 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003000 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003001 }
3002
3003 RetTy VisitParenExpr(const ParenExpr *E)
3004 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3005 RetTy VisitUnaryExtension(const UnaryOperator *E)
3006 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3007 RetTy VisitUnaryPlus(const UnaryOperator *E)
3008 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3009 RetTy VisitChooseExpr(const ChooseExpr *E)
3010 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
3011 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3012 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003013 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3014 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003015 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3016 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003017 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3018 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003019 // We cannot create any objects for which cleanups are required, so there is
3020 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3021 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3022 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003023
Richard Smith6d6ecc32011-12-12 12:46:16 +00003024 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3025 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3026 return static_cast<Derived*>(this)->VisitCastExpr(E);
3027 }
3028 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3029 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3030 return static_cast<Derived*>(this)->VisitCastExpr(E);
3031 }
3032
Richard Smith027bf112011-11-17 22:56:20 +00003033 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3034 switch (E->getOpcode()) {
3035 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003036 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003037
3038 case BO_Comma:
3039 VisitIgnoredValue(E->getLHS());
3040 return StmtVisitorTy::Visit(E->getRHS());
3041
3042 case BO_PtrMemD:
3043 case BO_PtrMemI: {
3044 LValue Obj;
3045 if (!HandleMemberPointerAccess(Info, E, Obj))
3046 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003047 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003048 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003049 return false;
3050 return DerivedSuccess(Result, E);
3051 }
3052 }
3053 }
3054
Peter Collingbournee9200682011-05-13 03:29:01 +00003055 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003056 // Evaluate and cache the common expression. We treat it as a temporary,
3057 // even though it's not quite the same thing.
3058 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3059 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003060 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003061
Richard Smith17100ba2012-02-16 02:46:34 +00003062 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003063 }
3064
3065 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003066 bool IsBcpCall = false;
3067 // If the condition (ignoring parens) is a __builtin_constant_p call,
3068 // the result is a constant expression if it can be folded without
3069 // side-effects. This is an important GNU extension. See GCC PR38377
3070 // for discussion.
3071 if (const CallExpr *CallCE =
3072 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3073 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3074 IsBcpCall = true;
3075
3076 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3077 // constant expression; we can't check whether it's potentially foldable.
3078 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3079 return false;
3080
3081 FoldConstant Fold(Info);
3082
Richard Smith17100ba2012-02-16 02:46:34 +00003083 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003084 return false;
3085
3086 if (IsBcpCall)
3087 Fold.Fold(Info);
3088
3089 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003090 }
3091
3092 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003093 APValue &Value = Info.CurrentCall->Temporaries[E];
3094 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003095 const Expr *Source = E->getSourceExpr();
3096 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003097 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003098 if (Source == E) { // sanity checking.
3099 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003100 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003101 }
3102 return StmtVisitorTy::Visit(Source);
3103 }
Richard Smith26d4cc12012-06-26 08:12:11 +00003104 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003105 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003106
Richard Smith254a73d2011-10-28 22:34:42 +00003107 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003108 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003109 QualType CalleeType = Callee->getType();
3110
Richard Smith254a73d2011-10-28 22:34:42 +00003111 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003112 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003113 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003114 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003115
Richard Smithe97cbd72011-11-11 04:05:33 +00003116 // Extract function decl and 'this' pointer from the callee.
3117 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003118 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003119 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3120 // Explicit bound member calls, such as x.f() or p->g();
3121 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003122 return false;
3123 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003124 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003125 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003126 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3127 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003128 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3129 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003130 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003131 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003132 return Error(Callee);
3133
3134 FD = dyn_cast<FunctionDecl>(Member);
3135 if (!FD)
3136 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003137 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003138 LValue Call;
3139 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003140 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003141
Richard Smitha8105bc2012-01-06 16:39:00 +00003142 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003143 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003144 FD = dyn_cast_or_null<FunctionDecl>(
3145 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003146 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003147 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003148
3149 // Overloaded operator calls to member functions are represented as normal
3150 // calls with '*this' as the first argument.
3151 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3152 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003153 // FIXME: When selecting an implicit conversion for an overloaded
3154 // operator delete, we sometimes try to evaluate calls to conversion
3155 // operators without a 'this' parameter!
3156 if (Args.empty())
3157 return Error(E);
3158
Richard Smithe97cbd72011-11-11 04:05:33 +00003159 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3160 return false;
3161 This = &ThisVal;
3162 Args = Args.slice(1);
3163 }
3164
3165 // Don't call function pointers which have been cast to some other type.
3166 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003167 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003168 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003169 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003170
Richard Smith47b34932012-02-01 02:39:43 +00003171 if (This && !This->checkSubobject(Info, E, CSK_This))
3172 return false;
3173
Richard Smith3607ffe2012-02-13 03:54:03 +00003174 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3175 // calls to such functions in constant expressions.
3176 if (This && !HasQualifier &&
3177 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3178 return Error(E, diag::note_constexpr_virtual_call);
3179
Richard Smith357362d2011-12-13 06:39:58 +00003180 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003181 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003182 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003183
Richard Smith357362d2011-12-13 06:39:58 +00003184 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003185 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3186 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003187 return false;
3188
Richard Smithb228a862012-02-15 02:18:13 +00003189 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003190 }
3191
Richard Smith11562c52011-10-28 17:51:58 +00003192 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3193 return StmtVisitorTy::Visit(E->getInitializer());
3194 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003195 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003196 if (E->getNumInits() == 0)
3197 return DerivedZeroInitialization(E);
3198 if (E->getNumInits() == 1)
3199 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003200 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003201 }
3202 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003203 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003204 }
3205 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003206 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003207 }
Richard Smith027bf112011-11-17 22:56:20 +00003208 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003209 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003210 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003211
Richard Smithd62306a2011-11-10 06:34:14 +00003212 /// A member expression where the object is a prvalue is itself a prvalue.
3213 RetTy VisitMemberExpr(const MemberExpr *E) {
3214 assert(!E->isArrow() && "missing call to bound member function?");
3215
Richard Smith2e312c82012-03-03 22:46:17 +00003216 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003217 if (!Evaluate(Val, Info, E->getBase()))
3218 return false;
3219
3220 QualType BaseTy = E->getBase()->getType();
3221
3222 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003223 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003224 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003225 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003226 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3227
Richard Smith3229b742013-05-05 21:17:10 +00003228 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003229 SubobjectDesignator Designator(BaseTy);
3230 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003231
Richard Smith3229b742013-05-05 21:17:10 +00003232 APValue Result;
3233 return extractSubobject(Info, E, Obj, Designator, Result) &&
3234 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003235 }
3236
Richard Smith11562c52011-10-28 17:51:58 +00003237 RetTy VisitCastExpr(const CastExpr *E) {
3238 switch (E->getCastKind()) {
3239 default:
3240 break;
3241
David Chisnallfa35df62012-01-16 17:27:18 +00003242 case CK_AtomicToNonAtomic:
3243 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00003244 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003245 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003246 return StmtVisitorTy::Visit(E->getSubExpr());
3247
3248 case CK_LValueToRValue: {
3249 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003250 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3251 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003252 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003253 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003254 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003255 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003256 return false;
3257 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003258 }
3259 }
3260
Richard Smithf57d8cb2011-12-09 22:58:01 +00003261 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003262 }
3263
Richard Smith243ef902013-05-05 23:31:59 +00003264 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3265 return VisitUnaryPostIncDec(UO);
3266 }
3267 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3268 return VisitUnaryPostIncDec(UO);
3269 }
3270 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3271 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3272 return Error(UO);
3273
3274 LValue LVal;
3275 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3276 return false;
3277 APValue RVal;
3278 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3279 UO->isIncrementOp(), &RVal))
3280 return false;
3281 return DerivedSuccess(RVal, UO);
3282 }
3283
Richard Smith4a678122011-10-24 18:44:57 +00003284 /// Visit a value which is evaluated, but whose value is ignored.
3285 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003286 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003287 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003288};
3289
3290}
3291
3292//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003293// Common base class for lvalue and temporary evaluation.
3294//===----------------------------------------------------------------------===//
3295namespace {
3296template<class Derived>
3297class LValueExprEvaluatorBase
3298 : public ExprEvaluatorBase<Derived, bool> {
3299protected:
3300 LValue &Result;
3301 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3302 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3303
3304 bool Success(APValue::LValueBase B) {
3305 Result.set(B);
3306 return true;
3307 }
3308
3309public:
3310 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3311 ExprEvaluatorBaseTy(Info), Result(Result) {}
3312
Richard Smith2e312c82012-03-03 22:46:17 +00003313 bool Success(const APValue &V, const Expr *E) {
3314 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003315 return true;
3316 }
Richard Smith027bf112011-11-17 22:56:20 +00003317
Richard Smith027bf112011-11-17 22:56:20 +00003318 bool VisitMemberExpr(const MemberExpr *E) {
3319 // Handle non-static data members.
3320 QualType BaseTy;
3321 if (E->isArrow()) {
3322 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3323 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003324 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003325 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003326 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003327 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3328 return false;
3329 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003330 } else {
3331 if (!this->Visit(E->getBase()))
3332 return false;
3333 BaseTy = E->getBase()->getType();
3334 }
Richard Smith027bf112011-11-17 22:56:20 +00003335
Richard Smith1b78b3d2012-01-25 22:15:11 +00003336 const ValueDecl *MD = E->getMemberDecl();
3337 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3338 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3339 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3340 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003341 if (!HandleLValueMember(this->Info, E, Result, FD))
3342 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003343 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003344 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3345 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003346 } else
3347 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003348
Richard Smith1b78b3d2012-01-25 22:15:11 +00003349 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003350 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003351 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003352 RefValue))
3353 return false;
3354 return Success(RefValue, E);
3355 }
3356 return true;
3357 }
3358
3359 bool VisitBinaryOperator(const BinaryOperator *E) {
3360 switch (E->getOpcode()) {
3361 default:
3362 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3363
3364 case BO_PtrMemD:
3365 case BO_PtrMemI:
3366 return HandleMemberPointerAccess(this->Info, E, Result);
3367 }
3368 }
3369
3370 bool VisitCastExpr(const CastExpr *E) {
3371 switch (E->getCastKind()) {
3372 default:
3373 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3374
3375 case CK_DerivedToBase:
3376 case CK_UncheckedDerivedToBase: {
3377 if (!this->Visit(E->getSubExpr()))
3378 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003379
3380 // Now figure out the necessary offset to add to the base LV to get from
3381 // the derived class to the base class.
3382 QualType Type = E->getSubExpr()->getType();
3383
3384 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3385 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003386 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00003387 *PathI))
3388 return false;
3389 Type = (*PathI)->getType();
3390 }
3391
3392 return true;
3393 }
3394 }
3395 }
3396};
3397}
3398
3399//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003400// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003401//
3402// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3403// function designators (in C), decl references to void objects (in C), and
3404// temporaries (if building with -Wno-address-of-temporary).
3405//
3406// LValue evaluation produces values comprising a base expression of one of the
3407// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003408// - Declarations
3409// * VarDecl
3410// * FunctionDecl
3411// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003412// * CompoundLiteralExpr in C
3413// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003414// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003415// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003416// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003417// * ObjCEncodeExpr
3418// * AddrLabelExpr
3419// * BlockExpr
3420// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003421// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00003422// * Any Expr, with a CallIndex indicating the function in which the temporary
3423// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00003424// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003425//===----------------------------------------------------------------------===//
3426namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003427class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003428 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003429public:
Richard Smith027bf112011-11-17 22:56:20 +00003430 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3431 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003432
Richard Smith11562c52011-10-28 17:51:58 +00003433 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00003434 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00003435
Peter Collingbournee9200682011-05-13 03:29:01 +00003436 bool VisitDeclRefExpr(const DeclRefExpr *E);
3437 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003438 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003439 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3440 bool VisitMemberExpr(const MemberExpr *E);
3441 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3442 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00003443 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00003444 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003445 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3446 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00003447 bool VisitUnaryReal(const UnaryOperator *E);
3448 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00003449 bool VisitUnaryPreInc(const UnaryOperator *UO) {
3450 return VisitUnaryPreIncDec(UO);
3451 }
3452 bool VisitUnaryPreDec(const UnaryOperator *UO) {
3453 return VisitUnaryPreIncDec(UO);
3454 }
Richard Smith3229b742013-05-05 21:17:10 +00003455 bool VisitBinAssign(const BinaryOperator *BO);
3456 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00003457
Peter Collingbournee9200682011-05-13 03:29:01 +00003458 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00003459 switch (E->getCastKind()) {
3460 default:
Richard Smith027bf112011-11-17 22:56:20 +00003461 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003462
Eli Friedmance3e02a2011-10-11 00:13:24 +00003463 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00003464 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00003465 if (!Visit(E->getSubExpr()))
3466 return false;
3467 Result.Designator.setInvalid();
3468 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00003469
Richard Smith027bf112011-11-17 22:56:20 +00003470 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00003471 if (!Visit(E->getSubExpr()))
3472 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003473 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00003474 }
3475 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003476};
3477} // end anonymous namespace
3478
Richard Smith11562c52011-10-28 17:51:58 +00003479/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00003480/// expressions which are not glvalues, in two cases:
3481/// * function designators in C, and
3482/// * "extern void" objects
3483static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
3484 assert(E->isGLValue() || E->getType()->isFunctionType() ||
3485 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003486 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003487}
3488
Peter Collingbournee9200682011-05-13 03:29:01 +00003489bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003490 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
3491 return Success(FD);
3492 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00003493 return VisitVarDecl(E, VD);
3494 return Error(E);
3495}
Richard Smith733237d2011-10-24 23:14:33 +00003496
Richard Smith11562c52011-10-28 17:51:58 +00003497bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00003498 CallStackFrame *Frame = 0;
3499 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
3500 Frame = Info.CurrentCall;
3501
Richard Smithfec09922011-11-01 16:57:24 +00003502 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00003503 if (Frame) {
3504 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00003505 return true;
3506 }
Richard Smithce40ad62011-11-12 22:28:03 +00003507 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00003508 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00003509
Richard Smith3229b742013-05-05 21:17:10 +00003510 APValue *V;
3511 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003512 return false;
Richard Smith3229b742013-05-05 21:17:10 +00003513 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00003514}
3515
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003516bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3517 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00003518 if (E->getType()->isRecordType())
3519 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00003520
Richard Smithb228a862012-02-15 02:18:13 +00003521 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00003522 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3523 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003524}
3525
Peter Collingbournee9200682011-05-13 03:29:01 +00003526bool
3527LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003528 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3529 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3530 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00003531 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003532}
3533
Richard Smith6e525142011-12-27 12:18:28 +00003534bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00003535 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00003536 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00003537
3538 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
3539 << E->getExprOperand()->getType()
3540 << E->getExprOperand()->getSourceRange();
3541 return false;
Richard Smith6e525142011-12-27 12:18:28 +00003542}
3543
Francois Pichet0066db92012-04-16 04:08:35 +00003544bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3545 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00003546}
Francois Pichet0066db92012-04-16 04:08:35 +00003547
Peter Collingbournee9200682011-05-13 03:29:01 +00003548bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003549 // Handle static data members.
3550 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3551 VisitIgnoredValue(E->getBase());
3552 return VisitVarDecl(E, VD);
3553 }
3554
Richard Smith254a73d2011-10-28 22:34:42 +00003555 // Handle static member functions.
3556 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3557 if (MD->isStatic()) {
3558 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00003559 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00003560 }
3561 }
3562
Richard Smithd62306a2011-11-10 06:34:14 +00003563 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00003564 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003565}
3566
Peter Collingbournee9200682011-05-13 03:29:01 +00003567bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003568 // FIXME: Deal with vectors as array subscript bases.
3569 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003570 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003571
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003572 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00003573 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003574
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003575 APSInt Index;
3576 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00003577 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003578 int64_t IndexValue
3579 = Index.isSigned() ? Index.getSExtValue()
3580 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003581
Richard Smitha8105bc2012-01-06 16:39:00 +00003582 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003583}
Eli Friedman9a156e52008-11-12 09:44:48 +00003584
Peter Collingbournee9200682011-05-13 03:29:01 +00003585bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00003586 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00003587}
3588
Richard Smith66c96992012-02-18 22:04:06 +00003589bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3590 if (!Visit(E->getSubExpr()))
3591 return false;
3592 // __real is a no-op on scalar lvalues.
3593 if (E->getSubExpr()->getType()->isAnyComplexType())
3594 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3595 return true;
3596}
3597
3598bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3599 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3600 "lvalue __imag__ on scalar?");
3601 if (!Visit(E->getSubExpr()))
3602 return false;
3603 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3604 return true;
3605}
3606
Richard Smith243ef902013-05-05 23:31:59 +00003607bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
3608 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00003609 return Error(UO);
3610
3611 if (!this->Visit(UO->getSubExpr()))
3612 return false;
3613
Richard Smith243ef902013-05-05 23:31:59 +00003614 return handleIncDec(
3615 this->Info, UO, Result, UO->getSubExpr()->getType(),
3616 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00003617}
3618
3619bool LValueExprEvaluator::VisitCompoundAssignOperator(
3620 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00003621 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00003622 return Error(CAO);
3623
Richard Smith3229b742013-05-05 21:17:10 +00003624 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00003625
3626 // The overall lvalue result is the result of evaluating the LHS.
3627 if (!this->Visit(CAO->getLHS())) {
3628 if (Info.keepEvaluatingAfterFailure())
3629 Evaluate(RHS, this->Info, CAO->getRHS());
3630 return false;
3631 }
3632
Richard Smith3229b742013-05-05 21:17:10 +00003633 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
3634 return false;
3635
3636 // FIXME:
3637 //return handleCompoundAssignment(
3638 // this->Info, CAO,
3639 // Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
3640 // RHS, CAO->getRHS()->getType(),
3641 // CAO->getOpForCompoundAssignment(CAO->getOpcode()),
3642 // CAO->getComputationResultType());
3643 return Error(CAO);
3644}
3645
3646bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00003647 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3648 return Error(E);
3649
Richard Smith3229b742013-05-05 21:17:10 +00003650 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00003651
3652 if (!this->Visit(E->getLHS())) {
3653 if (Info.keepEvaluatingAfterFailure())
3654 Evaluate(NewVal, this->Info, E->getRHS());
3655 return false;
3656 }
3657
Richard Smith3229b742013-05-05 21:17:10 +00003658 if (!Evaluate(NewVal, this->Info, E->getRHS()))
3659 return false;
Richard Smith243ef902013-05-05 23:31:59 +00003660
3661 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00003662 NewVal);
3663}
3664
Eli Friedman9a156e52008-11-12 09:44:48 +00003665//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003666// Pointer Evaluation
3667//===----------------------------------------------------------------------===//
3668
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003669namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003670class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003671 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00003672 LValue &Result;
3673
Peter Collingbournee9200682011-05-13 03:29:01 +00003674 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003675 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00003676 return true;
3677 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003678public:
Mike Stump11289f42009-09-09 15:08:12 +00003679
John McCall45d55e42010-05-07 21:00:08 +00003680 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003681 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003682
Richard Smith2e312c82012-03-03 22:46:17 +00003683 bool Success(const APValue &V, const Expr *E) {
3684 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00003685 return true;
3686 }
Richard Smithfddd3842011-12-30 21:15:51 +00003687 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00003688 return Success((Expr*)0);
3689 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003690
John McCall45d55e42010-05-07 21:00:08 +00003691 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003692 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00003693 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003694 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00003695 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00003696 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00003697 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003698 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00003699 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003700 bool VisitCallExpr(const CallExpr *E);
3701 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00003702 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00003703 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003704 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00003705 }
Richard Smithd62306a2011-11-10 06:34:14 +00003706 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3707 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003708 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003709 Result = *Info.CurrentCall->This;
3710 return true;
3711 }
John McCallc07a0c72011-02-17 10:25:35 +00003712
Eli Friedman449fe542009-03-23 04:56:01 +00003713 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003714};
Chris Lattner05706e882008-07-11 18:11:29 +00003715} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003716
John McCall45d55e42010-05-07 21:00:08 +00003717static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003718 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00003719 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00003720}
3721
John McCall45d55e42010-05-07 21:00:08 +00003722bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003723 if (E->getOpcode() != BO_Add &&
3724 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00003725 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00003726
Chris Lattner05706e882008-07-11 18:11:29 +00003727 const Expr *PExp = E->getLHS();
3728 const Expr *IExp = E->getRHS();
3729 if (IExp->getType()->isPointerType())
3730 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00003731
Richard Smith253c2a32012-01-27 01:14:48 +00003732 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3733 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00003734 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003735
John McCall45d55e42010-05-07 21:00:08 +00003736 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00003737 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00003738 return false;
3739 int64_t AdditionalOffset
3740 = Offset.isSigned() ? Offset.getSExtValue()
3741 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00003742 if (E->getOpcode() == BO_Sub)
3743 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00003744
Ted Kremenek28831752012-08-23 20:46:57 +00003745 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00003746 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3747 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00003748}
Eli Friedman9a156e52008-11-12 09:44:48 +00003749
John McCall45d55e42010-05-07 21:00:08 +00003750bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3751 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003752}
Mike Stump11289f42009-09-09 15:08:12 +00003753
Peter Collingbournee9200682011-05-13 03:29:01 +00003754bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3755 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00003756
Eli Friedman847a2bc2009-12-27 05:43:15 +00003757 switch (E->getCastKind()) {
3758 default:
3759 break;
3760
John McCalle3027922010-08-25 11:45:40 +00003761 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003762 case CK_CPointerToObjCPointerCast:
3763 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00003764 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00003765 if (!Visit(SubExpr))
3766 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00003767 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3768 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3769 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00003770 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00003771 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00003772 if (SubExpr->getType()->isVoidPointerType())
3773 CCEDiag(E, diag::note_constexpr_invalid_cast)
3774 << 3 << SubExpr->getType();
3775 else
3776 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3777 }
Richard Smith96e0c102011-11-04 02:25:55 +00003778 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00003779
Anders Carlsson18275092010-10-31 20:41:46 +00003780 case CK_DerivedToBase:
3781 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003782 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00003783 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003784 if (!Result.Base && Result.Offset.isZero())
3785 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00003786
Richard Smithd62306a2011-11-10 06:34:14 +00003787 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00003788 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00003789 QualType Type =
3790 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00003791
Richard Smithd62306a2011-11-10 06:34:14 +00003792 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00003793 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003794 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3795 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00003796 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003797 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00003798 }
3799
Anders Carlsson18275092010-10-31 20:41:46 +00003800 return true;
3801 }
3802
Richard Smith027bf112011-11-17 22:56:20 +00003803 case CK_BaseToDerived:
3804 if (!Visit(E->getSubExpr()))
3805 return false;
3806 if (!Result.Base && Result.Offset.isZero())
3807 return true;
3808 return HandleBaseToDerivedCast(Info, E, Result);
3809
Richard Smith0b0a0b62011-10-29 20:57:55 +00003810 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003811 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003812 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00003813
John McCalle3027922010-08-25 11:45:40 +00003814 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003815 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3816
Richard Smith2e312c82012-03-03 22:46:17 +00003817 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00003818 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00003819 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00003820
John McCall45d55e42010-05-07 21:00:08 +00003821 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003822 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3823 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00003824 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003825 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00003826 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00003827 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00003828 return true;
3829 } else {
3830 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00003831 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00003832 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00003833 }
3834 }
John McCalle3027922010-08-25 11:45:40 +00003835 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00003836 if (SubExpr->isGLValue()) {
3837 if (!EvaluateLValue(SubExpr, Result, Info))
3838 return false;
3839 } else {
Richard Smithb228a862012-02-15 02:18:13 +00003840 Result.set(SubExpr, Info.CurrentCall->Index);
3841 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3842 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00003843 return false;
3844 }
Richard Smith96e0c102011-11-04 02:25:55 +00003845 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00003846 if (const ConstantArrayType *CAT
3847 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3848 Result.addArray(Info, E, CAT);
3849 else
3850 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00003851 return true;
Richard Smithdd785442011-10-31 20:57:44 +00003852
John McCalle3027922010-08-25 11:45:40 +00003853 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00003854 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003855 }
3856
Richard Smith11562c52011-10-28 17:51:58 +00003857 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00003858}
Chris Lattner05706e882008-07-11 18:11:29 +00003859
Peter Collingbournee9200682011-05-13 03:29:01 +00003860bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003861 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00003862 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00003863
Peter Collingbournee9200682011-05-13 03:29:01 +00003864 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003865}
Chris Lattner05706e882008-07-11 18:11:29 +00003866
3867//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003868// Member Pointer Evaluation
3869//===----------------------------------------------------------------------===//
3870
3871namespace {
3872class MemberPointerExprEvaluator
3873 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3874 MemberPtr &Result;
3875
3876 bool Success(const ValueDecl *D) {
3877 Result = MemberPtr(D);
3878 return true;
3879 }
3880public:
3881
3882 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3883 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3884
Richard Smith2e312c82012-03-03 22:46:17 +00003885 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003886 Result.setFrom(V);
3887 return true;
3888 }
Richard Smithfddd3842011-12-30 21:15:51 +00003889 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003890 return Success((const ValueDecl*)0);
3891 }
3892
3893 bool VisitCastExpr(const CastExpr *E);
3894 bool VisitUnaryAddrOf(const UnaryOperator *E);
3895};
3896} // end anonymous namespace
3897
3898static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3899 EvalInfo &Info) {
3900 assert(E->isRValue() && E->getType()->isMemberPointerType());
3901 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3902}
3903
3904bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3905 switch (E->getCastKind()) {
3906 default:
3907 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3908
3909 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003910 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003911 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003912
3913 case CK_BaseToDerivedMemberPointer: {
3914 if (!Visit(E->getSubExpr()))
3915 return false;
3916 if (E->path_empty())
3917 return true;
3918 // Base-to-derived member pointer casts store the path in derived-to-base
3919 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3920 // the wrong end of the derived->base arc, so stagger the path by one class.
3921 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3922 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3923 PathI != PathE; ++PathI) {
3924 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3925 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3926 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003927 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003928 }
3929 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3930 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003931 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003932 return true;
3933 }
3934
3935 case CK_DerivedToBaseMemberPointer:
3936 if (!Visit(E->getSubExpr()))
3937 return false;
3938 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3939 PathE = E->path_end(); PathI != PathE; ++PathI) {
3940 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3941 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3942 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003943 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003944 }
3945 return true;
3946 }
3947}
3948
3949bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3950 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3951 // member can be formed.
3952 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3953}
3954
3955//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00003956// Record Evaluation
3957//===----------------------------------------------------------------------===//
3958
3959namespace {
3960 class RecordExprEvaluator
3961 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3962 const LValue &This;
3963 APValue &Result;
3964 public:
3965
3966 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3967 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3968
Richard Smith2e312c82012-03-03 22:46:17 +00003969 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003970 Result = V;
3971 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00003972 }
Richard Smithfddd3842011-12-30 21:15:51 +00003973 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003974
Richard Smithe97cbd72011-11-11 04:05:33 +00003975 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003976 bool VisitInitListExpr(const InitListExpr *E);
3977 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3978 };
3979}
3980
Richard Smithfddd3842011-12-30 21:15:51 +00003981/// Perform zero-initialization on an object of non-union class type.
3982/// C++11 [dcl.init]p5:
3983/// To zero-initialize an object or reference of type T means:
3984/// [...]
3985/// -- if T is a (possibly cv-qualified) non-union class type,
3986/// each non-static data member and each base-class subobject is
3987/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00003988static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3989 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00003990 const LValue &This, APValue &Result) {
3991 assert(!RD->isUnion() && "Expected non-union class type");
3992 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3993 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3994 std::distance(RD->field_begin(), RD->field_end()));
3995
John McCalld7bca762012-05-01 00:38:49 +00003996 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003997 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3998
3999 if (CD) {
4000 unsigned Index = 0;
4001 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004002 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004003 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4004 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004005 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4006 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004007 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004008 Result.getStructBase(Index)))
4009 return false;
4010 }
4011 }
4012
Richard Smitha8105bc2012-01-06 16:39:00 +00004013 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4014 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004015 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004016 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004017 continue;
4018
4019 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004020 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004021 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004022
David Blaikie2d7c57e2012-04-30 02:36:29 +00004023 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004024 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004025 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004026 return false;
4027 }
4028
4029 return true;
4030}
4031
4032bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4033 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004034 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004035 if (RD->isUnion()) {
4036 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4037 // object's first non-static named data member is zero-initialized
4038 RecordDecl::field_iterator I = RD->field_begin();
4039 if (I == RD->field_end()) {
4040 Result = APValue((const FieldDecl*)0);
4041 return true;
4042 }
4043
4044 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004045 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004046 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004047 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004048 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004049 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004050 }
4051
Richard Smith5d108602012-02-17 00:44:16 +00004052 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004053 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004054 return false;
4055 }
4056
Richard Smitha8105bc2012-01-06 16:39:00 +00004057 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004058}
4059
Richard Smithe97cbd72011-11-11 04:05:33 +00004060bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4061 switch (E->getCastKind()) {
4062 default:
4063 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4064
4065 case CK_ConstructorConversion:
4066 return Visit(E->getSubExpr());
4067
4068 case CK_DerivedToBase:
4069 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004070 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004071 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004072 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004073 if (!DerivedObject.isStruct())
4074 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004075
4076 // Derived-to-base rvalue conversion: just slice off the derived part.
4077 APValue *Value = &DerivedObject;
4078 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4079 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4080 PathE = E->path_end(); PathI != PathE; ++PathI) {
4081 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4082 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4083 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4084 RD = Base;
4085 }
4086 Result = *Value;
4087 return true;
4088 }
4089 }
4090}
4091
Richard Smithd62306a2011-11-10 06:34:14 +00004092bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00004093 // Cannot constant-evaluate std::initializer_list inits.
4094 if (E->initializesStdInitializerList())
4095 return false;
4096
Richard Smithd62306a2011-11-10 06:34:14 +00004097 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004098 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004099 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4100
4101 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004102 const FieldDecl *Field = E->getInitializedFieldInUnion();
4103 Result = APValue(Field);
4104 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004105 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004106
4107 // If the initializer list for a union does not contain any elements, the
4108 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004109 // FIXME: The element should be initialized from an initializer list.
4110 // Is this difference ever observable for initializer lists which
4111 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004112 ImplicitValueInitExpr VIE(Field->getType());
4113 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4114
Richard Smithd62306a2011-11-10 06:34:14 +00004115 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004116 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4117 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004118
4119 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4120 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4121 isa<CXXDefaultInitExpr>(InitExpr));
4122
Richard Smithb228a862012-02-15 02:18:13 +00004123 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004124 }
4125
4126 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4127 "initializer list for class with base classes");
4128 Result = APValue(APValue::UninitStruct(), 0,
4129 std::distance(RD->field_begin(), RD->field_end()));
4130 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004131 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004132 for (RecordDecl::field_iterator Field = RD->field_begin(),
4133 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4134 // Anonymous bit-fields are not considered members of the class for
4135 // purposes of aggregate initialization.
4136 if (Field->isUnnamedBitfield())
4137 continue;
4138
4139 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004140
Richard Smith253c2a32012-01-27 01:14:48 +00004141 bool HaveInit = ElementNo < E->getNumInits();
4142
4143 // FIXME: Diagnostics here should point to the end of the initializer
4144 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004145 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004146 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004147 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004148
4149 // Perform an implicit value-initialization for members beyond the end of
4150 // the initializer list.
4151 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004152 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004153
Richard Smith852c9db2013-04-20 22:23:05 +00004154 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4155 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4156 isa<CXXDefaultInitExpr>(Init));
4157
4158 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4159 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004160 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004161 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004162 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004163 }
4164 }
4165
Richard Smith253c2a32012-01-27 01:14:48 +00004166 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004167}
4168
4169bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4170 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004171 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4172
Richard Smithfddd3842011-12-30 21:15:51 +00004173 bool ZeroInit = E->requiresZeroInitialization();
4174 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004175 // If we've already performed zero-initialization, we're already done.
4176 if (!Result.isUninit())
4177 return true;
4178
Richard Smithfddd3842011-12-30 21:15:51 +00004179 if (ZeroInit)
4180 return ZeroInitialization(E);
4181
Richard Smithcc36f692011-12-22 02:22:31 +00004182 const CXXRecordDecl *RD = FD->getParent();
4183 if (RD->isUnion())
4184 Result = APValue((FieldDecl*)0);
4185 else
4186 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4187 std::distance(RD->field_begin(), RD->field_end()));
4188 return true;
4189 }
4190
Richard Smithd62306a2011-11-10 06:34:14 +00004191 const FunctionDecl *Definition = 0;
4192 FD->getBody(Definition);
4193
Richard Smith357362d2011-12-13 06:39:58 +00004194 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4195 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004196
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004197 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004198 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004199 if (const MaterializeTemporaryExpr *ME
4200 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4201 return Visit(ME->GetTemporaryExpr());
4202
Richard Smithfddd3842011-12-30 21:15:51 +00004203 if (ZeroInit && !ZeroInitialization(E))
4204 return false;
4205
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004206 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004207 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004208 cast<CXXConstructorDecl>(Definition), Info,
4209 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004210}
4211
4212static bool EvaluateRecord(const Expr *E, const LValue &This,
4213 APValue &Result, EvalInfo &Info) {
4214 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004215 "can't evaluate expression as a record rvalue");
4216 return RecordExprEvaluator(Info, This, Result).Visit(E);
4217}
4218
4219//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004220// Temporary Evaluation
4221//
4222// Temporaries are represented in the AST as rvalues, but generally behave like
4223// lvalues. The full-object of which the temporary is a subobject is implicitly
4224// materialized so that a reference can bind to it.
4225//===----------------------------------------------------------------------===//
4226namespace {
4227class TemporaryExprEvaluator
4228 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4229public:
4230 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4231 LValueExprEvaluatorBaseTy(Info, Result) {}
4232
4233 /// Visit an expression which constructs the value of this temporary.
4234 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004235 Result.set(E, Info.CurrentCall->Index);
4236 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004237 }
4238
4239 bool VisitCastExpr(const CastExpr *E) {
4240 switch (E->getCastKind()) {
4241 default:
4242 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4243
4244 case CK_ConstructorConversion:
4245 return VisitConstructExpr(E->getSubExpr());
4246 }
4247 }
4248 bool VisitInitListExpr(const InitListExpr *E) {
4249 return VisitConstructExpr(E);
4250 }
4251 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4252 return VisitConstructExpr(E);
4253 }
4254 bool VisitCallExpr(const CallExpr *E) {
4255 return VisitConstructExpr(E);
4256 }
4257};
4258} // end anonymous namespace
4259
4260/// Evaluate an expression of record type as a temporary.
4261static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004262 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004263 return TemporaryExprEvaluator(Info, Result).Visit(E);
4264}
4265
4266//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004267// Vector Evaluation
4268//===----------------------------------------------------------------------===//
4269
4270namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004271 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004272 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4273 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004274 public:
Mike Stump11289f42009-09-09 15:08:12 +00004275
Richard Smith2d406342011-10-22 21:10:00 +00004276 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4277 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004278
Richard Smith2d406342011-10-22 21:10:00 +00004279 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4280 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4281 // FIXME: remove this APValue copy.
4282 Result = APValue(V.data(), V.size());
4283 return true;
4284 }
Richard Smith2e312c82012-03-03 22:46:17 +00004285 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004286 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004287 Result = V;
4288 return true;
4289 }
Richard Smithfddd3842011-12-30 21:15:51 +00004290 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004291
Richard Smith2d406342011-10-22 21:10:00 +00004292 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00004293 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00004294 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00004295 bool VisitInitListExpr(const InitListExpr *E);
4296 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004297 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00004298 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00004299 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004300 };
4301} // end anonymous namespace
4302
4303static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004304 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00004305 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004306}
4307
Richard Smith2d406342011-10-22 21:10:00 +00004308bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
4309 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004310 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004311
Richard Smith161f09a2011-12-06 22:44:34 +00004312 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00004313 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004314
Eli Friedmanc757de22011-03-25 00:43:55 +00004315 switch (E->getCastKind()) {
4316 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00004317 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00004318 if (SETy->isIntegerType()) {
4319 APSInt IntResult;
4320 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004321 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004322 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00004323 } else if (SETy->isRealFloatingType()) {
4324 APFloat F(0.0);
4325 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004326 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004327 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004328 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004329 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004330 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004331
4332 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004333 SmallVector<APValue, 4> Elts(NElts, Val);
4334 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004335 }
Eli Friedman803acb32011-12-22 03:51:45 +00004336 case CK_BitCast: {
4337 // Evaluate the operand into an APInt we can extract from.
4338 llvm::APInt SValInt;
4339 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4340 return false;
4341 // Extract the elements
4342 QualType EltTy = VTy->getElementType();
4343 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4344 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4345 SmallVector<APValue, 4> Elts;
4346 if (EltTy->isRealFloatingType()) {
4347 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00004348 unsigned FloatEltSize = EltSize;
4349 if (&Sem == &APFloat::x87DoubleExtended)
4350 FloatEltSize = 80;
4351 for (unsigned i = 0; i < NElts; i++) {
4352 llvm::APInt Elt;
4353 if (BigEndian)
4354 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4355 else
4356 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00004357 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00004358 }
4359 } else if (EltTy->isIntegerType()) {
4360 for (unsigned i = 0; i < NElts; i++) {
4361 llvm::APInt Elt;
4362 if (BigEndian)
4363 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4364 else
4365 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4366 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4367 }
4368 } else {
4369 return Error(E);
4370 }
4371 return Success(Elts, E);
4372 }
Eli Friedmanc757de22011-03-25 00:43:55 +00004373 default:
Richard Smith11562c52011-10-28 17:51:58 +00004374 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004375 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004376}
4377
Richard Smith2d406342011-10-22 21:10:00 +00004378bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004379VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004380 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004381 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00004382 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004383
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004384 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004385 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004386
Eli Friedmanb9c71292012-01-03 23:24:20 +00004387 // The number of initializers can be less than the number of
4388 // vector elements. For OpenCL, this can be due to nested vector
4389 // initialization. For GCC compatibility, missing trailing elements
4390 // should be initialized with zeroes.
4391 unsigned CountInits = 0, CountElts = 0;
4392 while (CountElts < NumElements) {
4393 // Handle nested vector initialization.
4394 if (CountInits < NumInits
4395 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4396 APValue v;
4397 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4398 return Error(E);
4399 unsigned vlen = v.getVectorLength();
4400 for (unsigned j = 0; j < vlen; j++)
4401 Elements.push_back(v.getVectorElt(j));
4402 CountElts += vlen;
4403 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004404 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004405 if (CountInits < NumInits) {
4406 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004407 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004408 } else // trailing integer zero.
4409 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4410 Elements.push_back(APValue(sInt));
4411 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004412 } else {
4413 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004414 if (CountInits < NumInits) {
4415 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004416 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004417 } else // trailing float zero.
4418 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4419 Elements.push_back(APValue(f));
4420 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00004421 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00004422 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004423 }
Richard Smith2d406342011-10-22 21:10:00 +00004424 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004425}
4426
Richard Smith2d406342011-10-22 21:10:00 +00004427bool
Richard Smithfddd3842011-12-30 21:15:51 +00004428VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004429 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00004430 QualType EltTy = VT->getElementType();
4431 APValue ZeroElement;
4432 if (EltTy->isIntegerType())
4433 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4434 else
4435 ZeroElement =
4436 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4437
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004438 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00004439 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004440}
4441
Richard Smith2d406342011-10-22 21:10:00 +00004442bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00004443 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004444 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004445}
4446
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004447//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00004448// Array Evaluation
4449//===----------------------------------------------------------------------===//
4450
4451namespace {
4452 class ArrayExprEvaluator
4453 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00004454 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00004455 APValue &Result;
4456 public:
4457
Richard Smithd62306a2011-11-10 06:34:14 +00004458 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
4459 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00004460
4461 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00004462 assert((V.isArray() || V.isLValue()) &&
4463 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00004464 Result = V;
4465 return true;
4466 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004467
Richard Smithfddd3842011-12-30 21:15:51 +00004468 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004469 const ConstantArrayType *CAT =
4470 Info.Ctx.getAsConstantArrayType(E->getType());
4471 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004472 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004473
4474 Result = APValue(APValue::UninitArray(), 0,
4475 CAT->getSize().getZExtValue());
4476 if (!Result.hasArrayFiller()) return true;
4477
Richard Smithfddd3842011-12-30 21:15:51 +00004478 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00004479 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004480 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00004481 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00004482 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00004483 }
4484
Richard Smithf3e9e432011-11-07 09:22:26 +00004485 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00004486 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00004487 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
4488 const LValue &Subobject,
4489 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00004490 };
4491} // end anonymous namespace
4492
Richard Smithd62306a2011-11-10 06:34:14 +00004493static bool EvaluateArray(const Expr *E, const LValue &This,
4494 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00004495 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00004496 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004497}
4498
4499bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4500 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
4501 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004502 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004503
Richard Smithca2cfbf2011-12-22 01:07:19 +00004504 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
4505 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00004506 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00004507 LValue LV;
4508 if (!EvaluateLValue(E->getInit(0), LV, Info))
4509 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004510 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00004511 LV.moveInto(Val);
4512 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00004513 }
4514
Richard Smith253c2a32012-01-27 01:14:48 +00004515 bool Success = true;
4516
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004517 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
4518 "zero-initialized array shouldn't have any initialized elts");
4519 APValue Filler;
4520 if (Result.isArray() && Result.hasArrayFiller())
4521 Filler = Result.getArrayFiller();
4522
Richard Smith9543c5e2013-04-22 14:44:29 +00004523 unsigned NumEltsToInit = E->getNumInits();
4524 unsigned NumElts = CAT->getSize().getZExtValue();
4525 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
4526
4527 // If the initializer might depend on the array index, run it for each
4528 // array element. For now, just whitelist non-class value-initialization.
4529 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
4530 NumEltsToInit = NumElts;
4531
4532 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004533
4534 // If the array was previously zero-initialized, preserve the
4535 // zero-initialized values.
4536 if (!Filler.isUninit()) {
4537 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
4538 Result.getArrayInitializedElt(I) = Filler;
4539 if (Result.hasArrayFiller())
4540 Result.getArrayFiller() = Filler;
4541 }
4542
Richard Smithd62306a2011-11-10 06:34:14 +00004543 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004544 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00004545 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
4546 const Expr *Init =
4547 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00004548 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00004549 Info, Subobject, Init) ||
4550 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00004551 CAT->getElementType(), 1)) {
4552 if (!Info.keepEvaluatingAfterFailure())
4553 return false;
4554 Success = false;
4555 }
Richard Smithd62306a2011-11-10 06:34:14 +00004556 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004557
Richard Smith9543c5e2013-04-22 14:44:29 +00004558 if (!Result.hasArrayFiller())
4559 return Success;
4560
4561 // If we get here, we have a trivial filler, which we can just evaluate
4562 // once and splat over the rest of the array elements.
4563 assert(FillerExpr && "no array filler for incomplete init list");
4564 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
4565 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00004566}
4567
Richard Smith027bf112011-11-17 22:56:20 +00004568bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004569 return VisitCXXConstructExpr(E, This, &Result, E->getType());
4570}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004571
Richard Smith9543c5e2013-04-22 14:44:29 +00004572bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
4573 const LValue &Subobject,
4574 APValue *Value,
4575 QualType Type) {
4576 bool HadZeroInit = !Value->isUninit();
4577
4578 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
4579 unsigned N = CAT->getSize().getZExtValue();
4580
4581 // Preserve the array filler if we had prior zero-initialization.
4582 APValue Filler =
4583 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
4584 : APValue();
4585
4586 *Value = APValue(APValue::UninitArray(), N, N);
4587
4588 if (HadZeroInit)
4589 for (unsigned I = 0; I != N; ++I)
4590 Value->getArrayInitializedElt(I) = Filler;
4591
4592 // Initialize the elements.
4593 LValue ArrayElt = Subobject;
4594 ArrayElt.addArray(Info, E, CAT);
4595 for (unsigned I = 0; I != N; ++I)
4596 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
4597 CAT->getElementType()) ||
4598 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
4599 CAT->getElementType(), 1))
4600 return false;
4601
4602 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004603 }
Richard Smith027bf112011-11-17 22:56:20 +00004604
Richard Smith9543c5e2013-04-22 14:44:29 +00004605 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00004606 return Error(E);
4607
Richard Smith027bf112011-11-17 22:56:20 +00004608 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00004609
Richard Smithfddd3842011-12-30 21:15:51 +00004610 bool ZeroInit = E->requiresZeroInitialization();
4611 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004612 if (HadZeroInit)
4613 return true;
4614
Richard Smithfddd3842011-12-30 21:15:51 +00004615 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004616 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004617 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004618 }
4619
Richard Smithcc36f692011-12-22 02:22:31 +00004620 const CXXRecordDecl *RD = FD->getParent();
4621 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004622 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00004623 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004624 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00004625 APValue(APValue::UninitStruct(), RD->getNumBases(),
4626 std::distance(RD->field_begin(), RD->field_end()));
4627 return true;
4628 }
4629
Richard Smith027bf112011-11-17 22:56:20 +00004630 const FunctionDecl *Definition = 0;
4631 FD->getBody(Definition);
4632
Richard Smith357362d2011-12-13 06:39:58 +00004633 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4634 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004635
Richard Smith9eae7232012-01-12 18:54:33 +00004636 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004637 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004638 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004639 return false;
4640 }
4641
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004642 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004643 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00004644 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004645 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00004646}
4647
Richard Smithf3e9e432011-11-07 09:22:26 +00004648//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004649// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004650//
4651// As a GNU extension, we support casting pointers to sufficiently-wide integer
4652// types and back in constant folding. Integer values are thus represented
4653// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00004654//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004655
4656namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004657class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004658 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00004659 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004660public:
Richard Smith2e312c82012-03-03 22:46:17 +00004661 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004662 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004663
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004664 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004665 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004666 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004667 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004668 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004669 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004670 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004671 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004672 return true;
4673 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004674 bool Success(const llvm::APSInt &SI, const Expr *E) {
4675 return Success(SI, E, Result);
4676 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004677
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004678 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004679 assert(E->getType()->isIntegralOrEnumerationType() &&
4680 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004681 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004682 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004683 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004684 Result.getInt().setIsUnsigned(
4685 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004686 return true;
4687 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004688 bool Success(const llvm::APInt &I, const Expr *E) {
4689 return Success(I, E, Result);
4690 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004691
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004692 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004693 assert(E->getType()->isIntegralOrEnumerationType() &&
4694 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004695 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004696 return true;
4697 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004698 bool Success(uint64_t Value, const Expr *E) {
4699 return Success(Value, E, Result);
4700 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004701
Ken Dyckdbc01912011-03-11 02:13:43 +00004702 bool Success(CharUnits Size, const Expr *E) {
4703 return Success(Size.getQuantity(), E);
4704 }
4705
Richard Smith2e312c82012-03-03 22:46:17 +00004706 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004707 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00004708 Result = V;
4709 return true;
4710 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004711 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004712 }
Mike Stump11289f42009-09-09 15:08:12 +00004713
Richard Smithfddd3842011-12-30 21:15:51 +00004714 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00004715
Peter Collingbournee9200682011-05-13 03:29:01 +00004716 //===--------------------------------------------------------------------===//
4717 // Visitor Methods
4718 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004719
Chris Lattner7174bf32008-07-12 00:38:25 +00004720 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004721 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004722 }
4723 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004724 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004725 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004726
4727 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4728 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004729 if (CheckReferencedDecl(E, E->getDecl()))
4730 return true;
4731
4732 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004733 }
4734 bool VisitMemberExpr(const MemberExpr *E) {
4735 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00004736 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004737 return true;
4738 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004739
4740 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004741 }
4742
Peter Collingbournee9200682011-05-13 03:29:01 +00004743 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004744 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00004745 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004746 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00004747
Peter Collingbournee9200682011-05-13 03:29:01 +00004748 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004749 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00004750
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004751 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004752 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004753 }
Mike Stump11289f42009-09-09 15:08:12 +00004754
Ted Kremeneke65b0862012-03-06 20:05:56 +00004755 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4756 return Success(E->getValue(), E);
4757 }
4758
Richard Smith4ce706a2011-10-11 21:43:33 +00004759 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00004760 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004761 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004762 }
4763
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004764 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004765 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004766 }
4767
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004768 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4769 return Success(E->getValue(), E);
4770 }
4771
Douglas Gregor29c42f22012-02-24 07:38:34 +00004772 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4773 return Success(E->getValue(), E);
4774 }
4775
John Wiegley6242b6a2011-04-28 00:16:57 +00004776 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4777 return Success(E->getValue(), E);
4778 }
4779
John Wiegleyf9f65842011-04-25 06:54:41 +00004780 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4781 return Success(E->getValue(), E);
4782 }
4783
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004784 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004785 bool VisitUnaryImag(const UnaryOperator *E);
4786
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004787 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004788 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004789
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004790private:
Ken Dyck160146e2010-01-27 17:10:57 +00004791 CharUnits GetAlignOfExpr(const Expr *E);
4792 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00004793 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00004794 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004795 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00004796};
Chris Lattner05706e882008-07-11 18:11:29 +00004797} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004798
Richard Smith11562c52011-10-28 17:51:58 +00004799/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4800/// produce either the integer value or a pointer.
4801///
4802/// GCC has a heinous extension which folds casts between pointer types and
4803/// pointer-sized integral types. We support this by allowing the evaluation of
4804/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4805/// Some simple arithmetic on such values is supported (they are treated much
4806/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00004807static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00004808 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004809 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004810 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00004811}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004812
Richard Smithf57d8cb2011-12-09 22:58:01 +00004813static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00004814 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004815 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00004816 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004817 if (!Val.isInt()) {
4818 // FIXME: It would be better to produce the diagnostic for casting
4819 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00004820 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004821 return false;
4822 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004823 Result = Val.getInt();
4824 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004825}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004826
Richard Smithf57d8cb2011-12-09 22:58:01 +00004827/// Check whether the given declaration can be directly converted to an integral
4828/// rvalue. If not, no diagnostic is produced; there are other things we can
4829/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004830bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00004831 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004832 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004833 // Check for signedness/width mismatches between E type and ECD value.
4834 bool SameSign = (ECD->getInitVal().isSigned()
4835 == E->getType()->isSignedIntegerOrEnumerationType());
4836 bool SameWidth = (ECD->getInitVal().getBitWidth()
4837 == Info.Ctx.getIntWidth(E->getType()));
4838 if (SameSign && SameWidth)
4839 return Success(ECD->getInitVal(), E);
4840 else {
4841 // Get rid of mismatch (otherwise Success assertions will fail)
4842 // by computing a new value matching the type of E.
4843 llvm::APSInt Val = ECD->getInitVal();
4844 if (!SameSign)
4845 Val.setIsSigned(!ECD->getInitVal().isSigned());
4846 if (!SameWidth)
4847 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4848 return Success(Val, E);
4849 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004850 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004851 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00004852}
4853
Chris Lattner86ee2862008-10-06 06:40:35 +00004854/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4855/// as GCC.
4856static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4857 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004858 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00004859 enum gcc_type_class {
4860 no_type_class = -1,
4861 void_type_class, integer_type_class, char_type_class,
4862 enumeral_type_class, boolean_type_class,
4863 pointer_type_class, reference_type_class, offset_type_class,
4864 real_type_class, complex_type_class,
4865 function_type_class, method_type_class,
4866 record_type_class, union_type_class,
4867 array_type_class, string_type_class,
4868 lang_type_class
4869 };
Mike Stump11289f42009-09-09 15:08:12 +00004870
4871 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00004872 // ideal, however it is what gcc does.
4873 if (E->getNumArgs() == 0)
4874 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00004875
Chris Lattner86ee2862008-10-06 06:40:35 +00004876 QualType ArgTy = E->getArg(0)->getType();
4877 if (ArgTy->isVoidType())
4878 return void_type_class;
4879 else if (ArgTy->isEnumeralType())
4880 return enumeral_type_class;
4881 else if (ArgTy->isBooleanType())
4882 return boolean_type_class;
4883 else if (ArgTy->isCharType())
4884 return string_type_class; // gcc doesn't appear to use char_type_class
4885 else if (ArgTy->isIntegerType())
4886 return integer_type_class;
4887 else if (ArgTy->isPointerType())
4888 return pointer_type_class;
4889 else if (ArgTy->isReferenceType())
4890 return reference_type_class;
4891 else if (ArgTy->isRealType())
4892 return real_type_class;
4893 else if (ArgTy->isComplexType())
4894 return complex_type_class;
4895 else if (ArgTy->isFunctionType())
4896 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00004897 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00004898 return record_type_class;
4899 else if (ArgTy->isUnionType())
4900 return union_type_class;
4901 else if (ArgTy->isArrayType())
4902 return array_type_class;
4903 else if (ArgTy->isUnionType())
4904 return union_type_class;
4905 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00004906 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00004907}
4908
Richard Smith5fab0c92011-12-28 19:48:30 +00004909/// EvaluateBuiltinConstantPForLValue - Determine the result of
4910/// __builtin_constant_p when applied to the given lvalue.
4911///
4912/// An lvalue is only "constant" if it is a pointer or reference to the first
4913/// character of a string literal.
4914template<typename LValue>
4915static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00004916 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00004917 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4918}
4919
4920/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4921/// GCC as we can manage.
4922static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4923 QualType ArgType = Arg->getType();
4924
4925 // __builtin_constant_p always has one operand. The rules which gcc follows
4926 // are not precisely documented, but are as follows:
4927 //
4928 // - If the operand is of integral, floating, complex or enumeration type,
4929 // and can be folded to a known value of that type, it returns 1.
4930 // - If the operand and can be folded to a pointer to the first character
4931 // of a string literal (or such a pointer cast to an integral type), it
4932 // returns 1.
4933 //
4934 // Otherwise, it returns 0.
4935 //
4936 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4937 // its support for this does not currently work.
4938 if (ArgType->isIntegralOrEnumerationType()) {
4939 Expr::EvalResult Result;
4940 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4941 return false;
4942
4943 APValue &V = Result.Val;
4944 if (V.getKind() == APValue::Int)
4945 return true;
4946
4947 return EvaluateBuiltinConstantPForLValue(V);
4948 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4949 return Arg->isEvaluatable(Ctx);
4950 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4951 LValue LV;
4952 Expr::EvalStatus Status;
4953 EvalInfo Info(Ctx, Status);
4954 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4955 : EvaluatePointer(Arg, LV, Info)) &&
4956 !Status.HasSideEffects)
4957 return EvaluateBuiltinConstantPForLValue(LV);
4958 }
4959
4960 // Anything else isn't considered to be sufficiently constant.
4961 return false;
4962}
4963
John McCall95007602010-05-10 23:27:23 +00004964/// Retrieves the "underlying object type" of the given expression,
4965/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00004966QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4967 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4968 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00004969 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00004970 } else if (const Expr *E = B.get<const Expr*>()) {
4971 if (isa<CompoundLiteralExpr>(E))
4972 return E->getType();
John McCall95007602010-05-10 23:27:23 +00004973 }
4974
4975 return QualType();
4976}
4977
Peter Collingbournee9200682011-05-13 03:29:01 +00004978bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00004979 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00004980
4981 {
4982 // The operand of __builtin_object_size is never evaluated for side-effects.
4983 // If there are any, but we can determine the pointed-to object anyway, then
4984 // ignore the side-effects.
4985 SpeculativeEvaluationRAII SpeculativeEval(Info);
4986 if (!EvaluatePointer(E->getArg(0), Base, Info))
4987 return false;
4988 }
John McCall95007602010-05-10 23:27:23 +00004989
4990 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00004991 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00004992
Richard Smithce40ad62011-11-12 22:28:03 +00004993 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00004994 if (T.isNull() ||
4995 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00004996 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00004997 T->isVariablyModifiedType() ||
4998 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004999 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005000
5001 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5002 CharUnits Offset = Base.getLValueOffset();
5003
5004 if (!Offset.isNegative() && Offset <= Size)
5005 Size -= Offset;
5006 else
5007 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005008 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005009}
5010
Peter Collingbournee9200682011-05-13 03:29:01 +00005011bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005012 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005013 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005014 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005015
5016 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005017 if (TryEvaluateBuiltinObjectSize(E))
5018 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005019
Richard Smith0421ce72012-08-07 04:16:51 +00005020 // If evaluating the argument has side-effects, we can't determine the size
5021 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5022 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005023 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005024 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005025 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005026 return Success(0, E);
5027 }
Mike Stump876387b2009-10-27 22:09:17 +00005028
Richard Smith01ade172012-05-23 04:13:20 +00005029 // Expression had no side effects, but we couldn't statically determine the
5030 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005031 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005032 }
5033
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005034 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005035 case Builtin::BI__builtin_bswap32:
5036 case Builtin::BI__builtin_bswap64: {
5037 APSInt Val;
5038 if (!EvaluateInteger(E->getArg(0), Val, Info))
5039 return false;
5040
5041 return Success(Val.byteSwap(), E);
5042 }
5043
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005044 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005045 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00005046
Richard Smith5fab0c92011-12-28 19:48:30 +00005047 case Builtin::BI__builtin_constant_p:
5048 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00005049
Chris Lattnerd545ad12009-09-23 06:06:36 +00005050 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00005051 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00005052 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00005053 return Success(Operand, E);
5054 }
Eli Friedmand5c93992010-02-13 00:10:10 +00005055
5056 case Builtin::BI__builtin_expect:
5057 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00005058
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005059 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005060 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005061 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005062 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005063 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5064 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005065 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005066 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005067 case Builtin::BI__builtin_strlen:
5068 // As an extension, we support strlen() and __builtin_strlen() as constant
5069 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005070 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005071 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5072 // The string literal may have embedded null characters. Find the first
5073 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005074 StringRef Str = S->getString();
5075 StringRef::size_type Pos = Str.find(0);
5076 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005077 Str = Str.substr(0, Pos);
5078
5079 return Success(Str.size(), E);
5080 }
5081
Richard Smithf57d8cb2011-12-09 22:58:01 +00005082 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005083
Richard Smith01ba47d2012-04-13 00:45:38 +00005084 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005085 case Builtin::BI__atomic_is_lock_free:
5086 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005087 APSInt SizeVal;
5088 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5089 return false;
5090
5091 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5092 // of two less than the maximum inline atomic width, we know it is
5093 // lock-free. If the size isn't a power of two, or greater than the
5094 // maximum alignment where we promote atomics, we know it is not lock-free
5095 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5096 // the answer can only be determined at runtime; for example, 16-byte
5097 // atomics have lock-free implementations on some, but not all,
5098 // x86-64 processors.
5099
5100 // Check power-of-two.
5101 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005102 if (Size.isPowerOfTwo()) {
5103 // Check against inlining width.
5104 unsigned InlineWidthBits =
5105 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5106 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5107 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5108 Size == CharUnits::One() ||
5109 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5110 Expr::NPC_NeverValueDependent))
5111 // OK, we will inline appropriately-aligned operations of this size,
5112 // and _Atomic(T) is appropriately-aligned.
5113 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005114
Richard Smith01ba47d2012-04-13 00:45:38 +00005115 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5116 castAs<PointerType>()->getPointeeType();
5117 if (!PointeeType->isIncompleteType() &&
5118 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5119 // OK, we will inline operations on this object.
5120 return Success(1, E);
5121 }
5122 }
5123 }
Eli Friedmana4c26022011-10-17 21:44:23 +00005124
Richard Smith01ba47d2012-04-13 00:45:38 +00005125 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5126 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005127 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005128 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005129}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005130
Richard Smith8b3497e2011-10-31 01:37:14 +00005131static bool HasSameBase(const LValue &A, const LValue &B) {
5132 if (!A.getLValueBase())
5133 return !B.getLValueBase();
5134 if (!B.getLValueBase())
5135 return false;
5136
Richard Smithce40ad62011-11-12 22:28:03 +00005137 if (A.getLValueBase().getOpaqueValue() !=
5138 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005139 const Decl *ADecl = GetLValueBaseDecl(A);
5140 if (!ADecl)
5141 return false;
5142 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005143 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005144 return false;
5145 }
5146
5147 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005148 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005149}
5150
Richard Smithc8042322012-02-01 05:53:12 +00005151/// Perform the given integer operation, which is known to need at most BitWidth
5152/// bits, and check for overflow in the original type (if that type was not an
5153/// unsigned type).
5154template<typename Operation>
5155static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
5156 const APSInt &LHS, const APSInt &RHS,
5157 unsigned BitWidth, Operation Op) {
5158 if (LHS.isUnsigned())
5159 return Op(LHS, RHS);
5160
5161 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
5162 APSInt Result = Value.trunc(LHS.getBitWidth());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005163 if (Result.extend(BitWidth) != Value) {
5164 if (Info.getIntOverflowCheckMode())
5165 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
5166 diag::warn_integer_constant_overflow)
5167 << Result.toString(10) << E->getType();
5168 else
5169 HandleOverflow(Info, E, Value, E->getType());
5170 }
Richard Smithc8042322012-02-01 05:53:12 +00005171 return Result;
5172}
5173
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005174namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005175
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005176/// \brief Data recursive integer evaluator of certain binary operators.
5177///
5178/// We use a data recursive algorithm for binary operators so that we are able
5179/// to handle extreme cases of chained binary operators without causing stack
5180/// overflow.
5181class DataRecursiveIntBinOpEvaluator {
5182 struct EvalResult {
5183 APValue Val;
5184 bool Failed;
5185
5186 EvalResult() : Failed(false) { }
5187
5188 void swap(EvalResult &RHS) {
5189 Val.swap(RHS.Val);
5190 Failed = RHS.Failed;
5191 RHS.Failed = false;
5192 }
5193 };
5194
5195 struct Job {
5196 const Expr *E;
5197 EvalResult LHSResult; // meaningful only for binary operator expression.
5198 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5199
5200 Job() : StoredInfo(0) { }
5201 void startSpeculativeEval(EvalInfo &Info) {
5202 OldEvalStatus = Info.EvalStatus;
5203 Info.EvalStatus.Diag = 0;
5204 StoredInfo = &Info;
5205 }
5206 ~Job() {
5207 if (StoredInfo) {
5208 StoredInfo->EvalStatus = OldEvalStatus;
5209 }
5210 }
5211 private:
5212 EvalInfo *StoredInfo; // non-null if status changed.
5213 Expr::EvalStatus OldEvalStatus;
5214 };
5215
5216 SmallVector<Job, 16> Queue;
5217
5218 IntExprEvaluator &IntEval;
5219 EvalInfo &Info;
5220 APValue &FinalResult;
5221
5222public:
5223 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5224 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5225
5226 /// \brief True if \param E is a binary operator that we are going to handle
5227 /// data recursively.
5228 /// We handle binary operators that are comma, logical, or that have operands
5229 /// with integral or enumeration type.
5230 static bool shouldEnqueue(const BinaryOperator *E) {
5231 return E->getOpcode() == BO_Comma ||
5232 E->isLogicalOp() ||
5233 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5234 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005235 }
5236
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005237 bool Traverse(const BinaryOperator *E) {
5238 enqueue(E);
5239 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00005240 while (!Queue.empty())
5241 process(PrevResult);
5242
5243 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005244
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005245 FinalResult.swap(PrevResult.Val);
5246 return true;
5247 }
5248
5249private:
5250 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5251 return IntEval.Success(Value, E, Result);
5252 }
5253 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
5254 return IntEval.Success(Value, E, Result);
5255 }
5256 bool Error(const Expr *E) {
5257 return IntEval.Error(E);
5258 }
5259 bool Error(const Expr *E, diag::kind D) {
5260 return IntEval.Error(E, D);
5261 }
5262
5263 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5264 return Info.CCEDiag(E, D);
5265 }
5266
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005267 // \brief Returns true if visiting the RHS is necessary, false otherwise.
5268 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005269 bool &SuppressRHSDiags);
5270
5271 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5272 const BinaryOperator *E, APValue &Result);
5273
5274 void EvaluateExpr(const Expr *E, EvalResult &Result) {
5275 Result.Failed = !Evaluate(Result.Val, Info, E);
5276 if (Result.Failed)
5277 Result.Val = APValue();
5278 }
5279
Richard Trieuba4d0872012-03-21 23:30:30 +00005280 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005281
5282 void enqueue(const Expr *E) {
5283 E = E->IgnoreParens();
5284 Queue.resize(Queue.size()+1);
5285 Queue.back().E = E;
5286 Queue.back().Kind = Job::AnyExprKind;
5287 }
5288};
5289
5290}
5291
5292bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005293 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005294 bool &SuppressRHSDiags) {
5295 if (E->getOpcode() == BO_Comma) {
5296 // Ignore LHS but note if we could not evaluate it.
5297 if (LHSResult.Failed)
5298 Info.EvalStatus.HasSideEffects = true;
5299 return true;
5300 }
5301
5302 if (E->isLogicalOp()) {
5303 bool lhsResult;
5304 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005305 // We were able to evaluate the LHS, see if we can get away with not
5306 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005307 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005308 Success(lhsResult, E, LHSResult.Val);
5309 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005310 }
5311 } else {
5312 // Since we weren't able to evaluate the left hand side, it
5313 // must have had side effects.
5314 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005315
5316 // We can't evaluate the LHS; however, sometimes the result
5317 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5318 // Don't ignore RHS and suppress diagnostics from this arm.
5319 SuppressRHSDiags = true;
5320 }
5321
5322 return true;
5323 }
5324
5325 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5326 E->getRHS()->getType()->isIntegralOrEnumerationType());
5327
5328 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005329 return false; // Ignore RHS;
5330
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005331 return true;
5332}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005333
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005334bool DataRecursiveIntBinOpEvaluator::
5335 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5336 const BinaryOperator *E, APValue &Result) {
5337 if (E->getOpcode() == BO_Comma) {
5338 if (RHSResult.Failed)
5339 return false;
5340 Result = RHSResult.Val;
5341 return true;
5342 }
5343
5344 if (E->isLogicalOp()) {
5345 bool lhsResult, rhsResult;
5346 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5347 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5348
5349 if (LHSIsOK) {
5350 if (RHSIsOK) {
5351 if (E->getOpcode() == BO_LOr)
5352 return Success(lhsResult || rhsResult, E, Result);
5353 else
5354 return Success(lhsResult && rhsResult, E, Result);
5355 }
5356 } else {
5357 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005358 // We can't evaluate the LHS; however, sometimes the result
5359 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5360 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005361 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005362 }
5363 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005364
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005365 return false;
5366 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005367
5368 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5369 E->getRHS()->getType()->isIntegralOrEnumerationType());
5370
5371 if (LHSResult.Failed || RHSResult.Failed)
5372 return false;
5373
5374 const APValue &LHSVal = LHSResult.Val;
5375 const APValue &RHSVal = RHSResult.Val;
5376
5377 // Handle cases like (unsigned long)&a + 4.
5378 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5379 Result = LHSVal;
5380 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5381 RHSVal.getInt().getZExtValue());
5382 if (E->getOpcode() == BO_Add)
5383 Result.getLValueOffset() += AdditionalOffset;
5384 else
5385 Result.getLValueOffset() -= AdditionalOffset;
5386 return true;
5387 }
5388
5389 // Handle cases like 4 + (unsigned long)&a
5390 if (E->getOpcode() == BO_Add &&
5391 RHSVal.isLValue() && LHSVal.isInt()) {
5392 Result = RHSVal;
5393 Result.getLValueOffset() += CharUnits::fromQuantity(
5394 LHSVal.getInt().getZExtValue());
5395 return true;
5396 }
5397
5398 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5399 // Handle (intptr_t)&&A - (intptr_t)&&B.
5400 if (!LHSVal.getLValueOffset().isZero() ||
5401 !RHSVal.getLValueOffset().isZero())
5402 return false;
5403 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5404 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5405 if (!LHSExpr || !RHSExpr)
5406 return false;
5407 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5408 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5409 if (!LHSAddrExpr || !RHSAddrExpr)
5410 return false;
5411 // Make sure both labels come from the same function.
5412 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5413 RHSAddrExpr->getLabel()->getDeclContext())
5414 return false;
5415 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5416 return true;
5417 }
5418
5419 // All the following cases expect both operands to be an integer
5420 if (!LHSVal.isInt() || !RHSVal.isInt())
5421 return Error(E);
5422
5423 const APSInt &LHS = LHSVal.getInt();
5424 APSInt RHS = RHSVal.getInt();
5425
5426 switch (E->getOpcode()) {
5427 default:
5428 return Error(E);
5429 case BO_Mul:
5430 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5431 LHS.getBitWidth() * 2,
5432 std::multiplies<APSInt>()), E,
5433 Result);
5434 case BO_Add:
5435 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5436 LHS.getBitWidth() + 1,
5437 std::plus<APSInt>()), E, Result);
5438 case BO_Sub:
5439 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5440 LHS.getBitWidth() + 1,
5441 std::minus<APSInt>()), E, Result);
5442 case BO_And: return Success(LHS & RHS, E, Result);
5443 case BO_Xor: return Success(LHS ^ RHS, E, Result);
5444 case BO_Or: return Success(LHS | RHS, E, Result);
5445 case BO_Div:
5446 case BO_Rem:
5447 if (RHS == 0)
5448 return Error(E, diag::note_expr_divide_by_zero);
5449 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
5450 // not actually undefined behavior in C++11 due to a language defect.
5451 if (RHS.isNegative() && RHS.isAllOnesValue() &&
5452 LHS.isSigned() && LHS.isMinSignedValue())
5453 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
5454 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
5455 Result);
5456 case BO_Shl: {
David Tweed042e0882013-01-07 16:43:27 +00005457 if (Info.getLangOpts().OpenCL)
5458 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00005459 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00005460 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
5461 RHS.isUnsigned());
5462 else if (RHS.isSigned() && RHS.isNegative()) {
5463 // During constant-folding, a negative shift is an opposite shift. Such
5464 // a shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005465 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
5466 RHS = -RHS;
5467 goto shift_right;
5468 }
5469
5470 shift_left:
5471 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
5472 // the shifted type.
5473 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
5474 if (SA != RHS) {
5475 CCEDiag(E, diag::note_constexpr_large_shift)
5476 << RHS << E->getType() << LHS.getBitWidth();
5477 } else if (LHS.isSigned()) {
5478 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
5479 // operand, and must not overflow the corresponding unsigned type.
5480 if (LHS.isNegative())
5481 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
5482 else if (LHS.countLeadingZeros() < SA)
5483 CCEDiag(E, diag::note_constexpr_lshift_discards);
5484 }
5485
5486 return Success(LHS << SA, E, Result);
5487 }
5488 case BO_Shr: {
David Tweed042e0882013-01-07 16:43:27 +00005489 if (Info.getLangOpts().OpenCL)
5490 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00005491 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00005492 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
5493 RHS.isUnsigned());
5494 else if (RHS.isSigned() && RHS.isNegative()) {
5495 // During constant-folding, a negative shift is an opposite shift. Such a
5496 // shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005497 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
5498 RHS = -RHS;
5499 goto shift_left;
5500 }
5501
5502 shift_right:
5503 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
5504 // shifted type.
5505 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
5506 if (SA != RHS)
5507 CCEDiag(E, diag::note_constexpr_large_shift)
5508 << RHS << E->getType() << LHS.getBitWidth();
5509
5510 return Success(LHS >> SA, E, Result);
5511 }
5512
5513 case BO_LT: return Success(LHS < RHS, E, Result);
5514 case BO_GT: return Success(LHS > RHS, E, Result);
5515 case BO_LE: return Success(LHS <= RHS, E, Result);
5516 case BO_GE: return Success(LHS >= RHS, E, Result);
5517 case BO_EQ: return Success(LHS == RHS, E, Result);
5518 case BO_NE: return Success(LHS != RHS, E, Result);
5519 }
5520}
5521
Richard Trieuba4d0872012-03-21 23:30:30 +00005522void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005523 Job &job = Queue.back();
5524
5525 switch (job.Kind) {
5526 case Job::AnyExprKind: {
5527 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5528 if (shouldEnqueue(Bop)) {
5529 job.Kind = Job::BinOpKind;
5530 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005531 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005532 }
5533 }
5534
5535 EvaluateExpr(job.E, Result);
5536 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005537 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005538 }
5539
5540 case Job::BinOpKind: {
5541 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005542 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005543 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005544 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005545 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005546 }
5547 if (SuppressRHSDiags)
5548 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005549 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005550 job.Kind = Job::BinOpVisitedLHSKind;
5551 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005552 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005553 }
5554
5555 case Job::BinOpVisitedLHSKind: {
5556 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5557 EvalResult RHS;
5558 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00005559 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005560 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005561 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005562 }
5563 }
5564
5565 llvm_unreachable("Invalid Job::Kind!");
5566}
5567
5568bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5569 if (E->isAssignmentOp())
5570 return Error(E);
5571
5572 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
5573 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005574
Anders Carlssonacc79812008-11-16 07:17:21 +00005575 QualType LHSTy = E->getLHS()->getType();
5576 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005577
5578 if (LHSTy->isAnyComplexType()) {
5579 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00005580 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005581
Richard Smith253c2a32012-01-27 01:14:48 +00005582 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
5583 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005584 return false;
5585
Richard Smith253c2a32012-01-27 01:14:48 +00005586 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005587 return false;
5588
5589 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00005590 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005591 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00005592 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005593 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
5594
John McCalle3027922010-08-25 11:45:40 +00005595 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005596 return Success((CR_r == APFloat::cmpEqual &&
5597 CR_i == APFloat::cmpEqual), E);
5598 else {
John McCalle3027922010-08-25 11:45:40 +00005599 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005600 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00005601 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005602 CR_r == APFloat::cmpLessThan ||
5603 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00005604 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005605 CR_i == APFloat::cmpLessThan ||
5606 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005607 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005608 } else {
John McCalle3027922010-08-25 11:45:40 +00005609 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005610 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5611 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5612 else {
John McCalle3027922010-08-25 11:45:40 +00005613 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005614 "Invalid compex comparison.");
5615 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5616 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5617 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005618 }
5619 }
Mike Stump11289f42009-09-09 15:08:12 +00005620
Anders Carlssonacc79812008-11-16 07:17:21 +00005621 if (LHSTy->isRealFloatingType() &&
5622 RHSTy->isRealFloatingType()) {
5623 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00005624
Richard Smith253c2a32012-01-27 01:14:48 +00005625 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5626 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00005627 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005628
Richard Smith253c2a32012-01-27 01:14:48 +00005629 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00005630 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005631
Anders Carlssonacc79812008-11-16 07:17:21 +00005632 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00005633
Anders Carlssonacc79812008-11-16 07:17:21 +00005634 switch (E->getOpcode()) {
5635 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005636 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00005637 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005638 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00005639 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005640 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00005641 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005642 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005643 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00005644 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005645 E);
John McCalle3027922010-08-25 11:45:40 +00005646 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005647 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005648 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00005649 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00005650 || CR == APFloat::cmpLessThan
5651 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00005652 }
Anders Carlssonacc79812008-11-16 07:17:21 +00005653 }
Mike Stump11289f42009-09-09 15:08:12 +00005654
Eli Friedmana38da572009-04-28 19:17:36 +00005655 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005656 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005657 LValue LHSValue, RHSValue;
5658
5659 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
5660 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005661 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005662
Richard Smith253c2a32012-01-27 01:14:48 +00005663 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005664 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005665
Richard Smith8b3497e2011-10-31 01:37:14 +00005666 // Reject differing bases from the normal codepath; we special-case
5667 // comparisons to null.
5668 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005669 if (E->getOpcode() == BO_Sub) {
5670 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005671 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
5672 return false;
5673 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00005674 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005675 if (!LHSExpr || !RHSExpr)
5676 return false;
5677 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5678 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5679 if (!LHSAddrExpr || !RHSAddrExpr)
5680 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005681 // Make sure both labels come from the same function.
5682 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5683 RHSAddrExpr->getLabel()->getDeclContext())
5684 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005685 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005686 return true;
5687 }
Richard Smith83c68212011-10-31 05:11:32 +00005688 // Inequalities and subtractions between unrelated pointers have
5689 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00005690 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005691 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005692 // A constant address may compare equal to the address of a symbol.
5693 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00005694 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005695 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5696 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005697 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005698 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00005699 // distinct addresses. In clang, the result of such a comparison is
5700 // unspecified, so it is not a constant expression. However, we do know
5701 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00005702 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5703 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005704 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005705 // We can't tell whether weak symbols will end up pointing to the same
5706 // object.
5707 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005708 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005709 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00005710 // (Note that clang defaults to -fmerge-all-constants, which can
5711 // lead to inconsistent results for comparisons involving the address
5712 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00005713 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00005714 }
Eli Friedman64004332009-03-23 04:38:34 +00005715
Richard Smith1b470412012-02-01 08:10:20 +00005716 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5717 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5718
Richard Smith84f6dcf2012-02-02 01:16:57 +00005719 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5720 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5721
John McCalle3027922010-08-25 11:45:40 +00005722 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005723 // C++11 [expr.add]p6:
5724 // Unless both pointers point to elements of the same array object, or
5725 // one past the last element of the array object, the behavior is
5726 // undefined.
5727 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5728 !AreElementsOfSameArray(getType(LHSValue.Base),
5729 LHSDesignator, RHSDesignator))
5730 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5731
Chris Lattner882bdf22010-04-20 17:13:14 +00005732 QualType Type = E->getLHS()->getType();
5733 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005734
Richard Smithd62306a2011-11-10 06:34:14 +00005735 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00005736 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00005737 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005738
Richard Smith1b470412012-02-01 08:10:20 +00005739 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5740 // and produce incorrect results when it overflows. Such behavior
5741 // appears to be non-conforming, but is common, so perhaps we should
5742 // assume the standard intended for such cases to be undefined behavior
5743 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00005744
Richard Smith1b470412012-02-01 08:10:20 +00005745 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5746 // overflow in the final conversion to ptrdiff_t.
5747 APSInt LHS(
5748 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5749 APSInt RHS(
5750 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5751 APSInt ElemSize(
5752 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5753 APSInt TrueResult = (LHS - RHS) / ElemSize;
5754 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5755
5756 if (Result.extend(65) != TrueResult)
5757 HandleOverflow(Info, E, TrueResult, E->getType());
5758 return Success(Result, E);
5759 }
Richard Smithde21b242012-01-31 06:41:30 +00005760
5761 // C++11 [expr.rel]p3:
5762 // Pointers to void (after pointer conversions) can be compared, with a
5763 // result defined as follows: If both pointers represent the same
5764 // address or are both the null pointer value, the result is true if the
5765 // operator is <= or >= and false otherwise; otherwise the result is
5766 // unspecified.
5767 // We interpret this as applying to pointers to *cv* void.
5768 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00005769 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00005770 CCEDiag(E, diag::note_constexpr_void_comparison);
5771
Richard Smith84f6dcf2012-02-02 01:16:57 +00005772 // C++11 [expr.rel]p2:
5773 // - If two pointers point to non-static data members of the same object,
5774 // or to subobjects or array elements fo such members, recursively, the
5775 // pointer to the later declared member compares greater provided the
5776 // two members have the same access control and provided their class is
5777 // not a union.
5778 // [...]
5779 // - Otherwise pointer comparisons are unspecified.
5780 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5781 E->isRelationalOp()) {
5782 bool WasArrayIndex;
5783 unsigned Mismatch =
5784 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5785 RHSDesignator, WasArrayIndex);
5786 // At the point where the designators diverge, the comparison has a
5787 // specified value if:
5788 // - we are comparing array indices
5789 // - we are comparing fields of a union, or fields with the same access
5790 // Otherwise, the result is unspecified and thus the comparison is not a
5791 // constant expression.
5792 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5793 Mismatch < RHSDesignator.Entries.size()) {
5794 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5795 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5796 if (!LF && !RF)
5797 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5798 else if (!LF)
5799 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5800 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5801 << RF->getParent() << RF;
5802 else if (!RF)
5803 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5804 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5805 << LF->getParent() << LF;
5806 else if (!LF->getParent()->isUnion() &&
5807 LF->getAccess() != RF->getAccess())
5808 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5809 << LF << LF->getAccess() << RF << RF->getAccess()
5810 << LF->getParent();
5811 }
5812 }
5813
Eli Friedman6c31cb42012-04-16 04:30:08 +00005814 // The comparison here must be unsigned, and performed with the same
5815 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00005816 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5817 uint64_t CompareLHS = LHSOffset.getQuantity();
5818 uint64_t CompareRHS = RHSOffset.getQuantity();
5819 assert(PtrSize <= 64 && "Unexpected pointer width");
5820 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5821 CompareLHS &= Mask;
5822 CompareRHS &= Mask;
5823
Eli Friedman2f5b7c52012-04-16 19:23:57 +00005824 // If there is a base and this is a relational operator, we can only
5825 // compare pointers within the object in question; otherwise, the result
5826 // depends on where the object is located in memory.
5827 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5828 QualType BaseTy = getType(LHSValue.Base);
5829 if (BaseTy->isIncompleteType())
5830 return Error(E);
5831 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5832 uint64_t OffsetLimit = Size.getQuantity();
5833 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5834 return Error(E);
5835 }
5836
Richard Smith8b3497e2011-10-31 01:37:14 +00005837 switch (E->getOpcode()) {
5838 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00005839 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5840 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5841 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5842 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5843 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5844 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00005845 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005846 }
5847 }
Richard Smith7bb00672012-02-01 01:42:44 +00005848
5849 if (LHSTy->isMemberPointerType()) {
5850 assert(E->isEqualityOp() && "unexpected member pointer operation");
5851 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5852
5853 MemberPtr LHSValue, RHSValue;
5854
5855 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5856 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5857 return false;
5858
5859 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5860 return false;
5861
5862 // C++11 [expr.eq]p2:
5863 // If both operands are null, they compare equal. Otherwise if only one is
5864 // null, they compare unequal.
5865 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5866 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5867 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5868 }
5869
5870 // Otherwise if either is a pointer to a virtual member function, the
5871 // result is unspecified.
5872 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5873 if (MD->isVirtual())
5874 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5875 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5876 if (MD->isVirtual())
5877 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5878
5879 // Otherwise they compare equal if and only if they would refer to the
5880 // same member of the same most derived object or the same subobject if
5881 // they were dereferenced with a hypothetical object of the associated
5882 // class type.
5883 bool Equal = LHSValue == RHSValue;
5884 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5885 }
5886
Richard Smithab44d9b2012-02-14 22:35:28 +00005887 if (LHSTy->isNullPtrType()) {
5888 assert(E->isComparisonOp() && "unexpected nullptr operation");
5889 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5890 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5891 // are compared, the result is true of the operator is <=, >= or ==, and
5892 // false otherwise.
5893 BinaryOperator::Opcode Opcode = E->getOpcode();
5894 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5895 }
5896
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005897 assert((!LHSTy->isIntegralOrEnumerationType() ||
5898 !RHSTy->isIntegralOrEnumerationType()) &&
5899 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5900 // We can't continue from here for non-integral types.
5901 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00005902}
5903
Ken Dyck160146e2010-01-27 17:10:57 +00005904CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00005905 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5906 // result shall be the alignment of the referenced type."
5907 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5908 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00005909
5910 // __alignof is defined to return the preferred alignment.
5911 return Info.Ctx.toCharUnitsFromBits(
5912 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00005913}
5914
Ken Dyck160146e2010-01-27 17:10:57 +00005915CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00005916 E = E->IgnoreParens();
5917
5918 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00005919 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00005920 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005921 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5922 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00005923
Chris Lattner68061312009-01-24 21:53:27 +00005924 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005925 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5926 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00005927
Chris Lattner24aeeab2009-01-24 21:09:06 +00005928 return GetAlignOfType(E->getType());
5929}
5930
5931
Peter Collingbournee190dee2011-03-11 19:24:49 +00005932/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5933/// a result as the expression's type.
5934bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5935 const UnaryExprOrTypeTraitExpr *E) {
5936 switch(E->getKind()) {
5937 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00005938 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00005939 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005940 else
Ken Dyckdbc01912011-03-11 02:13:43 +00005941 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005942 }
Eli Friedman64004332009-03-23 04:38:34 +00005943
Peter Collingbournee190dee2011-03-11 19:24:49 +00005944 case UETT_VecStep: {
5945 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00005946
Peter Collingbournee190dee2011-03-11 19:24:49 +00005947 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00005948 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00005949
Peter Collingbournee190dee2011-03-11 19:24:49 +00005950 // The vec_step built-in functions that take a 3-component
5951 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5952 if (n == 3)
5953 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00005954
Peter Collingbournee190dee2011-03-11 19:24:49 +00005955 return Success(n, E);
5956 } else
5957 return Success(1, E);
5958 }
5959
5960 case UETT_SizeOf: {
5961 QualType SrcTy = E->getTypeOfArgument();
5962 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5963 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00005964 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5965 SrcTy = Ref->getPointeeType();
5966
Richard Smithd62306a2011-11-10 06:34:14 +00005967 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00005968 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00005969 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005970 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005971 }
5972 }
5973
5974 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005975}
5976
Peter Collingbournee9200682011-05-13 03:29:01 +00005977bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00005978 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00005979 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00005980 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005981 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00005982 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00005983 for (unsigned i = 0; i != n; ++i) {
5984 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5985 switch (ON.getKind()) {
5986 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00005987 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00005988 APSInt IdxResult;
5989 if (!EvaluateInteger(Idx, IdxResult, Info))
5990 return false;
5991 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5992 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005993 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005994 CurrentType = AT->getElementType();
5995 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5996 Result += IdxResult.getSExtValue() * ElementSize;
5997 break;
5998 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005999
Douglas Gregor882211c2010-04-28 22:16:22 +00006000 case OffsetOfExpr::OffsetOfNode::Field: {
6001 FieldDecl *MemberDecl = ON.getField();
6002 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006003 if (!RT)
6004 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006005 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006006 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006007 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006008 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006009 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006010 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006011 CurrentType = MemberDecl->getType().getNonReferenceType();
6012 break;
6013 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006014
Douglas Gregor882211c2010-04-28 22:16:22 +00006015 case OffsetOfExpr::OffsetOfNode::Identifier:
6016 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006017
Douglas Gregord1702062010-04-29 00:18:15 +00006018 case OffsetOfExpr::OffsetOfNode::Base: {
6019 CXXBaseSpecifier *BaseSpec = ON.getBase();
6020 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006021 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006022
6023 // Find the layout of the class whose base we are looking into.
6024 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006025 if (!RT)
6026 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006027 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006028 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006029 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6030
6031 // Find the base class itself.
6032 CurrentType = BaseSpec->getType();
6033 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6034 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006035 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006036
6037 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006038 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006039 break;
6040 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006041 }
6042 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006043 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006044}
6045
Chris Lattnere13042c2008-07-11 19:10:17 +00006046bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006047 switch (E->getOpcode()) {
6048 default:
6049 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6050 // See C99 6.6p3.
6051 return Error(E);
6052 case UO_Extension:
6053 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6054 // If so, we could clear the diagnostic ID.
6055 return Visit(E->getSubExpr());
6056 case UO_Plus:
6057 // The result is just the value.
6058 return Visit(E->getSubExpr());
6059 case UO_Minus: {
6060 if (!Visit(E->getSubExpr()))
6061 return false;
6062 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006063 const APSInt &Value = Result.getInt();
6064 if (Value.isSigned() && Value.isMinSignedValue())
6065 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6066 E->getType());
6067 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006068 }
6069 case UO_Not: {
6070 if (!Visit(E->getSubExpr()))
6071 return false;
6072 if (!Result.isInt()) return Error(E);
6073 return Success(~Result.getInt(), E);
6074 }
6075 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006076 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006077 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006078 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006079 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006080 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006081 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006082}
Mike Stump11289f42009-09-09 15:08:12 +00006083
Chris Lattner477c4be2008-07-12 01:15:53 +00006084/// HandleCast - This is used to evaluate implicit or explicit casts where the
6085/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006086bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6087 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006088 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006089 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006090
Eli Friedmanc757de22011-03-25 00:43:55 +00006091 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006092 case CK_BaseToDerived:
6093 case CK_DerivedToBase:
6094 case CK_UncheckedDerivedToBase:
6095 case CK_Dynamic:
6096 case CK_ToUnion:
6097 case CK_ArrayToPointerDecay:
6098 case CK_FunctionToPointerDecay:
6099 case CK_NullToPointer:
6100 case CK_NullToMemberPointer:
6101 case CK_BaseToDerivedMemberPointer:
6102 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006103 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006104 case CK_ConstructorConversion:
6105 case CK_IntegralToPointer:
6106 case CK_ToVoid:
6107 case CK_VectorSplat:
6108 case CK_IntegralToFloating:
6109 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006110 case CK_CPointerToObjCPointerCast:
6111 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006112 case CK_AnyPointerToBlockPointerCast:
6113 case CK_ObjCObjectLValueCast:
6114 case CK_FloatingRealToComplex:
6115 case CK_FloatingComplexToReal:
6116 case CK_FloatingComplexCast:
6117 case CK_FloatingComplexToIntegralComplex:
6118 case CK_IntegralRealToComplex:
6119 case CK_IntegralComplexCast:
6120 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006121 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006122 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006123 llvm_unreachable("invalid cast kind for integral value");
6124
Eli Friedman9faf2f92011-03-25 19:07:11 +00006125 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006126 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006127 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006128 case CK_ARCProduceObject:
6129 case CK_ARCConsumeObject:
6130 case CK_ARCReclaimReturnedObject:
6131 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006132 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006133 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006134
Richard Smith4ef685b2012-01-17 21:17:26 +00006135 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006136 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006137 case CK_AtomicToNonAtomic:
6138 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006139 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006140 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006141
6142 case CK_MemberPointerToBoolean:
6143 case CK_PointerToBoolean:
6144 case CK_IntegralToBoolean:
6145 case CK_FloatingToBoolean:
6146 case CK_FloatingComplexToBoolean:
6147 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006148 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006149 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006150 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006151 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006152 }
6153
Eli Friedmanc757de22011-03-25 00:43:55 +00006154 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006155 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006156 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006157
Eli Friedman742421e2009-02-20 01:15:07 +00006158 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006159 // Allow casts of address-of-label differences if they are no-ops
6160 // or narrowing. (The narrowing case isn't actually guaranteed to
6161 // be constant-evaluatable except in some narrow cases which are hard
6162 // to detect here. We let it through on the assumption the user knows
6163 // what they are doing.)
6164 if (Result.isAddrLabelDiff())
6165 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006166 // Only allow casts of lvalues if they are lossless.
6167 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6168 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006169
Richard Smith911e1422012-01-30 22:27:01 +00006170 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6171 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006172 }
Mike Stump11289f42009-09-09 15:08:12 +00006173
Eli Friedmanc757de22011-03-25 00:43:55 +00006174 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006175 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6176
John McCall45d55e42010-05-07 21:00:08 +00006177 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006178 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006179 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006180
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006181 if (LV.getLValueBase()) {
6182 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006183 // FIXME: Allow a larger integer size than the pointer size, and allow
6184 // narrowing back down to pointer width in subsequent integral casts.
6185 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006186 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006187 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006188
Richard Smithcf74da72011-11-16 07:18:12 +00006189 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006190 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006191 return true;
6192 }
6193
Ken Dyck02990832010-01-15 12:37:54 +00006194 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6195 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006196 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006197 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006198
Eli Friedmanc757de22011-03-25 00:43:55 +00006199 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006200 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006201 if (!EvaluateComplex(SubExpr, C, Info))
6202 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006203 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006204 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006205
Eli Friedmanc757de22011-03-25 00:43:55 +00006206 case CK_FloatingToIntegral: {
6207 APFloat F(0.0);
6208 if (!EvaluateFloat(SubExpr, F, Info))
6209 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006210
Richard Smith357362d2011-12-13 06:39:58 +00006211 APSInt Value;
6212 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6213 return false;
6214 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006215 }
6216 }
Mike Stump11289f42009-09-09 15:08:12 +00006217
Eli Friedmanc757de22011-03-25 00:43:55 +00006218 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006219}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006220
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006221bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6222 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006223 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006224 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6225 return false;
6226 if (!LV.isComplexInt())
6227 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006228 return Success(LV.getComplexIntReal(), E);
6229 }
6230
6231 return Visit(E->getSubExpr());
6232}
6233
Eli Friedman4e7a2412009-02-27 04:45:43 +00006234bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006235 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006236 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006237 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6238 return false;
6239 if (!LV.isComplexInt())
6240 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006241 return Success(LV.getComplexIntImag(), E);
6242 }
6243
Richard Smith4a678122011-10-24 18:44:57 +00006244 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006245 return Success(0, E);
6246}
6247
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006248bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6249 return Success(E->getPackLength(), E);
6250}
6251
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006252bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6253 return Success(E->getValue(), E);
6254}
6255
Chris Lattner05706e882008-07-11 18:11:29 +00006256//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006257// Float Evaluation
6258//===----------------------------------------------------------------------===//
6259
6260namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006261class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006262 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006263 APFloat &Result;
6264public:
6265 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006266 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006267
Richard Smith2e312c82012-03-03 22:46:17 +00006268 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006269 Result = V.getFloat();
6270 return true;
6271 }
Eli Friedman24c01542008-08-22 00:06:13 +00006272
Richard Smithfddd3842011-12-30 21:15:51 +00006273 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006274 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6275 return true;
6276 }
6277
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006278 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006279
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006280 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006281 bool VisitBinaryOperator(const BinaryOperator *E);
6282 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006283 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006284
John McCallb1fb0d32010-05-07 22:08:54 +00006285 bool VisitUnaryReal(const UnaryOperator *E);
6286 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006287
Richard Smithfddd3842011-12-30 21:15:51 +00006288 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006289};
6290} // end anonymous namespace
6291
6292static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006293 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006294 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006295}
6296
Jay Foad39c79802011-01-12 09:06:06 +00006297static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006298 QualType ResultTy,
6299 const Expr *Arg,
6300 bool SNaN,
6301 llvm::APFloat &Result) {
6302 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6303 if (!S) return false;
6304
6305 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6306
6307 llvm::APInt fill;
6308
6309 // Treat empty strings as if they were zero.
6310 if (S->getString().empty())
6311 fill = llvm::APInt(32, 0);
6312 else if (S->getString().getAsInteger(0, fill))
6313 return false;
6314
6315 if (SNaN)
6316 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6317 else
6318 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6319 return true;
6320}
6321
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006322bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006323 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006324 default:
6325 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6326
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006327 case Builtin::BI__builtin_huge_val:
6328 case Builtin::BI__builtin_huge_valf:
6329 case Builtin::BI__builtin_huge_vall:
6330 case Builtin::BI__builtin_inf:
6331 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006332 case Builtin::BI__builtin_infl: {
6333 const llvm::fltSemantics &Sem =
6334 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006335 Result = llvm::APFloat::getInf(Sem);
6336 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006337 }
Mike Stump11289f42009-09-09 15:08:12 +00006338
John McCall16291492010-02-28 13:00:19 +00006339 case Builtin::BI__builtin_nans:
6340 case Builtin::BI__builtin_nansf:
6341 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006342 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6343 true, Result))
6344 return Error(E);
6345 return true;
John McCall16291492010-02-28 13:00:19 +00006346
Chris Lattner0b7282e2008-10-06 06:31:58 +00006347 case Builtin::BI__builtin_nan:
6348 case Builtin::BI__builtin_nanf:
6349 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006350 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006351 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006352 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6353 false, Result))
6354 return Error(E);
6355 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006356
6357 case Builtin::BI__builtin_fabs:
6358 case Builtin::BI__builtin_fabsf:
6359 case Builtin::BI__builtin_fabsl:
6360 if (!EvaluateFloat(E->getArg(0), Result, Info))
6361 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006362
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006363 if (Result.isNegative())
6364 Result.changeSign();
6365 return true;
6366
Mike Stump11289f42009-09-09 15:08:12 +00006367 case Builtin::BI__builtin_copysign:
6368 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006369 case Builtin::BI__builtin_copysignl: {
6370 APFloat RHS(0.);
6371 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6372 !EvaluateFloat(E->getArg(1), RHS, Info))
6373 return false;
6374 Result.copySign(RHS);
6375 return true;
6376 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006377 }
6378}
6379
John McCallb1fb0d32010-05-07 22:08:54 +00006380bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006381 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6382 ComplexValue CV;
6383 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6384 return false;
6385 Result = CV.FloatReal;
6386 return true;
6387 }
6388
6389 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00006390}
6391
6392bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006393 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6394 ComplexValue CV;
6395 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6396 return false;
6397 Result = CV.FloatImag;
6398 return true;
6399 }
6400
Richard Smith4a678122011-10-24 18:44:57 +00006401 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00006402 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6403 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00006404 return true;
6405}
6406
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006407bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006408 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006409 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006410 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00006411 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00006412 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00006413 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6414 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006415 Result.changeSign();
6416 return true;
6417 }
6418}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006419
Eli Friedman24c01542008-08-22 00:06:13 +00006420bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006421 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6422 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00006423
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006424 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00006425 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6426 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00006427 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006428 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedman24c01542008-08-22 00:06:13 +00006429 return false;
6430
6431 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006432 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006433 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00006434 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006435 break;
John McCalle3027922010-08-25 11:45:40 +00006436 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00006437 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006438 break;
John McCalle3027922010-08-25 11:45:40 +00006439 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00006440 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006441 break;
John McCalle3027922010-08-25 11:45:40 +00006442 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00006443 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00006444 break;
Eli Friedman24c01542008-08-22 00:06:13 +00006445 }
Richard Smithc8042322012-02-01 05:53:12 +00006446
6447 if (Result.isInfinity() || Result.isNaN())
6448 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
6449 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00006450}
6451
6452bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6453 Result = E->getValue();
6454 return true;
6455}
6456
Peter Collingbournee9200682011-05-13 03:29:01 +00006457bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6458 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00006459
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006460 switch (E->getCastKind()) {
6461 default:
Richard Smith11562c52011-10-28 17:51:58 +00006462 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006463
6464 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006465 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00006466 return EvaluateInteger(SubExpr, IntResult, Info) &&
6467 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6468 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006469 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006470
6471 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006472 if (!Visit(SubExpr))
6473 return false;
Richard Smith357362d2011-12-13 06:39:58 +00006474 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6475 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006476 }
John McCalld7646252010-11-14 08:17:51 +00006477
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006478 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00006479 ComplexValue V;
6480 if (!EvaluateComplex(SubExpr, V, Info))
6481 return false;
6482 Result = V.getComplexFloatReal();
6483 return true;
6484 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006485 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006486}
6487
Eli Friedman24c01542008-08-22 00:06:13 +00006488//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006489// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00006490//===----------------------------------------------------------------------===//
6491
6492namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006493class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006494 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00006495 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00006496
Anders Carlsson537969c2008-11-16 20:27:53 +00006497public:
John McCall93d91dc2010-05-07 17:22:02 +00006498 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006499 : ExprEvaluatorBaseTy(info), Result(Result) {}
6500
Richard Smith2e312c82012-03-03 22:46:17 +00006501 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006502 Result.setFrom(V);
6503 return true;
6504 }
Mike Stump11289f42009-09-09 15:08:12 +00006505
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006506 bool ZeroInitialization(const Expr *E);
6507
Anders Carlsson537969c2008-11-16 20:27:53 +00006508 //===--------------------------------------------------------------------===//
6509 // Visitor Methods
6510 //===--------------------------------------------------------------------===//
6511
Peter Collingbournee9200682011-05-13 03:29:01 +00006512 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006513 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00006514 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006515 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006516 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006517};
6518} // end anonymous namespace
6519
John McCall93d91dc2010-05-07 17:22:02 +00006520static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6521 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006522 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006523 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006524}
6525
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006526bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00006527 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006528 if (ElemTy->isRealFloatingType()) {
6529 Result.makeComplexFloat();
6530 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6531 Result.FloatReal = Zero;
6532 Result.FloatImag = Zero;
6533 } else {
6534 Result.makeComplexInt();
6535 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6536 Result.IntReal = Zero;
6537 Result.IntImag = Zero;
6538 }
6539 return true;
6540}
6541
Peter Collingbournee9200682011-05-13 03:29:01 +00006542bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6543 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006544
6545 if (SubExpr->getType()->isRealFloatingType()) {
6546 Result.makeComplexFloat();
6547 APFloat &Imag = Result.FloatImag;
6548 if (!EvaluateFloat(SubExpr, Imag, Info))
6549 return false;
6550
6551 Result.FloatReal = APFloat(Imag.getSemantics());
6552 return true;
6553 } else {
6554 assert(SubExpr->getType()->isIntegerType() &&
6555 "Unexpected imaginary literal.");
6556
6557 Result.makeComplexInt();
6558 APSInt &Imag = Result.IntImag;
6559 if (!EvaluateInteger(SubExpr, Imag, Info))
6560 return false;
6561
6562 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6563 return true;
6564 }
6565}
6566
Peter Collingbournee9200682011-05-13 03:29:01 +00006567bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006568
John McCallfcef3cf2010-12-14 17:51:41 +00006569 switch (E->getCastKind()) {
6570 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006571 case CK_BaseToDerived:
6572 case CK_DerivedToBase:
6573 case CK_UncheckedDerivedToBase:
6574 case CK_Dynamic:
6575 case CK_ToUnion:
6576 case CK_ArrayToPointerDecay:
6577 case CK_FunctionToPointerDecay:
6578 case CK_NullToPointer:
6579 case CK_NullToMemberPointer:
6580 case CK_BaseToDerivedMemberPointer:
6581 case CK_DerivedToBaseMemberPointer:
6582 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00006583 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00006584 case CK_ConstructorConversion:
6585 case CK_IntegralToPointer:
6586 case CK_PointerToIntegral:
6587 case CK_PointerToBoolean:
6588 case CK_ToVoid:
6589 case CK_VectorSplat:
6590 case CK_IntegralCast:
6591 case CK_IntegralToBoolean:
6592 case CK_IntegralToFloating:
6593 case CK_FloatingToIntegral:
6594 case CK_FloatingToBoolean:
6595 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006596 case CK_CPointerToObjCPointerCast:
6597 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006598 case CK_AnyPointerToBlockPointerCast:
6599 case CK_ObjCObjectLValueCast:
6600 case CK_FloatingComplexToReal:
6601 case CK_FloatingComplexToBoolean:
6602 case CK_IntegralComplexToReal:
6603 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00006604 case CK_ARCProduceObject:
6605 case CK_ARCConsumeObject:
6606 case CK_ARCReclaimReturnedObject:
6607 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006608 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00006609 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006610 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00006611 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00006612
John McCallfcef3cf2010-12-14 17:51:41 +00006613 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006614 case CK_AtomicToNonAtomic:
6615 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006616 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006617 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006618
6619 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006620 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006621 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006622 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006623
6624 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006625 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00006626 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006627 return false;
6628
John McCallfcef3cf2010-12-14 17:51:41 +00006629 Result.makeComplexFloat();
6630 Result.FloatImag = APFloat(Real.getSemantics());
6631 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006632 }
6633
John McCallfcef3cf2010-12-14 17:51:41 +00006634 case CK_FloatingComplexCast: {
6635 if (!Visit(E->getSubExpr()))
6636 return false;
6637
6638 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6639 QualType From
6640 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6641
Richard Smith357362d2011-12-13 06:39:58 +00006642 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6643 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006644 }
6645
6646 case CK_FloatingComplexToIntegralComplex: {
6647 if (!Visit(E->getSubExpr()))
6648 return false;
6649
6650 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6651 QualType From
6652 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6653 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00006654 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6655 To, Result.IntReal) &&
6656 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6657 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006658 }
6659
6660 case CK_IntegralRealToComplex: {
6661 APSInt &Real = Result.IntReal;
6662 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6663 return false;
6664
6665 Result.makeComplexInt();
6666 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
6667 return true;
6668 }
6669
6670 case CK_IntegralComplexCast: {
6671 if (!Visit(E->getSubExpr()))
6672 return false;
6673
6674 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6675 QualType From
6676 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6677
Richard Smith911e1422012-01-30 22:27:01 +00006678 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
6679 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006680 return true;
6681 }
6682
6683 case CK_IntegralComplexToFloatingComplex: {
6684 if (!Visit(E->getSubExpr()))
6685 return false;
6686
Ted Kremenek28831752012-08-23 20:46:57 +00006687 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006688 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00006689 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006690 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00006691 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6692 To, Result.FloatReal) &&
6693 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6694 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006695 }
6696 }
6697
6698 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006699}
6700
John McCall93d91dc2010-05-07 17:22:02 +00006701bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006702 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00006703 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6704
Richard Smith253c2a32012-01-27 01:14:48 +00006705 bool LHSOK = Visit(E->getLHS());
6706 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00006707 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006708
John McCall93d91dc2010-05-07 17:22:02 +00006709 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00006710 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00006711 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006712
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006713 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6714 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006715 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006716 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006717 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006718 if (Result.isComplexFloat()) {
6719 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6720 APFloat::rmNearestTiesToEven);
6721 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6722 APFloat::rmNearestTiesToEven);
6723 } else {
6724 Result.getComplexIntReal() += RHS.getComplexIntReal();
6725 Result.getComplexIntImag() += RHS.getComplexIntImag();
6726 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006727 break;
John McCalle3027922010-08-25 11:45:40 +00006728 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006729 if (Result.isComplexFloat()) {
6730 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6731 APFloat::rmNearestTiesToEven);
6732 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6733 APFloat::rmNearestTiesToEven);
6734 } else {
6735 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6736 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6737 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006738 break;
John McCalle3027922010-08-25 11:45:40 +00006739 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006740 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00006741 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006742 APFloat &LHS_r = LHS.getComplexFloatReal();
6743 APFloat &LHS_i = LHS.getComplexFloatImag();
6744 APFloat &RHS_r = RHS.getComplexFloatReal();
6745 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00006746
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006747 APFloat Tmp = LHS_r;
6748 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6749 Result.getComplexFloatReal() = Tmp;
6750 Tmp = LHS_i;
6751 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6752 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6753
6754 Tmp = LHS_r;
6755 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6756 Result.getComplexFloatImag() = Tmp;
6757 Tmp = LHS_i;
6758 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6759 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6760 } else {
John McCall93d91dc2010-05-07 17:22:02 +00006761 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00006762 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006763 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6764 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00006765 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006766 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6767 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6768 }
6769 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006770 case BO_Div:
6771 if (Result.isComplexFloat()) {
6772 ComplexValue LHS = Result;
6773 APFloat &LHS_r = LHS.getComplexFloatReal();
6774 APFloat &LHS_i = LHS.getComplexFloatImag();
6775 APFloat &RHS_r = RHS.getComplexFloatReal();
6776 APFloat &RHS_i = RHS.getComplexFloatImag();
6777 APFloat &Res_r = Result.getComplexFloatReal();
6778 APFloat &Res_i = Result.getComplexFloatImag();
6779
6780 APFloat Den = RHS_r;
6781 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6782 APFloat Tmp = RHS_i;
6783 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6784 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6785
6786 Res_r = LHS_r;
6787 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6788 Tmp = LHS_i;
6789 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6790 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6791 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6792
6793 Res_i = LHS_i;
6794 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6795 Tmp = LHS_r;
6796 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6797 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6798 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6799 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006800 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6801 return Error(E, diag::note_expr_divide_by_zero);
6802
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006803 ComplexValue LHS = Result;
6804 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6805 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6806 Result.getComplexIntReal() =
6807 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6808 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6809 Result.getComplexIntImag() =
6810 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6811 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6812 }
6813 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006814 }
6815
John McCall93d91dc2010-05-07 17:22:02 +00006816 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006817}
6818
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006819bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6820 // Get the operand value into 'Result'.
6821 if (!Visit(E->getSubExpr()))
6822 return false;
6823
6824 switch (E->getOpcode()) {
6825 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006826 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006827 case UO_Extension:
6828 return true;
6829 case UO_Plus:
6830 // The result is always just the subexpr.
6831 return true;
6832 case UO_Minus:
6833 if (Result.isComplexFloat()) {
6834 Result.getComplexFloatReal().changeSign();
6835 Result.getComplexFloatImag().changeSign();
6836 }
6837 else {
6838 Result.getComplexIntReal() = -Result.getComplexIntReal();
6839 Result.getComplexIntImag() = -Result.getComplexIntImag();
6840 }
6841 return true;
6842 case UO_Not:
6843 if (Result.isComplexFloat())
6844 Result.getComplexFloatImag().changeSign();
6845 else
6846 Result.getComplexIntImag() = -Result.getComplexIntImag();
6847 return true;
6848 }
6849}
6850
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006851bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6852 if (E->getNumInits() == 2) {
6853 if (E->getType()->isComplexType()) {
6854 Result.makeComplexFloat();
6855 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6856 return false;
6857 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6858 return false;
6859 } else {
6860 Result.makeComplexInt();
6861 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6862 return false;
6863 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6864 return false;
6865 }
6866 return true;
6867 }
6868 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6869}
6870
Anders Carlsson537969c2008-11-16 20:27:53 +00006871//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00006872// Void expression evaluation, primarily for a cast to void on the LHS of a
6873// comma operator
6874//===----------------------------------------------------------------------===//
6875
6876namespace {
6877class VoidExprEvaluator
6878 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6879public:
6880 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6881
Richard Smith2e312c82012-03-03 22:46:17 +00006882 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00006883
6884 bool VisitCastExpr(const CastExpr *E) {
6885 switch (E->getCastKind()) {
6886 default:
6887 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6888 case CK_ToVoid:
6889 VisitIgnoredValue(E->getSubExpr());
6890 return true;
6891 }
6892 }
6893};
6894} // end anonymous namespace
6895
6896static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6897 assert(E->isRValue() && E->getType()->isVoidType());
6898 return VoidExprEvaluator(Info).Visit(E);
6899}
6900
6901//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00006902// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00006903//===----------------------------------------------------------------------===//
6904
Richard Smith2e312c82012-03-03 22:46:17 +00006905static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006906 // In C, function designators are not lvalues, but we evaluate them as if they
6907 // are.
6908 if (E->isGLValue() || E->getType()->isFunctionType()) {
6909 LValue LV;
6910 if (!EvaluateLValue(E, LV, Info))
6911 return false;
6912 LV.moveInto(Result);
6913 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006914 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006915 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006916 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006917 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006918 return false;
John McCall45d55e42010-05-07 21:00:08 +00006919 } else if (E->getType()->hasPointerRepresentation()) {
6920 LValue LV;
6921 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006922 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006923 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00006924 } else if (E->getType()->isRealFloatingType()) {
6925 llvm::APFloat F(0.0);
6926 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006927 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006928 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00006929 } else if (E->getType()->isAnyComplexType()) {
6930 ComplexValue C;
6931 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006932 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006933 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00006934 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00006935 MemberPtr P;
6936 if (!EvaluateMemberPointer(E, P, Info))
6937 return false;
6938 P.moveInto(Result);
6939 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00006940 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006941 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006942 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006943 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00006944 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006945 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00006946 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006947 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006948 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006949 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6950 return false;
6951 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00006952 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006953 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006954 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00006955 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00006956 if (!EvaluateVoid(E, Info))
6957 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006958 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006959 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00006960 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006961 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006962 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00006963 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006964 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006965
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00006966 return true;
6967}
6968
Richard Smithb228a862012-02-15 02:18:13 +00006969/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6970/// cases, the in-place evaluation is essential, since later initializers for
6971/// an object can indirectly refer to subobjects which were initialized earlier.
6972static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6973 const Expr *E, CheckConstantExpressionKind CCEK,
6974 bool AllowNonLiteralTypes) {
Richard Smith6331c402012-02-13 22:16:19 +00006975 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00006976 return false;
6977
6978 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00006979 // Evaluate arrays and record types in-place, so that later initializers can
6980 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00006981 if (E->getType()->isArrayType())
6982 return EvaluateArray(E, This, Result, Info);
6983 else if (E->getType()->isRecordType())
6984 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00006985 }
6986
6987 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00006988 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00006989}
6990
Richard Smithf57d8cb2011-12-09 22:58:01 +00006991/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6992/// lvalue-to-rvalue cast if it is an lvalue.
6993static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00006994 if (!CheckLiteralType(Info, E))
6995 return false;
6996
Richard Smith2e312c82012-03-03 22:46:17 +00006997 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006998 return false;
6999
7000 if (E->isGLValue()) {
7001 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007002 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007003 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007004 return false;
7005 }
7006
Richard Smith2e312c82012-03-03 22:46:17 +00007007 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007008 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007009}
Richard Smith11562c52011-10-28 17:51:58 +00007010
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007011static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7012 const ASTContext &Ctx, bool &IsConst) {
7013 // Fast-path evaluations of integer literals, since we sometimes see files
7014 // containing vast quantities of these.
7015 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7016 Result.Val = APValue(APSInt(L->getValue(),
7017 L->getType()->isUnsignedIntegerType()));
7018 IsConst = true;
7019 return true;
7020 }
7021
7022 // FIXME: Evaluating values of large array and record types can cause
7023 // performance problems. Only do so in C++11 for now.
7024 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7025 Exp->getType()->isRecordType()) &&
7026 !Ctx.getLangOpts().CPlusPlus11) {
7027 IsConst = false;
7028 return true;
7029 }
7030 return false;
7031}
7032
7033
Richard Smith7b553f12011-10-29 00:50:52 +00007034/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007035/// any crazy technique (that has nothing to do with language standards) that
7036/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007037/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7038/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007039bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007040 bool IsConst;
7041 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7042 return IsConst;
7043
Richard Smithf57d8cb2011-12-09 22:58:01 +00007044 EvalInfo Info(Ctx, Result);
7045 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007046}
7047
Jay Foad39c79802011-01-12 09:06:06 +00007048bool Expr::EvaluateAsBooleanCondition(bool &Result,
7049 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007050 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007051 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007052 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007053}
7054
Richard Smith5fab0c92011-12-28 19:48:30 +00007055bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7056 SideEffectsKind AllowSideEffects) const {
7057 if (!getType()->isIntegralOrEnumerationType())
7058 return false;
7059
Richard Smith11562c52011-10-28 17:51:58 +00007060 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007061 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7062 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007063 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007064
Richard Smith11562c52011-10-28 17:51:58 +00007065 Result = ExprResult.Val.getInt();
7066 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007067}
7068
Jay Foad39c79802011-01-12 09:06:06 +00007069bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007070 EvalInfo Info(Ctx, Result);
7071
John McCall45d55e42010-05-07 21:00:08 +00007072 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007073 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7074 !CheckLValueConstantExpression(Info, getExprLoc(),
7075 Ctx.getLValueReferenceType(getType()), LV))
7076 return false;
7077
Richard Smith2e312c82012-03-03 22:46:17 +00007078 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007079 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007080}
7081
Richard Smithd0b4dd62011-12-19 06:19:21 +00007082bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7083 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007084 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007085 // FIXME: Evaluating initializers for large array and record types can cause
7086 // performance problems. Only do so in C++11 for now.
7087 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007088 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007089 return false;
7090
Richard Smithd0b4dd62011-12-19 06:19:21 +00007091 Expr::EvalStatus EStatus;
7092 EStatus.Diag = &Notes;
7093
7094 EvalInfo InitInfo(Ctx, EStatus);
7095 InitInfo.setEvaluatingDecl(VD, Value);
7096
7097 LValue LVal;
7098 LVal.set(VD);
7099
Richard Smithfddd3842011-12-30 21:15:51 +00007100 // C++11 [basic.start.init]p2:
7101 // Variables with static storage duration or thread storage duration shall be
7102 // zero-initialized before any other initialization takes place.
7103 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007104 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007105 !VD->getType()->isReferenceType()) {
7106 ImplicitValueInitExpr VIE(VD->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007107 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
7108 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007109 return false;
7110 }
7111
Richard Smithb228a862012-02-15 02:18:13 +00007112 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
7113 /*AllowNonLiteralTypes=*/true) ||
7114 EStatus.HasSideEffects)
7115 return false;
7116
7117 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7118 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007119}
7120
Richard Smith7b553f12011-10-29 00:50:52 +00007121/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7122/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007123bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007124 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007125 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007126}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007127
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007128APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007129 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007130 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007131 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007132 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007133 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007134 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007135 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007136
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007137 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007138}
John McCall864e3962010-05-07 05:32:02 +00007139
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007140void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7141 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7142 bool IsConst;
7143 EvalResult EvalResult;
7144 EvalResult.Diag = Diags;
7145 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7146 EvalInfo Info(Ctx, EvalResult, true);
7147 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7148 }
7149}
7150
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007151 bool Expr::EvalResult::isGlobalLValue() const {
7152 assert(Val.isLValue());
7153 return IsGlobalLValue(Val.getLValueBase());
7154 }
7155
7156
John McCall864e3962010-05-07 05:32:02 +00007157/// isIntegerConstantExpr - this recursive routine will test if an expression is
7158/// an integer constant expression.
7159
7160/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7161/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007162
7163// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007164// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7165// and a (possibly null) SourceLocation indicating the location of the problem.
7166//
John McCall864e3962010-05-07 05:32:02 +00007167// Note that to reduce code duplication, this helper does no evaluation
7168// itself; the caller checks whether the expression is evaluatable, and
7169// in the rare cases where CheckICE actually cares about the evaluated
7170// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007171
Dan Gohman28ade552010-07-26 21:25:24 +00007172namespace {
7173
Richard Smith9e575da2012-12-28 13:25:52 +00007174enum ICEKind {
7175 /// This expression is an ICE.
7176 IK_ICE,
7177 /// This expression is not an ICE, but if it isn't evaluated, it's
7178 /// a legal subexpression for an ICE. This return value is used to handle
7179 /// the comma operator in C99 mode, and non-constant subexpressions.
7180 IK_ICEIfUnevaluated,
7181 /// This expression is not an ICE, and is not a legal subexpression for one.
7182 IK_NotICE
7183};
7184
John McCall864e3962010-05-07 05:32:02 +00007185struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007186 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007187 SourceLocation Loc;
7188
Richard Smith9e575da2012-12-28 13:25:52 +00007189 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007190};
7191
Dan Gohman28ade552010-07-26 21:25:24 +00007192}
7193
Richard Smith9e575da2012-12-28 13:25:52 +00007194static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7195
7196static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007197
7198static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7199 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007200 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007201 !EVResult.Val.isInt())
7202 return ICEDiag(IK_NotICE, E->getLocStart());
7203
John McCall864e3962010-05-07 05:32:02 +00007204 return NoDiag();
7205}
7206
7207static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7208 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007209 if (!E->getType()->isIntegralOrEnumerationType())
7210 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007211
7212 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007213#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007214#define STMT(Node, Base) case Expr::Node##Class:
7215#define EXPR(Node, Base)
7216#include "clang/AST/StmtNodes.inc"
7217 case Expr::PredefinedExprClass:
7218 case Expr::FloatingLiteralClass:
7219 case Expr::ImaginaryLiteralClass:
7220 case Expr::StringLiteralClass:
7221 case Expr::ArraySubscriptExprClass:
7222 case Expr::MemberExprClass:
7223 case Expr::CompoundAssignOperatorClass:
7224 case Expr::CompoundLiteralExprClass:
7225 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007226 case Expr::DesignatedInitExprClass:
7227 case Expr::ImplicitValueInitExprClass:
7228 case Expr::ParenListExprClass:
7229 case Expr::VAArgExprClass:
7230 case Expr::AddrLabelExprClass:
7231 case Expr::StmtExprClass:
7232 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007233 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007234 case Expr::CXXDynamicCastExprClass:
7235 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007236 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007237 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007238 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007239 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007240 case Expr::CXXThisExprClass:
7241 case Expr::CXXThrowExprClass:
7242 case Expr::CXXNewExprClass:
7243 case Expr::CXXDeleteExprClass:
7244 case Expr::CXXPseudoDestructorExprClass:
7245 case Expr::UnresolvedLookupExprClass:
7246 case Expr::DependentScopeDeclRefExprClass:
7247 case Expr::CXXConstructExprClass:
7248 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007249 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007250 case Expr::CXXTemporaryObjectExprClass:
7251 case Expr::CXXUnresolvedConstructExprClass:
7252 case Expr::CXXDependentScopeMemberExprClass:
7253 case Expr::UnresolvedMemberExprClass:
7254 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007255 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007256 case Expr::ObjCArrayLiteralClass:
7257 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007258 case Expr::ObjCEncodeExprClass:
7259 case Expr::ObjCMessageExprClass:
7260 case Expr::ObjCSelectorExprClass:
7261 case Expr::ObjCProtocolExprClass:
7262 case Expr::ObjCIvarRefExprClass:
7263 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007264 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007265 case Expr::ObjCIsaExprClass:
7266 case Expr::ShuffleVectorExprClass:
7267 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007268 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007269 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007270 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007271 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007272 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007273 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007274 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007275 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007276 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007277 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007278 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007279 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007280 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007281
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007282 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007283 case Expr::GNUNullExprClass:
7284 // GCC considers the GNU __null value to be an integral constant expression.
7285 return NoDiag();
7286
John McCall7c454bb2011-07-15 05:09:51 +00007287 case Expr::SubstNonTypeTemplateParmExprClass:
7288 return
7289 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7290
John McCall864e3962010-05-07 05:32:02 +00007291 case Expr::ParenExprClass:
7292 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00007293 case Expr::GenericSelectionExprClass:
7294 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007295 case Expr::IntegerLiteralClass:
7296 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007297 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00007298 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00007299 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00007300 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00007301 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00007302 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00007303 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00007304 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007305 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00007306 return NoDiag();
7307 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00007308 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00007309 // C99 6.6/3 allows function calls within unevaluated subexpressions of
7310 // constant expressions, but they can never be ICEs because an ICE cannot
7311 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00007312 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007313 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00007314 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007315 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007316 }
Richard Smith6365c912012-02-24 22:12:32 +00007317 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007318 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
7319 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00007320 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007321 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00007322 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00007323 // Parameter variables are never constants. Without this check,
7324 // getAnyInitializer() can find a default argument, which leads
7325 // to chaos.
7326 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007327 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007328
7329 // C++ 7.1.5.1p2
7330 // A variable of non-volatile const-qualified integral or enumeration
7331 // type initialized by an ICE can be used in ICEs.
7332 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007333 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007334 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007335
Richard Smithd0b4dd62011-12-19 06:19:21 +00007336 const VarDecl *VD;
7337 // Look for a declaration of this variable that has an initializer, and
7338 // check whether it is an ICE.
7339 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7340 return NoDiag();
7341 else
Richard Smith9e575da2012-12-28 13:25:52 +00007342 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007343 }
7344 }
Richard Smith9e575da2012-12-28 13:25:52 +00007345 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00007346 }
John McCall864e3962010-05-07 05:32:02 +00007347 case Expr::UnaryOperatorClass: {
7348 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7349 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007350 case UO_PostInc:
7351 case UO_PostDec:
7352 case UO_PreInc:
7353 case UO_PreDec:
7354 case UO_AddrOf:
7355 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00007356 // C99 6.6/3 allows increment and decrement within unevaluated
7357 // subexpressions of constant expressions, but they can never be ICEs
7358 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007359 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00007360 case UO_Extension:
7361 case UO_LNot:
7362 case UO_Plus:
7363 case UO_Minus:
7364 case UO_Not:
7365 case UO_Real:
7366 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00007367 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007368 }
Richard Smith9e575da2012-12-28 13:25:52 +00007369
John McCall864e3962010-05-07 05:32:02 +00007370 // OffsetOf falls through here.
7371 }
7372 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00007373 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7374 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7375 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7376 // compliance: we should warn earlier for offsetof expressions with
7377 // array subscripts that aren't ICEs, and if the array subscripts
7378 // are ICEs, the value of the offsetof must be an integer constant.
7379 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007380 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00007381 case Expr::UnaryExprOrTypeTraitExprClass: {
7382 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7383 if ((Exp->getKind() == UETT_SizeOf) &&
7384 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00007385 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007386 return NoDiag();
7387 }
7388 case Expr::BinaryOperatorClass: {
7389 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7390 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007391 case BO_PtrMemD:
7392 case BO_PtrMemI:
7393 case BO_Assign:
7394 case BO_MulAssign:
7395 case BO_DivAssign:
7396 case BO_RemAssign:
7397 case BO_AddAssign:
7398 case BO_SubAssign:
7399 case BO_ShlAssign:
7400 case BO_ShrAssign:
7401 case BO_AndAssign:
7402 case BO_XorAssign:
7403 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00007404 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7405 // constant expressions, but they can never be ICEs because an ICE cannot
7406 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007407 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007408
John McCalle3027922010-08-25 11:45:40 +00007409 case BO_Mul:
7410 case BO_Div:
7411 case BO_Rem:
7412 case BO_Add:
7413 case BO_Sub:
7414 case BO_Shl:
7415 case BO_Shr:
7416 case BO_LT:
7417 case BO_GT:
7418 case BO_LE:
7419 case BO_GE:
7420 case BO_EQ:
7421 case BO_NE:
7422 case BO_And:
7423 case BO_Xor:
7424 case BO_Or:
7425 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00007426 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7427 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00007428 if (Exp->getOpcode() == BO_Div ||
7429 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00007430 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00007431 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00007432 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00007433 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007434 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00007435 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007436 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00007437 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007438 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00007439 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007440 }
7441 }
7442 }
John McCalle3027922010-08-25 11:45:40 +00007443 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007444 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00007445 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7446 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00007447 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7448 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007449 } else {
7450 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00007451 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007452 }
7453 }
Richard Smith9e575da2012-12-28 13:25:52 +00007454 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007455 }
John McCalle3027922010-08-25 11:45:40 +00007456 case BO_LAnd:
7457 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00007458 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7459 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007460 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00007461 // Rare case where the RHS has a comma "side-effect"; we need
7462 // to actually check the condition to see whether the side
7463 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00007464 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00007465 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00007466 return RHSResult;
7467 return NoDiag();
7468 }
7469
Richard Smith9e575da2012-12-28 13:25:52 +00007470 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007471 }
7472 }
7473 }
7474 case Expr::ImplicitCastExprClass:
7475 case Expr::CStyleCastExprClass:
7476 case Expr::CXXFunctionalCastExprClass:
7477 case Expr::CXXStaticCastExprClass:
7478 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00007479 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007480 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007481 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00007482 if (isa<ExplicitCastExpr>(E)) {
7483 if (const FloatingLiteral *FL
7484 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7485 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7486 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7487 APSInt IgnoredVal(DestWidth, !DestSigned);
7488 bool Ignored;
7489 // If the value does not fit in the destination type, the behavior is
7490 // undefined, so we are not required to treat it as a constant
7491 // expression.
7492 if (FL->getValue().convertToInteger(IgnoredVal,
7493 llvm::APFloat::rmTowardZero,
7494 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00007495 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00007496 return NoDiag();
7497 }
7498 }
Eli Friedman76d4e432011-09-29 21:49:34 +00007499 switch (cast<CastExpr>(E)->getCastKind()) {
7500 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007501 case CK_AtomicToNonAtomic:
7502 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00007503 case CK_NoOp:
7504 case CK_IntegralToBoolean:
7505 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00007506 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00007507 default:
Richard Smith9e575da2012-12-28 13:25:52 +00007508 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00007509 }
John McCall864e3962010-05-07 05:32:02 +00007510 }
John McCallc07a0c72011-02-17 10:25:35 +00007511 case Expr::BinaryConditionalOperatorClass: {
7512 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7513 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007514 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00007515 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007516 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7517 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7518 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00007519 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00007520 return FalseResult;
7521 }
John McCall864e3962010-05-07 05:32:02 +00007522 case Expr::ConditionalOperatorClass: {
7523 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7524 // If the condition (ignoring parens) is a __builtin_constant_p call,
7525 // then only the true side is actually considered in an integer constant
7526 // expression, and it is fully evaluated. This is an important GNU
7527 // extension. See GCC PR38377 for discussion.
7528 if (const CallExpr *CallCE
7529 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00007530 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7531 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007532 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007533 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007534 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007535
Richard Smithf57d8cb2011-12-09 22:58:01 +00007536 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7537 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007538
Richard Smith9e575da2012-12-28 13:25:52 +00007539 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007540 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007541 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007542 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007543 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00007544 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007545 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00007546 return NoDiag();
7547 // Rare case where the diagnostics depend on which side is evaluated
7548 // Note that if we get here, CondResult is 0, and at least one of
7549 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00007550 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00007551 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00007552 return TrueResult;
7553 }
7554 case Expr::CXXDefaultArgExprClass:
7555 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00007556 case Expr::CXXDefaultInitExprClass:
7557 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007558 case Expr::ChooseExprClass: {
7559 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
7560 }
7561 }
7562
David Blaikiee4d798f2012-01-20 21:50:17 +00007563 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00007564}
7565
Richard Smithf57d8cb2011-12-09 22:58:01 +00007566/// Evaluate an expression as a C++11 integral constant expression.
7567static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
7568 const Expr *E,
7569 llvm::APSInt *Value,
7570 SourceLocation *Loc) {
7571 if (!E->getType()->isIntegralOrEnumerationType()) {
7572 if (Loc) *Loc = E->getExprLoc();
7573 return false;
7574 }
7575
Richard Smith66e05fe2012-01-18 05:21:49 +00007576 APValue Result;
7577 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00007578 return false;
7579
Richard Smith66e05fe2012-01-18 05:21:49 +00007580 assert(Result.isInt() && "pointer cast to int is not an ICE");
7581 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00007582 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007583}
7584
Richard Smith92b1ce02011-12-12 09:28:41 +00007585bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007586 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007587 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
7588
Richard Smith9e575da2012-12-28 13:25:52 +00007589 ICEDiag D = CheckICE(this, Ctx);
7590 if (D.Kind != IK_ICE) {
7591 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00007592 return false;
7593 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007594 return true;
7595}
7596
7597bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
7598 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007599 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007600 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
7601
7602 if (!isIntegerConstantExpr(Ctx, Loc))
7603 return false;
7604 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00007605 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00007606 return true;
7607}
Richard Smith66e05fe2012-01-18 05:21:49 +00007608
Richard Smith98a0a492012-02-14 21:38:30 +00007609bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00007610 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00007611}
7612
Richard Smith66e05fe2012-01-18 05:21:49 +00007613bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7614 SourceLocation *Loc) const {
7615 // We support this checking in C++98 mode in order to diagnose compatibility
7616 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007617 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00007618
Richard Smith98a0a492012-02-14 21:38:30 +00007619 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00007620 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007621 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00007622 Status.Diag = &Diags;
7623 EvalInfo Info(Ctx, Status);
7624
7625 APValue Scratch;
7626 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
7627
7628 if (!Diags.empty()) {
7629 IsConstExpr = false;
7630 if (Loc) *Loc = Diags[0].first;
7631 } else if (!IsConstExpr) {
7632 // FIXME: This shouldn't happen.
7633 if (Loc) *Loc = getExprLoc();
7634 }
7635
7636 return IsConstExpr;
7637}
Richard Smith253c2a32012-01-27 01:14:48 +00007638
7639bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007640 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00007641 PartialDiagnosticAt> &Diags) {
7642 // FIXME: It would be useful to check constexpr function templates, but at the
7643 // moment the constant expression evaluator cannot cope with the non-rigorous
7644 // ASTs which we build for dependent expressions.
7645 if (FD->isDependentContext())
7646 return true;
7647
7648 Expr::EvalStatus Status;
7649 Status.Diag = &Diags;
7650
7651 EvalInfo Info(FD->getASTContext(), Status);
7652 Info.CheckingPotentialConstantExpression = true;
7653
7654 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7655 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
7656
7657 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
7658 // is a temporary being used as the 'this' pointer.
7659 LValue This;
7660 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00007661 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00007662
Richard Smith253c2a32012-01-27 01:14:48 +00007663 ArrayRef<const Expr*> Args;
7664
7665 SourceLocation Loc = FD->getLocation();
7666
Richard Smith2e312c82012-03-03 22:46:17 +00007667 APValue Scratch;
7668 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith253c2a32012-01-27 01:14:48 +00007669 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith2e312c82012-03-03 22:46:17 +00007670 else
Richard Smith253c2a32012-01-27 01:14:48 +00007671 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
7672 Args, FD->getBody(), Info, Scratch);
7673
7674 return Diags.empty();
7675}