blob: 08c26a3ce30882bc5ff259aa16f250aff46e7900 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
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 Smitha3d3bd22013-05-08 02:12:03 +0000383 /// StepsLeft - The remaining number of evaluation steps we're permitted
384 /// to perform. This is essentially a limit for the number of statements
385 /// we will evaluate.
386 unsigned StepsLeft;
387
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000388 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000389 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000390 CallStackFrame BottomFrame;
391
Richard Smithd62306a2011-11-10 06:34:14 +0000392 /// EvaluatingDecl - This is the declaration whose initializer is being
393 /// evaluated, if any.
394 const VarDecl *EvaluatingDecl;
395
396 /// EvaluatingDeclValue - This is the value being constructed for the
397 /// declaration whose initializer is being evaluated, if any.
398 APValue *EvaluatingDeclValue;
399
Richard Smith357362d2011-12-13 06:39:58 +0000400 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
401 /// notes attached to it will also be stored, otherwise they will not be.
402 bool HasActiveDiagnostic;
403
Richard Smith253c2a32012-01-27 01:14:48 +0000404 /// CheckingPotentialConstantExpression - Are we checking whether the
405 /// expression is a potential constant expression? If so, some diagnostics
406 /// are suppressed.
407 bool CheckingPotentialConstantExpression;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000408
409 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000410
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000411 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
Richard Smitha3d3bd22013-05-08 02:12:03 +0000412 bool OverflowCheckMode = false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000413 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000414 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000415 StepsLeft(getLangOpts().ConstexprStepLimit),
Richard Smithb228a862012-02-15 02:18:13 +0000416 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith253c2a32012-01-27 01:14:48 +0000417 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000418 CheckingPotentialConstantExpression(false),
419 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000420
Richard Smithd62306a2011-11-10 06:34:14 +0000421 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
422 EvaluatingDecl = VD;
423 EvaluatingDeclValue = &Value;
424 }
425
David Blaikiebbafb8a2012-03-11 07:00:24 +0000426 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000427
Richard Smith357362d2011-12-13 06:39:58 +0000428 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000429 // Don't perform any constexpr calls (other than the call we're checking)
430 // when checking a potential constant expression.
431 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
432 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000433 if (NextCallIndex == 0) {
434 // NextCallIndex has wrapped around.
435 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
436 return false;
437 }
Richard Smith357362d2011-12-13 06:39:58 +0000438 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
439 return true;
440 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
441 << getLangOpts().ConstexprCallDepth;
442 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000443 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000444
Richard Smithb228a862012-02-15 02:18:13 +0000445 CallStackFrame *getCallFrame(unsigned CallIndex) {
446 assert(CallIndex && "no call index in getCallFrame");
447 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
448 // be null in this loop.
449 CallStackFrame *Frame = CurrentCall;
450 while (Frame->Index > CallIndex)
451 Frame = Frame->Caller;
452 return (Frame->Index == CallIndex) ? Frame : 0;
453 }
454
Richard Smitha3d3bd22013-05-08 02:12:03 +0000455 bool nextStep(const Stmt *S) {
456 if (!StepsLeft) {
457 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
458 return false;
459 }
460 --StepsLeft;
461 return true;
462 }
463
Richard Smith357362d2011-12-13 06:39:58 +0000464 private:
465 /// Add a diagnostic to the diagnostics list.
466 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
467 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
468 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
469 return EvalStatus.Diag->back().second;
470 }
471
Richard Smithf6f003a2011-12-16 19:06:07 +0000472 /// Add notes containing a call stack to the current point of evaluation.
473 void addCallStack(unsigned Limit);
474
Richard Smith357362d2011-12-13 06:39:58 +0000475 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000476 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000477 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
478 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000479 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000480 // If we have a prior diagnostic, it will be noting that the expression
481 // isn't a constant expression. This diagnostic is more important.
482 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000483 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000484 unsigned CallStackNotes = CallStackDepth - 1;
485 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
486 if (Limit)
487 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith253c2a32012-01-27 01:14:48 +0000488 if (CheckingPotentialConstantExpression)
489 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000490
Richard Smith357362d2011-12-13 06:39:58 +0000491 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000492 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000493 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
494 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000495 if (!CheckingPotentialConstantExpression)
496 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000497 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000498 }
Richard Smith357362d2011-12-13 06:39:58 +0000499 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000500 return OptionalDiagnostic();
501 }
502
Richard Smithce1ec5e2012-03-15 04:53:45 +0000503 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
504 = diag::note_invalid_subexpr_in_const_expr,
505 unsigned ExtraNotes = 0) {
506 if (EvalStatus.Diag)
507 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
508 HasActiveDiagnostic = false;
509 return OptionalDiagnostic();
510 }
511
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000512 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
513
Richard Smith92b1ce02011-12-12 09:28:41 +0000514 /// Diagnose that the evaluation does not produce a C++11 core constant
515 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000516 template<typename LocArg>
517 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000518 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000519 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000520 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000521 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
522 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000523 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000524 }
Richard Smith357362d2011-12-13 06:39:58 +0000525 return Diag(Loc, DiagId, ExtraNotes);
526 }
527
528 /// Add a note to a prior diagnostic.
529 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
530 if (!HasActiveDiagnostic)
531 return OptionalDiagnostic();
532 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000533 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000534
535 /// Add a stack of notes to a prior diagnostic.
536 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
537 if (HasActiveDiagnostic) {
538 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
539 Diags.begin(), Diags.end());
540 }
541 }
Richard Smith253c2a32012-01-27 01:14:48 +0000542
543 /// Should we continue evaluation as much as possible after encountering a
544 /// construct which can't be folded?
545 bool keepEvaluatingAfterFailure() {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000546 // Should return true in IntOverflowCheckMode, so that we check for
547 // overflow even if some subexpressions can't be evaluated as constants.
Richard Smitha3d3bd22013-05-08 02:12:03 +0000548 return StepsLeft && (IntOverflowCheckMode ||
549 (CheckingPotentialConstantExpression &&
550 EvalStatus.Diag && EvalStatus.Diag->empty()));
Richard Smith253c2a32012-01-27 01:14:48 +0000551 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000552 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000553
554 /// Object used to treat all foldable expressions as constant expressions.
555 struct FoldConstant {
556 bool Enabled;
557
558 explicit FoldConstant(EvalInfo &Info)
559 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
560 !Info.EvalStatus.HasSideEffects) {
561 }
562 // Treat the value we've computed since this object was created as constant.
563 void Fold(EvalInfo &Info) {
564 if (Enabled && !Info.EvalStatus.Diag->empty() &&
565 !Info.EvalStatus.HasSideEffects)
566 Info.EvalStatus.Diag->clear();
567 }
568 };
Richard Smith17100ba2012-02-16 02:46:34 +0000569
570 /// RAII object used to suppress diagnostics and side-effects from a
571 /// speculative evaluation.
572 class SpeculativeEvaluationRAII {
573 EvalInfo &Info;
574 Expr::EvalStatus Old;
575
576 public:
577 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000578 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000579 : Info(Info), Old(Info.EvalStatus) {
580 Info.EvalStatus.Diag = NewDiag;
581 }
582 ~SpeculativeEvaluationRAII() {
583 Info.EvalStatus = Old;
584 }
585 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000586}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000587
Richard Smitha8105bc2012-01-06 16:39:00 +0000588bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
589 CheckSubobjectKind CSK) {
590 if (Invalid)
591 return false;
592 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000593 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000594 << CSK;
595 setInvalid();
596 return false;
597 }
598 return true;
599}
600
601void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
602 const Expr *E, uint64_t N) {
603 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000604 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000605 << static_cast<int>(N) << /*array*/ 0
606 << static_cast<unsigned>(MostDerivedArraySize);
607 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000608 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000609 << static_cast<int>(N) << /*non-array*/ 1;
610 setInvalid();
611}
612
Richard Smithf6f003a2011-12-16 19:06:07 +0000613CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
614 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000615 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000616 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000617 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000618 Info.CurrentCall = this;
619 ++Info.CallStackDepth;
620}
621
622CallStackFrame::~CallStackFrame() {
623 assert(Info.CurrentCall == this && "calls retired out of order");
624 --Info.CallStackDepth;
625 Info.CurrentCall = Caller;
626}
627
628/// Produce a string describing the given constexpr call.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000629static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000630 unsigned ArgIndex = 0;
631 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith74388b42012-02-04 00:33:54 +0000632 !isa<CXXConstructorDecl>(Frame->Callee) &&
633 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smithf6f003a2011-12-16 19:06:07 +0000634
635 if (!IsMemberCall)
636 Out << *Frame->Callee << '(';
637
638 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
639 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumib8efa1e2012-01-26 09:37:36 +0000640 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smithf6f003a2011-12-16 19:06:07 +0000641 Out << ", ";
642
643 const ParmVarDecl *Param = *I;
Richard Smith2e312c82012-03-03 22:46:17 +0000644 const APValue &Arg = Frame->Arguments[ArgIndex];
645 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smithf6f003a2011-12-16 19:06:07 +0000646
647 if (ArgIndex == 0 && IsMemberCall)
648 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000649 }
650
Richard Smithf6f003a2011-12-16 19:06:07 +0000651 Out << ')';
652}
653
654void EvalInfo::addCallStack(unsigned Limit) {
655 // Determine which calls to skip, if any.
656 unsigned ActiveCalls = CallStackDepth - 1;
657 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
658 if (Limit && Limit < ActiveCalls) {
659 SkipStart = Limit / 2 + Limit % 2;
660 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000661 }
662
Richard Smithf6f003a2011-12-16 19:06:07 +0000663 // Walk the call stack and add the diagnostics.
664 unsigned CallIdx = 0;
665 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
666 Frame = Frame->Caller, ++CallIdx) {
667 // Skip this call?
668 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
669 if (CallIdx == SkipStart) {
670 // Note that we're skipping calls.
671 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
672 << unsigned(ActiveCalls - Limit);
673 }
674 continue;
675 }
676
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000677 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000678 llvm::raw_svector_ostream Out(Buffer);
679 describeCall(Frame, Out);
680 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
681 }
682}
683
684namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000685 struct ComplexValue {
686 private:
687 bool IsInt;
688
689 public:
690 APSInt IntReal, IntImag;
691 APFloat FloatReal, FloatImag;
692
693 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
694
695 void makeComplexFloat() { IsInt = false; }
696 bool isComplexFloat() const { return !IsInt; }
697 APFloat &getComplexFloatReal() { return FloatReal; }
698 APFloat &getComplexFloatImag() { return FloatImag; }
699
700 void makeComplexInt() { IsInt = true; }
701 bool isComplexInt() const { return IsInt; }
702 APSInt &getComplexIntReal() { return IntReal; }
703 APSInt &getComplexIntImag() { return IntImag; }
704
Richard Smith2e312c82012-03-03 22:46:17 +0000705 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000706 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000707 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000708 else
Richard Smith2e312c82012-03-03 22:46:17 +0000709 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000710 }
Richard Smith2e312c82012-03-03 22:46:17 +0000711 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000712 assert(v.isComplexFloat() || v.isComplexInt());
713 if (v.isComplexFloat()) {
714 makeComplexFloat();
715 FloatReal = v.getComplexFloatReal();
716 FloatImag = v.getComplexFloatImag();
717 } else {
718 makeComplexInt();
719 IntReal = v.getComplexIntReal();
720 IntImag = v.getComplexIntImag();
721 }
722 }
John McCall93d91dc2010-05-07 17:22:02 +0000723 };
John McCall45d55e42010-05-07 21:00:08 +0000724
725 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000726 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000727 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000728 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000729 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000730
Richard Smithce40ad62011-11-12 22:28:03 +0000731 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000732 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000733 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000734 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000735 SubobjectDesignator &getLValueDesignator() { return Designator; }
736 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000737
Richard Smith2e312c82012-03-03 22:46:17 +0000738 void moveInto(APValue &V) const {
739 if (Designator.Invalid)
740 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
741 else
742 V = APValue(Base, Offset, Designator.Entries,
743 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000744 }
Richard Smith2e312c82012-03-03 22:46:17 +0000745 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000746 assert(V.isLValue());
747 Base = V.getLValueBase();
748 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000749 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000750 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000751 }
752
Richard Smithb228a862012-02-15 02:18:13 +0000753 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000754 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000755 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000756 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000757 Designator = SubobjectDesignator(getType(B));
758 }
759
760 // Check that this LValue is not based on a null pointer. If it is, produce
761 // a diagnostic and mark the designator as invalid.
762 bool checkNullPointer(EvalInfo &Info, const Expr *E,
763 CheckSubobjectKind CSK) {
764 if (Designator.Invalid)
765 return false;
766 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000767 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000768 << CSK;
769 Designator.setInvalid();
770 return false;
771 }
772 return true;
773 }
774
775 // Check this LValue refers to an object. If not, set the designator to be
776 // invalid and emit a diagnostic.
777 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000778 // Outside C++11, do not build a designator referring to a subobject of
779 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000780 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000781 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000782 return checkNullPointer(Info, E, CSK) &&
783 Designator.checkSubobject(Info, E, CSK);
784 }
785
786 void addDecl(EvalInfo &Info, const Expr *E,
787 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000788 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
789 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000790 }
791 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000792 if (checkSubobject(Info, E, CSK_ArrayToPointer))
793 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000794 }
Richard Smith66c96992012-02-18 22:04:06 +0000795 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000796 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
797 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000798 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000799 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000800 if (checkNullPointer(Info, E, CSK_ArrayIndex))
801 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000802 }
John McCall45d55e42010-05-07 21:00:08 +0000803 };
Richard Smith027bf112011-11-17 22:56:20 +0000804
805 struct MemberPtr {
806 MemberPtr() {}
807 explicit MemberPtr(const ValueDecl *Decl) :
808 DeclAndIsDerivedMember(Decl, false), Path() {}
809
810 /// The member or (direct or indirect) field referred to by this member
811 /// pointer, or 0 if this is a null member pointer.
812 const ValueDecl *getDecl() const {
813 return DeclAndIsDerivedMember.getPointer();
814 }
815 /// Is this actually a member of some type derived from the relevant class?
816 bool isDerivedMember() const {
817 return DeclAndIsDerivedMember.getInt();
818 }
819 /// Get the class which the declaration actually lives in.
820 const CXXRecordDecl *getContainingRecord() const {
821 return cast<CXXRecordDecl>(
822 DeclAndIsDerivedMember.getPointer()->getDeclContext());
823 }
824
Richard Smith2e312c82012-03-03 22:46:17 +0000825 void moveInto(APValue &V) const {
826 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000827 }
Richard Smith2e312c82012-03-03 22:46:17 +0000828 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000829 assert(V.isMemberPointer());
830 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
831 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
832 Path.clear();
833 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
834 Path.insert(Path.end(), P.begin(), P.end());
835 }
836
837 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
838 /// whether the member is a member of some class derived from the class type
839 /// of the member pointer.
840 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
841 /// Path - The path of base/derived classes from the member declaration's
842 /// class (exclusive) to the class type of the member pointer (inclusive).
843 SmallVector<const CXXRecordDecl*, 4> Path;
844
845 /// Perform a cast towards the class of the Decl (either up or down the
846 /// hierarchy).
847 bool castBack(const CXXRecordDecl *Class) {
848 assert(!Path.empty());
849 const CXXRecordDecl *Expected;
850 if (Path.size() >= 2)
851 Expected = Path[Path.size() - 2];
852 else
853 Expected = getContainingRecord();
854 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
855 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
856 // if B does not contain the original member and is not a base or
857 // derived class of the class containing the original member, the result
858 // of the cast is undefined.
859 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
860 // (D::*). We consider that to be a language defect.
861 return false;
862 }
863 Path.pop_back();
864 return true;
865 }
866 /// Perform a base-to-derived member pointer cast.
867 bool castToDerived(const CXXRecordDecl *Derived) {
868 if (!getDecl())
869 return true;
870 if (!isDerivedMember()) {
871 Path.push_back(Derived);
872 return true;
873 }
874 if (!castBack(Derived))
875 return false;
876 if (Path.empty())
877 DeclAndIsDerivedMember.setInt(false);
878 return true;
879 }
880 /// Perform a derived-to-base member pointer cast.
881 bool castToBase(const CXXRecordDecl *Base) {
882 if (!getDecl())
883 return true;
884 if (Path.empty())
885 DeclAndIsDerivedMember.setInt(true);
886 if (isDerivedMember()) {
887 Path.push_back(Base);
888 return true;
889 }
890 return castBack(Base);
891 }
892 };
Richard Smith357362d2011-12-13 06:39:58 +0000893
Richard Smith7bb00672012-02-01 01:42:44 +0000894 /// Compare two member pointers, which are assumed to be of the same type.
895 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
896 if (!LHS.getDecl() || !RHS.getDecl())
897 return !LHS.getDecl() && !RHS.getDecl();
898 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
899 return false;
900 return LHS.Path == RHS.Path;
901 }
902
Richard Smith357362d2011-12-13 06:39:58 +0000903 /// Kinds of constant expression checking, for diagnostics.
904 enum CheckConstantExpressionKind {
905 CCEK_Constant, ///< A normal constant.
906 CCEK_ReturnValue, ///< A constexpr function return value.
907 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
908 };
John McCall93d91dc2010-05-07 17:22:02 +0000909}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000910
Richard Smith2e312c82012-03-03 22:46:17 +0000911static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000912static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
913 const LValue &This, const Expr *E,
914 CheckConstantExpressionKind CCEK = CCEK_Constant,
915 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000916static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
917static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000918static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
919 EvalInfo &Info);
920static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000921static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000922static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000923 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000924static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000925static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000926
927//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000928// Misc utilities
929//===----------------------------------------------------------------------===//
930
Richard Smithd9f663b2013-04-22 15:31:51 +0000931/// Evaluate an expression to see if it had side-effects, and discard its
932/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +0000933/// \return \c true if the caller should keep evaluating.
934static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000935 APValue Scratch;
Richard Smith4e18ca52013-05-06 05:56:11 +0000936 if (!Evaluate(Scratch, Info, E)) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000937 Info.EvalStatus.HasSideEffects = true;
Richard Smith4e18ca52013-05-06 05:56:11 +0000938 return Info.keepEvaluatingAfterFailure();
939 }
940 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +0000941}
942
Richard Smith861b5b52013-05-07 23:34:45 +0000943/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
944/// return its existing value.
945static int64_t getExtValue(const APSInt &Value) {
946 return Value.isSigned() ? Value.getSExtValue()
947 : static_cast<int64_t>(Value.getZExtValue());
948}
949
Richard Smithd62306a2011-11-10 06:34:14 +0000950/// Should this call expression be treated as a string literal?
951static bool IsStringLiteralCall(const CallExpr *E) {
952 unsigned Builtin = E->isBuiltinCall();
953 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
954 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
955}
956
Richard Smithce40ad62011-11-12 22:28:03 +0000957static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000958 // C++11 [expr.const]p3 An address constant expression is a prvalue core
959 // constant expression of pointer type that evaluates to...
960
961 // ... a null pointer value, or a prvalue core constant expression of type
962 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000963 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000964
Richard Smithce40ad62011-11-12 22:28:03 +0000965 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
966 // ... the address of an object with static storage duration,
967 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
968 return VD->hasGlobalStorage();
969 // ... the address of a function,
970 return isa<FunctionDecl>(D);
971 }
972
973 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000974 switch (E->getStmtClass()) {
975 default:
976 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000977 case Expr::CompoundLiteralExprClass: {
978 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
979 return CLE->isFileScope() && CLE->isLValue();
980 }
Richard Smithd62306a2011-11-10 06:34:14 +0000981 // A string literal has static storage duration.
982 case Expr::StringLiteralClass:
983 case Expr::PredefinedExprClass:
984 case Expr::ObjCStringLiteralClass:
985 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000986 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000987 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000988 return true;
989 case Expr::CallExprClass:
990 return IsStringLiteralCall(cast<CallExpr>(E));
991 // For GCC compatibility, &&label has static storage duration.
992 case Expr::AddrLabelExprClass:
993 return true;
994 // A Block literal expression may be used as the initialization value for
995 // Block variables at global or local static scope.
996 case Expr::BlockExprClass:
997 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000998 case Expr::ImplicitValueInitExprClass:
999 // FIXME:
1000 // We can never form an lvalue with an implicit value initialization as its
1001 // base through expression evaluation, so these only appear in one case: the
1002 // implicit variable declaration we invent when checking whether a constexpr
1003 // constructor can produce a constant expression. We must assume that such
1004 // an expression might be a global lvalue.
1005 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001006 }
John McCall95007602010-05-10 23:27:23 +00001007}
1008
Richard Smithb228a862012-02-15 02:18:13 +00001009static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1010 assert(Base && "no location for a null lvalue");
1011 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1012 if (VD)
1013 Info.Note(VD->getLocation(), diag::note_declared_at);
1014 else
Ted Kremenek28831752012-08-23 20:46:57 +00001015 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001016 diag::note_constexpr_temporary_here);
1017}
1018
Richard Smith80815602011-11-07 05:07:52 +00001019/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001020/// value for an address or reference constant expression. Return true if we
1021/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001022static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1023 QualType Type, const LValue &LVal) {
1024 bool IsReferenceType = Type->isReferenceType();
1025
Richard Smith357362d2011-12-13 06:39:58 +00001026 APValue::LValueBase Base = LVal.getLValueBase();
1027 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1028
Richard Smith0dea49e2012-02-18 04:58:18 +00001029 // Check that the object is a global. Note that the fake 'this' object we
1030 // manufacture when checking potential constant expressions is conservatively
1031 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001032 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001033 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001034 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001035 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1036 << IsReferenceType << !Designator.Entries.empty()
1037 << !!VD << VD;
1038 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001039 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001040 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001041 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001042 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001043 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001044 }
Richard Smithb228a862012-02-15 02:18:13 +00001045 assert((Info.CheckingPotentialConstantExpression ||
1046 LVal.getLValueCallIndex() == 0) &&
1047 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001048
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001049 // Check if this is a thread-local variable.
1050 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1051 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001052 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001053 return false;
1054 }
1055 }
1056
Richard Smitha8105bc2012-01-06 16:39:00 +00001057 // Allow address constant expressions to be past-the-end pointers. This is
1058 // an extension: the standard requires them to point to an object.
1059 if (!IsReferenceType)
1060 return true;
1061
1062 // A reference constant expression must refer to an object.
1063 if (!Base) {
1064 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001065 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001066 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001067 }
1068
Richard Smith357362d2011-12-13 06:39:58 +00001069 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001070 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001071 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001072 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001073 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001074 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001075 }
1076
Richard Smith80815602011-11-07 05:07:52 +00001077 return true;
1078}
1079
Richard Smithfddd3842011-12-30 21:15:51 +00001080/// Check that this core constant expression is of literal type, and if not,
1081/// produce an appropriate diagnostic.
1082static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001083 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001084 return true;
1085
1086 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001087 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001088 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001089 << E->getType();
1090 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001091 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001092 return false;
1093}
1094
Richard Smith0b0a0b62011-10-29 20:57:55 +00001095/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001096/// constant expression. If not, report an appropriate diagnostic. Does not
1097/// check that the expression is of literal type.
1098static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1099 QualType Type, const APValue &Value) {
1100 // Core issue 1454: For a literal constant expression of array or class type,
1101 // each subobject of its value shall have been initialized by a constant
1102 // expression.
1103 if (Value.isArray()) {
1104 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1105 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1106 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1107 Value.getArrayInitializedElt(I)))
1108 return false;
1109 }
1110 if (!Value.hasArrayFiller())
1111 return true;
1112 return CheckConstantExpression(Info, DiagLoc, EltTy,
1113 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001114 }
Richard Smithb228a862012-02-15 02:18:13 +00001115 if (Value.isUnion() && Value.getUnionField()) {
1116 return CheckConstantExpression(Info, DiagLoc,
1117 Value.getUnionField()->getType(),
1118 Value.getUnionValue());
1119 }
1120 if (Value.isStruct()) {
1121 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1122 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1123 unsigned BaseIndex = 0;
1124 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1125 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1126 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1127 Value.getStructBase(BaseIndex)))
1128 return false;
1129 }
1130 }
1131 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1132 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001133 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1134 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001135 return false;
1136 }
1137 }
1138
1139 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001140 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001141 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001142 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1143 }
1144
1145 // Everything else is fine.
1146 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001147}
1148
Richard Smith83c68212011-10-31 05:11:32 +00001149const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001150 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001151}
1152
1153static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001154 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001155}
1156
Richard Smithcecf1842011-11-01 21:06:14 +00001157static bool IsWeakLValue(const LValue &Value) {
1158 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001159 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001160}
1161
Richard Smith2e312c82012-03-03 22:46:17 +00001162static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001163 // A null base expression indicates a null pointer. These are always
1164 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001165 if (!Value.getLValueBase()) {
1166 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001167 return true;
1168 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001169
Richard Smith027bf112011-11-17 22:56:20 +00001170 // We have a non-null base. These are generally known to be true, but if it's
1171 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001172 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001173 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001174 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001175}
1176
Richard Smith2e312c82012-03-03 22:46:17 +00001177static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001178 switch (Val.getKind()) {
1179 case APValue::Uninitialized:
1180 return false;
1181 case APValue::Int:
1182 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001183 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001184 case APValue::Float:
1185 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001186 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001187 case APValue::ComplexInt:
1188 Result = Val.getComplexIntReal().getBoolValue() ||
1189 Val.getComplexIntImag().getBoolValue();
1190 return true;
1191 case APValue::ComplexFloat:
1192 Result = !Val.getComplexFloatReal().isZero() ||
1193 !Val.getComplexFloatImag().isZero();
1194 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001195 case APValue::LValue:
1196 return EvalPointerValueAsBool(Val, Result);
1197 case APValue::MemberPointer:
1198 Result = Val.getMemberPointerDecl();
1199 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001200 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001201 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001202 case APValue::Struct:
1203 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001204 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001205 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001206 }
1207
Richard Smith11562c52011-10-28 17:51:58 +00001208 llvm_unreachable("unknown APValue kind");
1209}
1210
1211static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1212 EvalInfo &Info) {
1213 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001214 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001215 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001216 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001217 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001218}
1219
Richard Smith357362d2011-12-13 06:39:58 +00001220template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001221static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001222 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001223 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001224 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001225}
1226
1227static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1228 QualType SrcType, const APFloat &Value,
1229 QualType DestType, APSInt &Result) {
1230 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001231 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001232 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001233
Richard Smith357362d2011-12-13 06:39:58 +00001234 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001235 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001236 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1237 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001238 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001239 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001240}
1241
Richard Smith357362d2011-12-13 06:39:58 +00001242static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1243 QualType SrcType, QualType DestType,
1244 APFloat &Result) {
1245 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001246 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001247 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1248 APFloat::rmNearestTiesToEven, &ignored)
1249 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001250 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001251 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001252}
1253
Richard Smith911e1422012-01-30 22:27:01 +00001254static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1255 QualType DestType, QualType SrcType,
1256 APSInt &Value) {
1257 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001258 APSInt Result = Value;
1259 // Figure out if this is a truncate, extend or noop cast.
1260 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001261 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001262 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001263 return Result;
1264}
1265
Richard Smith357362d2011-12-13 06:39:58 +00001266static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1267 QualType SrcType, const APSInt &Value,
1268 QualType DestType, APFloat &Result) {
1269 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1270 if (Result.convertFromAPInt(Value, Value.isSigned(),
1271 APFloat::rmNearestTiesToEven)
1272 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001273 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001274 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001275}
1276
Eli Friedman803acb32011-12-22 03:51:45 +00001277static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1278 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001279 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001280 if (!Evaluate(SVal, Info, E))
1281 return false;
1282 if (SVal.isInt()) {
1283 Res = SVal.getInt();
1284 return true;
1285 }
1286 if (SVal.isFloat()) {
1287 Res = SVal.getFloat().bitcastToAPInt();
1288 return true;
1289 }
1290 if (SVal.isVector()) {
1291 QualType VecTy = E->getType();
1292 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1293 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1294 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1295 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1296 Res = llvm::APInt::getNullValue(VecSize);
1297 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1298 APValue &Elt = SVal.getVectorElt(i);
1299 llvm::APInt EltAsInt;
1300 if (Elt.isInt()) {
1301 EltAsInt = Elt.getInt();
1302 } else if (Elt.isFloat()) {
1303 EltAsInt = Elt.getFloat().bitcastToAPInt();
1304 } else {
1305 // Don't try to handle vectors of anything other than int or float
1306 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001307 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001308 return false;
1309 }
1310 unsigned BaseEltSize = EltAsInt.getBitWidth();
1311 if (BigEndian)
1312 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1313 else
1314 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1315 }
1316 return true;
1317 }
1318 // Give up if the input isn't an int, float, or vector. For example, we
1319 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001320 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001321 return false;
1322}
1323
Richard Smith43e77732013-05-07 04:50:00 +00001324/// Perform the given integer operation, which is known to need at most BitWidth
1325/// bits, and check for overflow in the original type (if that type was not an
1326/// unsigned type).
1327template<typename Operation>
1328static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1329 const APSInt &LHS, const APSInt &RHS,
1330 unsigned BitWidth, Operation Op) {
1331 if (LHS.isUnsigned())
1332 return Op(LHS, RHS);
1333
1334 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1335 APSInt Result = Value.trunc(LHS.getBitWidth());
1336 if (Result.extend(BitWidth) != Value) {
1337 if (Info.getIntOverflowCheckMode())
1338 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1339 diag::warn_integer_constant_overflow)
1340 << Result.toString(10) << E->getType();
1341 else
1342 HandleOverflow(Info, E, Value, E->getType());
1343 }
1344 return Result;
1345}
1346
1347/// Perform the given binary integer operation.
1348static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1349 BinaryOperatorKind Opcode, APSInt RHS,
1350 APSInt &Result) {
1351 switch (Opcode) {
1352 default:
1353 Info.Diag(E);
1354 return false;
1355 case BO_Mul:
1356 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1357 std::multiplies<APSInt>());
1358 return true;
1359 case BO_Add:
1360 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1361 std::plus<APSInt>());
1362 return true;
1363 case BO_Sub:
1364 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1365 std::minus<APSInt>());
1366 return true;
1367 case BO_And: Result = LHS & RHS; return true;
1368 case BO_Xor: Result = LHS ^ RHS; return true;
1369 case BO_Or: Result = LHS | RHS; return true;
1370 case BO_Div:
1371 case BO_Rem:
1372 if (RHS == 0) {
1373 Info.Diag(E, diag::note_expr_divide_by_zero);
1374 return false;
1375 }
1376 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1377 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1378 LHS.isSigned() && LHS.isMinSignedValue())
1379 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1380 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1381 return true;
1382 case BO_Shl: {
1383 if (Info.getLangOpts().OpenCL)
1384 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1385 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1386 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1387 RHS.isUnsigned());
1388 else if (RHS.isSigned() && RHS.isNegative()) {
1389 // During constant-folding, a negative shift is an opposite shift. Such
1390 // a shift is not a constant expression.
1391 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1392 RHS = -RHS;
1393 goto shift_right;
1394 }
1395 shift_left:
1396 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1397 // the shifted type.
1398 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1399 if (SA != RHS) {
1400 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1401 << RHS << E->getType() << LHS.getBitWidth();
1402 } else if (LHS.isSigned()) {
1403 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1404 // operand, and must not overflow the corresponding unsigned type.
1405 if (LHS.isNegative())
1406 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1407 else if (LHS.countLeadingZeros() < SA)
1408 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1409 }
1410 Result = LHS << SA;
1411 return true;
1412 }
1413 case BO_Shr: {
1414 if (Info.getLangOpts().OpenCL)
1415 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1416 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1417 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1418 RHS.isUnsigned());
1419 else if (RHS.isSigned() && RHS.isNegative()) {
1420 // During constant-folding, a negative shift is an opposite shift. Such a
1421 // shift is not a constant expression.
1422 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1423 RHS = -RHS;
1424 goto shift_left;
1425 }
1426 shift_right:
1427 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1428 // shifted type.
1429 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1430 if (SA != RHS)
1431 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1432 << RHS << E->getType() << LHS.getBitWidth();
1433 Result = LHS >> SA;
1434 return true;
1435 }
1436
1437 case BO_LT: Result = LHS < RHS; return true;
1438 case BO_GT: Result = LHS > RHS; return true;
1439 case BO_LE: Result = LHS <= RHS; return true;
1440 case BO_GE: Result = LHS >= RHS; return true;
1441 case BO_EQ: Result = LHS == RHS; return true;
1442 case BO_NE: Result = LHS != RHS; return true;
1443 }
1444}
1445
Richard Smith861b5b52013-05-07 23:34:45 +00001446/// Perform the given binary floating-point operation, in-place, on LHS.
1447static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1448 APFloat &LHS, BinaryOperatorKind Opcode,
1449 const APFloat &RHS) {
1450 switch (Opcode) {
1451 default:
1452 Info.Diag(E);
1453 return false;
1454 case BO_Mul:
1455 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1456 break;
1457 case BO_Add:
1458 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1459 break;
1460 case BO_Sub:
1461 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1462 break;
1463 case BO_Div:
1464 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1465 break;
1466 }
1467
1468 if (LHS.isInfinity() || LHS.isNaN())
1469 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1470 return true;
1471}
1472
Richard Smitha8105bc2012-01-06 16:39:00 +00001473/// Cast an lvalue referring to a base subobject to a derived class, by
1474/// truncating the lvalue's path to the given length.
1475static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1476 const RecordDecl *TruncatedType,
1477 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001478 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001479
1480 // Check we actually point to a derived class object.
1481 if (TruncatedElements == D.Entries.size())
1482 return true;
1483 assert(TruncatedElements >= D.MostDerivedPathLength &&
1484 "not casting to a derived class");
1485 if (!Result.checkSubobject(Info, E, CSK_Derived))
1486 return false;
1487
1488 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001489 const RecordDecl *RD = TruncatedType;
1490 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001491 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001492 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1493 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001494 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001495 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001496 else
Richard Smithd62306a2011-11-10 06:34:14 +00001497 Result.Offset -= Layout.getBaseClassOffset(Base);
1498 RD = Base;
1499 }
Richard Smith027bf112011-11-17 22:56:20 +00001500 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001501 return true;
1502}
1503
John McCalld7bca762012-05-01 00:38:49 +00001504static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001505 const CXXRecordDecl *Derived,
1506 const CXXRecordDecl *Base,
1507 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001508 if (!RL) {
1509 if (Derived->isInvalidDecl()) return false;
1510 RL = &Info.Ctx.getASTRecordLayout(Derived);
1511 }
1512
Richard Smithd62306a2011-11-10 06:34:14 +00001513 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001514 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001515 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001516}
1517
Richard Smitha8105bc2012-01-06 16:39:00 +00001518static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001519 const CXXRecordDecl *DerivedDecl,
1520 const CXXBaseSpecifier *Base) {
1521 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1522
John McCalld7bca762012-05-01 00:38:49 +00001523 if (!Base->isVirtual())
1524 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001525
Richard Smitha8105bc2012-01-06 16:39:00 +00001526 SubobjectDesignator &D = Obj.Designator;
1527 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001528 return false;
1529
Richard Smitha8105bc2012-01-06 16:39:00 +00001530 // Extract most-derived object and corresponding type.
1531 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1532 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1533 return false;
1534
1535 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001536 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001537 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1538 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001539 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001540 return true;
1541}
1542
1543/// Update LVal to refer to the given field, which must be a member of the type
1544/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001545static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001546 const FieldDecl *FD,
1547 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001548 if (!RL) {
1549 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001550 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001551 }
Richard Smithd62306a2011-11-10 06:34:14 +00001552
1553 unsigned I = FD->getFieldIndex();
1554 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001555 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001556 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001557}
1558
Richard Smith1b78b3d2012-01-25 22:15:11 +00001559/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001560static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001561 LValue &LVal,
1562 const IndirectFieldDecl *IFD) {
1563 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1564 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001565 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1566 return false;
1567 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001568}
1569
Richard Smithd62306a2011-11-10 06:34:14 +00001570/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001571static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1572 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001573 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1574 // extension.
1575 if (Type->isVoidType() || Type->isFunctionType()) {
1576 Size = CharUnits::One();
1577 return true;
1578 }
1579
1580 if (!Type->isConstantSizeType()) {
1581 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001582 // FIXME: Better diagnostic.
1583 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001584 return false;
1585 }
1586
1587 Size = Info.Ctx.getTypeSizeInChars(Type);
1588 return true;
1589}
1590
1591/// Update a pointer value to model pointer arithmetic.
1592/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001593/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001594/// \param LVal - The pointer value to be updated.
1595/// \param EltTy - The pointee type represented by LVal.
1596/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001597static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1598 LValue &LVal, QualType EltTy,
1599 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001600 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001601 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001602 return false;
1603
1604 // Compute the new offset in the appropriate width.
1605 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001606 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001607 return true;
1608}
1609
Richard Smith66c96992012-02-18 22:04:06 +00001610/// Update an lvalue to refer to a component of a complex number.
1611/// \param Info - Information about the ongoing evaluation.
1612/// \param LVal - The lvalue to be updated.
1613/// \param EltTy - The complex number's component type.
1614/// \param Imag - False for the real component, true for the imaginary.
1615static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1616 LValue &LVal, QualType EltTy,
1617 bool Imag) {
1618 if (Imag) {
1619 CharUnits SizeOfComponent;
1620 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1621 return false;
1622 LVal.Offset += SizeOfComponent;
1623 }
1624 LVal.addComplex(Info, E, EltTy, Imag);
1625 return true;
1626}
1627
Richard Smith27908702011-10-24 17:54:18 +00001628/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001629///
1630/// \param Info Information about the ongoing evaluation.
1631/// \param E An expression to be used when printing diagnostics.
1632/// \param VD The variable whose initializer should be obtained.
1633/// \param Frame The frame in which the variable was created. Must be null
1634/// if this variable is not local to the evaluation.
1635/// \param Result Filled in with a pointer to the value of the variable.
1636static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1637 const VarDecl *VD, CallStackFrame *Frame,
1638 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001639 // If this is a parameter to an active constexpr function call, perform
1640 // argument substitution.
1641 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001642 // Assume arguments of a potential constant expression are unknown
1643 // constant expressions.
1644 if (Info.CheckingPotentialConstantExpression)
1645 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001646 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001647 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001648 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001649 }
Richard Smith3229b742013-05-05 21:17:10 +00001650 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001651 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001652 }
Richard Smith27908702011-10-24 17:54:18 +00001653
Richard Smithd9f663b2013-04-22 15:31:51 +00001654 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001655 if (Frame) {
1656 Result = &Frame->Temporaries[VD];
Richard Smithd9f663b2013-04-22 15:31:51 +00001657 // If we've carried on past an unevaluatable local variable initializer,
1658 // we can't go any further. This can happen during potential constant
1659 // expression checking.
Richard Smith3229b742013-05-05 21:17:10 +00001660 return !Result->isUninit();
Richard Smithd9f663b2013-04-22 15:31:51 +00001661 }
1662
Richard Smithd0b4dd62011-12-19 06:19:21 +00001663 // Dig out the initializer, and use the declaration which it's attached to.
1664 const Expr *Init = VD->getAnyInitializer(VD);
1665 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001666 // If we're checking a potential constant expression, the variable could be
1667 // initialized later.
1668 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001669 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001670 return false;
1671 }
1672
Richard Smithd62306a2011-11-10 06:34:14 +00001673 // If we're currently evaluating the initializer of this declaration, use that
1674 // in-flight value.
1675 if (Info.EvaluatingDecl == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001676 Result = Info.EvaluatingDeclValue;
1677 return !Result->isUninit();
Richard Smithd62306a2011-11-10 06:34:14 +00001678 }
1679
Richard Smithcecf1842011-11-01 21:06:14 +00001680 // Never evaluate the initializer of a weak variable. We can't be sure that
1681 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001682 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001683 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001684 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001685 }
Richard Smithcecf1842011-11-01 21:06:14 +00001686
Richard Smithd0b4dd62011-12-19 06:19:21 +00001687 // Check that we can fold the initializer. In C++, we will have already done
1688 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001689 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001690 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001691 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001692 Notes.size() + 1) << VD;
1693 Info.Note(VD->getLocation(), diag::note_declared_at);
1694 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001695 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001696 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001697 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001698 Notes.size() + 1) << VD;
1699 Info.Note(VD->getLocation(), diag::note_declared_at);
1700 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001701 }
Richard Smith27908702011-10-24 17:54:18 +00001702
Richard Smith3229b742013-05-05 21:17:10 +00001703 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001704 return true;
Richard Smith27908702011-10-24 17:54:18 +00001705}
1706
Richard Smith11562c52011-10-28 17:51:58 +00001707static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001708 Qualifiers Quals = T.getQualifiers();
1709 return Quals.hasConst() && !Quals.hasVolatile();
1710}
1711
Richard Smithe97cbd72011-11-11 04:05:33 +00001712/// Get the base index of the given base class within an APValue representing
1713/// the given derived class.
1714static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1715 const CXXRecordDecl *Base) {
1716 Base = Base->getCanonicalDecl();
1717 unsigned Index = 0;
1718 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1719 E = Derived->bases_end(); I != E; ++I, ++Index) {
1720 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1721 return Index;
1722 }
1723
1724 llvm_unreachable("base class missing from derived class's bases list");
1725}
1726
Richard Smith3da88fa2013-04-26 14:36:30 +00001727/// Extract the value of a character from a string literal.
1728static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1729 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001730 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001731 const StringLiteral *S = cast<StringLiteral>(Lit);
1732 const ConstantArrayType *CAT =
1733 Info.Ctx.getAsConstantArrayType(S->getType());
1734 assert(CAT && "string literal isn't an array");
1735 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001736 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001737
1738 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001739 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001740 if (Index < S->getLength())
1741 Value = S->getCodeUnit(Index);
1742 return Value;
1743}
1744
Richard Smith3da88fa2013-04-26 14:36:30 +00001745// Expand a string literal into an array of characters.
1746static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1747 APValue &Result) {
1748 const StringLiteral *S = cast<StringLiteral>(Lit);
1749 const ConstantArrayType *CAT =
1750 Info.Ctx.getAsConstantArrayType(S->getType());
1751 assert(CAT && "string literal isn't an array");
1752 QualType CharType = CAT->getElementType();
1753 assert(CharType->isIntegerType() && "unexpected character type");
1754
1755 unsigned Elts = CAT->getSize().getZExtValue();
1756 Result = APValue(APValue::UninitArray(),
1757 std::min(S->getLength(), Elts), Elts);
1758 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1759 CharType->isUnsignedIntegerType());
1760 if (Result.hasArrayFiller())
1761 Result.getArrayFiller() = APValue(Value);
1762 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1763 Value = S->getCodeUnit(I);
1764 Result.getArrayInitializedElt(I) = APValue(Value);
1765 }
1766}
1767
1768// Expand an array so that it has more than Index filled elements.
1769static void expandArray(APValue &Array, unsigned Index) {
1770 unsigned Size = Array.getArraySize();
1771 assert(Index < Size);
1772
1773 // Always at least double the number of elements for which we store a value.
1774 unsigned OldElts = Array.getArrayInitializedElts();
1775 unsigned NewElts = std::max(Index+1, OldElts * 2);
1776 NewElts = std::min(Size, std::max(NewElts, 8u));
1777
1778 // Copy the data across.
1779 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1780 for (unsigned I = 0; I != OldElts; ++I)
1781 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1782 for (unsigned I = OldElts; I != NewElts; ++I)
1783 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1784 if (NewValue.hasArrayFiller())
1785 NewValue.getArrayFiller() = Array.getArrayFiller();
1786 Array.swap(NewValue);
1787}
1788
Richard Smith861b5b52013-05-07 23:34:45 +00001789/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00001790enum AccessKinds {
1791 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001792 AK_Assign,
1793 AK_Increment,
1794 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001795};
1796
Richard Smith3229b742013-05-05 21:17:10 +00001797/// A handle to a complete object (an object that is not a subobject of
1798/// another object).
1799struct CompleteObject {
1800 /// The value of the complete object.
1801 APValue *Value;
1802 /// The type of the complete object.
1803 QualType Type;
1804
1805 CompleteObject() : Value(0) {}
1806 CompleteObject(APValue *Value, QualType Type)
1807 : Value(Value), Type(Type) {
1808 assert(Value && "missing value for complete object");
1809 }
1810
1811 operator bool() const { return Value; }
1812};
1813
Richard Smith3da88fa2013-04-26 14:36:30 +00001814/// Find the designated sub-object of an rvalue.
1815template<typename SubobjectHandler>
1816typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001817findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001818 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001819 if (Sub.Invalid)
1820 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001821 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001822 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001823 if (Info.getLangOpts().CPlusPlus11)
1824 Info.Diag(E, diag::note_constexpr_access_past_end)
1825 << handler.AccessKind;
1826 else
1827 Info.Diag(E);
1828 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001829 }
Richard Smith6804be52011-11-11 08:28:03 +00001830 if (Sub.Entries.empty())
Richard Smith3229b742013-05-05 21:17:10 +00001831 return handler.found(*Obj.Value, Obj.Type);
1832 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
Richard Smith253c2a32012-01-27 01:14:48 +00001833 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001834 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001835
Richard Smith3229b742013-05-05 21:17:10 +00001836 APValue *O = Obj.Value;
1837 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001838 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001839 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001840 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001841 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001842 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001843 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001844 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001845 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001846 // Note, it should not be possible to form a pointer with a valid
1847 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001848 if (Info.getLangOpts().CPlusPlus11)
1849 Info.Diag(E, diag::note_constexpr_access_past_end)
1850 << handler.AccessKind;
1851 else
1852 Info.Diag(E);
1853 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001854 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001855
1856 ObjType = CAT->getElementType();
1857
Richard Smith14a94132012-02-17 03:35:37 +00001858 // An array object is represented as either an Array APValue or as an
1859 // LValue which refers to a string literal.
1860 if (O->isLValue()) {
1861 assert(I == N - 1 && "extracting subobject of character?");
1862 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001863 if (handler.AccessKind != AK_Read)
1864 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1865 *O);
1866 else
1867 return handler.foundString(*O, ObjType, Index);
1868 }
1869
1870 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001871 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001872 else if (handler.AccessKind != AK_Read) {
1873 expandArray(*O, Index);
1874 O = &O->getArrayInitializedElt(Index);
1875 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001876 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001877 } else if (ObjType->isAnyComplexType()) {
1878 // Next subobject is a complex number.
1879 uint64_t Index = Sub.Entries[I].ArrayIndex;
1880 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001881 if (Info.getLangOpts().CPlusPlus11)
1882 Info.Diag(E, diag::note_constexpr_access_past_end)
1883 << handler.AccessKind;
1884 else
1885 Info.Diag(E);
1886 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001887 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001888
1889 bool WasConstQualified = ObjType.isConstQualified();
1890 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1891 if (WasConstQualified)
1892 ObjType.addConst();
1893
Richard Smith66c96992012-02-18 22:04:06 +00001894 assert(I == N - 1 && "extracting subobject of scalar?");
1895 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001896 return handler.found(Index ? O->getComplexIntImag()
1897 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001898 } else {
1899 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001900 return handler.found(Index ? O->getComplexFloatImag()
1901 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001902 }
Richard Smithd62306a2011-11-10 06:34:14 +00001903 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001904 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001905 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001906 << Field;
1907 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001908 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001909 }
1910
Richard Smithd62306a2011-11-10 06:34:14 +00001911 // Next subobject is a class, struct or union field.
1912 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1913 if (RD->isUnion()) {
1914 const FieldDecl *UnionField = O->getUnionField();
1915 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001916 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001917 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1918 << handler.AccessKind << Field << !UnionField << UnionField;
1919 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001920 }
Richard Smithd62306a2011-11-10 06:34:14 +00001921 O = &O->getUnionValue();
1922 } else
1923 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001924
1925 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001926 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001927 if (WasConstQualified && !Field->isMutable())
1928 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001929
1930 if (ObjType.isVolatileQualified()) {
1931 if (Info.getLangOpts().CPlusPlus) {
1932 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001933 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1934 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001935 Info.Note(Field->getLocation(), diag::note_declared_at);
1936 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001937 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001938 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001939 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001940 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001941 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001942 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001943 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1944 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1945 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00001946
1947 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00001948 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00001949 if (WasConstQualified)
1950 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00001951 }
Richard Smithd62306a2011-11-10 06:34:14 +00001952
Richard Smithf57d8cb2011-12-09 22:58:01 +00001953 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001954 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00001955 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1956 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001957 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001958 }
1959
Richard Smith3da88fa2013-04-26 14:36:30 +00001960 return handler.found(*O, ObjType);
1961}
1962
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001963namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001964struct ExtractSubobjectHandler {
1965 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00001966 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00001967
1968 static const AccessKinds AccessKind = AK_Read;
1969
1970 typedef bool result_type;
1971 bool failed() { return false; }
1972 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001973 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00001974 return true;
1975 }
1976 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001977 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001978 return true;
1979 }
1980 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001981 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001982 return true;
1983 }
1984 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00001985 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00001986 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
1987 return true;
1988 }
1989};
Richard Smith3229b742013-05-05 21:17:10 +00001990} // end anonymous namespace
1991
Richard Smith3da88fa2013-04-26 14:36:30 +00001992const AccessKinds ExtractSubobjectHandler::AccessKind;
1993
1994/// Extract the designated sub-object of an rvalue.
1995static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00001996 const CompleteObject &Obj,
1997 const SubobjectDesignator &Sub,
1998 APValue &Result) {
1999 ExtractSubobjectHandler Handler = { Info, Result };
2000 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002001}
2002
Richard Smith3229b742013-05-05 21:17:10 +00002003namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002004struct ModifySubobjectHandler {
2005 EvalInfo &Info;
2006 APValue &NewVal;
2007 const Expr *E;
2008
2009 typedef bool result_type;
2010 static const AccessKinds AccessKind = AK_Assign;
2011
2012 bool checkConst(QualType QT) {
2013 // Assigning to a const object has undefined behavior.
2014 if (QT.isConstQualified()) {
2015 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2016 return false;
2017 }
2018 return true;
2019 }
2020
2021 bool failed() { return false; }
2022 bool found(APValue &Subobj, QualType SubobjType) {
2023 if (!checkConst(SubobjType))
2024 return false;
2025 // We've been given ownership of NewVal, so just swap it in.
2026 Subobj.swap(NewVal);
2027 return true;
2028 }
2029 bool found(APSInt &Value, QualType SubobjType) {
2030 if (!checkConst(SubobjType))
2031 return false;
2032 if (!NewVal.isInt()) {
2033 // Maybe trying to write a cast pointer value into a complex?
2034 Info.Diag(E);
2035 return false;
2036 }
2037 Value = NewVal.getInt();
2038 return true;
2039 }
2040 bool found(APFloat &Value, QualType SubobjType) {
2041 if (!checkConst(SubobjType))
2042 return false;
2043 Value = NewVal.getFloat();
2044 return true;
2045 }
2046 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2047 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2048 }
2049};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002050} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002051
Richard Smith3229b742013-05-05 21:17:10 +00002052const AccessKinds ModifySubobjectHandler::AccessKind;
2053
Richard Smith3da88fa2013-04-26 14:36:30 +00002054/// Update the designated sub-object of an rvalue to the given value.
2055static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002056 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002057 const SubobjectDesignator &Sub,
2058 APValue &NewVal) {
2059 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002060 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002061}
2062
Richard Smith84f6dcf2012-02-02 01:16:57 +00002063/// Find the position where two subobject designators diverge, or equivalently
2064/// the length of the common initial subsequence.
2065static unsigned FindDesignatorMismatch(QualType ObjType,
2066 const SubobjectDesignator &A,
2067 const SubobjectDesignator &B,
2068 bool &WasArrayIndex) {
2069 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2070 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002071 if (!ObjType.isNull() &&
2072 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002073 // Next subobject is an array element.
2074 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2075 WasArrayIndex = true;
2076 return I;
2077 }
Richard Smith66c96992012-02-18 22:04:06 +00002078 if (ObjType->isAnyComplexType())
2079 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2080 else
2081 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002082 } else {
2083 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2084 WasArrayIndex = false;
2085 return I;
2086 }
2087 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2088 // Next subobject is a field.
2089 ObjType = FD->getType();
2090 else
2091 // Next subobject is a base class.
2092 ObjType = QualType();
2093 }
2094 }
2095 WasArrayIndex = false;
2096 return I;
2097}
2098
2099/// Determine whether the given subobject designators refer to elements of the
2100/// same array object.
2101static bool AreElementsOfSameArray(QualType ObjType,
2102 const SubobjectDesignator &A,
2103 const SubobjectDesignator &B) {
2104 if (A.Entries.size() != B.Entries.size())
2105 return false;
2106
2107 bool IsArray = A.MostDerivedArraySize != 0;
2108 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2109 // A is a subobject of the array element.
2110 return false;
2111
2112 // If A (and B) designates an array element, the last entry will be the array
2113 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2114 // of length 1' case, and the entire path must match.
2115 bool WasArrayIndex;
2116 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2117 return CommonLength >= A.Entries.size() - IsArray;
2118}
2119
Richard Smith3229b742013-05-05 21:17:10 +00002120/// Find the complete object to which an LValue refers.
2121CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2122 const LValue &LVal, QualType LValType) {
2123 if (!LVal.Base) {
2124 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2125 return CompleteObject();
2126 }
2127
2128 CallStackFrame *Frame = 0;
2129 if (LVal.CallIndex) {
2130 Frame = Info.getCallFrame(LVal.CallIndex);
2131 if (!Frame) {
2132 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2133 << AK << LVal.Base.is<const ValueDecl*>();
2134 NoteLValueLocation(Info, LVal.Base);
2135 return CompleteObject();
2136 }
2137 } else if (AK != AK_Read) {
2138 Info.Diag(E, diag::note_constexpr_modify_global);
2139 return CompleteObject();
2140 }
2141
2142 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2143 // is not a constant expression (even if the object is non-volatile). We also
2144 // apply this rule to C++98, in order to conform to the expected 'volatile'
2145 // semantics.
2146 if (LValType.isVolatileQualified()) {
2147 if (Info.getLangOpts().CPlusPlus)
2148 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2149 << AK << LValType;
2150 else
2151 Info.Diag(E);
2152 return CompleteObject();
2153 }
2154
2155 // Compute value storage location and type of base object.
2156 APValue *BaseVal = 0;
2157 QualType BaseType;
2158
2159 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2160 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2161 // In C++11, constexpr, non-volatile variables initialized with constant
2162 // expressions are constant expressions too. Inside constexpr functions,
2163 // parameters are constant expressions even if they're non-const.
2164 // In C++1y, objects local to a constant expression (those with a Frame) are
2165 // both readable and writable inside constant expressions.
2166 // In C, such things can also be folded, although they are not ICEs.
2167 const VarDecl *VD = dyn_cast<VarDecl>(D);
2168 if (VD) {
2169 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2170 VD = VDef;
2171 }
2172 if (!VD || VD->isInvalidDecl()) {
2173 Info.Diag(E);
2174 return CompleteObject();
2175 }
2176
2177 // Accesses of volatile-qualified objects are not allowed.
2178 BaseType = VD->getType();
2179 if (BaseType.isVolatileQualified()) {
2180 if (Info.getLangOpts().CPlusPlus) {
2181 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2182 << AK << 1 << VD;
2183 Info.Note(VD->getLocation(), diag::note_declared_at);
2184 } else {
2185 Info.Diag(E);
2186 }
2187 return CompleteObject();
2188 }
2189
2190 // Unless we're looking at a local variable or argument in a constexpr call,
2191 // the variable we're reading must be const.
2192 if (!Frame) {
2193 assert(AK == AK_Read && "can't modify non-local");
2194 if (VD->isConstexpr()) {
2195 // OK, we can read this variable.
2196 } else if (BaseType->isIntegralOrEnumerationType()) {
2197 if (!BaseType.isConstQualified()) {
2198 if (Info.getLangOpts().CPlusPlus) {
2199 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2200 Info.Note(VD->getLocation(), diag::note_declared_at);
2201 } else {
2202 Info.Diag(E);
2203 }
2204 return CompleteObject();
2205 }
2206 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2207 // We support folding of const floating-point types, in order to make
2208 // static const data members of such types (supported as an extension)
2209 // more useful.
2210 if (Info.getLangOpts().CPlusPlus11) {
2211 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2212 Info.Note(VD->getLocation(), diag::note_declared_at);
2213 } else {
2214 Info.CCEDiag(E);
2215 }
2216 } else {
2217 // FIXME: Allow folding of values of any literal type in all languages.
2218 if (Info.getLangOpts().CPlusPlus11) {
2219 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2220 Info.Note(VD->getLocation(), diag::note_declared_at);
2221 } else {
2222 Info.Diag(E);
2223 }
2224 return CompleteObject();
2225 }
2226 }
2227
2228 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2229 return CompleteObject();
2230 } else {
2231 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2232
2233 if (!Frame) {
2234 Info.Diag(E);
2235 return CompleteObject();
2236 }
2237
2238 BaseType = Base->getType();
2239 BaseVal = &Frame->Temporaries[Base];
2240
2241 // Volatile temporary objects cannot be accessed in constant expressions.
2242 if (BaseType.isVolatileQualified()) {
2243 if (Info.getLangOpts().CPlusPlus) {
2244 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2245 << AK << 0;
2246 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2247 } else {
2248 Info.Diag(E);
2249 }
2250 return CompleteObject();
2251 }
2252 }
2253
2254 // In C++1y, we can't safely access any mutable state when checking a
2255 // potential constant expression.
2256 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2257 Info.CheckingPotentialConstantExpression)
2258 return CompleteObject();
2259
2260 return CompleteObject(BaseVal, BaseType);
2261}
2262
Richard Smith243ef902013-05-05 23:31:59 +00002263/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2264/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2265/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002266///
2267/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002268/// \param Conv - The expression for which we are performing the conversion.
2269/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002270/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2271/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002272/// \param LVal - The glvalue on which we are attempting to perform this action.
2273/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002274static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002275 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002276 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002277 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002278 return false;
2279
Richard Smith3229b742013-05-05 21:17:10 +00002280 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002281 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002282 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2283 !Type.isVolatileQualified()) {
2284 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2285 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2286 // initializer until now for such expressions. Such an expression can't be
2287 // an ICE in C, so this only matters for fold.
2288 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2289 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002290 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002291 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002292 }
Richard Smith3229b742013-05-05 21:17:10 +00002293 APValue Lit;
2294 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2295 return false;
2296 CompleteObject LitObj(&Lit, Base->getType());
2297 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2298 } else if (isa<StringLiteral>(Base)) {
2299 // We represent a string literal array as an lvalue pointing at the
2300 // corresponding expression, rather than building an array of chars.
2301 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2302 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2303 CompleteObject StrObj(&Str, Base->getType());
2304 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002305 }
Richard Smith11562c52011-10-28 17:51:58 +00002306 }
2307
Richard Smith3229b742013-05-05 21:17:10 +00002308 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2309 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002310}
2311
2312/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002313static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002314 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002315 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002316 return false;
2317
Richard Smith3229b742013-05-05 21:17:10 +00002318 if (!Info.getLangOpts().CPlusPlus1y) {
2319 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002320 return false;
2321 }
2322
Richard Smith3229b742013-05-05 21:17:10 +00002323 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2324 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002325}
2326
Richard Smith243ef902013-05-05 23:31:59 +00002327static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2328 return T->isSignedIntegerType() &&
2329 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2330}
2331
2332namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002333struct CompoundAssignSubobjectHandler {
2334 EvalInfo &Info;
2335 const Expr *E;
2336 QualType PromotedLHSType;
2337 BinaryOperatorKind Opcode;
2338 const APValue &RHS;
2339
2340 static const AccessKinds AccessKind = AK_Assign;
2341
2342 typedef bool result_type;
2343
2344 bool checkConst(QualType QT) {
2345 // Assigning to a const object has undefined behavior.
2346 if (QT.isConstQualified()) {
2347 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2348 return false;
2349 }
2350 return true;
2351 }
2352
2353 bool failed() { return false; }
2354 bool found(APValue &Subobj, QualType SubobjType) {
2355 switch (Subobj.getKind()) {
2356 case APValue::Int:
2357 return found(Subobj.getInt(), SubobjType);
2358 case APValue::Float:
2359 return found(Subobj.getFloat(), SubobjType);
2360 case APValue::ComplexInt:
2361 case APValue::ComplexFloat:
2362 // FIXME: Implement complex compound assignment.
2363 Info.Diag(E);
2364 return false;
2365 case APValue::LValue:
2366 return foundPointer(Subobj, SubobjType);
2367 default:
2368 // FIXME: can this happen?
2369 Info.Diag(E);
2370 return false;
2371 }
2372 }
2373 bool found(APSInt &Value, QualType SubobjType) {
2374 if (!checkConst(SubobjType))
2375 return false;
2376
2377 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2378 // We don't support compound assignment on integer-cast-to-pointer
2379 // values.
2380 Info.Diag(E);
2381 return false;
2382 }
2383
2384 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2385 SubobjType, Value);
2386 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2387 return false;
2388 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2389 return true;
2390 }
2391 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002392 return checkConst(SubobjType) &&
2393 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2394 Value) &&
2395 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2396 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002397 }
2398 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2399 if (!checkConst(SubobjType))
2400 return false;
2401
2402 QualType PointeeType;
2403 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2404 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002405
2406 if (PointeeType.isNull() || !RHS.isInt() ||
2407 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002408 Info.Diag(E);
2409 return false;
2410 }
2411
Richard Smith861b5b52013-05-07 23:34:45 +00002412 int64_t Offset = getExtValue(RHS.getInt());
2413 if (Opcode == BO_Sub)
2414 Offset = -Offset;
2415
2416 LValue LVal;
2417 LVal.setFrom(Info.Ctx, Subobj);
2418 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2419 return false;
2420 LVal.moveInto(Subobj);
2421 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002422 }
2423 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2424 llvm_unreachable("shouldn't encounter string elements here");
2425 }
2426};
2427} // end anonymous namespace
2428
2429const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2430
2431/// Perform a compound assignment of LVal <op>= RVal.
2432static bool handleCompoundAssignment(
2433 EvalInfo &Info, const Expr *E,
2434 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2435 BinaryOperatorKind Opcode, const APValue &RVal) {
2436 if (LVal.Designator.Invalid)
2437 return false;
2438
2439 if (!Info.getLangOpts().CPlusPlus1y) {
2440 Info.Diag(E);
2441 return false;
2442 }
2443
2444 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2445 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2446 RVal };
2447 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2448}
2449
2450namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002451struct IncDecSubobjectHandler {
2452 EvalInfo &Info;
2453 const Expr *E;
2454 AccessKinds AccessKind;
2455 APValue *Old;
2456
2457 typedef bool result_type;
2458
2459 bool checkConst(QualType QT) {
2460 // Assigning to a const object has undefined behavior.
2461 if (QT.isConstQualified()) {
2462 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2463 return false;
2464 }
2465 return true;
2466 }
2467
2468 bool failed() { return false; }
2469 bool found(APValue &Subobj, QualType SubobjType) {
2470 // Stash the old value. Also clear Old, so we don't clobber it later
2471 // if we're post-incrementing a complex.
2472 if (Old) {
2473 *Old = Subobj;
2474 Old = 0;
2475 }
2476
2477 switch (Subobj.getKind()) {
2478 case APValue::Int:
2479 return found(Subobj.getInt(), SubobjType);
2480 case APValue::Float:
2481 return found(Subobj.getFloat(), SubobjType);
2482 case APValue::ComplexInt:
2483 return found(Subobj.getComplexIntReal(),
2484 SubobjType->castAs<ComplexType>()->getElementType()
2485 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2486 case APValue::ComplexFloat:
2487 return found(Subobj.getComplexFloatReal(),
2488 SubobjType->castAs<ComplexType>()->getElementType()
2489 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2490 case APValue::LValue:
2491 return foundPointer(Subobj, SubobjType);
2492 default:
2493 // FIXME: can this happen?
2494 Info.Diag(E);
2495 return false;
2496 }
2497 }
2498 bool found(APSInt &Value, QualType SubobjType) {
2499 if (!checkConst(SubobjType))
2500 return false;
2501
2502 if (!SubobjType->isIntegerType()) {
2503 // We don't support increment / decrement on integer-cast-to-pointer
2504 // values.
2505 Info.Diag(E);
2506 return false;
2507 }
2508
2509 if (Old) *Old = APValue(Value);
2510
2511 // bool arithmetic promotes to int, and the conversion back to bool
2512 // doesn't reduce mod 2^n, so special-case it.
2513 if (SubobjType->isBooleanType()) {
2514 if (AccessKind == AK_Increment)
2515 Value = 1;
2516 else
2517 Value = !Value;
2518 return true;
2519 }
2520
2521 bool WasNegative = Value.isNegative();
2522 if (AccessKind == AK_Increment) {
2523 ++Value;
2524
2525 if (!WasNegative && Value.isNegative() &&
2526 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2527 APSInt ActualValue(Value, /*IsUnsigned*/true);
2528 HandleOverflow(Info, E, ActualValue, SubobjType);
2529 }
2530 } else {
2531 --Value;
2532
2533 if (WasNegative && !Value.isNegative() &&
2534 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2535 unsigned BitWidth = Value.getBitWidth();
2536 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2537 ActualValue.setBit(BitWidth);
2538 HandleOverflow(Info, E, ActualValue, SubobjType);
2539 }
2540 }
2541 return true;
2542 }
2543 bool found(APFloat &Value, QualType SubobjType) {
2544 if (!checkConst(SubobjType))
2545 return false;
2546
2547 if (Old) *Old = APValue(Value);
2548
2549 APFloat One(Value.getSemantics(), 1);
2550 if (AccessKind == AK_Increment)
2551 Value.add(One, APFloat::rmNearestTiesToEven);
2552 else
2553 Value.subtract(One, APFloat::rmNearestTiesToEven);
2554 return true;
2555 }
2556 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2557 if (!checkConst(SubobjType))
2558 return false;
2559
2560 QualType PointeeType;
2561 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2562 PointeeType = PT->getPointeeType();
2563 else {
2564 Info.Diag(E);
2565 return false;
2566 }
2567
2568 LValue LVal;
2569 LVal.setFrom(Info.Ctx, Subobj);
2570 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2571 AccessKind == AK_Increment ? 1 : -1))
2572 return false;
2573 LVal.moveInto(Subobj);
2574 return true;
2575 }
2576 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2577 llvm_unreachable("shouldn't encounter string elements here");
2578 }
2579};
2580} // end anonymous namespace
2581
2582/// Perform an increment or decrement on LVal.
2583static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2584 QualType LValType, bool IsIncrement, APValue *Old) {
2585 if (LVal.Designator.Invalid)
2586 return false;
2587
2588 if (!Info.getLangOpts().CPlusPlus1y) {
2589 Info.Diag(E);
2590 return false;
2591 }
2592
2593 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2594 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2595 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2596 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2597}
2598
Richard Smithe97cbd72011-11-11 04:05:33 +00002599/// Build an lvalue for the object argument of a member function call.
2600static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2601 LValue &This) {
2602 if (Object->getType()->isPointerType())
2603 return EvaluatePointer(Object, This, Info);
2604
2605 if (Object->isGLValue())
2606 return EvaluateLValue(Object, This, Info);
2607
Richard Smithd9f663b2013-04-22 15:31:51 +00002608 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002609 return EvaluateTemporary(Object, This, Info);
2610
2611 return false;
2612}
2613
2614/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2615/// lvalue referring to the result.
2616///
2617/// \param Info - Information about the ongoing evaluation.
2618/// \param BO - The member pointer access operation.
2619/// \param LV - Filled in with a reference to the resulting object.
2620/// \param IncludeMember - Specifies whether the member itself is included in
2621/// the resulting LValue subobject designator. This is not possible when
2622/// creating a bound member function.
2623/// \return The field or method declaration to which the member pointer refers,
2624/// or 0 if evaluation fails.
2625static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2626 const BinaryOperator *BO,
2627 LValue &LV,
2628 bool IncludeMember = true) {
2629 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2630
Richard Smith253c2a32012-01-27 01:14:48 +00002631 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
2632 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00002633 return 0;
2634
2635 MemberPtr MemPtr;
2636 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
2637 return 0;
2638
2639 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2640 // member value, the behavior is undefined.
2641 if (!MemPtr.getDecl())
2642 return 0;
2643
Richard Smith253c2a32012-01-27 01:14:48 +00002644 if (!EvalObjOK)
2645 return 0;
2646
Richard Smith027bf112011-11-17 22:56:20 +00002647 if (MemPtr.isDerivedMember()) {
2648 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002649 // The end of the derived-to-base path for the base object must match the
2650 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002651 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00002652 LV.Designator.Entries.size())
2653 return 0;
2654 unsigned PathLengthToMember =
2655 LV.Designator.Entries.size() - MemPtr.Path.size();
2656 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2657 const CXXRecordDecl *LVDecl = getAsBaseClass(
2658 LV.Designator.Entries[PathLengthToMember + I]);
2659 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2660 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
2661 return 0;
2662 }
2663
2664 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002665 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
2666 PathLengthToMember))
2667 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002668 } else if (!MemPtr.Path.empty()) {
2669 // Extend the LValue path with the member pointer's path.
2670 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2671 MemPtr.Path.size() + IncludeMember);
2672
2673 // Walk down to the appropriate base class.
2674 QualType LVType = BO->getLHS()->getType();
2675 if (const PointerType *PT = LVType->getAs<PointerType>())
2676 LVType = PT->getPointeeType();
2677 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2678 assert(RD && "member pointer access on non-class-type expression");
2679 // The first class in the path is that of the lvalue.
2680 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2681 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00002682 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
2683 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002684 RD = Base;
2685 }
2686 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00002687 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
2688 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002689 }
2690
2691 // Add the member. Note that we cannot build bound member functions here.
2692 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002693 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2694 if (!HandleLValueMember(Info, BO, LV, FD))
2695 return 0;
2696 } else if (const IndirectFieldDecl *IFD =
2697 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2698 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2699 return 0;
2700 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002701 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002702 }
Richard Smith027bf112011-11-17 22:56:20 +00002703 }
2704
2705 return MemPtr.getDecl();
2706}
2707
2708/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2709/// the provided lvalue, which currently refers to the base object.
2710static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2711 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002712 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002713 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002714 return false;
2715
Richard Smitha8105bc2012-01-06 16:39:00 +00002716 QualType TargetQT = E->getType();
2717 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2718 TargetQT = PT->getPointeeType();
2719
2720 // Check this cast lands within the final derived-to-base subobject path.
2721 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002722 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002723 << D.MostDerivedType << TargetQT;
2724 return false;
2725 }
2726
Richard Smith027bf112011-11-17 22:56:20 +00002727 // Check the type of the final cast. We don't need to check the path,
2728 // since a cast can only be formed if the path is unique.
2729 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002730 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2731 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002732 if (NewEntriesSize == D.MostDerivedPathLength)
2733 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2734 else
Richard Smith027bf112011-11-17 22:56:20 +00002735 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002736 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002737 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002738 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002739 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002740 }
Richard Smith027bf112011-11-17 22:56:20 +00002741
2742 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002743 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002744}
2745
Mike Stump876387b2009-10-27 22:09:17 +00002746namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002747enum EvalStmtResult {
2748 /// Evaluation failed.
2749 ESR_Failed,
2750 /// Hit a 'return' statement.
2751 ESR_Returned,
2752 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002753 ESR_Succeeded,
2754 /// Hit a 'continue' statement.
2755 ESR_Continue,
2756 /// Hit a 'break' statement.
2757 ESR_Break
Richard Smith254a73d2011-10-28 22:34:42 +00002758};
2759}
2760
Richard Smithd9f663b2013-04-22 15:31:51 +00002761static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2762 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2763 // We don't need to evaluate the initializer for a static local.
2764 if (!VD->hasLocalStorage())
2765 return true;
2766
2767 LValue Result;
2768 Result.set(VD, Info.CurrentCall->Index);
2769 APValue &Val = Info.CurrentCall->Temporaries[VD];
2770
2771 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2772 // Wipe out any partially-computed value, to allow tracking that this
2773 // evaluation failed.
2774 Val = APValue();
2775 return false;
2776 }
2777 }
2778
2779 return true;
2780}
2781
Richard Smith4e18ca52013-05-06 05:56:11 +00002782/// Evaluate a condition (either a variable declaration or an expression).
2783static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2784 const Expr *Cond, bool &Result) {
2785 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2786 return false;
2787 return EvaluateAsBooleanCondition(Cond, Result, Info);
2788}
2789
2790static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
2791 const Stmt *S);
2792
2793/// Evaluate the body of a loop, and translate the result as appropriate.
2794static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
2795 const Stmt *Body) {
2796 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body)) {
2797 case ESR_Break:
2798 return ESR_Succeeded;
2799 case ESR_Succeeded:
2800 case ESR_Continue:
2801 return ESR_Continue;
2802 case ESR_Failed:
2803 case ESR_Returned:
2804 return ESR;
2805 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00002806 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00002807}
2808
Richard Smith254a73d2011-10-28 22:34:42 +00002809// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002810static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00002811 const Stmt *S) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00002812 if (!Info.nextStep(S))
2813 return ESR_Failed;
2814
Richard Smithd9f663b2013-04-22 15:31:51 +00002815 // FIXME: Mark all temporaries in the current frame as destroyed at
2816 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00002817 switch (S->getStmtClass()) {
2818 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00002819 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002820 // Don't bother evaluating beyond an expression-statement which couldn't
2821 // be evaluated.
Richard Smith4e18ca52013-05-06 05:56:11 +00002822 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00002823 return ESR_Failed;
2824 return ESR_Succeeded;
2825 }
2826
2827 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00002828 return ESR_Failed;
2829
2830 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00002831 return ESR_Succeeded;
2832
Richard Smithd9f663b2013-04-22 15:31:51 +00002833 case Stmt::DeclStmtClass: {
2834 const DeclStmt *DS = cast<DeclStmt>(S);
2835 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
2836 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
2837 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
2838 return ESR_Failed;
2839 return ESR_Succeeded;
2840 }
2841
Richard Smith357362d2011-12-13 06:39:58 +00002842 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002843 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00002844 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002845 return ESR_Failed;
2846 return ESR_Returned;
2847 }
Richard Smith254a73d2011-10-28 22:34:42 +00002848
2849 case Stmt::CompoundStmtClass: {
2850 const CompoundStmt *CS = cast<CompoundStmt>(S);
2851 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2852 BE = CS->body_end(); BI != BE; ++BI) {
2853 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2854 if (ESR != ESR_Succeeded)
2855 return ESR;
2856 }
2857 return ESR_Succeeded;
2858 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002859
2860 case Stmt::IfStmtClass: {
2861 const IfStmt *IS = cast<IfStmt>(S);
2862
2863 // Evaluate the condition, as either a var decl or as an expression.
2864 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00002865 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00002866 return ESR_Failed;
2867
2868 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
2869 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
2870 if (ESR != ESR_Succeeded)
2871 return ESR;
2872 }
2873 return ESR_Succeeded;
2874 }
Richard Smith4e18ca52013-05-06 05:56:11 +00002875
2876 case Stmt::WhileStmtClass: {
2877 const WhileStmt *WS = cast<WhileStmt>(S);
2878 while (true) {
2879 bool Continue;
2880 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
2881 Continue))
2882 return ESR_Failed;
2883 if (!Continue)
2884 break;
2885
2886 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
2887 if (ESR != ESR_Continue)
2888 return ESR;
2889 }
2890 return ESR_Succeeded;
2891 }
2892
2893 case Stmt::DoStmtClass: {
2894 const DoStmt *DS = cast<DoStmt>(S);
2895 bool Continue;
2896 do {
2897 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody());
2898 if (ESR != ESR_Continue)
2899 return ESR;
2900
2901 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
2902 return ESR_Failed;
2903 } while (Continue);
2904 return ESR_Succeeded;
2905 }
2906
2907 case Stmt::ForStmtClass: {
2908 const ForStmt *FS = cast<ForStmt>(S);
2909 if (FS->getInit()) {
2910 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
2911 if (ESR != ESR_Succeeded)
2912 return ESR;
2913 }
2914 while (true) {
2915 bool Continue = true;
2916 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
2917 FS->getCond(), Continue))
2918 return ESR_Failed;
2919 if (!Continue)
2920 break;
2921
2922 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
2923 if (ESR != ESR_Continue)
2924 return ESR;
2925
2926 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
2927 return ESR_Failed;
2928 }
2929 return ESR_Succeeded;
2930 }
2931
Richard Smith896e0d72013-05-06 06:51:17 +00002932 case Stmt::CXXForRangeStmtClass: {
2933 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
2934
2935 // Initialize the __range variable.
2936 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
2937 if (ESR != ESR_Succeeded)
2938 return ESR;
2939
2940 // Create the __begin and __end iterators.
2941 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
2942 if (ESR != ESR_Succeeded)
2943 return ESR;
2944
2945 while (true) {
2946 // Condition: __begin != __end.
2947 bool Continue = true;
2948 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
2949 return ESR_Failed;
2950 if (!Continue)
2951 break;
2952
2953 // User's variable declaration, initialized by *__begin.
2954 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
2955 if (ESR != ESR_Succeeded)
2956 return ESR;
2957
2958 // Loop body.
2959 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
2960 if (ESR != ESR_Continue)
2961 return ESR;
2962
2963 // Increment: ++__begin
2964 if (!EvaluateIgnoredValue(Info, FS->getInc()))
2965 return ESR_Failed;
2966 }
2967
2968 return ESR_Succeeded;
2969 }
2970
Richard Smith4e18ca52013-05-06 05:56:11 +00002971 case Stmt::ContinueStmtClass:
2972 return ESR_Continue;
2973
2974 case Stmt::BreakStmtClass:
2975 return ESR_Break;
Richard Smith254a73d2011-10-28 22:34:42 +00002976 }
2977}
2978
Richard Smithcc36f692011-12-22 02:22:31 +00002979/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2980/// default constructor. If so, we'll fold it whether or not it's marked as
2981/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2982/// so we need special handling.
2983static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00002984 const CXXConstructorDecl *CD,
2985 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00002986 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2987 return false;
2988
Richard Smith66e05fe2012-01-18 05:21:49 +00002989 // Value-initialization does not call a trivial default constructor, so such a
2990 // call is a core constant expression whether or not the constructor is
2991 // constexpr.
2992 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002993 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00002994 // FIXME: If DiagDecl is an implicitly-declared special member function,
2995 // we should be much more explicit about why it's not constexpr.
2996 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2997 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2998 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00002999 } else {
3000 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3001 }
3002 }
3003 return true;
3004}
3005
Richard Smith357362d2011-12-13 06:39:58 +00003006/// CheckConstexprFunction - Check that a function can be called in a constant
3007/// expression.
3008static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3009 const FunctionDecl *Declaration,
3010 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003011 // Potential constant expressions can contain calls to declared, but not yet
3012 // defined, constexpr functions.
3013 if (Info.CheckingPotentialConstantExpression && !Definition &&
3014 Declaration->isConstexpr())
3015 return false;
3016
Richard Smith357362d2011-12-13 06:39:58 +00003017 // Can we evaluate this function call?
3018 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3019 return true;
3020
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003021 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003022 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003023 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3024 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003025 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3026 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3027 << DiagDecl;
3028 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3029 } else {
3030 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3031 }
3032 return false;
3033}
3034
Richard Smithd62306a2011-11-10 06:34:14 +00003035namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003036typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003037}
3038
3039/// EvaluateArgs - Evaluate the arguments to a function call.
3040static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3041 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003042 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003043 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003044 I != E; ++I) {
3045 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3046 // If we're checking for a potential constant expression, evaluate all
3047 // initializers even if some of them fail.
3048 if (!Info.keepEvaluatingAfterFailure())
3049 return false;
3050 Success = false;
3051 }
3052 }
3053 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003054}
3055
Richard Smith254a73d2011-10-28 22:34:42 +00003056/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003057static bool HandleFunctionCall(SourceLocation CallLoc,
3058 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003059 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003060 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003061 ArgVector ArgValues(Args.size());
3062 if (!EvaluateArgs(Args, ArgValues, Info))
3063 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003064
Richard Smith253c2a32012-01-27 01:14:48 +00003065 if (!Info.CheckCallLimit(CallLoc))
3066 return false;
3067
3068 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003069
3070 // For a trivial copy or move assignment, perform an APValue copy. This is
3071 // essential for unions, where the operations performed by the assignment
3072 // operator cannot be represented as statements.
3073 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3074 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3075 assert(This &&
3076 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3077 LValue RHS;
3078 RHS.setFrom(Info.Ctx, ArgValues[0]);
3079 APValue RHSValue;
3080 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3081 RHS, RHSValue))
3082 return false;
3083 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3084 RHSValue))
3085 return false;
3086 This->moveInto(Result);
3087 return true;
3088 }
3089
Richard Smithd9f663b2013-04-22 15:31:51 +00003090 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003091 if (ESR == ESR_Succeeded) {
3092 if (Callee->getResultType()->isVoidType())
3093 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003094 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003095 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003096 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003097}
3098
Richard Smithd62306a2011-11-10 06:34:14 +00003099/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003100static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003101 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003102 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003103 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003104 ArgVector ArgValues(Args.size());
3105 if (!EvaluateArgs(Args, ArgValues, Info))
3106 return false;
3107
Richard Smith253c2a32012-01-27 01:14:48 +00003108 if (!Info.CheckCallLimit(CallLoc))
3109 return false;
3110
Richard Smith3607ffe2012-02-13 03:54:03 +00003111 const CXXRecordDecl *RD = Definition->getParent();
3112 if (RD->getNumVBases()) {
3113 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3114 return false;
3115 }
3116
Richard Smith253c2a32012-01-27 01:14:48 +00003117 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003118
3119 // If it's a delegating constructor, just delegate.
3120 if (Definition->isDelegatingConstructor()) {
3121 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003122 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3123 return false;
3124 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003125 }
3126
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003127 // For a trivial copy or move constructor, perform an APValue copy. This is
3128 // essential for unions, where the operations performed by the constructor
3129 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003130 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003131 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3132 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003133 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003134 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003135 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003136 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003137 }
3138
3139 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003140 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003141 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3142 std::distance(RD->field_begin(), RD->field_end()));
3143
John McCalld7bca762012-05-01 00:38:49 +00003144 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003145 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3146
Richard Smith253c2a32012-01-27 01:14:48 +00003147 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003148 unsigned BasesSeen = 0;
3149#ifndef NDEBUG
3150 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3151#endif
3152 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3153 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003154 LValue Subobject = This;
3155 APValue *Value = &Result;
3156
3157 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00003158 if ((*I)->isBaseInitializer()) {
3159 QualType BaseType((*I)->getBaseClass(), 0);
3160#ifndef NDEBUG
3161 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003162 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003163 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3164 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3165 "base class initializers not in expected order");
3166 ++BaseIt;
3167#endif
John McCalld7bca762012-05-01 00:38:49 +00003168 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3169 BaseType->getAsCXXRecordDecl(), &Layout))
3170 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003171 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00003172 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00003173 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3174 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003175 if (RD->isUnion()) {
3176 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003177 Value = &Result.getUnionValue();
3178 } else {
3179 Value = &Result.getStructField(FD->getFieldIndex());
3180 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003181 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003182 // Walk the indirect field decl's chain to find the object to initialize,
3183 // and make sure we've initialized every step along it.
3184 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3185 CE = IFD->chain_end();
3186 C != CE; ++C) {
3187 FieldDecl *FD = cast<FieldDecl>(*C);
3188 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3189 // Switch the union field if it differs. This happens if we had
3190 // preceding zero-initialization, and we're now initializing a union
3191 // subobject other than the first.
3192 // FIXME: In this case, the values of the other subobjects are
3193 // specified, since zero-initialization sets all padding bits to zero.
3194 if (Value->isUninit() ||
3195 (Value->isUnion() && Value->getUnionField() != FD)) {
3196 if (CD->isUnion())
3197 *Value = APValue(FD);
3198 else
3199 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3200 std::distance(CD->field_begin(), CD->field_end()));
3201 }
John McCalld7bca762012-05-01 00:38:49 +00003202 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3203 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003204 if (CD->isUnion())
3205 Value = &Value->getUnionValue();
3206 else
3207 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003208 }
Richard Smithd62306a2011-11-10 06:34:14 +00003209 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003210 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003211 }
Richard Smith253c2a32012-01-27 01:14:48 +00003212
Richard Smithb228a862012-02-15 02:18:13 +00003213 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
3214 (*I)->isBaseInitializer()
Richard Smith253c2a32012-01-27 01:14:48 +00003215 ? CCEK_Constant : CCEK_MemberInit)) {
3216 // If we're checking for a potential constant expression, evaluate all
3217 // initializers even if some of them fail.
3218 if (!Info.keepEvaluatingAfterFailure())
3219 return false;
3220 Success = false;
3221 }
Richard Smithd62306a2011-11-10 06:34:14 +00003222 }
3223
Richard Smithd9f663b2013-04-22 15:31:51 +00003224 return Success &&
3225 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003226}
3227
Eli Friedman9a156e52008-11-12 09:44:48 +00003228//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003229// Generic Evaluation
3230//===----------------------------------------------------------------------===//
3231namespace {
3232
Richard Smithf57d8cb2011-12-09 22:58:01 +00003233// FIXME: RetTy is always bool. Remove it.
3234template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003235class ExprEvaluatorBase
3236 : public ConstStmtVisitor<Derived, RetTy> {
3237private:
Richard Smith2e312c82012-03-03 22:46:17 +00003238 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003239 return static_cast<Derived*>(this)->Success(V, E);
3240 }
Richard Smithfddd3842011-12-30 21:15:51 +00003241 RetTy DerivedZeroInitialization(const Expr *E) {
3242 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003243 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003244
Richard Smith17100ba2012-02-16 02:46:34 +00003245 // Check whether a conditional operator with a non-constant condition is a
3246 // potential constant expression. If neither arm is a potential constant
3247 // expression, then the conditional operator is not either.
3248 template<typename ConditionalOperator>
3249 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3250 assert(Info.CheckingPotentialConstantExpression);
3251
3252 // Speculatively evaluate both arms.
3253 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003254 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003255 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3256
3257 StmtVisitorTy::Visit(E->getFalseExpr());
3258 if (Diag.empty())
3259 return;
3260
3261 Diag.clear();
3262 StmtVisitorTy::Visit(E->getTrueExpr());
3263 if (Diag.empty())
3264 return;
3265 }
3266
3267 Error(E, diag::note_constexpr_conditional_never_const);
3268 }
3269
3270
3271 template<typename ConditionalOperator>
3272 bool HandleConditionalOperator(const ConditionalOperator *E) {
3273 bool BoolResult;
3274 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3275 if (Info.CheckingPotentialConstantExpression)
3276 CheckPotentialConstantConditional(E);
3277 return false;
3278 }
3279
3280 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3281 return StmtVisitorTy::Visit(EvalExpr);
3282 }
3283
Peter Collingbournee9200682011-05-13 03:29:01 +00003284protected:
3285 EvalInfo &Info;
3286 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3287 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3288
Richard Smith92b1ce02011-12-12 09:28:41 +00003289 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003290 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003291 }
3292
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003293 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3294
3295public:
3296 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3297
3298 EvalInfo &getEvalInfo() { return Info; }
3299
Richard Smithf57d8cb2011-12-09 22:58:01 +00003300 /// Report an evaluation error. This should only be called when an error is
3301 /// first discovered. When propagating an error, just return false.
3302 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003303 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003304 return false;
3305 }
3306 bool Error(const Expr *E) {
3307 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3308 }
3309
Peter Collingbournee9200682011-05-13 03:29:01 +00003310 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003311 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003312 }
3313 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003314 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003315 }
3316
3317 RetTy VisitParenExpr(const ParenExpr *E)
3318 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3319 RetTy VisitUnaryExtension(const UnaryOperator *E)
3320 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3321 RetTy VisitUnaryPlus(const UnaryOperator *E)
3322 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3323 RetTy VisitChooseExpr(const ChooseExpr *E)
3324 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
3325 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3326 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003327 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3328 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003329 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3330 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003331 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3332 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003333 // We cannot create any objects for which cleanups are required, so there is
3334 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3335 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3336 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003337
Richard Smith6d6ecc32011-12-12 12:46:16 +00003338 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3339 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3340 return static_cast<Derived*>(this)->VisitCastExpr(E);
3341 }
3342 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3343 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3344 return static_cast<Derived*>(this)->VisitCastExpr(E);
3345 }
3346
Richard Smith027bf112011-11-17 22:56:20 +00003347 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3348 switch (E->getOpcode()) {
3349 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003350 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003351
3352 case BO_Comma:
3353 VisitIgnoredValue(E->getLHS());
3354 return StmtVisitorTy::Visit(E->getRHS());
3355
3356 case BO_PtrMemD:
3357 case BO_PtrMemI: {
3358 LValue Obj;
3359 if (!HandleMemberPointerAccess(Info, E, Obj))
3360 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003361 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003362 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003363 return false;
3364 return DerivedSuccess(Result, E);
3365 }
3366 }
3367 }
3368
Peter Collingbournee9200682011-05-13 03:29:01 +00003369 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003370 // Evaluate and cache the common expression. We treat it as a temporary,
3371 // even though it's not quite the same thing.
3372 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3373 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003374 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003375
Richard Smith17100ba2012-02-16 02:46:34 +00003376 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003377 }
3378
3379 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003380 bool IsBcpCall = false;
3381 // If the condition (ignoring parens) is a __builtin_constant_p call,
3382 // the result is a constant expression if it can be folded without
3383 // side-effects. This is an important GNU extension. See GCC PR38377
3384 // for discussion.
3385 if (const CallExpr *CallCE =
3386 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3387 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3388 IsBcpCall = true;
3389
3390 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3391 // constant expression; we can't check whether it's potentially foldable.
3392 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3393 return false;
3394
3395 FoldConstant Fold(Info);
3396
Richard Smith17100ba2012-02-16 02:46:34 +00003397 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003398 return false;
3399
3400 if (IsBcpCall)
3401 Fold.Fold(Info);
3402
3403 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003404 }
3405
3406 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003407 APValue &Value = Info.CurrentCall->Temporaries[E];
3408 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003409 const Expr *Source = E->getSourceExpr();
3410 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003411 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003412 if (Source == E) { // sanity checking.
3413 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003414 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003415 }
3416 return StmtVisitorTy::Visit(Source);
3417 }
Richard Smith26d4cc12012-06-26 08:12:11 +00003418 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003419 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003420
Richard Smith254a73d2011-10-28 22:34:42 +00003421 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003422 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003423 QualType CalleeType = Callee->getType();
3424
Richard Smith254a73d2011-10-28 22:34:42 +00003425 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003426 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003427 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003428 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003429
Richard Smithe97cbd72011-11-11 04:05:33 +00003430 // Extract function decl and 'this' pointer from the callee.
3431 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003432 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003433 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3434 // Explicit bound member calls, such as x.f() or p->g();
3435 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003436 return false;
3437 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003438 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003439 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003440 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3441 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003442 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3443 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003444 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003445 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003446 return Error(Callee);
3447
3448 FD = dyn_cast<FunctionDecl>(Member);
3449 if (!FD)
3450 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003451 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003452 LValue Call;
3453 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003454 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003455
Richard Smitha8105bc2012-01-06 16:39:00 +00003456 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003457 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003458 FD = dyn_cast_or_null<FunctionDecl>(
3459 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003460 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003461 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003462
3463 // Overloaded operator calls to member functions are represented as normal
3464 // calls with '*this' as the first argument.
3465 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3466 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003467 // FIXME: When selecting an implicit conversion for an overloaded
3468 // operator delete, we sometimes try to evaluate calls to conversion
3469 // operators without a 'this' parameter!
3470 if (Args.empty())
3471 return Error(E);
3472
Richard Smithe97cbd72011-11-11 04:05:33 +00003473 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3474 return false;
3475 This = &ThisVal;
3476 Args = Args.slice(1);
3477 }
3478
3479 // Don't call function pointers which have been cast to some other type.
3480 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003481 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003482 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003483 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003484
Richard Smith47b34932012-02-01 02:39:43 +00003485 if (This && !This->checkSubobject(Info, E, CSK_This))
3486 return false;
3487
Richard Smith3607ffe2012-02-13 03:54:03 +00003488 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3489 // calls to such functions in constant expressions.
3490 if (This && !HasQualifier &&
3491 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3492 return Error(E, diag::note_constexpr_virtual_call);
3493
Richard Smith357362d2011-12-13 06:39:58 +00003494 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003495 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003496 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003497
Richard Smith357362d2011-12-13 06:39:58 +00003498 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003499 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3500 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003501 return false;
3502
Richard Smithb228a862012-02-15 02:18:13 +00003503 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003504 }
3505
Richard Smith11562c52011-10-28 17:51:58 +00003506 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3507 return StmtVisitorTy::Visit(E->getInitializer());
3508 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003509 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003510 if (E->getNumInits() == 0)
3511 return DerivedZeroInitialization(E);
3512 if (E->getNumInits() == 1)
3513 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003514 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003515 }
3516 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003517 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003518 }
3519 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003520 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003521 }
Richard Smith027bf112011-11-17 22:56:20 +00003522 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003523 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003524 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003525
Richard Smithd62306a2011-11-10 06:34:14 +00003526 /// A member expression where the object is a prvalue is itself a prvalue.
3527 RetTy VisitMemberExpr(const MemberExpr *E) {
3528 assert(!E->isArrow() && "missing call to bound member function?");
3529
Richard Smith2e312c82012-03-03 22:46:17 +00003530 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003531 if (!Evaluate(Val, Info, E->getBase()))
3532 return false;
3533
3534 QualType BaseTy = E->getBase()->getType();
3535
3536 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003537 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003538 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003539 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003540 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3541
Richard Smith3229b742013-05-05 21:17:10 +00003542 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003543 SubobjectDesignator Designator(BaseTy);
3544 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003545
Richard Smith3229b742013-05-05 21:17:10 +00003546 APValue Result;
3547 return extractSubobject(Info, E, Obj, Designator, Result) &&
3548 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003549 }
3550
Richard Smith11562c52011-10-28 17:51:58 +00003551 RetTy VisitCastExpr(const CastExpr *E) {
3552 switch (E->getCastKind()) {
3553 default:
3554 break;
3555
David Chisnallfa35df62012-01-16 17:27:18 +00003556 case CK_AtomicToNonAtomic:
3557 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00003558 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003559 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003560 return StmtVisitorTy::Visit(E->getSubExpr());
3561
3562 case CK_LValueToRValue: {
3563 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003564 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3565 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003566 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003567 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003568 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003569 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003570 return false;
3571 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003572 }
3573 }
3574
Richard Smithf57d8cb2011-12-09 22:58:01 +00003575 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003576 }
3577
Richard Smith243ef902013-05-05 23:31:59 +00003578 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3579 return VisitUnaryPostIncDec(UO);
3580 }
3581 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3582 return VisitUnaryPostIncDec(UO);
3583 }
3584 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3585 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3586 return Error(UO);
3587
3588 LValue LVal;
3589 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3590 return false;
3591 APValue RVal;
3592 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3593 UO->isIncrementOp(), &RVal))
3594 return false;
3595 return DerivedSuccess(RVal, UO);
3596 }
3597
Richard Smith4a678122011-10-24 18:44:57 +00003598 /// Visit a value which is evaluated, but whose value is ignored.
3599 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003600 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003601 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003602};
3603
3604}
3605
3606//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003607// Common base class for lvalue and temporary evaluation.
3608//===----------------------------------------------------------------------===//
3609namespace {
3610template<class Derived>
3611class LValueExprEvaluatorBase
3612 : public ExprEvaluatorBase<Derived, bool> {
3613protected:
3614 LValue &Result;
3615 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3616 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3617
3618 bool Success(APValue::LValueBase B) {
3619 Result.set(B);
3620 return true;
3621 }
3622
3623public:
3624 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3625 ExprEvaluatorBaseTy(Info), Result(Result) {}
3626
Richard Smith2e312c82012-03-03 22:46:17 +00003627 bool Success(const APValue &V, const Expr *E) {
3628 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003629 return true;
3630 }
Richard Smith027bf112011-11-17 22:56:20 +00003631
Richard Smith027bf112011-11-17 22:56:20 +00003632 bool VisitMemberExpr(const MemberExpr *E) {
3633 // Handle non-static data members.
3634 QualType BaseTy;
3635 if (E->isArrow()) {
3636 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3637 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003638 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003639 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003640 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003641 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3642 return false;
3643 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003644 } else {
3645 if (!this->Visit(E->getBase()))
3646 return false;
3647 BaseTy = E->getBase()->getType();
3648 }
Richard Smith027bf112011-11-17 22:56:20 +00003649
Richard Smith1b78b3d2012-01-25 22:15:11 +00003650 const ValueDecl *MD = E->getMemberDecl();
3651 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3652 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3653 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3654 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003655 if (!HandleLValueMember(this->Info, E, Result, FD))
3656 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003657 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003658 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3659 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003660 } else
3661 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003662
Richard Smith1b78b3d2012-01-25 22:15:11 +00003663 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003664 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003665 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003666 RefValue))
3667 return false;
3668 return Success(RefValue, E);
3669 }
3670 return true;
3671 }
3672
3673 bool VisitBinaryOperator(const BinaryOperator *E) {
3674 switch (E->getOpcode()) {
3675 default:
3676 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3677
3678 case BO_PtrMemD:
3679 case BO_PtrMemI:
3680 return HandleMemberPointerAccess(this->Info, E, Result);
3681 }
3682 }
3683
3684 bool VisitCastExpr(const CastExpr *E) {
3685 switch (E->getCastKind()) {
3686 default:
3687 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3688
3689 case CK_DerivedToBase:
3690 case CK_UncheckedDerivedToBase: {
3691 if (!this->Visit(E->getSubExpr()))
3692 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003693
3694 // Now figure out the necessary offset to add to the base LV to get from
3695 // the derived class to the base class.
3696 QualType Type = E->getSubExpr()->getType();
3697
3698 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3699 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003700 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00003701 *PathI))
3702 return false;
3703 Type = (*PathI)->getType();
3704 }
3705
3706 return true;
3707 }
3708 }
3709 }
3710};
3711}
3712
3713//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003714// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003715//
3716// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3717// function designators (in C), decl references to void objects (in C), and
3718// temporaries (if building with -Wno-address-of-temporary).
3719//
3720// LValue evaluation produces values comprising a base expression of one of the
3721// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003722// - Declarations
3723// * VarDecl
3724// * FunctionDecl
3725// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003726// * CompoundLiteralExpr in C
3727// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003728// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003729// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003730// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003731// * ObjCEncodeExpr
3732// * AddrLabelExpr
3733// * BlockExpr
3734// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003735// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00003736// * Any Expr, with a CallIndex indicating the function in which the temporary
3737// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00003738// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003739//===----------------------------------------------------------------------===//
3740namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003741class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003742 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003743public:
Richard Smith027bf112011-11-17 22:56:20 +00003744 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3745 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003746
Richard Smith11562c52011-10-28 17:51:58 +00003747 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00003748 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00003749
Peter Collingbournee9200682011-05-13 03:29:01 +00003750 bool VisitDeclRefExpr(const DeclRefExpr *E);
3751 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003752 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003753 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3754 bool VisitMemberExpr(const MemberExpr *E);
3755 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3756 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00003757 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00003758 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003759 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3760 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00003761 bool VisitUnaryReal(const UnaryOperator *E);
3762 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00003763 bool VisitUnaryPreInc(const UnaryOperator *UO) {
3764 return VisitUnaryPreIncDec(UO);
3765 }
3766 bool VisitUnaryPreDec(const UnaryOperator *UO) {
3767 return VisitUnaryPreIncDec(UO);
3768 }
Richard Smith3229b742013-05-05 21:17:10 +00003769 bool VisitBinAssign(const BinaryOperator *BO);
3770 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00003771
Peter Collingbournee9200682011-05-13 03:29:01 +00003772 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00003773 switch (E->getCastKind()) {
3774 default:
Richard Smith027bf112011-11-17 22:56:20 +00003775 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003776
Eli Friedmance3e02a2011-10-11 00:13:24 +00003777 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00003778 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00003779 if (!Visit(E->getSubExpr()))
3780 return false;
3781 Result.Designator.setInvalid();
3782 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00003783
Richard Smith027bf112011-11-17 22:56:20 +00003784 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00003785 if (!Visit(E->getSubExpr()))
3786 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003787 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00003788 }
3789 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003790};
3791} // end anonymous namespace
3792
Richard Smith11562c52011-10-28 17:51:58 +00003793/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00003794/// expressions which are not glvalues, in two cases:
3795/// * function designators in C, and
3796/// * "extern void" objects
3797static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
3798 assert(E->isGLValue() || E->getType()->isFunctionType() ||
3799 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003800 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003801}
3802
Peter Collingbournee9200682011-05-13 03:29:01 +00003803bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003804 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
3805 return Success(FD);
3806 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00003807 return VisitVarDecl(E, VD);
3808 return Error(E);
3809}
Richard Smith733237d2011-10-24 23:14:33 +00003810
Richard Smith11562c52011-10-28 17:51:58 +00003811bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00003812 CallStackFrame *Frame = 0;
3813 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
3814 Frame = Info.CurrentCall;
3815
Richard Smithfec09922011-11-01 16:57:24 +00003816 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00003817 if (Frame) {
3818 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00003819 return true;
3820 }
Richard Smithce40ad62011-11-12 22:28:03 +00003821 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00003822 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00003823
Richard Smith3229b742013-05-05 21:17:10 +00003824 APValue *V;
3825 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003826 return false;
Richard Smith3229b742013-05-05 21:17:10 +00003827 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00003828}
3829
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003830bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3831 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00003832 if (E->getType()->isRecordType())
3833 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00003834
Richard Smithb228a862012-02-15 02:18:13 +00003835 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00003836 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3837 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003838}
3839
Peter Collingbournee9200682011-05-13 03:29:01 +00003840bool
3841LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003842 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3843 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3844 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00003845 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003846}
3847
Richard Smith6e525142011-12-27 12:18:28 +00003848bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00003849 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00003850 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00003851
3852 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
3853 << E->getExprOperand()->getType()
3854 << E->getExprOperand()->getSourceRange();
3855 return false;
Richard Smith6e525142011-12-27 12:18:28 +00003856}
3857
Francois Pichet0066db92012-04-16 04:08:35 +00003858bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3859 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00003860}
Francois Pichet0066db92012-04-16 04:08:35 +00003861
Peter Collingbournee9200682011-05-13 03:29:01 +00003862bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003863 // Handle static data members.
3864 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3865 VisitIgnoredValue(E->getBase());
3866 return VisitVarDecl(E, VD);
3867 }
3868
Richard Smith254a73d2011-10-28 22:34:42 +00003869 // Handle static member functions.
3870 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3871 if (MD->isStatic()) {
3872 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00003873 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00003874 }
3875 }
3876
Richard Smithd62306a2011-11-10 06:34:14 +00003877 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00003878 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003879}
3880
Peter Collingbournee9200682011-05-13 03:29:01 +00003881bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003882 // FIXME: Deal with vectors as array subscript bases.
3883 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003884 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003885
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003886 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00003887 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003888
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003889 APSInt Index;
3890 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00003891 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003892
Richard Smith861b5b52013-05-07 23:34:45 +00003893 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
3894 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003895}
Eli Friedman9a156e52008-11-12 09:44:48 +00003896
Peter Collingbournee9200682011-05-13 03:29:01 +00003897bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00003898 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00003899}
3900
Richard Smith66c96992012-02-18 22:04:06 +00003901bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3902 if (!Visit(E->getSubExpr()))
3903 return false;
3904 // __real is a no-op on scalar lvalues.
3905 if (E->getSubExpr()->getType()->isAnyComplexType())
3906 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3907 return true;
3908}
3909
3910bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3911 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3912 "lvalue __imag__ on scalar?");
3913 if (!Visit(E->getSubExpr()))
3914 return false;
3915 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3916 return true;
3917}
3918
Richard Smith243ef902013-05-05 23:31:59 +00003919bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
3920 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00003921 return Error(UO);
3922
3923 if (!this->Visit(UO->getSubExpr()))
3924 return false;
3925
Richard Smith243ef902013-05-05 23:31:59 +00003926 return handleIncDec(
3927 this->Info, UO, Result, UO->getSubExpr()->getType(),
3928 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00003929}
3930
3931bool LValueExprEvaluator::VisitCompoundAssignOperator(
3932 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00003933 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00003934 return Error(CAO);
3935
Richard Smith3229b742013-05-05 21:17:10 +00003936 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00003937
3938 // The overall lvalue result is the result of evaluating the LHS.
3939 if (!this->Visit(CAO->getLHS())) {
3940 if (Info.keepEvaluatingAfterFailure())
3941 Evaluate(RHS, this->Info, CAO->getRHS());
3942 return false;
3943 }
3944
Richard Smith3229b742013-05-05 21:17:10 +00003945 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
3946 return false;
3947
Richard Smith43e77732013-05-07 04:50:00 +00003948 return handleCompoundAssignment(
3949 this->Info, CAO,
3950 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
3951 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00003952}
3953
3954bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00003955 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3956 return Error(E);
3957
Richard Smith3229b742013-05-05 21:17:10 +00003958 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00003959
3960 if (!this->Visit(E->getLHS())) {
3961 if (Info.keepEvaluatingAfterFailure())
3962 Evaluate(NewVal, this->Info, E->getRHS());
3963 return false;
3964 }
3965
Richard Smith3229b742013-05-05 21:17:10 +00003966 if (!Evaluate(NewVal, this->Info, E->getRHS()))
3967 return false;
Richard Smith243ef902013-05-05 23:31:59 +00003968
3969 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00003970 NewVal);
3971}
3972
Eli Friedman9a156e52008-11-12 09:44:48 +00003973//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003974// Pointer Evaluation
3975//===----------------------------------------------------------------------===//
3976
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003977namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003978class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003979 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00003980 LValue &Result;
3981
Peter Collingbournee9200682011-05-13 03:29:01 +00003982 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003983 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00003984 return true;
3985 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003986public:
Mike Stump11289f42009-09-09 15:08:12 +00003987
John McCall45d55e42010-05-07 21:00:08 +00003988 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003989 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003990
Richard Smith2e312c82012-03-03 22:46:17 +00003991 bool Success(const APValue &V, const Expr *E) {
3992 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00003993 return true;
3994 }
Richard Smithfddd3842011-12-30 21:15:51 +00003995 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00003996 return Success((Expr*)0);
3997 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003998
John McCall45d55e42010-05-07 21:00:08 +00003999 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004000 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004001 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004002 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004003 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004004 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004005 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004006 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004007 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004008 bool VisitCallExpr(const CallExpr *E);
4009 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004010 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004011 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004012 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004013 }
Richard Smithd62306a2011-11-10 06:34:14 +00004014 bool VisitCXXThisExpr(const CXXThisExpr *E) {
4015 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004016 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004017 Result = *Info.CurrentCall->This;
4018 return true;
4019 }
John McCallc07a0c72011-02-17 10:25:35 +00004020
Eli Friedman449fe542009-03-23 04:56:01 +00004021 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004022};
Chris Lattner05706e882008-07-11 18:11:29 +00004023} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004024
John McCall45d55e42010-05-07 21:00:08 +00004025static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004026 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004027 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004028}
4029
John McCall45d55e42010-05-07 21:00:08 +00004030bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004031 if (E->getOpcode() != BO_Add &&
4032 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004033 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004034
Chris Lattner05706e882008-07-11 18:11:29 +00004035 const Expr *PExp = E->getLHS();
4036 const Expr *IExp = E->getRHS();
4037 if (IExp->getType()->isPointerType())
4038 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004039
Richard Smith253c2a32012-01-27 01:14:48 +00004040 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4041 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004042 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004043
John McCall45d55e42010-05-07 21:00:08 +00004044 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004045 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004046 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004047
4048 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004049 if (E->getOpcode() == BO_Sub)
4050 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004051
Ted Kremenek28831752012-08-23 20:46:57 +00004052 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004053 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4054 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004055}
Eli Friedman9a156e52008-11-12 09:44:48 +00004056
John McCall45d55e42010-05-07 21:00:08 +00004057bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4058 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004059}
Mike Stump11289f42009-09-09 15:08:12 +00004060
Peter Collingbournee9200682011-05-13 03:29:01 +00004061bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4062 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004063
Eli Friedman847a2bc2009-12-27 05:43:15 +00004064 switch (E->getCastKind()) {
4065 default:
4066 break;
4067
John McCalle3027922010-08-25 11:45:40 +00004068 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004069 case CK_CPointerToObjCPointerCast:
4070 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004071 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004072 if (!Visit(SubExpr))
4073 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004074 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4075 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4076 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004077 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004078 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004079 if (SubExpr->getType()->isVoidPointerType())
4080 CCEDiag(E, diag::note_constexpr_invalid_cast)
4081 << 3 << SubExpr->getType();
4082 else
4083 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4084 }
Richard Smith96e0c102011-11-04 02:25:55 +00004085 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004086
Anders Carlsson18275092010-10-31 20:41:46 +00004087 case CK_DerivedToBase:
4088 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004089 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004090 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004091 if (!Result.Base && Result.Offset.isZero())
4092 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004093
Richard Smithd62306a2011-11-10 06:34:14 +00004094 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004095 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00004096 QualType Type =
4097 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00004098
Richard Smithd62306a2011-11-10 06:34:14 +00004099 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00004100 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004101 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
4102 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00004103 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004104 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00004105 }
4106
Anders Carlsson18275092010-10-31 20:41:46 +00004107 return true;
4108 }
4109
Richard Smith027bf112011-11-17 22:56:20 +00004110 case CK_BaseToDerived:
4111 if (!Visit(E->getSubExpr()))
4112 return false;
4113 if (!Result.Base && Result.Offset.isZero())
4114 return true;
4115 return HandleBaseToDerivedCast(Info, E, Result);
4116
Richard Smith0b0a0b62011-10-29 20:57:55 +00004117 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004118 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004119 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004120
John McCalle3027922010-08-25 11:45:40 +00004121 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004122 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4123
Richard Smith2e312c82012-03-03 22:46:17 +00004124 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004125 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004126 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004127
John McCall45d55e42010-05-07 21:00:08 +00004128 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004129 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4130 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004131 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004132 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004133 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004134 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004135 return true;
4136 } else {
4137 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004138 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004139 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004140 }
4141 }
John McCalle3027922010-08-25 11:45:40 +00004142 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004143 if (SubExpr->isGLValue()) {
4144 if (!EvaluateLValue(SubExpr, Result, Info))
4145 return false;
4146 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004147 Result.set(SubExpr, Info.CurrentCall->Index);
4148 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
4149 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004150 return false;
4151 }
Richard Smith96e0c102011-11-04 02:25:55 +00004152 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004153 if (const ConstantArrayType *CAT
4154 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4155 Result.addArray(Info, E, CAT);
4156 else
4157 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004158 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004159
John McCalle3027922010-08-25 11:45:40 +00004160 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004161 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004162 }
4163
Richard Smith11562c52011-10-28 17:51:58 +00004164 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004165}
Chris Lattner05706e882008-07-11 18:11:29 +00004166
Peter Collingbournee9200682011-05-13 03:29:01 +00004167bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004168 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004169 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004170
Peter Collingbournee9200682011-05-13 03:29:01 +00004171 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004172}
Chris Lattner05706e882008-07-11 18:11:29 +00004173
4174//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004175// Member Pointer Evaluation
4176//===----------------------------------------------------------------------===//
4177
4178namespace {
4179class MemberPointerExprEvaluator
4180 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4181 MemberPtr &Result;
4182
4183 bool Success(const ValueDecl *D) {
4184 Result = MemberPtr(D);
4185 return true;
4186 }
4187public:
4188
4189 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4190 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4191
Richard Smith2e312c82012-03-03 22:46:17 +00004192 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004193 Result.setFrom(V);
4194 return true;
4195 }
Richard Smithfddd3842011-12-30 21:15:51 +00004196 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004197 return Success((const ValueDecl*)0);
4198 }
4199
4200 bool VisitCastExpr(const CastExpr *E);
4201 bool VisitUnaryAddrOf(const UnaryOperator *E);
4202};
4203} // end anonymous namespace
4204
4205static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4206 EvalInfo &Info) {
4207 assert(E->isRValue() && E->getType()->isMemberPointerType());
4208 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4209}
4210
4211bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4212 switch (E->getCastKind()) {
4213 default:
4214 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4215
4216 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004217 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004218 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004219
4220 case CK_BaseToDerivedMemberPointer: {
4221 if (!Visit(E->getSubExpr()))
4222 return false;
4223 if (E->path_empty())
4224 return true;
4225 // Base-to-derived member pointer casts store the path in derived-to-base
4226 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4227 // the wrong end of the derived->base arc, so stagger the path by one class.
4228 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4229 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4230 PathI != PathE; ++PathI) {
4231 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4232 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4233 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004234 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004235 }
4236 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4237 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004238 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004239 return true;
4240 }
4241
4242 case CK_DerivedToBaseMemberPointer:
4243 if (!Visit(E->getSubExpr()))
4244 return false;
4245 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4246 PathE = E->path_end(); PathI != PathE; ++PathI) {
4247 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4248 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4249 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004250 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004251 }
4252 return true;
4253 }
4254}
4255
4256bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4257 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4258 // member can be formed.
4259 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4260}
4261
4262//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004263// Record Evaluation
4264//===----------------------------------------------------------------------===//
4265
4266namespace {
4267 class RecordExprEvaluator
4268 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4269 const LValue &This;
4270 APValue &Result;
4271 public:
4272
4273 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4274 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4275
Richard Smith2e312c82012-03-03 22:46:17 +00004276 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004277 Result = V;
4278 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004279 }
Richard Smithfddd3842011-12-30 21:15:51 +00004280 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004281
Richard Smithe97cbd72011-11-11 04:05:33 +00004282 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004283 bool VisitInitListExpr(const InitListExpr *E);
4284 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
4285 };
4286}
4287
Richard Smithfddd3842011-12-30 21:15:51 +00004288/// Perform zero-initialization on an object of non-union class type.
4289/// C++11 [dcl.init]p5:
4290/// To zero-initialize an object or reference of type T means:
4291/// [...]
4292/// -- if T is a (possibly cv-qualified) non-union class type,
4293/// each non-static data member and each base-class subobject is
4294/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004295static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4296 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004297 const LValue &This, APValue &Result) {
4298 assert(!RD->isUnion() && "Expected non-union class type");
4299 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4300 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4301 std::distance(RD->field_begin(), RD->field_end()));
4302
John McCalld7bca762012-05-01 00:38:49 +00004303 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004304 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4305
4306 if (CD) {
4307 unsigned Index = 0;
4308 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004309 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004310 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4311 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004312 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4313 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004314 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004315 Result.getStructBase(Index)))
4316 return false;
4317 }
4318 }
4319
Richard Smitha8105bc2012-01-06 16:39:00 +00004320 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4321 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004322 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004323 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004324 continue;
4325
4326 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004327 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004328 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004329
David Blaikie2d7c57e2012-04-30 02:36:29 +00004330 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004331 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004332 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004333 return false;
4334 }
4335
4336 return true;
4337}
4338
4339bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4340 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004341 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004342 if (RD->isUnion()) {
4343 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4344 // object's first non-static named data member is zero-initialized
4345 RecordDecl::field_iterator I = RD->field_begin();
4346 if (I == RD->field_end()) {
4347 Result = APValue((const FieldDecl*)0);
4348 return true;
4349 }
4350
4351 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004352 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004353 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004354 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004355 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004356 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004357 }
4358
Richard Smith5d108602012-02-17 00:44:16 +00004359 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004360 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004361 return false;
4362 }
4363
Richard Smitha8105bc2012-01-06 16:39:00 +00004364 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004365}
4366
Richard Smithe97cbd72011-11-11 04:05:33 +00004367bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4368 switch (E->getCastKind()) {
4369 default:
4370 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4371
4372 case CK_ConstructorConversion:
4373 return Visit(E->getSubExpr());
4374
4375 case CK_DerivedToBase:
4376 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004377 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004378 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004379 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004380 if (!DerivedObject.isStruct())
4381 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004382
4383 // Derived-to-base rvalue conversion: just slice off the derived part.
4384 APValue *Value = &DerivedObject;
4385 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4386 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4387 PathE = E->path_end(); PathI != PathE; ++PathI) {
4388 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4389 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4390 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4391 RD = Base;
4392 }
4393 Result = *Value;
4394 return true;
4395 }
4396 }
4397}
4398
Richard Smithd62306a2011-11-10 06:34:14 +00004399bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00004400 // Cannot constant-evaluate std::initializer_list inits.
4401 if (E->initializesStdInitializerList())
4402 return false;
4403
Richard Smithd62306a2011-11-10 06:34:14 +00004404 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004405 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004406 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4407
4408 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004409 const FieldDecl *Field = E->getInitializedFieldInUnion();
4410 Result = APValue(Field);
4411 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004412 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004413
4414 // If the initializer list for a union does not contain any elements, the
4415 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004416 // FIXME: The element should be initialized from an initializer list.
4417 // Is this difference ever observable for initializer lists which
4418 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004419 ImplicitValueInitExpr VIE(Field->getType());
4420 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4421
Richard Smithd62306a2011-11-10 06:34:14 +00004422 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004423 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4424 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004425
4426 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4427 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4428 isa<CXXDefaultInitExpr>(InitExpr));
4429
Richard Smithb228a862012-02-15 02:18:13 +00004430 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004431 }
4432
4433 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4434 "initializer list for class with base classes");
4435 Result = APValue(APValue::UninitStruct(), 0,
4436 std::distance(RD->field_begin(), RD->field_end()));
4437 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004438 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004439 for (RecordDecl::field_iterator Field = RD->field_begin(),
4440 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4441 // Anonymous bit-fields are not considered members of the class for
4442 // purposes of aggregate initialization.
4443 if (Field->isUnnamedBitfield())
4444 continue;
4445
4446 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004447
Richard Smith253c2a32012-01-27 01:14:48 +00004448 bool HaveInit = ElementNo < E->getNumInits();
4449
4450 // FIXME: Diagnostics here should point to the end of the initializer
4451 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004452 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004453 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004454 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004455
4456 // Perform an implicit value-initialization for members beyond the end of
4457 // the initializer list.
4458 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004459 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004460
Richard Smith852c9db2013-04-20 22:23:05 +00004461 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4462 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4463 isa<CXXDefaultInitExpr>(Init));
4464
4465 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4466 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004467 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004468 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004469 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004470 }
4471 }
4472
Richard Smith253c2a32012-01-27 01:14:48 +00004473 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004474}
4475
4476bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4477 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004478 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4479
Richard Smithfddd3842011-12-30 21:15:51 +00004480 bool ZeroInit = E->requiresZeroInitialization();
4481 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004482 // If we've already performed zero-initialization, we're already done.
4483 if (!Result.isUninit())
4484 return true;
4485
Richard Smithfddd3842011-12-30 21:15:51 +00004486 if (ZeroInit)
4487 return ZeroInitialization(E);
4488
Richard Smithcc36f692011-12-22 02:22:31 +00004489 const CXXRecordDecl *RD = FD->getParent();
4490 if (RD->isUnion())
4491 Result = APValue((FieldDecl*)0);
4492 else
4493 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4494 std::distance(RD->field_begin(), RD->field_end()));
4495 return true;
4496 }
4497
Richard Smithd62306a2011-11-10 06:34:14 +00004498 const FunctionDecl *Definition = 0;
4499 FD->getBody(Definition);
4500
Richard Smith357362d2011-12-13 06:39:58 +00004501 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4502 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004503
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004504 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004505 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004506 if (const MaterializeTemporaryExpr *ME
4507 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4508 return Visit(ME->GetTemporaryExpr());
4509
Richard Smithfddd3842011-12-30 21:15:51 +00004510 if (ZeroInit && !ZeroInitialization(E))
4511 return false;
4512
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004513 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004514 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004515 cast<CXXConstructorDecl>(Definition), Info,
4516 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004517}
4518
4519static bool EvaluateRecord(const Expr *E, const LValue &This,
4520 APValue &Result, EvalInfo &Info) {
4521 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004522 "can't evaluate expression as a record rvalue");
4523 return RecordExprEvaluator(Info, This, Result).Visit(E);
4524}
4525
4526//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004527// Temporary Evaluation
4528//
4529// Temporaries are represented in the AST as rvalues, but generally behave like
4530// lvalues. The full-object of which the temporary is a subobject is implicitly
4531// materialized so that a reference can bind to it.
4532//===----------------------------------------------------------------------===//
4533namespace {
4534class TemporaryExprEvaluator
4535 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4536public:
4537 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4538 LValueExprEvaluatorBaseTy(Info, Result) {}
4539
4540 /// Visit an expression which constructs the value of this temporary.
4541 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004542 Result.set(E, Info.CurrentCall->Index);
4543 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004544 }
4545
4546 bool VisitCastExpr(const CastExpr *E) {
4547 switch (E->getCastKind()) {
4548 default:
4549 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4550
4551 case CK_ConstructorConversion:
4552 return VisitConstructExpr(E->getSubExpr());
4553 }
4554 }
4555 bool VisitInitListExpr(const InitListExpr *E) {
4556 return VisitConstructExpr(E);
4557 }
4558 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4559 return VisitConstructExpr(E);
4560 }
4561 bool VisitCallExpr(const CallExpr *E) {
4562 return VisitConstructExpr(E);
4563 }
4564};
4565} // end anonymous namespace
4566
4567/// Evaluate an expression of record type as a temporary.
4568static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004569 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004570 return TemporaryExprEvaluator(Info, Result).Visit(E);
4571}
4572
4573//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004574// Vector Evaluation
4575//===----------------------------------------------------------------------===//
4576
4577namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004578 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004579 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4580 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004581 public:
Mike Stump11289f42009-09-09 15:08:12 +00004582
Richard Smith2d406342011-10-22 21:10:00 +00004583 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4584 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004585
Richard Smith2d406342011-10-22 21:10:00 +00004586 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4587 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4588 // FIXME: remove this APValue copy.
4589 Result = APValue(V.data(), V.size());
4590 return true;
4591 }
Richard Smith2e312c82012-03-03 22:46:17 +00004592 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004593 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004594 Result = V;
4595 return true;
4596 }
Richard Smithfddd3842011-12-30 21:15:51 +00004597 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004598
Richard Smith2d406342011-10-22 21:10:00 +00004599 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00004600 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00004601 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00004602 bool VisitInitListExpr(const InitListExpr *E);
4603 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004604 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00004605 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00004606 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004607 };
4608} // end anonymous namespace
4609
4610static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004611 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00004612 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004613}
4614
Richard Smith2d406342011-10-22 21:10:00 +00004615bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
4616 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004617 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004618
Richard Smith161f09a2011-12-06 22:44:34 +00004619 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00004620 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004621
Eli Friedmanc757de22011-03-25 00:43:55 +00004622 switch (E->getCastKind()) {
4623 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00004624 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00004625 if (SETy->isIntegerType()) {
4626 APSInt IntResult;
4627 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004628 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004629 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00004630 } else if (SETy->isRealFloatingType()) {
4631 APFloat F(0.0);
4632 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004633 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004634 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004635 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004636 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004637 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004638
4639 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004640 SmallVector<APValue, 4> Elts(NElts, Val);
4641 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004642 }
Eli Friedman803acb32011-12-22 03:51:45 +00004643 case CK_BitCast: {
4644 // Evaluate the operand into an APInt we can extract from.
4645 llvm::APInt SValInt;
4646 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4647 return false;
4648 // Extract the elements
4649 QualType EltTy = VTy->getElementType();
4650 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4651 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4652 SmallVector<APValue, 4> Elts;
4653 if (EltTy->isRealFloatingType()) {
4654 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00004655 unsigned FloatEltSize = EltSize;
4656 if (&Sem == &APFloat::x87DoubleExtended)
4657 FloatEltSize = 80;
4658 for (unsigned i = 0; i < NElts; i++) {
4659 llvm::APInt Elt;
4660 if (BigEndian)
4661 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4662 else
4663 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00004664 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00004665 }
4666 } else if (EltTy->isIntegerType()) {
4667 for (unsigned i = 0; i < NElts; i++) {
4668 llvm::APInt Elt;
4669 if (BigEndian)
4670 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4671 else
4672 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4673 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4674 }
4675 } else {
4676 return Error(E);
4677 }
4678 return Success(Elts, E);
4679 }
Eli Friedmanc757de22011-03-25 00:43:55 +00004680 default:
Richard Smith11562c52011-10-28 17:51:58 +00004681 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004682 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004683}
4684
Richard Smith2d406342011-10-22 21:10:00 +00004685bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004686VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004687 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004688 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00004689 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004690
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004691 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004692 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004693
Eli Friedmanb9c71292012-01-03 23:24:20 +00004694 // The number of initializers can be less than the number of
4695 // vector elements. For OpenCL, this can be due to nested vector
4696 // initialization. For GCC compatibility, missing trailing elements
4697 // should be initialized with zeroes.
4698 unsigned CountInits = 0, CountElts = 0;
4699 while (CountElts < NumElements) {
4700 // Handle nested vector initialization.
4701 if (CountInits < NumInits
4702 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4703 APValue v;
4704 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4705 return Error(E);
4706 unsigned vlen = v.getVectorLength();
4707 for (unsigned j = 0; j < vlen; j++)
4708 Elements.push_back(v.getVectorElt(j));
4709 CountElts += vlen;
4710 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004711 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004712 if (CountInits < NumInits) {
4713 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004714 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004715 } else // trailing integer zero.
4716 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4717 Elements.push_back(APValue(sInt));
4718 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004719 } else {
4720 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004721 if (CountInits < NumInits) {
4722 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004723 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004724 } else // trailing float zero.
4725 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4726 Elements.push_back(APValue(f));
4727 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00004728 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00004729 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004730 }
Richard Smith2d406342011-10-22 21:10:00 +00004731 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004732}
4733
Richard Smith2d406342011-10-22 21:10:00 +00004734bool
Richard Smithfddd3842011-12-30 21:15:51 +00004735VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004736 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00004737 QualType EltTy = VT->getElementType();
4738 APValue ZeroElement;
4739 if (EltTy->isIntegerType())
4740 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4741 else
4742 ZeroElement =
4743 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4744
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004745 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00004746 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004747}
4748
Richard Smith2d406342011-10-22 21:10:00 +00004749bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00004750 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004751 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004752}
4753
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004754//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00004755// Array Evaluation
4756//===----------------------------------------------------------------------===//
4757
4758namespace {
4759 class ArrayExprEvaluator
4760 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00004761 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00004762 APValue &Result;
4763 public:
4764
Richard Smithd62306a2011-11-10 06:34:14 +00004765 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
4766 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00004767
4768 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00004769 assert((V.isArray() || V.isLValue()) &&
4770 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00004771 Result = V;
4772 return true;
4773 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004774
Richard Smithfddd3842011-12-30 21:15:51 +00004775 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004776 const ConstantArrayType *CAT =
4777 Info.Ctx.getAsConstantArrayType(E->getType());
4778 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004779 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004780
4781 Result = APValue(APValue::UninitArray(), 0,
4782 CAT->getSize().getZExtValue());
4783 if (!Result.hasArrayFiller()) return true;
4784
Richard Smithfddd3842011-12-30 21:15:51 +00004785 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00004786 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004787 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00004788 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00004789 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00004790 }
4791
Richard Smithf3e9e432011-11-07 09:22:26 +00004792 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00004793 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00004794 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
4795 const LValue &Subobject,
4796 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00004797 };
4798} // end anonymous namespace
4799
Richard Smithd62306a2011-11-10 06:34:14 +00004800static bool EvaluateArray(const Expr *E, const LValue &This,
4801 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00004802 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00004803 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004804}
4805
4806bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4807 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
4808 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004809 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004810
Richard Smithca2cfbf2011-12-22 01:07:19 +00004811 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
4812 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00004813 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00004814 LValue LV;
4815 if (!EvaluateLValue(E->getInit(0), LV, Info))
4816 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004817 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00004818 LV.moveInto(Val);
4819 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00004820 }
4821
Richard Smith253c2a32012-01-27 01:14:48 +00004822 bool Success = true;
4823
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004824 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
4825 "zero-initialized array shouldn't have any initialized elts");
4826 APValue Filler;
4827 if (Result.isArray() && Result.hasArrayFiller())
4828 Filler = Result.getArrayFiller();
4829
Richard Smith9543c5e2013-04-22 14:44:29 +00004830 unsigned NumEltsToInit = E->getNumInits();
4831 unsigned NumElts = CAT->getSize().getZExtValue();
4832 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
4833
4834 // If the initializer might depend on the array index, run it for each
4835 // array element. For now, just whitelist non-class value-initialization.
4836 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
4837 NumEltsToInit = NumElts;
4838
4839 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004840
4841 // If the array was previously zero-initialized, preserve the
4842 // zero-initialized values.
4843 if (!Filler.isUninit()) {
4844 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
4845 Result.getArrayInitializedElt(I) = Filler;
4846 if (Result.hasArrayFiller())
4847 Result.getArrayFiller() = Filler;
4848 }
4849
Richard Smithd62306a2011-11-10 06:34:14 +00004850 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004851 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00004852 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
4853 const Expr *Init =
4854 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00004855 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00004856 Info, Subobject, Init) ||
4857 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00004858 CAT->getElementType(), 1)) {
4859 if (!Info.keepEvaluatingAfterFailure())
4860 return false;
4861 Success = false;
4862 }
Richard Smithd62306a2011-11-10 06:34:14 +00004863 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004864
Richard Smith9543c5e2013-04-22 14:44:29 +00004865 if (!Result.hasArrayFiller())
4866 return Success;
4867
4868 // If we get here, we have a trivial filler, which we can just evaluate
4869 // once and splat over the rest of the array elements.
4870 assert(FillerExpr && "no array filler for incomplete init list");
4871 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
4872 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00004873}
4874
Richard Smith027bf112011-11-17 22:56:20 +00004875bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004876 return VisitCXXConstructExpr(E, This, &Result, E->getType());
4877}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004878
Richard Smith9543c5e2013-04-22 14:44:29 +00004879bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
4880 const LValue &Subobject,
4881 APValue *Value,
4882 QualType Type) {
4883 bool HadZeroInit = !Value->isUninit();
4884
4885 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
4886 unsigned N = CAT->getSize().getZExtValue();
4887
4888 // Preserve the array filler if we had prior zero-initialization.
4889 APValue Filler =
4890 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
4891 : APValue();
4892
4893 *Value = APValue(APValue::UninitArray(), N, N);
4894
4895 if (HadZeroInit)
4896 for (unsigned I = 0; I != N; ++I)
4897 Value->getArrayInitializedElt(I) = Filler;
4898
4899 // Initialize the elements.
4900 LValue ArrayElt = Subobject;
4901 ArrayElt.addArray(Info, E, CAT);
4902 for (unsigned I = 0; I != N; ++I)
4903 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
4904 CAT->getElementType()) ||
4905 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
4906 CAT->getElementType(), 1))
4907 return false;
4908
4909 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004910 }
Richard Smith027bf112011-11-17 22:56:20 +00004911
Richard Smith9543c5e2013-04-22 14:44:29 +00004912 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00004913 return Error(E);
4914
Richard Smith027bf112011-11-17 22:56:20 +00004915 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00004916
Richard Smithfddd3842011-12-30 21:15:51 +00004917 bool ZeroInit = E->requiresZeroInitialization();
4918 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004919 if (HadZeroInit)
4920 return true;
4921
Richard Smithfddd3842011-12-30 21:15:51 +00004922 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004923 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004924 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004925 }
4926
Richard Smithcc36f692011-12-22 02:22:31 +00004927 const CXXRecordDecl *RD = FD->getParent();
4928 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004929 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00004930 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004931 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00004932 APValue(APValue::UninitStruct(), RD->getNumBases(),
4933 std::distance(RD->field_begin(), RD->field_end()));
4934 return true;
4935 }
4936
Richard Smith027bf112011-11-17 22:56:20 +00004937 const FunctionDecl *Definition = 0;
4938 FD->getBody(Definition);
4939
Richard Smith357362d2011-12-13 06:39:58 +00004940 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4941 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004942
Richard Smith9eae7232012-01-12 18:54:33 +00004943 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004944 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004945 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004946 return false;
4947 }
4948
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004949 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004950 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00004951 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004952 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00004953}
4954
Richard Smithf3e9e432011-11-07 09:22:26 +00004955//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004956// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004957//
4958// As a GNU extension, we support casting pointers to sufficiently-wide integer
4959// types and back in constant folding. Integer values are thus represented
4960// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00004961//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004962
4963namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004964class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004965 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00004966 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004967public:
Richard Smith2e312c82012-03-03 22:46:17 +00004968 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004969 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004970
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004971 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004972 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004973 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004974 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004975 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004976 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004977 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004978 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004979 return true;
4980 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004981 bool Success(const llvm::APSInt &SI, const Expr *E) {
4982 return Success(SI, E, Result);
4983 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004984
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004985 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004986 assert(E->getType()->isIntegralOrEnumerationType() &&
4987 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004988 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004989 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004990 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004991 Result.getInt().setIsUnsigned(
4992 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004993 return true;
4994 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004995 bool Success(const llvm::APInt &I, const Expr *E) {
4996 return Success(I, E, Result);
4997 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004998
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004999 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005000 assert(E->getType()->isIntegralOrEnumerationType() &&
5001 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005002 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005003 return true;
5004 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005005 bool Success(uint64_t Value, const Expr *E) {
5006 return Success(Value, E, Result);
5007 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005008
Ken Dyckdbc01912011-03-11 02:13:43 +00005009 bool Success(CharUnits Size, const Expr *E) {
5010 return Success(Size.getQuantity(), E);
5011 }
5012
Richard Smith2e312c82012-03-03 22:46:17 +00005013 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005014 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005015 Result = V;
5016 return true;
5017 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005018 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005019 }
Mike Stump11289f42009-09-09 15:08:12 +00005020
Richard Smithfddd3842011-12-30 21:15:51 +00005021 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005022
Peter Collingbournee9200682011-05-13 03:29:01 +00005023 //===--------------------------------------------------------------------===//
5024 // Visitor Methods
5025 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005026
Chris Lattner7174bf32008-07-12 00:38:25 +00005027 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005028 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005029 }
5030 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005031 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005032 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005033
5034 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5035 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005036 if (CheckReferencedDecl(E, E->getDecl()))
5037 return true;
5038
5039 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005040 }
5041 bool VisitMemberExpr(const MemberExpr *E) {
5042 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005043 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005044 return true;
5045 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005046
5047 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005048 }
5049
Peter Collingbournee9200682011-05-13 03:29:01 +00005050 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005051 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005052 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005053 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005054
Peter Collingbournee9200682011-05-13 03:29:01 +00005055 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005056 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005057
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005058 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005059 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005060 }
Mike Stump11289f42009-09-09 15:08:12 +00005061
Ted Kremeneke65b0862012-03-06 20:05:56 +00005062 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5063 return Success(E->getValue(), E);
5064 }
5065
Richard Smith4ce706a2011-10-11 21:43:33 +00005066 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005067 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005068 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005069 }
5070
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005071 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005072 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005073 }
5074
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005075 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5076 return Success(E->getValue(), E);
5077 }
5078
Douglas Gregor29c42f22012-02-24 07:38:34 +00005079 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5080 return Success(E->getValue(), E);
5081 }
5082
John Wiegley6242b6a2011-04-28 00:16:57 +00005083 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5084 return Success(E->getValue(), E);
5085 }
5086
John Wiegleyf9f65842011-04-25 06:54:41 +00005087 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5088 return Success(E->getValue(), E);
5089 }
5090
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005091 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005092 bool VisitUnaryImag(const UnaryOperator *E);
5093
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005094 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005095 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005096
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005097private:
Ken Dyck160146e2010-01-27 17:10:57 +00005098 CharUnits GetAlignOfExpr(const Expr *E);
5099 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005100 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005101 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005102 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005103};
Chris Lattner05706e882008-07-11 18:11:29 +00005104} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005105
Richard Smith11562c52011-10-28 17:51:58 +00005106/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5107/// produce either the integer value or a pointer.
5108///
5109/// GCC has a heinous extension which folds casts between pointer types and
5110/// pointer-sized integral types. We support this by allowing the evaluation of
5111/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5112/// Some simple arithmetic on such values is supported (they are treated much
5113/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005114static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005115 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005116 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005117 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005118}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005119
Richard Smithf57d8cb2011-12-09 22:58:01 +00005120static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005121 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005122 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005123 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005124 if (!Val.isInt()) {
5125 // FIXME: It would be better to produce the diagnostic for casting
5126 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005127 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005128 return false;
5129 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005130 Result = Val.getInt();
5131 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005132}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005133
Richard Smithf57d8cb2011-12-09 22:58:01 +00005134/// Check whether the given declaration can be directly converted to an integral
5135/// rvalue. If not, no diagnostic is produced; there are other things we can
5136/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005137bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005138 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005139 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005140 // Check for signedness/width mismatches between E type and ECD value.
5141 bool SameSign = (ECD->getInitVal().isSigned()
5142 == E->getType()->isSignedIntegerOrEnumerationType());
5143 bool SameWidth = (ECD->getInitVal().getBitWidth()
5144 == Info.Ctx.getIntWidth(E->getType()));
5145 if (SameSign && SameWidth)
5146 return Success(ECD->getInitVal(), E);
5147 else {
5148 // Get rid of mismatch (otherwise Success assertions will fail)
5149 // by computing a new value matching the type of E.
5150 llvm::APSInt Val = ECD->getInitVal();
5151 if (!SameSign)
5152 Val.setIsSigned(!ECD->getInitVal().isSigned());
5153 if (!SameWidth)
5154 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5155 return Success(Val, E);
5156 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005157 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005158 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005159}
5160
Chris Lattner86ee2862008-10-06 06:40:35 +00005161/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5162/// as GCC.
5163static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5164 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005165 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005166 enum gcc_type_class {
5167 no_type_class = -1,
5168 void_type_class, integer_type_class, char_type_class,
5169 enumeral_type_class, boolean_type_class,
5170 pointer_type_class, reference_type_class, offset_type_class,
5171 real_type_class, complex_type_class,
5172 function_type_class, method_type_class,
5173 record_type_class, union_type_class,
5174 array_type_class, string_type_class,
5175 lang_type_class
5176 };
Mike Stump11289f42009-09-09 15:08:12 +00005177
5178 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005179 // ideal, however it is what gcc does.
5180 if (E->getNumArgs() == 0)
5181 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005182
Chris Lattner86ee2862008-10-06 06:40:35 +00005183 QualType ArgTy = E->getArg(0)->getType();
5184 if (ArgTy->isVoidType())
5185 return void_type_class;
5186 else if (ArgTy->isEnumeralType())
5187 return enumeral_type_class;
5188 else if (ArgTy->isBooleanType())
5189 return boolean_type_class;
5190 else if (ArgTy->isCharType())
5191 return string_type_class; // gcc doesn't appear to use char_type_class
5192 else if (ArgTy->isIntegerType())
5193 return integer_type_class;
5194 else if (ArgTy->isPointerType())
5195 return pointer_type_class;
5196 else if (ArgTy->isReferenceType())
5197 return reference_type_class;
5198 else if (ArgTy->isRealType())
5199 return real_type_class;
5200 else if (ArgTy->isComplexType())
5201 return complex_type_class;
5202 else if (ArgTy->isFunctionType())
5203 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005204 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005205 return record_type_class;
5206 else if (ArgTy->isUnionType())
5207 return union_type_class;
5208 else if (ArgTy->isArrayType())
5209 return array_type_class;
5210 else if (ArgTy->isUnionType())
5211 return union_type_class;
5212 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005213 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005214}
5215
Richard Smith5fab0c92011-12-28 19:48:30 +00005216/// EvaluateBuiltinConstantPForLValue - Determine the result of
5217/// __builtin_constant_p when applied to the given lvalue.
5218///
5219/// An lvalue is only "constant" if it is a pointer or reference to the first
5220/// character of a string literal.
5221template<typename LValue>
5222static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005223 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005224 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5225}
5226
5227/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5228/// GCC as we can manage.
5229static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5230 QualType ArgType = Arg->getType();
5231
5232 // __builtin_constant_p always has one operand. The rules which gcc follows
5233 // are not precisely documented, but are as follows:
5234 //
5235 // - If the operand is of integral, floating, complex or enumeration type,
5236 // and can be folded to a known value of that type, it returns 1.
5237 // - If the operand and can be folded to a pointer to the first character
5238 // of a string literal (or such a pointer cast to an integral type), it
5239 // returns 1.
5240 //
5241 // Otherwise, it returns 0.
5242 //
5243 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5244 // its support for this does not currently work.
5245 if (ArgType->isIntegralOrEnumerationType()) {
5246 Expr::EvalResult Result;
5247 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5248 return false;
5249
5250 APValue &V = Result.Val;
5251 if (V.getKind() == APValue::Int)
5252 return true;
5253
5254 return EvaluateBuiltinConstantPForLValue(V);
5255 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5256 return Arg->isEvaluatable(Ctx);
5257 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5258 LValue LV;
5259 Expr::EvalStatus Status;
5260 EvalInfo Info(Ctx, Status);
5261 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5262 : EvaluatePointer(Arg, LV, Info)) &&
5263 !Status.HasSideEffects)
5264 return EvaluateBuiltinConstantPForLValue(LV);
5265 }
5266
5267 // Anything else isn't considered to be sufficiently constant.
5268 return false;
5269}
5270
John McCall95007602010-05-10 23:27:23 +00005271/// Retrieves the "underlying object type" of the given expression,
5272/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005273QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5274 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5275 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005276 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005277 } else if (const Expr *E = B.get<const Expr*>()) {
5278 if (isa<CompoundLiteralExpr>(E))
5279 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005280 }
5281
5282 return QualType();
5283}
5284
Peter Collingbournee9200682011-05-13 03:29:01 +00005285bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005286 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005287
5288 {
5289 // The operand of __builtin_object_size is never evaluated for side-effects.
5290 // If there are any, but we can determine the pointed-to object anyway, then
5291 // ignore the side-effects.
5292 SpeculativeEvaluationRAII SpeculativeEval(Info);
5293 if (!EvaluatePointer(E->getArg(0), Base, Info))
5294 return false;
5295 }
John McCall95007602010-05-10 23:27:23 +00005296
5297 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005298 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005299
Richard Smithce40ad62011-11-12 22:28:03 +00005300 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005301 if (T.isNull() ||
5302 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005303 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005304 T->isVariablyModifiedType() ||
5305 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005306 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005307
5308 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5309 CharUnits Offset = Base.getLValueOffset();
5310
5311 if (!Offset.isNegative() && Offset <= Size)
5312 Size -= Offset;
5313 else
5314 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005315 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005316}
5317
Peter Collingbournee9200682011-05-13 03:29:01 +00005318bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005319 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005320 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005321 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005322
5323 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005324 if (TryEvaluateBuiltinObjectSize(E))
5325 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005326
Richard Smith0421ce72012-08-07 04:16:51 +00005327 // If evaluating the argument has side-effects, we can't determine the size
5328 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5329 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005330 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005331 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005332 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005333 return Success(0, E);
5334 }
Mike Stump876387b2009-10-27 22:09:17 +00005335
Richard Smith01ade172012-05-23 04:13:20 +00005336 // Expression had no side effects, but we couldn't statically determine the
5337 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005338 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005339 }
5340
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005341 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005342 case Builtin::BI__builtin_bswap32:
5343 case Builtin::BI__builtin_bswap64: {
5344 APSInt Val;
5345 if (!EvaluateInteger(E->getArg(0), Val, Info))
5346 return false;
5347
5348 return Success(Val.byteSwap(), E);
5349 }
5350
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005351 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005352 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00005353
Richard Smith5fab0c92011-12-28 19:48:30 +00005354 case Builtin::BI__builtin_constant_p:
5355 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00005356
Chris Lattnerd545ad12009-09-23 06:06:36 +00005357 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00005358 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00005359 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00005360 return Success(Operand, E);
5361 }
Eli Friedmand5c93992010-02-13 00:10:10 +00005362
5363 case Builtin::BI__builtin_expect:
5364 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00005365
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005366 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005367 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005368 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005369 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005370 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5371 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005372 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005373 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005374 case Builtin::BI__builtin_strlen:
5375 // As an extension, we support strlen() and __builtin_strlen() as constant
5376 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005377 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005378 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5379 // The string literal may have embedded null characters. Find the first
5380 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005381 StringRef Str = S->getString();
5382 StringRef::size_type Pos = Str.find(0);
5383 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005384 Str = Str.substr(0, Pos);
5385
5386 return Success(Str.size(), E);
5387 }
5388
Richard Smithf57d8cb2011-12-09 22:58:01 +00005389 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005390
Richard Smith01ba47d2012-04-13 00:45:38 +00005391 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005392 case Builtin::BI__atomic_is_lock_free:
5393 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005394 APSInt SizeVal;
5395 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5396 return false;
5397
5398 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5399 // of two less than the maximum inline atomic width, we know it is
5400 // lock-free. If the size isn't a power of two, or greater than the
5401 // maximum alignment where we promote atomics, we know it is not lock-free
5402 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5403 // the answer can only be determined at runtime; for example, 16-byte
5404 // atomics have lock-free implementations on some, but not all,
5405 // x86-64 processors.
5406
5407 // Check power-of-two.
5408 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005409 if (Size.isPowerOfTwo()) {
5410 // Check against inlining width.
5411 unsigned InlineWidthBits =
5412 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5413 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5414 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5415 Size == CharUnits::One() ||
5416 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5417 Expr::NPC_NeverValueDependent))
5418 // OK, we will inline appropriately-aligned operations of this size,
5419 // and _Atomic(T) is appropriately-aligned.
5420 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005421
Richard Smith01ba47d2012-04-13 00:45:38 +00005422 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5423 castAs<PointerType>()->getPointeeType();
5424 if (!PointeeType->isIncompleteType() &&
5425 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5426 // OK, we will inline operations on this object.
5427 return Success(1, E);
5428 }
5429 }
5430 }
Eli Friedmana4c26022011-10-17 21:44:23 +00005431
Richard Smith01ba47d2012-04-13 00:45:38 +00005432 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5433 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005434 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005435 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005436}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005437
Richard Smith8b3497e2011-10-31 01:37:14 +00005438static bool HasSameBase(const LValue &A, const LValue &B) {
5439 if (!A.getLValueBase())
5440 return !B.getLValueBase();
5441 if (!B.getLValueBase())
5442 return false;
5443
Richard Smithce40ad62011-11-12 22:28:03 +00005444 if (A.getLValueBase().getOpaqueValue() !=
5445 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005446 const Decl *ADecl = GetLValueBaseDecl(A);
5447 if (!ADecl)
5448 return false;
5449 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005450 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005451 return false;
5452 }
5453
5454 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005455 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005456}
5457
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005458namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005459
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005460/// \brief Data recursive integer evaluator of certain binary operators.
5461///
5462/// We use a data recursive algorithm for binary operators so that we are able
5463/// to handle extreme cases of chained binary operators without causing stack
5464/// overflow.
5465class DataRecursiveIntBinOpEvaluator {
5466 struct EvalResult {
5467 APValue Val;
5468 bool Failed;
5469
5470 EvalResult() : Failed(false) { }
5471
5472 void swap(EvalResult &RHS) {
5473 Val.swap(RHS.Val);
5474 Failed = RHS.Failed;
5475 RHS.Failed = false;
5476 }
5477 };
5478
5479 struct Job {
5480 const Expr *E;
5481 EvalResult LHSResult; // meaningful only for binary operator expression.
5482 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5483
5484 Job() : StoredInfo(0) { }
5485 void startSpeculativeEval(EvalInfo &Info) {
5486 OldEvalStatus = Info.EvalStatus;
5487 Info.EvalStatus.Diag = 0;
5488 StoredInfo = &Info;
5489 }
5490 ~Job() {
5491 if (StoredInfo) {
5492 StoredInfo->EvalStatus = OldEvalStatus;
5493 }
5494 }
5495 private:
5496 EvalInfo *StoredInfo; // non-null if status changed.
5497 Expr::EvalStatus OldEvalStatus;
5498 };
5499
5500 SmallVector<Job, 16> Queue;
5501
5502 IntExprEvaluator &IntEval;
5503 EvalInfo &Info;
5504 APValue &FinalResult;
5505
5506public:
5507 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5508 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5509
5510 /// \brief True if \param E is a binary operator that we are going to handle
5511 /// data recursively.
5512 /// We handle binary operators that are comma, logical, or that have operands
5513 /// with integral or enumeration type.
5514 static bool shouldEnqueue(const BinaryOperator *E) {
5515 return E->getOpcode() == BO_Comma ||
5516 E->isLogicalOp() ||
5517 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5518 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005519 }
5520
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005521 bool Traverse(const BinaryOperator *E) {
5522 enqueue(E);
5523 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00005524 while (!Queue.empty())
5525 process(PrevResult);
5526
5527 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005528
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005529 FinalResult.swap(PrevResult.Val);
5530 return true;
5531 }
5532
5533private:
5534 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5535 return IntEval.Success(Value, E, Result);
5536 }
5537 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
5538 return IntEval.Success(Value, E, Result);
5539 }
5540 bool Error(const Expr *E) {
5541 return IntEval.Error(E);
5542 }
5543 bool Error(const Expr *E, diag::kind D) {
5544 return IntEval.Error(E, D);
5545 }
5546
5547 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5548 return Info.CCEDiag(E, D);
5549 }
5550
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005551 // \brief Returns true if visiting the RHS is necessary, false otherwise.
5552 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005553 bool &SuppressRHSDiags);
5554
5555 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5556 const BinaryOperator *E, APValue &Result);
5557
5558 void EvaluateExpr(const Expr *E, EvalResult &Result) {
5559 Result.Failed = !Evaluate(Result.Val, Info, E);
5560 if (Result.Failed)
5561 Result.Val = APValue();
5562 }
5563
Richard Trieuba4d0872012-03-21 23:30:30 +00005564 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005565
5566 void enqueue(const Expr *E) {
5567 E = E->IgnoreParens();
5568 Queue.resize(Queue.size()+1);
5569 Queue.back().E = E;
5570 Queue.back().Kind = Job::AnyExprKind;
5571 }
5572};
5573
5574}
5575
5576bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005577 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005578 bool &SuppressRHSDiags) {
5579 if (E->getOpcode() == BO_Comma) {
5580 // Ignore LHS but note if we could not evaluate it.
5581 if (LHSResult.Failed)
5582 Info.EvalStatus.HasSideEffects = true;
5583 return true;
5584 }
5585
5586 if (E->isLogicalOp()) {
5587 bool lhsResult;
5588 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005589 // We were able to evaluate the LHS, see if we can get away with not
5590 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005591 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005592 Success(lhsResult, E, LHSResult.Val);
5593 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005594 }
5595 } else {
5596 // Since we weren't able to evaluate the left hand side, it
5597 // must have had side effects.
5598 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005599
5600 // We can't evaluate the LHS; however, sometimes the result
5601 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5602 // Don't ignore RHS and suppress diagnostics from this arm.
5603 SuppressRHSDiags = true;
5604 }
5605
5606 return true;
5607 }
5608
5609 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5610 E->getRHS()->getType()->isIntegralOrEnumerationType());
5611
5612 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005613 return false; // Ignore RHS;
5614
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005615 return true;
5616}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005617
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005618bool DataRecursiveIntBinOpEvaluator::
5619 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5620 const BinaryOperator *E, APValue &Result) {
5621 if (E->getOpcode() == BO_Comma) {
5622 if (RHSResult.Failed)
5623 return false;
5624 Result = RHSResult.Val;
5625 return true;
5626 }
5627
5628 if (E->isLogicalOp()) {
5629 bool lhsResult, rhsResult;
5630 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5631 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5632
5633 if (LHSIsOK) {
5634 if (RHSIsOK) {
5635 if (E->getOpcode() == BO_LOr)
5636 return Success(lhsResult || rhsResult, E, Result);
5637 else
5638 return Success(lhsResult && rhsResult, E, Result);
5639 }
5640 } else {
5641 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005642 // We can't evaluate the LHS; however, sometimes the result
5643 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5644 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005645 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005646 }
5647 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005648
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005649 return false;
5650 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005651
5652 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5653 E->getRHS()->getType()->isIntegralOrEnumerationType());
5654
5655 if (LHSResult.Failed || RHSResult.Failed)
5656 return false;
5657
5658 const APValue &LHSVal = LHSResult.Val;
5659 const APValue &RHSVal = RHSResult.Val;
5660
5661 // Handle cases like (unsigned long)&a + 4.
5662 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5663 Result = LHSVal;
5664 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5665 RHSVal.getInt().getZExtValue());
5666 if (E->getOpcode() == BO_Add)
5667 Result.getLValueOffset() += AdditionalOffset;
5668 else
5669 Result.getLValueOffset() -= AdditionalOffset;
5670 return true;
5671 }
5672
5673 // Handle cases like 4 + (unsigned long)&a
5674 if (E->getOpcode() == BO_Add &&
5675 RHSVal.isLValue() && LHSVal.isInt()) {
5676 Result = RHSVal;
5677 Result.getLValueOffset() += CharUnits::fromQuantity(
5678 LHSVal.getInt().getZExtValue());
5679 return true;
5680 }
5681
5682 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5683 // Handle (intptr_t)&&A - (intptr_t)&&B.
5684 if (!LHSVal.getLValueOffset().isZero() ||
5685 !RHSVal.getLValueOffset().isZero())
5686 return false;
5687 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5688 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5689 if (!LHSExpr || !RHSExpr)
5690 return false;
5691 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5692 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5693 if (!LHSAddrExpr || !RHSAddrExpr)
5694 return false;
5695 // Make sure both labels come from the same function.
5696 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5697 RHSAddrExpr->getLabel()->getDeclContext())
5698 return false;
5699 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5700 return true;
5701 }
Richard Smith43e77732013-05-07 04:50:00 +00005702
5703 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005704 if (!LHSVal.isInt() || !RHSVal.isInt())
5705 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00005706
5707 // Set up the width and signedness manually, in case it can't be deduced
5708 // from the operation we're performing.
5709 // FIXME: Don't do this in the cases where we can deduce it.
5710 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
5711 E->getType()->isUnsignedIntegerOrEnumerationType());
5712 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
5713 RHSVal.getInt(), Value))
5714 return false;
5715 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005716}
5717
Richard Trieuba4d0872012-03-21 23:30:30 +00005718void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005719 Job &job = Queue.back();
5720
5721 switch (job.Kind) {
5722 case Job::AnyExprKind: {
5723 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5724 if (shouldEnqueue(Bop)) {
5725 job.Kind = Job::BinOpKind;
5726 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005727 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005728 }
5729 }
5730
5731 EvaluateExpr(job.E, Result);
5732 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005733 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005734 }
5735
5736 case Job::BinOpKind: {
5737 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005738 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005739 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005740 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005741 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005742 }
5743 if (SuppressRHSDiags)
5744 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005745 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005746 job.Kind = Job::BinOpVisitedLHSKind;
5747 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005748 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005749 }
5750
5751 case Job::BinOpVisitedLHSKind: {
5752 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5753 EvalResult RHS;
5754 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00005755 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005756 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005757 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005758 }
5759 }
5760
5761 llvm_unreachable("Invalid Job::Kind!");
5762}
5763
5764bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5765 if (E->isAssignmentOp())
5766 return Error(E);
5767
5768 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
5769 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005770
Anders Carlssonacc79812008-11-16 07:17:21 +00005771 QualType LHSTy = E->getLHS()->getType();
5772 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005773
5774 if (LHSTy->isAnyComplexType()) {
5775 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00005776 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005777
Richard Smith253c2a32012-01-27 01:14:48 +00005778 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
5779 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005780 return false;
5781
Richard Smith253c2a32012-01-27 01:14:48 +00005782 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005783 return false;
5784
5785 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00005786 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005787 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00005788 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005789 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
5790
John McCalle3027922010-08-25 11:45:40 +00005791 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005792 return Success((CR_r == APFloat::cmpEqual &&
5793 CR_i == APFloat::cmpEqual), E);
5794 else {
John McCalle3027922010-08-25 11:45:40 +00005795 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005796 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00005797 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005798 CR_r == APFloat::cmpLessThan ||
5799 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00005800 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005801 CR_i == APFloat::cmpLessThan ||
5802 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005803 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005804 } else {
John McCalle3027922010-08-25 11:45:40 +00005805 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005806 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5807 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5808 else {
John McCalle3027922010-08-25 11:45:40 +00005809 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005810 "Invalid compex comparison.");
5811 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5812 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5813 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005814 }
5815 }
Mike Stump11289f42009-09-09 15:08:12 +00005816
Anders Carlssonacc79812008-11-16 07:17:21 +00005817 if (LHSTy->isRealFloatingType() &&
5818 RHSTy->isRealFloatingType()) {
5819 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00005820
Richard Smith253c2a32012-01-27 01:14:48 +00005821 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5822 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00005823 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005824
Richard Smith253c2a32012-01-27 01:14:48 +00005825 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00005826 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005827
Anders Carlssonacc79812008-11-16 07:17:21 +00005828 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00005829
Anders Carlssonacc79812008-11-16 07:17:21 +00005830 switch (E->getOpcode()) {
5831 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005832 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00005833 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005834 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00005835 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005836 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00005837 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005838 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005839 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00005840 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005841 E);
John McCalle3027922010-08-25 11:45:40 +00005842 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005843 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005844 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00005845 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00005846 || CR == APFloat::cmpLessThan
5847 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00005848 }
Anders Carlssonacc79812008-11-16 07:17:21 +00005849 }
Mike Stump11289f42009-09-09 15:08:12 +00005850
Eli Friedmana38da572009-04-28 19:17:36 +00005851 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005852 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005853 LValue LHSValue, RHSValue;
5854
5855 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
5856 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005857 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005858
Richard Smith253c2a32012-01-27 01:14:48 +00005859 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005860 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005861
Richard Smith8b3497e2011-10-31 01:37:14 +00005862 // Reject differing bases from the normal codepath; we special-case
5863 // comparisons to null.
5864 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005865 if (E->getOpcode() == BO_Sub) {
5866 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005867 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
5868 return false;
5869 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00005870 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005871 if (!LHSExpr || !RHSExpr)
5872 return false;
5873 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5874 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5875 if (!LHSAddrExpr || !RHSAddrExpr)
5876 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005877 // Make sure both labels come from the same function.
5878 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5879 RHSAddrExpr->getLabel()->getDeclContext())
5880 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005881 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005882 return true;
5883 }
Richard Smith83c68212011-10-31 05:11:32 +00005884 // Inequalities and subtractions between unrelated pointers have
5885 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00005886 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005887 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005888 // A constant address may compare equal to the address of a symbol.
5889 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00005890 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005891 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5892 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005893 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005894 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00005895 // distinct addresses. In clang, the result of such a comparison is
5896 // unspecified, so it is not a constant expression. However, we do know
5897 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00005898 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5899 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005900 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005901 // We can't tell whether weak symbols will end up pointing to the same
5902 // object.
5903 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005904 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005905 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00005906 // (Note that clang defaults to -fmerge-all-constants, which can
5907 // lead to inconsistent results for comparisons involving the address
5908 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00005909 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00005910 }
Eli Friedman64004332009-03-23 04:38:34 +00005911
Richard Smith1b470412012-02-01 08:10:20 +00005912 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5913 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5914
Richard Smith84f6dcf2012-02-02 01:16:57 +00005915 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5916 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5917
John McCalle3027922010-08-25 11:45:40 +00005918 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005919 // C++11 [expr.add]p6:
5920 // Unless both pointers point to elements of the same array object, or
5921 // one past the last element of the array object, the behavior is
5922 // undefined.
5923 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5924 !AreElementsOfSameArray(getType(LHSValue.Base),
5925 LHSDesignator, RHSDesignator))
5926 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5927
Chris Lattner882bdf22010-04-20 17:13:14 +00005928 QualType Type = E->getLHS()->getType();
5929 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005930
Richard Smithd62306a2011-11-10 06:34:14 +00005931 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00005932 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00005933 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005934
Richard Smith1b470412012-02-01 08:10:20 +00005935 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5936 // and produce incorrect results when it overflows. Such behavior
5937 // appears to be non-conforming, but is common, so perhaps we should
5938 // assume the standard intended for such cases to be undefined behavior
5939 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00005940
Richard Smith1b470412012-02-01 08:10:20 +00005941 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5942 // overflow in the final conversion to ptrdiff_t.
5943 APSInt LHS(
5944 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5945 APSInt RHS(
5946 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5947 APSInt ElemSize(
5948 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5949 APSInt TrueResult = (LHS - RHS) / ElemSize;
5950 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5951
5952 if (Result.extend(65) != TrueResult)
5953 HandleOverflow(Info, E, TrueResult, E->getType());
5954 return Success(Result, E);
5955 }
Richard Smithde21b242012-01-31 06:41:30 +00005956
5957 // C++11 [expr.rel]p3:
5958 // Pointers to void (after pointer conversions) can be compared, with a
5959 // result defined as follows: If both pointers represent the same
5960 // address or are both the null pointer value, the result is true if the
5961 // operator is <= or >= and false otherwise; otherwise the result is
5962 // unspecified.
5963 // We interpret this as applying to pointers to *cv* void.
5964 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00005965 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00005966 CCEDiag(E, diag::note_constexpr_void_comparison);
5967
Richard Smith84f6dcf2012-02-02 01:16:57 +00005968 // C++11 [expr.rel]p2:
5969 // - If two pointers point to non-static data members of the same object,
5970 // or to subobjects or array elements fo such members, recursively, the
5971 // pointer to the later declared member compares greater provided the
5972 // two members have the same access control and provided their class is
5973 // not a union.
5974 // [...]
5975 // - Otherwise pointer comparisons are unspecified.
5976 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5977 E->isRelationalOp()) {
5978 bool WasArrayIndex;
5979 unsigned Mismatch =
5980 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5981 RHSDesignator, WasArrayIndex);
5982 // At the point where the designators diverge, the comparison has a
5983 // specified value if:
5984 // - we are comparing array indices
5985 // - we are comparing fields of a union, or fields with the same access
5986 // Otherwise, the result is unspecified and thus the comparison is not a
5987 // constant expression.
5988 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5989 Mismatch < RHSDesignator.Entries.size()) {
5990 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5991 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5992 if (!LF && !RF)
5993 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5994 else if (!LF)
5995 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5996 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5997 << RF->getParent() << RF;
5998 else if (!RF)
5999 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6000 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6001 << LF->getParent() << LF;
6002 else if (!LF->getParent()->isUnion() &&
6003 LF->getAccess() != RF->getAccess())
6004 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6005 << LF << LF->getAccess() << RF << RF->getAccess()
6006 << LF->getParent();
6007 }
6008 }
6009
Eli Friedman6c31cb42012-04-16 04:30:08 +00006010 // The comparison here must be unsigned, and performed with the same
6011 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006012 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6013 uint64_t CompareLHS = LHSOffset.getQuantity();
6014 uint64_t CompareRHS = RHSOffset.getQuantity();
6015 assert(PtrSize <= 64 && "Unexpected pointer width");
6016 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6017 CompareLHS &= Mask;
6018 CompareRHS &= Mask;
6019
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006020 // If there is a base and this is a relational operator, we can only
6021 // compare pointers within the object in question; otherwise, the result
6022 // depends on where the object is located in memory.
6023 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6024 QualType BaseTy = getType(LHSValue.Base);
6025 if (BaseTy->isIncompleteType())
6026 return Error(E);
6027 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6028 uint64_t OffsetLimit = Size.getQuantity();
6029 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6030 return Error(E);
6031 }
6032
Richard Smith8b3497e2011-10-31 01:37:14 +00006033 switch (E->getOpcode()) {
6034 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006035 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6036 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6037 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6038 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6039 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6040 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006041 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006042 }
6043 }
Richard Smith7bb00672012-02-01 01:42:44 +00006044
6045 if (LHSTy->isMemberPointerType()) {
6046 assert(E->isEqualityOp() && "unexpected member pointer operation");
6047 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6048
6049 MemberPtr LHSValue, RHSValue;
6050
6051 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6052 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6053 return false;
6054
6055 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6056 return false;
6057
6058 // C++11 [expr.eq]p2:
6059 // If both operands are null, they compare equal. Otherwise if only one is
6060 // null, they compare unequal.
6061 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6062 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6063 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6064 }
6065
6066 // Otherwise if either is a pointer to a virtual member function, the
6067 // result is unspecified.
6068 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6069 if (MD->isVirtual())
6070 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6071 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6072 if (MD->isVirtual())
6073 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6074
6075 // Otherwise they compare equal if and only if they would refer to the
6076 // same member of the same most derived object or the same subobject if
6077 // they were dereferenced with a hypothetical object of the associated
6078 // class type.
6079 bool Equal = LHSValue == RHSValue;
6080 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6081 }
6082
Richard Smithab44d9b2012-02-14 22:35:28 +00006083 if (LHSTy->isNullPtrType()) {
6084 assert(E->isComparisonOp() && "unexpected nullptr operation");
6085 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6086 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6087 // are compared, the result is true of the operator is <=, >= or ==, and
6088 // false otherwise.
6089 BinaryOperator::Opcode Opcode = E->getOpcode();
6090 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6091 }
6092
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006093 assert((!LHSTy->isIntegralOrEnumerationType() ||
6094 !RHSTy->isIntegralOrEnumerationType()) &&
6095 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6096 // We can't continue from here for non-integral types.
6097 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006098}
6099
Ken Dyck160146e2010-01-27 17:10:57 +00006100CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006101 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6102 // result shall be the alignment of the referenced type."
6103 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6104 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006105
6106 // __alignof is defined to return the preferred alignment.
6107 return Info.Ctx.toCharUnitsFromBits(
6108 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006109}
6110
Ken Dyck160146e2010-01-27 17:10:57 +00006111CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006112 E = E->IgnoreParens();
6113
John McCall768439e2013-05-06 07:40:34 +00006114 // The kinds of expressions that we have special-case logic here for
6115 // should be kept up to date with the special checks for those
6116 // expressions in Sema.
6117
Chris Lattner68061312009-01-24 21:53:27 +00006118 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006119 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006120 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006121 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6122 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006123
Chris Lattner68061312009-01-24 21:53:27 +00006124 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006125 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6126 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006127
Chris Lattner24aeeab2009-01-24 21:09:06 +00006128 return GetAlignOfType(E->getType());
6129}
6130
6131
Peter Collingbournee190dee2011-03-11 19:24:49 +00006132/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6133/// a result as the expression's type.
6134bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6135 const UnaryExprOrTypeTraitExpr *E) {
6136 switch(E->getKind()) {
6137 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006138 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006139 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006140 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006141 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006142 }
Eli Friedman64004332009-03-23 04:38:34 +00006143
Peter Collingbournee190dee2011-03-11 19:24:49 +00006144 case UETT_VecStep: {
6145 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006146
Peter Collingbournee190dee2011-03-11 19:24:49 +00006147 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006148 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006149
Peter Collingbournee190dee2011-03-11 19:24:49 +00006150 // The vec_step built-in functions that take a 3-component
6151 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6152 if (n == 3)
6153 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006154
Peter Collingbournee190dee2011-03-11 19:24:49 +00006155 return Success(n, E);
6156 } else
6157 return Success(1, E);
6158 }
6159
6160 case UETT_SizeOf: {
6161 QualType SrcTy = E->getTypeOfArgument();
6162 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6163 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006164 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6165 SrcTy = Ref->getPointeeType();
6166
Richard Smithd62306a2011-11-10 06:34:14 +00006167 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006168 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006169 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006170 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006171 }
6172 }
6173
6174 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006175}
6176
Peter Collingbournee9200682011-05-13 03:29:01 +00006177bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006178 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006179 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006180 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006181 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006182 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006183 for (unsigned i = 0; i != n; ++i) {
6184 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6185 switch (ON.getKind()) {
6186 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006187 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006188 APSInt IdxResult;
6189 if (!EvaluateInteger(Idx, IdxResult, Info))
6190 return false;
6191 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6192 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006193 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006194 CurrentType = AT->getElementType();
6195 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6196 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006197 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006198 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006199
Douglas Gregor882211c2010-04-28 22:16:22 +00006200 case OffsetOfExpr::OffsetOfNode::Field: {
6201 FieldDecl *MemberDecl = ON.getField();
6202 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006203 if (!RT)
6204 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006205 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006206 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006207 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006208 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006209 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006210 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006211 CurrentType = MemberDecl->getType().getNonReferenceType();
6212 break;
6213 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006214
Douglas Gregor882211c2010-04-28 22:16:22 +00006215 case OffsetOfExpr::OffsetOfNode::Identifier:
6216 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006217
Douglas Gregord1702062010-04-29 00:18:15 +00006218 case OffsetOfExpr::OffsetOfNode::Base: {
6219 CXXBaseSpecifier *BaseSpec = ON.getBase();
6220 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006221 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006222
6223 // Find the layout of the class whose base we are looking into.
6224 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006225 if (!RT)
6226 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006227 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006228 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006229 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6230
6231 // Find the base class itself.
6232 CurrentType = BaseSpec->getType();
6233 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6234 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006235 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006236
6237 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006238 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006239 break;
6240 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006241 }
6242 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006243 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006244}
6245
Chris Lattnere13042c2008-07-11 19:10:17 +00006246bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006247 switch (E->getOpcode()) {
6248 default:
6249 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6250 // See C99 6.6p3.
6251 return Error(E);
6252 case UO_Extension:
6253 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6254 // If so, we could clear the diagnostic ID.
6255 return Visit(E->getSubExpr());
6256 case UO_Plus:
6257 // The result is just the value.
6258 return Visit(E->getSubExpr());
6259 case UO_Minus: {
6260 if (!Visit(E->getSubExpr()))
6261 return false;
6262 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006263 const APSInt &Value = Result.getInt();
6264 if (Value.isSigned() && Value.isMinSignedValue())
6265 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6266 E->getType());
6267 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006268 }
6269 case UO_Not: {
6270 if (!Visit(E->getSubExpr()))
6271 return false;
6272 if (!Result.isInt()) return Error(E);
6273 return Success(~Result.getInt(), E);
6274 }
6275 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006276 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006277 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006278 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006279 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006280 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006281 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006282}
Mike Stump11289f42009-09-09 15:08:12 +00006283
Chris Lattner477c4be2008-07-12 01:15:53 +00006284/// HandleCast - This is used to evaluate implicit or explicit casts where the
6285/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006286bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6287 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006288 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006289 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006290
Eli Friedmanc757de22011-03-25 00:43:55 +00006291 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006292 case CK_BaseToDerived:
6293 case CK_DerivedToBase:
6294 case CK_UncheckedDerivedToBase:
6295 case CK_Dynamic:
6296 case CK_ToUnion:
6297 case CK_ArrayToPointerDecay:
6298 case CK_FunctionToPointerDecay:
6299 case CK_NullToPointer:
6300 case CK_NullToMemberPointer:
6301 case CK_BaseToDerivedMemberPointer:
6302 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006303 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006304 case CK_ConstructorConversion:
6305 case CK_IntegralToPointer:
6306 case CK_ToVoid:
6307 case CK_VectorSplat:
6308 case CK_IntegralToFloating:
6309 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006310 case CK_CPointerToObjCPointerCast:
6311 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006312 case CK_AnyPointerToBlockPointerCast:
6313 case CK_ObjCObjectLValueCast:
6314 case CK_FloatingRealToComplex:
6315 case CK_FloatingComplexToReal:
6316 case CK_FloatingComplexCast:
6317 case CK_FloatingComplexToIntegralComplex:
6318 case CK_IntegralRealToComplex:
6319 case CK_IntegralComplexCast:
6320 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006321 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006322 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006323 llvm_unreachable("invalid cast kind for integral value");
6324
Eli Friedman9faf2f92011-03-25 19:07:11 +00006325 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006326 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006327 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006328 case CK_ARCProduceObject:
6329 case CK_ARCConsumeObject:
6330 case CK_ARCReclaimReturnedObject:
6331 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006332 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006333 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006334
Richard Smith4ef685b2012-01-17 21:17:26 +00006335 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006336 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006337 case CK_AtomicToNonAtomic:
6338 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006339 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006340 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006341
6342 case CK_MemberPointerToBoolean:
6343 case CK_PointerToBoolean:
6344 case CK_IntegralToBoolean:
6345 case CK_FloatingToBoolean:
6346 case CK_FloatingComplexToBoolean:
6347 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006348 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006349 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006350 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006351 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006352 }
6353
Eli Friedmanc757de22011-03-25 00:43:55 +00006354 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006355 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006356 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006357
Eli Friedman742421e2009-02-20 01:15:07 +00006358 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006359 // Allow casts of address-of-label differences if they are no-ops
6360 // or narrowing. (The narrowing case isn't actually guaranteed to
6361 // be constant-evaluatable except in some narrow cases which are hard
6362 // to detect here. We let it through on the assumption the user knows
6363 // what they are doing.)
6364 if (Result.isAddrLabelDiff())
6365 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006366 // Only allow casts of lvalues if they are lossless.
6367 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6368 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006369
Richard Smith911e1422012-01-30 22:27:01 +00006370 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6371 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006372 }
Mike Stump11289f42009-09-09 15:08:12 +00006373
Eli Friedmanc757de22011-03-25 00:43:55 +00006374 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006375 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6376
John McCall45d55e42010-05-07 21:00:08 +00006377 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006378 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006379 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006380
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006381 if (LV.getLValueBase()) {
6382 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006383 // FIXME: Allow a larger integer size than the pointer size, and allow
6384 // narrowing back down to pointer width in subsequent integral casts.
6385 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006386 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006387 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006388
Richard Smithcf74da72011-11-16 07:18:12 +00006389 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006390 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006391 return true;
6392 }
6393
Ken Dyck02990832010-01-15 12:37:54 +00006394 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6395 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006396 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006397 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006398
Eli Friedmanc757de22011-03-25 00:43:55 +00006399 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006400 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006401 if (!EvaluateComplex(SubExpr, C, Info))
6402 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006403 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006404 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006405
Eli Friedmanc757de22011-03-25 00:43:55 +00006406 case CK_FloatingToIntegral: {
6407 APFloat F(0.0);
6408 if (!EvaluateFloat(SubExpr, F, Info))
6409 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006410
Richard Smith357362d2011-12-13 06:39:58 +00006411 APSInt Value;
6412 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6413 return false;
6414 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006415 }
6416 }
Mike Stump11289f42009-09-09 15:08:12 +00006417
Eli Friedmanc757de22011-03-25 00:43:55 +00006418 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006419}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006420
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006421bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6422 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006423 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006424 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6425 return false;
6426 if (!LV.isComplexInt())
6427 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006428 return Success(LV.getComplexIntReal(), E);
6429 }
6430
6431 return Visit(E->getSubExpr());
6432}
6433
Eli Friedman4e7a2412009-02-27 04:45:43 +00006434bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006435 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006436 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006437 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6438 return false;
6439 if (!LV.isComplexInt())
6440 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006441 return Success(LV.getComplexIntImag(), E);
6442 }
6443
Richard Smith4a678122011-10-24 18:44:57 +00006444 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006445 return Success(0, E);
6446}
6447
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006448bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6449 return Success(E->getPackLength(), E);
6450}
6451
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006452bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6453 return Success(E->getValue(), E);
6454}
6455
Chris Lattner05706e882008-07-11 18:11:29 +00006456//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006457// Float Evaluation
6458//===----------------------------------------------------------------------===//
6459
6460namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006461class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006462 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006463 APFloat &Result;
6464public:
6465 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006466 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006467
Richard Smith2e312c82012-03-03 22:46:17 +00006468 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006469 Result = V.getFloat();
6470 return true;
6471 }
Eli Friedman24c01542008-08-22 00:06:13 +00006472
Richard Smithfddd3842011-12-30 21:15:51 +00006473 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006474 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6475 return true;
6476 }
6477
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006478 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006479
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006480 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006481 bool VisitBinaryOperator(const BinaryOperator *E);
6482 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006483 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006484
John McCallb1fb0d32010-05-07 22:08:54 +00006485 bool VisitUnaryReal(const UnaryOperator *E);
6486 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006487
Richard Smithfddd3842011-12-30 21:15:51 +00006488 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006489};
6490} // end anonymous namespace
6491
6492static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006493 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006494 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006495}
6496
Jay Foad39c79802011-01-12 09:06:06 +00006497static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006498 QualType ResultTy,
6499 const Expr *Arg,
6500 bool SNaN,
6501 llvm::APFloat &Result) {
6502 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6503 if (!S) return false;
6504
6505 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6506
6507 llvm::APInt fill;
6508
6509 // Treat empty strings as if they were zero.
6510 if (S->getString().empty())
6511 fill = llvm::APInt(32, 0);
6512 else if (S->getString().getAsInteger(0, fill))
6513 return false;
6514
6515 if (SNaN)
6516 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6517 else
6518 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6519 return true;
6520}
6521
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006522bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006523 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006524 default:
6525 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6526
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006527 case Builtin::BI__builtin_huge_val:
6528 case Builtin::BI__builtin_huge_valf:
6529 case Builtin::BI__builtin_huge_vall:
6530 case Builtin::BI__builtin_inf:
6531 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006532 case Builtin::BI__builtin_infl: {
6533 const llvm::fltSemantics &Sem =
6534 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006535 Result = llvm::APFloat::getInf(Sem);
6536 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006537 }
Mike Stump11289f42009-09-09 15:08:12 +00006538
John McCall16291492010-02-28 13:00:19 +00006539 case Builtin::BI__builtin_nans:
6540 case Builtin::BI__builtin_nansf:
6541 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006542 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6543 true, Result))
6544 return Error(E);
6545 return true;
John McCall16291492010-02-28 13:00:19 +00006546
Chris Lattner0b7282e2008-10-06 06:31:58 +00006547 case Builtin::BI__builtin_nan:
6548 case Builtin::BI__builtin_nanf:
6549 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006550 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006551 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006552 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6553 false, Result))
6554 return Error(E);
6555 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006556
6557 case Builtin::BI__builtin_fabs:
6558 case Builtin::BI__builtin_fabsf:
6559 case Builtin::BI__builtin_fabsl:
6560 if (!EvaluateFloat(E->getArg(0), Result, Info))
6561 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006562
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006563 if (Result.isNegative())
6564 Result.changeSign();
6565 return true;
6566
Mike Stump11289f42009-09-09 15:08:12 +00006567 case Builtin::BI__builtin_copysign:
6568 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006569 case Builtin::BI__builtin_copysignl: {
6570 APFloat RHS(0.);
6571 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6572 !EvaluateFloat(E->getArg(1), RHS, Info))
6573 return false;
6574 Result.copySign(RHS);
6575 return true;
6576 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006577 }
6578}
6579
John McCallb1fb0d32010-05-07 22:08:54 +00006580bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006581 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6582 ComplexValue CV;
6583 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6584 return false;
6585 Result = CV.FloatReal;
6586 return true;
6587 }
6588
6589 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00006590}
6591
6592bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006593 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6594 ComplexValue CV;
6595 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6596 return false;
6597 Result = CV.FloatImag;
6598 return true;
6599 }
6600
Richard Smith4a678122011-10-24 18:44:57 +00006601 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00006602 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6603 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00006604 return true;
6605}
6606
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006607bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006608 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006609 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006610 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00006611 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00006612 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00006613 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6614 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006615 Result.changeSign();
6616 return true;
6617 }
6618}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006619
Eli Friedman24c01542008-08-22 00:06:13 +00006620bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006621 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6622 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00006623
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006624 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00006625 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6626 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00006627 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00006628 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
6629 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00006630}
6631
6632bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6633 Result = E->getValue();
6634 return true;
6635}
6636
Peter Collingbournee9200682011-05-13 03:29:01 +00006637bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6638 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00006639
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006640 switch (E->getCastKind()) {
6641 default:
Richard Smith11562c52011-10-28 17:51:58 +00006642 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006643
6644 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006645 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00006646 return EvaluateInteger(SubExpr, IntResult, Info) &&
6647 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6648 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006649 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006650
6651 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006652 if (!Visit(SubExpr))
6653 return false;
Richard Smith357362d2011-12-13 06:39:58 +00006654 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6655 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006656 }
John McCalld7646252010-11-14 08:17:51 +00006657
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006658 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00006659 ComplexValue V;
6660 if (!EvaluateComplex(SubExpr, V, Info))
6661 return false;
6662 Result = V.getComplexFloatReal();
6663 return true;
6664 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006665 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006666}
6667
Eli Friedman24c01542008-08-22 00:06:13 +00006668//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006669// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00006670//===----------------------------------------------------------------------===//
6671
6672namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006673class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006674 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00006675 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00006676
Anders Carlsson537969c2008-11-16 20:27:53 +00006677public:
John McCall93d91dc2010-05-07 17:22:02 +00006678 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006679 : ExprEvaluatorBaseTy(info), Result(Result) {}
6680
Richard Smith2e312c82012-03-03 22:46:17 +00006681 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006682 Result.setFrom(V);
6683 return true;
6684 }
Mike Stump11289f42009-09-09 15:08:12 +00006685
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006686 bool ZeroInitialization(const Expr *E);
6687
Anders Carlsson537969c2008-11-16 20:27:53 +00006688 //===--------------------------------------------------------------------===//
6689 // Visitor Methods
6690 //===--------------------------------------------------------------------===//
6691
Peter Collingbournee9200682011-05-13 03:29:01 +00006692 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006693 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00006694 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006695 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006696 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006697};
6698} // end anonymous namespace
6699
John McCall93d91dc2010-05-07 17:22:02 +00006700static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6701 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006702 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006703 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006704}
6705
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006706bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00006707 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006708 if (ElemTy->isRealFloatingType()) {
6709 Result.makeComplexFloat();
6710 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6711 Result.FloatReal = Zero;
6712 Result.FloatImag = Zero;
6713 } else {
6714 Result.makeComplexInt();
6715 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6716 Result.IntReal = Zero;
6717 Result.IntImag = Zero;
6718 }
6719 return true;
6720}
6721
Peter Collingbournee9200682011-05-13 03:29:01 +00006722bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6723 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006724
6725 if (SubExpr->getType()->isRealFloatingType()) {
6726 Result.makeComplexFloat();
6727 APFloat &Imag = Result.FloatImag;
6728 if (!EvaluateFloat(SubExpr, Imag, Info))
6729 return false;
6730
6731 Result.FloatReal = APFloat(Imag.getSemantics());
6732 return true;
6733 } else {
6734 assert(SubExpr->getType()->isIntegerType() &&
6735 "Unexpected imaginary literal.");
6736
6737 Result.makeComplexInt();
6738 APSInt &Imag = Result.IntImag;
6739 if (!EvaluateInteger(SubExpr, Imag, Info))
6740 return false;
6741
6742 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6743 return true;
6744 }
6745}
6746
Peter Collingbournee9200682011-05-13 03:29:01 +00006747bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006748
John McCallfcef3cf2010-12-14 17:51:41 +00006749 switch (E->getCastKind()) {
6750 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006751 case CK_BaseToDerived:
6752 case CK_DerivedToBase:
6753 case CK_UncheckedDerivedToBase:
6754 case CK_Dynamic:
6755 case CK_ToUnion:
6756 case CK_ArrayToPointerDecay:
6757 case CK_FunctionToPointerDecay:
6758 case CK_NullToPointer:
6759 case CK_NullToMemberPointer:
6760 case CK_BaseToDerivedMemberPointer:
6761 case CK_DerivedToBaseMemberPointer:
6762 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00006763 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00006764 case CK_ConstructorConversion:
6765 case CK_IntegralToPointer:
6766 case CK_PointerToIntegral:
6767 case CK_PointerToBoolean:
6768 case CK_ToVoid:
6769 case CK_VectorSplat:
6770 case CK_IntegralCast:
6771 case CK_IntegralToBoolean:
6772 case CK_IntegralToFloating:
6773 case CK_FloatingToIntegral:
6774 case CK_FloatingToBoolean:
6775 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006776 case CK_CPointerToObjCPointerCast:
6777 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006778 case CK_AnyPointerToBlockPointerCast:
6779 case CK_ObjCObjectLValueCast:
6780 case CK_FloatingComplexToReal:
6781 case CK_FloatingComplexToBoolean:
6782 case CK_IntegralComplexToReal:
6783 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00006784 case CK_ARCProduceObject:
6785 case CK_ARCConsumeObject:
6786 case CK_ARCReclaimReturnedObject:
6787 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006788 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00006789 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006790 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00006791 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00006792
John McCallfcef3cf2010-12-14 17:51:41 +00006793 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006794 case CK_AtomicToNonAtomic:
6795 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006796 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006797 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006798
6799 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006800 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006801 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006802 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006803
6804 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006805 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00006806 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006807 return false;
6808
John McCallfcef3cf2010-12-14 17:51:41 +00006809 Result.makeComplexFloat();
6810 Result.FloatImag = APFloat(Real.getSemantics());
6811 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006812 }
6813
John McCallfcef3cf2010-12-14 17:51:41 +00006814 case CK_FloatingComplexCast: {
6815 if (!Visit(E->getSubExpr()))
6816 return false;
6817
6818 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6819 QualType From
6820 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6821
Richard Smith357362d2011-12-13 06:39:58 +00006822 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6823 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006824 }
6825
6826 case CK_FloatingComplexToIntegralComplex: {
6827 if (!Visit(E->getSubExpr()))
6828 return false;
6829
6830 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6831 QualType From
6832 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6833 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00006834 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6835 To, Result.IntReal) &&
6836 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6837 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006838 }
6839
6840 case CK_IntegralRealToComplex: {
6841 APSInt &Real = Result.IntReal;
6842 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6843 return false;
6844
6845 Result.makeComplexInt();
6846 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
6847 return true;
6848 }
6849
6850 case CK_IntegralComplexCast: {
6851 if (!Visit(E->getSubExpr()))
6852 return false;
6853
6854 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6855 QualType From
6856 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6857
Richard Smith911e1422012-01-30 22:27:01 +00006858 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
6859 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006860 return true;
6861 }
6862
6863 case CK_IntegralComplexToFloatingComplex: {
6864 if (!Visit(E->getSubExpr()))
6865 return false;
6866
Ted Kremenek28831752012-08-23 20:46:57 +00006867 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006868 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00006869 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006870 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00006871 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6872 To, Result.FloatReal) &&
6873 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6874 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006875 }
6876 }
6877
6878 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006879}
6880
John McCall93d91dc2010-05-07 17:22:02 +00006881bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006882 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00006883 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6884
Richard Smith253c2a32012-01-27 01:14:48 +00006885 bool LHSOK = Visit(E->getLHS());
6886 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00006887 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006888
John McCall93d91dc2010-05-07 17:22:02 +00006889 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00006890 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00006891 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006892
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006893 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6894 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006895 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006896 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006897 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006898 if (Result.isComplexFloat()) {
6899 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6900 APFloat::rmNearestTiesToEven);
6901 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6902 APFloat::rmNearestTiesToEven);
6903 } else {
6904 Result.getComplexIntReal() += RHS.getComplexIntReal();
6905 Result.getComplexIntImag() += RHS.getComplexIntImag();
6906 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006907 break;
John McCalle3027922010-08-25 11:45:40 +00006908 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006909 if (Result.isComplexFloat()) {
6910 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6911 APFloat::rmNearestTiesToEven);
6912 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6913 APFloat::rmNearestTiesToEven);
6914 } else {
6915 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6916 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6917 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006918 break;
John McCalle3027922010-08-25 11:45:40 +00006919 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006920 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00006921 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006922 APFloat &LHS_r = LHS.getComplexFloatReal();
6923 APFloat &LHS_i = LHS.getComplexFloatImag();
6924 APFloat &RHS_r = RHS.getComplexFloatReal();
6925 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00006926
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006927 APFloat Tmp = LHS_r;
6928 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6929 Result.getComplexFloatReal() = Tmp;
6930 Tmp = LHS_i;
6931 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6932 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6933
6934 Tmp = LHS_r;
6935 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6936 Result.getComplexFloatImag() = Tmp;
6937 Tmp = LHS_i;
6938 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6939 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6940 } else {
John McCall93d91dc2010-05-07 17:22:02 +00006941 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00006942 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006943 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6944 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00006945 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006946 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6947 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6948 }
6949 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006950 case BO_Div:
6951 if (Result.isComplexFloat()) {
6952 ComplexValue LHS = Result;
6953 APFloat &LHS_r = LHS.getComplexFloatReal();
6954 APFloat &LHS_i = LHS.getComplexFloatImag();
6955 APFloat &RHS_r = RHS.getComplexFloatReal();
6956 APFloat &RHS_i = RHS.getComplexFloatImag();
6957 APFloat &Res_r = Result.getComplexFloatReal();
6958 APFloat &Res_i = Result.getComplexFloatImag();
6959
6960 APFloat Den = RHS_r;
6961 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6962 APFloat Tmp = RHS_i;
6963 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6964 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6965
6966 Res_r = LHS_r;
6967 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6968 Tmp = LHS_i;
6969 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6970 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6971 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6972
6973 Res_i = LHS_i;
6974 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6975 Tmp = LHS_r;
6976 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6977 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6978 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6979 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006980 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6981 return Error(E, diag::note_expr_divide_by_zero);
6982
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006983 ComplexValue LHS = Result;
6984 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6985 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6986 Result.getComplexIntReal() =
6987 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6988 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6989 Result.getComplexIntImag() =
6990 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6991 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6992 }
6993 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006994 }
6995
John McCall93d91dc2010-05-07 17:22:02 +00006996 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006997}
6998
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006999bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7000 // Get the operand value into 'Result'.
7001 if (!Visit(E->getSubExpr()))
7002 return false;
7003
7004 switch (E->getOpcode()) {
7005 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007006 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007007 case UO_Extension:
7008 return true;
7009 case UO_Plus:
7010 // The result is always just the subexpr.
7011 return true;
7012 case UO_Minus:
7013 if (Result.isComplexFloat()) {
7014 Result.getComplexFloatReal().changeSign();
7015 Result.getComplexFloatImag().changeSign();
7016 }
7017 else {
7018 Result.getComplexIntReal() = -Result.getComplexIntReal();
7019 Result.getComplexIntImag() = -Result.getComplexIntImag();
7020 }
7021 return true;
7022 case UO_Not:
7023 if (Result.isComplexFloat())
7024 Result.getComplexFloatImag().changeSign();
7025 else
7026 Result.getComplexIntImag() = -Result.getComplexIntImag();
7027 return true;
7028 }
7029}
7030
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007031bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7032 if (E->getNumInits() == 2) {
7033 if (E->getType()->isComplexType()) {
7034 Result.makeComplexFloat();
7035 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7036 return false;
7037 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7038 return false;
7039 } else {
7040 Result.makeComplexInt();
7041 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7042 return false;
7043 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7044 return false;
7045 }
7046 return true;
7047 }
7048 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7049}
7050
Anders Carlsson537969c2008-11-16 20:27:53 +00007051//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007052// Void expression evaluation, primarily for a cast to void on the LHS of a
7053// comma operator
7054//===----------------------------------------------------------------------===//
7055
7056namespace {
7057class VoidExprEvaluator
7058 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7059public:
7060 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7061
Richard Smith2e312c82012-03-03 22:46:17 +00007062 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007063
7064 bool VisitCastExpr(const CastExpr *E) {
7065 switch (E->getCastKind()) {
7066 default:
7067 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7068 case CK_ToVoid:
7069 VisitIgnoredValue(E->getSubExpr());
7070 return true;
7071 }
7072 }
7073};
7074} // end anonymous namespace
7075
7076static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7077 assert(E->isRValue() && E->getType()->isVoidType());
7078 return VoidExprEvaluator(Info).Visit(E);
7079}
7080
7081//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007082// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007083//===----------------------------------------------------------------------===//
7084
Richard Smith2e312c82012-03-03 22:46:17 +00007085static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007086 // In C, function designators are not lvalues, but we evaluate them as if they
7087 // are.
7088 if (E->isGLValue() || E->getType()->isFunctionType()) {
7089 LValue LV;
7090 if (!EvaluateLValue(E, LV, Info))
7091 return false;
7092 LV.moveInto(Result);
7093 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007094 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007095 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007096 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007097 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007098 return false;
John McCall45d55e42010-05-07 21:00:08 +00007099 } else if (E->getType()->hasPointerRepresentation()) {
7100 LValue LV;
7101 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007102 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007103 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00007104 } else if (E->getType()->isRealFloatingType()) {
7105 llvm::APFloat F(0.0);
7106 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007107 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007108 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00007109 } else if (E->getType()->isAnyComplexType()) {
7110 ComplexValue C;
7111 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007112 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007113 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00007114 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007115 MemberPtr P;
7116 if (!EvaluateMemberPointer(E, P, Info))
7117 return false;
7118 P.moveInto(Result);
7119 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00007120 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007121 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007122 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007123 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007124 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007125 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00007126 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007127 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007128 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007129 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
7130 return false;
7131 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00007132 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007133 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007134 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007135 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007136 if (!EvaluateVoid(E, Info))
7137 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007138 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007139 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007140 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007141 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007142 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007143 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007144 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007145
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007146 return true;
7147}
7148
Richard Smithb228a862012-02-15 02:18:13 +00007149/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7150/// cases, the in-place evaluation is essential, since later initializers for
7151/// an object can indirectly refer to subobjects which were initialized earlier.
7152static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
7153 const Expr *E, CheckConstantExpressionKind CCEK,
7154 bool AllowNonLiteralTypes) {
Richard Smith6331c402012-02-13 22:16:19 +00007155 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00007156 return false;
7157
7158 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007159 // Evaluate arrays and record types in-place, so that later initializers can
7160 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007161 if (E->getType()->isArrayType())
7162 return EvaluateArray(E, This, Result, Info);
7163 else if (E->getType()->isRecordType())
7164 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007165 }
7166
7167 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007168 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007169}
7170
Richard Smithf57d8cb2011-12-09 22:58:01 +00007171/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7172/// lvalue-to-rvalue cast if it is an lvalue.
7173static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007174 if (!CheckLiteralType(Info, E))
7175 return false;
7176
Richard Smith2e312c82012-03-03 22:46:17 +00007177 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007178 return false;
7179
7180 if (E->isGLValue()) {
7181 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007182 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007183 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007184 return false;
7185 }
7186
Richard Smith2e312c82012-03-03 22:46:17 +00007187 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007188 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007189}
Richard Smith11562c52011-10-28 17:51:58 +00007190
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007191static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7192 const ASTContext &Ctx, bool &IsConst) {
7193 // Fast-path evaluations of integer literals, since we sometimes see files
7194 // containing vast quantities of these.
7195 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7196 Result.Val = APValue(APSInt(L->getValue(),
7197 L->getType()->isUnsignedIntegerType()));
7198 IsConst = true;
7199 return true;
7200 }
7201
7202 // FIXME: Evaluating values of large array and record types can cause
7203 // performance problems. Only do so in C++11 for now.
7204 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7205 Exp->getType()->isRecordType()) &&
7206 !Ctx.getLangOpts().CPlusPlus11) {
7207 IsConst = false;
7208 return true;
7209 }
7210 return false;
7211}
7212
7213
Richard Smith7b553f12011-10-29 00:50:52 +00007214/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007215/// any crazy technique (that has nothing to do with language standards) that
7216/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007217/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7218/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007219bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007220 bool IsConst;
7221 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7222 return IsConst;
7223
Richard Smithf57d8cb2011-12-09 22:58:01 +00007224 EvalInfo Info(Ctx, Result);
7225 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007226}
7227
Jay Foad39c79802011-01-12 09:06:06 +00007228bool Expr::EvaluateAsBooleanCondition(bool &Result,
7229 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007230 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007231 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007232 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007233}
7234
Richard Smith5fab0c92011-12-28 19:48:30 +00007235bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7236 SideEffectsKind AllowSideEffects) const {
7237 if (!getType()->isIntegralOrEnumerationType())
7238 return false;
7239
Richard Smith11562c52011-10-28 17:51:58 +00007240 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007241 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7242 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007243 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007244
Richard Smith11562c52011-10-28 17:51:58 +00007245 Result = ExprResult.Val.getInt();
7246 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007247}
7248
Jay Foad39c79802011-01-12 09:06:06 +00007249bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007250 EvalInfo Info(Ctx, Result);
7251
John McCall45d55e42010-05-07 21:00:08 +00007252 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007253 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7254 !CheckLValueConstantExpression(Info, getExprLoc(),
7255 Ctx.getLValueReferenceType(getType()), LV))
7256 return false;
7257
Richard Smith2e312c82012-03-03 22:46:17 +00007258 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007259 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007260}
7261
Richard Smithd0b4dd62011-12-19 06:19:21 +00007262bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7263 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007264 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007265 // FIXME: Evaluating initializers for large array and record types can cause
7266 // performance problems. Only do so in C++11 for now.
7267 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007268 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007269 return false;
7270
Richard Smithd0b4dd62011-12-19 06:19:21 +00007271 Expr::EvalStatus EStatus;
7272 EStatus.Diag = &Notes;
7273
7274 EvalInfo InitInfo(Ctx, EStatus);
7275 InitInfo.setEvaluatingDecl(VD, Value);
7276
7277 LValue LVal;
7278 LVal.set(VD);
7279
Richard Smithfddd3842011-12-30 21:15:51 +00007280 // C++11 [basic.start.init]p2:
7281 // Variables with static storage duration or thread storage duration shall be
7282 // zero-initialized before any other initialization takes place.
7283 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007284 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007285 !VD->getType()->isReferenceType()) {
7286 ImplicitValueInitExpr VIE(VD->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007287 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
7288 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007289 return false;
7290 }
7291
Richard Smithb228a862012-02-15 02:18:13 +00007292 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
7293 /*AllowNonLiteralTypes=*/true) ||
7294 EStatus.HasSideEffects)
7295 return false;
7296
7297 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7298 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007299}
7300
Richard Smith7b553f12011-10-29 00:50:52 +00007301/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7302/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007303bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007304 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007305 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007306}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007307
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007308APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007309 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007310 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007311 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007312 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007313 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007314 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007315 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007316
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007317 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007318}
John McCall864e3962010-05-07 05:32:02 +00007319
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007320void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7321 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7322 bool IsConst;
7323 EvalResult EvalResult;
7324 EvalResult.Diag = Diags;
7325 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7326 EvalInfo Info(Ctx, EvalResult, true);
7327 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7328 }
7329}
7330
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007331 bool Expr::EvalResult::isGlobalLValue() const {
7332 assert(Val.isLValue());
7333 return IsGlobalLValue(Val.getLValueBase());
7334 }
7335
7336
John McCall864e3962010-05-07 05:32:02 +00007337/// isIntegerConstantExpr - this recursive routine will test if an expression is
7338/// an integer constant expression.
7339
7340/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7341/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007342
7343// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007344// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7345// and a (possibly null) SourceLocation indicating the location of the problem.
7346//
John McCall864e3962010-05-07 05:32:02 +00007347// Note that to reduce code duplication, this helper does no evaluation
7348// itself; the caller checks whether the expression is evaluatable, and
7349// in the rare cases where CheckICE actually cares about the evaluated
7350// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007351
Dan Gohman28ade552010-07-26 21:25:24 +00007352namespace {
7353
Richard Smith9e575da2012-12-28 13:25:52 +00007354enum ICEKind {
7355 /// This expression is an ICE.
7356 IK_ICE,
7357 /// This expression is not an ICE, but if it isn't evaluated, it's
7358 /// a legal subexpression for an ICE. This return value is used to handle
7359 /// the comma operator in C99 mode, and non-constant subexpressions.
7360 IK_ICEIfUnevaluated,
7361 /// This expression is not an ICE, and is not a legal subexpression for one.
7362 IK_NotICE
7363};
7364
John McCall864e3962010-05-07 05:32:02 +00007365struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007366 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007367 SourceLocation Loc;
7368
Richard Smith9e575da2012-12-28 13:25:52 +00007369 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007370};
7371
Dan Gohman28ade552010-07-26 21:25:24 +00007372}
7373
Richard Smith9e575da2012-12-28 13:25:52 +00007374static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7375
7376static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007377
7378static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7379 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007380 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007381 !EVResult.Val.isInt())
7382 return ICEDiag(IK_NotICE, E->getLocStart());
7383
John McCall864e3962010-05-07 05:32:02 +00007384 return NoDiag();
7385}
7386
7387static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7388 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007389 if (!E->getType()->isIntegralOrEnumerationType())
7390 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007391
7392 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007393#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007394#define STMT(Node, Base) case Expr::Node##Class:
7395#define EXPR(Node, Base)
7396#include "clang/AST/StmtNodes.inc"
7397 case Expr::PredefinedExprClass:
7398 case Expr::FloatingLiteralClass:
7399 case Expr::ImaginaryLiteralClass:
7400 case Expr::StringLiteralClass:
7401 case Expr::ArraySubscriptExprClass:
7402 case Expr::MemberExprClass:
7403 case Expr::CompoundAssignOperatorClass:
7404 case Expr::CompoundLiteralExprClass:
7405 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007406 case Expr::DesignatedInitExprClass:
7407 case Expr::ImplicitValueInitExprClass:
7408 case Expr::ParenListExprClass:
7409 case Expr::VAArgExprClass:
7410 case Expr::AddrLabelExprClass:
7411 case Expr::StmtExprClass:
7412 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007413 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007414 case Expr::CXXDynamicCastExprClass:
7415 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007416 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007417 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007418 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007419 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007420 case Expr::CXXThisExprClass:
7421 case Expr::CXXThrowExprClass:
7422 case Expr::CXXNewExprClass:
7423 case Expr::CXXDeleteExprClass:
7424 case Expr::CXXPseudoDestructorExprClass:
7425 case Expr::UnresolvedLookupExprClass:
7426 case Expr::DependentScopeDeclRefExprClass:
7427 case Expr::CXXConstructExprClass:
7428 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007429 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007430 case Expr::CXXTemporaryObjectExprClass:
7431 case Expr::CXXUnresolvedConstructExprClass:
7432 case Expr::CXXDependentScopeMemberExprClass:
7433 case Expr::UnresolvedMemberExprClass:
7434 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007435 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007436 case Expr::ObjCArrayLiteralClass:
7437 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007438 case Expr::ObjCEncodeExprClass:
7439 case Expr::ObjCMessageExprClass:
7440 case Expr::ObjCSelectorExprClass:
7441 case Expr::ObjCProtocolExprClass:
7442 case Expr::ObjCIvarRefExprClass:
7443 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007444 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007445 case Expr::ObjCIsaExprClass:
7446 case Expr::ShuffleVectorExprClass:
7447 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007448 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007449 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007450 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007451 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007452 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007453 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007454 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007455 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007456 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007457 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007458 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007459 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007460 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007461
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007462 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007463 case Expr::GNUNullExprClass:
7464 // GCC considers the GNU __null value to be an integral constant expression.
7465 return NoDiag();
7466
John McCall7c454bb2011-07-15 05:09:51 +00007467 case Expr::SubstNonTypeTemplateParmExprClass:
7468 return
7469 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7470
John McCall864e3962010-05-07 05:32:02 +00007471 case Expr::ParenExprClass:
7472 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00007473 case Expr::GenericSelectionExprClass:
7474 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007475 case Expr::IntegerLiteralClass:
7476 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007477 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00007478 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00007479 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00007480 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00007481 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00007482 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00007483 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00007484 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007485 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00007486 return NoDiag();
7487 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00007488 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00007489 // C99 6.6/3 allows function calls within unevaluated subexpressions of
7490 // constant expressions, but they can never be ICEs because an ICE cannot
7491 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00007492 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007493 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00007494 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007495 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007496 }
Richard Smith6365c912012-02-24 22:12:32 +00007497 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007498 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
7499 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00007500 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007501 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00007502 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00007503 // Parameter variables are never constants. Without this check,
7504 // getAnyInitializer() can find a default argument, which leads
7505 // to chaos.
7506 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007507 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007508
7509 // C++ 7.1.5.1p2
7510 // A variable of non-volatile const-qualified integral or enumeration
7511 // type initialized by an ICE can be used in ICEs.
7512 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007513 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007514 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007515
Richard Smithd0b4dd62011-12-19 06:19:21 +00007516 const VarDecl *VD;
7517 // Look for a declaration of this variable that has an initializer, and
7518 // check whether it is an ICE.
7519 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7520 return NoDiag();
7521 else
Richard Smith9e575da2012-12-28 13:25:52 +00007522 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007523 }
7524 }
Richard Smith9e575da2012-12-28 13:25:52 +00007525 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00007526 }
John McCall864e3962010-05-07 05:32:02 +00007527 case Expr::UnaryOperatorClass: {
7528 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7529 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007530 case UO_PostInc:
7531 case UO_PostDec:
7532 case UO_PreInc:
7533 case UO_PreDec:
7534 case UO_AddrOf:
7535 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00007536 // C99 6.6/3 allows increment and decrement within unevaluated
7537 // subexpressions of constant expressions, but they can never be ICEs
7538 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007539 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00007540 case UO_Extension:
7541 case UO_LNot:
7542 case UO_Plus:
7543 case UO_Minus:
7544 case UO_Not:
7545 case UO_Real:
7546 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00007547 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007548 }
Richard Smith9e575da2012-12-28 13:25:52 +00007549
John McCall864e3962010-05-07 05:32:02 +00007550 // OffsetOf falls through here.
7551 }
7552 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00007553 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7554 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7555 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7556 // compliance: we should warn earlier for offsetof expressions with
7557 // array subscripts that aren't ICEs, and if the array subscripts
7558 // are ICEs, the value of the offsetof must be an integer constant.
7559 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007560 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00007561 case Expr::UnaryExprOrTypeTraitExprClass: {
7562 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7563 if ((Exp->getKind() == UETT_SizeOf) &&
7564 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00007565 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007566 return NoDiag();
7567 }
7568 case Expr::BinaryOperatorClass: {
7569 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7570 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007571 case BO_PtrMemD:
7572 case BO_PtrMemI:
7573 case BO_Assign:
7574 case BO_MulAssign:
7575 case BO_DivAssign:
7576 case BO_RemAssign:
7577 case BO_AddAssign:
7578 case BO_SubAssign:
7579 case BO_ShlAssign:
7580 case BO_ShrAssign:
7581 case BO_AndAssign:
7582 case BO_XorAssign:
7583 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00007584 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7585 // constant expressions, but they can never be ICEs because an ICE cannot
7586 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007587 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007588
John McCalle3027922010-08-25 11:45:40 +00007589 case BO_Mul:
7590 case BO_Div:
7591 case BO_Rem:
7592 case BO_Add:
7593 case BO_Sub:
7594 case BO_Shl:
7595 case BO_Shr:
7596 case BO_LT:
7597 case BO_GT:
7598 case BO_LE:
7599 case BO_GE:
7600 case BO_EQ:
7601 case BO_NE:
7602 case BO_And:
7603 case BO_Xor:
7604 case BO_Or:
7605 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00007606 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7607 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00007608 if (Exp->getOpcode() == BO_Div ||
7609 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00007610 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00007611 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00007612 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00007613 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007614 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00007615 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007616 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00007617 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007618 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00007619 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007620 }
7621 }
7622 }
John McCalle3027922010-08-25 11:45:40 +00007623 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007624 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00007625 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7626 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00007627 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7628 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007629 } else {
7630 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00007631 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007632 }
7633 }
Richard Smith9e575da2012-12-28 13:25:52 +00007634 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007635 }
John McCalle3027922010-08-25 11:45:40 +00007636 case BO_LAnd:
7637 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00007638 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7639 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007640 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00007641 // Rare case where the RHS has a comma "side-effect"; we need
7642 // to actually check the condition to see whether the side
7643 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00007644 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00007645 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00007646 return RHSResult;
7647 return NoDiag();
7648 }
7649
Richard Smith9e575da2012-12-28 13:25:52 +00007650 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007651 }
7652 }
7653 }
7654 case Expr::ImplicitCastExprClass:
7655 case Expr::CStyleCastExprClass:
7656 case Expr::CXXFunctionalCastExprClass:
7657 case Expr::CXXStaticCastExprClass:
7658 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00007659 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007660 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007661 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00007662 if (isa<ExplicitCastExpr>(E)) {
7663 if (const FloatingLiteral *FL
7664 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7665 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7666 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7667 APSInt IgnoredVal(DestWidth, !DestSigned);
7668 bool Ignored;
7669 // If the value does not fit in the destination type, the behavior is
7670 // undefined, so we are not required to treat it as a constant
7671 // expression.
7672 if (FL->getValue().convertToInteger(IgnoredVal,
7673 llvm::APFloat::rmTowardZero,
7674 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00007675 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00007676 return NoDiag();
7677 }
7678 }
Eli Friedman76d4e432011-09-29 21:49:34 +00007679 switch (cast<CastExpr>(E)->getCastKind()) {
7680 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007681 case CK_AtomicToNonAtomic:
7682 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00007683 case CK_NoOp:
7684 case CK_IntegralToBoolean:
7685 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00007686 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00007687 default:
Richard Smith9e575da2012-12-28 13:25:52 +00007688 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00007689 }
John McCall864e3962010-05-07 05:32:02 +00007690 }
John McCallc07a0c72011-02-17 10:25:35 +00007691 case Expr::BinaryConditionalOperatorClass: {
7692 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7693 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007694 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00007695 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007696 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7697 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7698 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00007699 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00007700 return FalseResult;
7701 }
John McCall864e3962010-05-07 05:32:02 +00007702 case Expr::ConditionalOperatorClass: {
7703 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7704 // If the condition (ignoring parens) is a __builtin_constant_p call,
7705 // then only the true side is actually considered in an integer constant
7706 // expression, and it is fully evaluated. This is an important GNU
7707 // extension. See GCC PR38377 for discussion.
7708 if (const CallExpr *CallCE
7709 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00007710 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7711 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007712 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007713 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007714 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007715
Richard Smithf57d8cb2011-12-09 22:58:01 +00007716 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7717 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007718
Richard Smith9e575da2012-12-28 13:25:52 +00007719 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007720 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007721 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007722 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007723 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00007724 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007725 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00007726 return NoDiag();
7727 // Rare case where the diagnostics depend on which side is evaluated
7728 // Note that if we get here, CondResult is 0, and at least one of
7729 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00007730 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00007731 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00007732 return TrueResult;
7733 }
7734 case Expr::CXXDefaultArgExprClass:
7735 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00007736 case Expr::CXXDefaultInitExprClass:
7737 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007738 case Expr::ChooseExprClass: {
7739 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
7740 }
7741 }
7742
David Blaikiee4d798f2012-01-20 21:50:17 +00007743 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00007744}
7745
Richard Smithf57d8cb2011-12-09 22:58:01 +00007746/// Evaluate an expression as a C++11 integral constant expression.
7747static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
7748 const Expr *E,
7749 llvm::APSInt *Value,
7750 SourceLocation *Loc) {
7751 if (!E->getType()->isIntegralOrEnumerationType()) {
7752 if (Loc) *Loc = E->getExprLoc();
7753 return false;
7754 }
7755
Richard Smith66e05fe2012-01-18 05:21:49 +00007756 APValue Result;
7757 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00007758 return false;
7759
Richard Smith66e05fe2012-01-18 05:21:49 +00007760 assert(Result.isInt() && "pointer cast to int is not an ICE");
7761 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00007762 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007763}
7764
Richard Smith92b1ce02011-12-12 09:28:41 +00007765bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007766 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007767 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
7768
Richard Smith9e575da2012-12-28 13:25:52 +00007769 ICEDiag D = CheckICE(this, Ctx);
7770 if (D.Kind != IK_ICE) {
7771 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00007772 return false;
7773 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007774 return true;
7775}
7776
7777bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
7778 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007779 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007780 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
7781
7782 if (!isIntegerConstantExpr(Ctx, Loc))
7783 return false;
7784 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00007785 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00007786 return true;
7787}
Richard Smith66e05fe2012-01-18 05:21:49 +00007788
Richard Smith98a0a492012-02-14 21:38:30 +00007789bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00007790 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00007791}
7792
Richard Smith66e05fe2012-01-18 05:21:49 +00007793bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7794 SourceLocation *Loc) const {
7795 // We support this checking in C++98 mode in order to diagnose compatibility
7796 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007797 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00007798
Richard Smith98a0a492012-02-14 21:38:30 +00007799 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00007800 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007801 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00007802 Status.Diag = &Diags;
7803 EvalInfo Info(Ctx, Status);
7804
7805 APValue Scratch;
7806 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
7807
7808 if (!Diags.empty()) {
7809 IsConstExpr = false;
7810 if (Loc) *Loc = Diags[0].first;
7811 } else if (!IsConstExpr) {
7812 // FIXME: This shouldn't happen.
7813 if (Loc) *Loc = getExprLoc();
7814 }
7815
7816 return IsConstExpr;
7817}
Richard Smith253c2a32012-01-27 01:14:48 +00007818
7819bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007820 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00007821 PartialDiagnosticAt> &Diags) {
7822 // FIXME: It would be useful to check constexpr function templates, but at the
7823 // moment the constant expression evaluator cannot cope with the non-rigorous
7824 // ASTs which we build for dependent expressions.
7825 if (FD->isDependentContext())
7826 return true;
7827
7828 Expr::EvalStatus Status;
7829 Status.Diag = &Diags;
7830
7831 EvalInfo Info(FD->getASTContext(), Status);
7832 Info.CheckingPotentialConstantExpression = true;
7833
7834 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7835 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
7836
7837 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
7838 // is a temporary being used as the 'this' pointer.
7839 LValue This;
7840 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00007841 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00007842
Richard Smith253c2a32012-01-27 01:14:48 +00007843 ArrayRef<const Expr*> Args;
7844
7845 SourceLocation Loc = FD->getLocation();
7846
Richard Smith2e312c82012-03-03 22:46:17 +00007847 APValue Scratch;
7848 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith253c2a32012-01-27 01:14:48 +00007849 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith2e312c82012-03-03 22:46:17 +00007850 else
Richard Smith253c2a32012-01-27 01:14:48 +00007851 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
7852 Args, FD->getBody(), Info, Scratch);
7853
7854 return Diags.empty();
7855}