blob: bf967961aa06e671f282c9b576a279ee36f1d67f [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.
Richard Smith7525ff62013-05-09 07:14:00 +0000394 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000395
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 Smith7525ff62013-05-09 07:14:00 +0000417 EvaluatingDecl((const ValueDecl*)0), EvaluatingDeclValue(0),
418 HasActiveDiagnostic(false), CheckingPotentialConstantExpression(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000419 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000420
Richard Smith7525ff62013-05-09 07:14:00 +0000421 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
422 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000423 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 }
John McCall93d91dc2010-05-07 17:22:02 +0000902}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000903
Richard Smith2e312c82012-03-03 22:46:17 +0000904static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000905static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
906 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +0000907 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000908static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
909static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000910static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
911 EvalInfo &Info);
912static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000913static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000914static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000915 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000916static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000917static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000918
919//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000920// Misc utilities
921//===----------------------------------------------------------------------===//
922
Richard Smithd9f663b2013-04-22 15:31:51 +0000923/// Evaluate an expression to see if it had side-effects, and discard its
924/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +0000925/// \return \c true if the caller should keep evaluating.
926static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000927 APValue Scratch;
Richard Smith4e18ca52013-05-06 05:56:11 +0000928 if (!Evaluate(Scratch, Info, E)) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000929 Info.EvalStatus.HasSideEffects = true;
Richard Smith4e18ca52013-05-06 05:56:11 +0000930 return Info.keepEvaluatingAfterFailure();
931 }
932 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +0000933}
934
Richard Smith861b5b52013-05-07 23:34:45 +0000935/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
936/// return its existing value.
937static int64_t getExtValue(const APSInt &Value) {
938 return Value.isSigned() ? Value.getSExtValue()
939 : static_cast<int64_t>(Value.getZExtValue());
940}
941
Richard Smithd62306a2011-11-10 06:34:14 +0000942/// Should this call expression be treated as a string literal?
943static bool IsStringLiteralCall(const CallExpr *E) {
944 unsigned Builtin = E->isBuiltinCall();
945 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
946 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
947}
948
Richard Smithce40ad62011-11-12 22:28:03 +0000949static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000950 // C++11 [expr.const]p3 An address constant expression is a prvalue core
951 // constant expression of pointer type that evaluates to...
952
953 // ... a null pointer value, or a prvalue core constant expression of type
954 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000955 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000956
Richard Smithce40ad62011-11-12 22:28:03 +0000957 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
958 // ... the address of an object with static storage duration,
959 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
960 return VD->hasGlobalStorage();
961 // ... the address of a function,
962 return isa<FunctionDecl>(D);
963 }
964
965 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000966 switch (E->getStmtClass()) {
967 default:
968 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000969 case Expr::CompoundLiteralExprClass: {
970 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
971 return CLE->isFileScope() && CLE->isLValue();
972 }
Richard Smithd62306a2011-11-10 06:34:14 +0000973 // A string literal has static storage duration.
974 case Expr::StringLiteralClass:
975 case Expr::PredefinedExprClass:
976 case Expr::ObjCStringLiteralClass:
977 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000978 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000979 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000980 return true;
981 case Expr::CallExprClass:
982 return IsStringLiteralCall(cast<CallExpr>(E));
983 // For GCC compatibility, &&label has static storage duration.
984 case Expr::AddrLabelExprClass:
985 return true;
986 // A Block literal expression may be used as the initialization value for
987 // Block variables at global or local static scope.
988 case Expr::BlockExprClass:
989 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000990 case Expr::ImplicitValueInitExprClass:
991 // FIXME:
992 // We can never form an lvalue with an implicit value initialization as its
993 // base through expression evaluation, so these only appear in one case: the
994 // implicit variable declaration we invent when checking whether a constexpr
995 // constructor can produce a constant expression. We must assume that such
996 // an expression might be a global lvalue.
997 return true;
Richard Smithd62306a2011-11-10 06:34:14 +0000998 }
John McCall95007602010-05-10 23:27:23 +0000999}
1000
Richard Smithb228a862012-02-15 02:18:13 +00001001static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1002 assert(Base && "no location for a null lvalue");
1003 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1004 if (VD)
1005 Info.Note(VD->getLocation(), diag::note_declared_at);
1006 else
Ted Kremenek28831752012-08-23 20:46:57 +00001007 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001008 diag::note_constexpr_temporary_here);
1009}
1010
Richard Smith80815602011-11-07 05:07:52 +00001011/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001012/// value for an address or reference constant expression. Return true if we
1013/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001014static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1015 QualType Type, const LValue &LVal) {
1016 bool IsReferenceType = Type->isReferenceType();
1017
Richard Smith357362d2011-12-13 06:39:58 +00001018 APValue::LValueBase Base = LVal.getLValueBase();
1019 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1020
Richard Smith0dea49e2012-02-18 04:58:18 +00001021 // Check that the object is a global. Note that the fake 'this' object we
1022 // manufacture when checking potential constant expressions is conservatively
1023 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001024 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001025 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001026 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001027 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1028 << IsReferenceType << !Designator.Entries.empty()
1029 << !!VD << VD;
1030 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001031 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001032 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001033 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001034 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001035 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001036 }
Richard Smithb228a862012-02-15 02:18:13 +00001037 assert((Info.CheckingPotentialConstantExpression ||
1038 LVal.getLValueCallIndex() == 0) &&
1039 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001040
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001041 // Check if this is a thread-local variable.
1042 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1043 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001044 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001045 return false;
1046 }
1047 }
1048
Richard Smitha8105bc2012-01-06 16:39:00 +00001049 // Allow address constant expressions to be past-the-end pointers. This is
1050 // an extension: the standard requires them to point to an object.
1051 if (!IsReferenceType)
1052 return true;
1053
1054 // A reference constant expression must refer to an object.
1055 if (!Base) {
1056 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001057 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001058 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001059 }
1060
Richard Smith357362d2011-12-13 06:39:58 +00001061 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001062 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001063 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001064 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001065 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001066 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001067 }
1068
Richard Smith80815602011-11-07 05:07:52 +00001069 return true;
1070}
1071
Richard Smithfddd3842011-12-30 21:15:51 +00001072/// Check that this core constant expression is of literal type, and if not,
1073/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001074static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1075 const LValue *This = 0) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001076 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001077 return true;
1078
Richard Smith7525ff62013-05-09 07:14:00 +00001079 // C++1y: A constant initializer for an object o [...] may also invoke
1080 // constexpr constructors for o and its subobjects even if those objects
1081 // are of non-literal class types.
1082 if (Info.getLangOpts().CPlusPlus1y && This &&
1083 Info.EvaluatingDecl.getOpaqueValue() ==
1084 This->getLValueBase().getOpaqueValue())
1085 return true;
1086
Richard Smithfddd3842011-12-30 21:15:51 +00001087 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001088 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001089 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001090 << E->getType();
1091 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001092 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001093 return false;
1094}
1095
Richard Smith0b0a0b62011-10-29 20:57:55 +00001096/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001097/// constant expression. If not, report an appropriate diagnostic. Does not
1098/// check that the expression is of literal type.
1099static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1100 QualType Type, const APValue &Value) {
1101 // Core issue 1454: For a literal constant expression of array or class type,
1102 // each subobject of its value shall have been initialized by a constant
1103 // expression.
1104 if (Value.isArray()) {
1105 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1106 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1107 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1108 Value.getArrayInitializedElt(I)))
1109 return false;
1110 }
1111 if (!Value.hasArrayFiller())
1112 return true;
1113 return CheckConstantExpression(Info, DiagLoc, EltTy,
1114 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001115 }
Richard Smithb228a862012-02-15 02:18:13 +00001116 if (Value.isUnion() && Value.getUnionField()) {
1117 return CheckConstantExpression(Info, DiagLoc,
1118 Value.getUnionField()->getType(),
1119 Value.getUnionValue());
1120 }
1121 if (Value.isStruct()) {
1122 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1123 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1124 unsigned BaseIndex = 0;
1125 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1126 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1127 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1128 Value.getStructBase(BaseIndex)))
1129 return false;
1130 }
1131 }
1132 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1133 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001134 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1135 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001136 return false;
1137 }
1138 }
1139
1140 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001141 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001142 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001143 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1144 }
1145
1146 // Everything else is fine.
1147 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001148}
1149
Richard Smith83c68212011-10-31 05:11:32 +00001150const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001151 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001152}
1153
1154static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001155 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001156}
1157
Richard Smithcecf1842011-11-01 21:06:14 +00001158static bool IsWeakLValue(const LValue &Value) {
1159 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001160 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001161}
1162
Richard Smith2e312c82012-03-03 22:46:17 +00001163static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001164 // A null base expression indicates a null pointer. These are always
1165 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001166 if (!Value.getLValueBase()) {
1167 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001168 return true;
1169 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001170
Richard Smith027bf112011-11-17 22:56:20 +00001171 // We have a non-null base. These are generally known to be true, but if it's
1172 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001173 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001174 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001175 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001176}
1177
Richard Smith2e312c82012-03-03 22:46:17 +00001178static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001179 switch (Val.getKind()) {
1180 case APValue::Uninitialized:
1181 return false;
1182 case APValue::Int:
1183 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001184 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001185 case APValue::Float:
1186 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001187 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001188 case APValue::ComplexInt:
1189 Result = Val.getComplexIntReal().getBoolValue() ||
1190 Val.getComplexIntImag().getBoolValue();
1191 return true;
1192 case APValue::ComplexFloat:
1193 Result = !Val.getComplexFloatReal().isZero() ||
1194 !Val.getComplexFloatImag().isZero();
1195 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001196 case APValue::LValue:
1197 return EvalPointerValueAsBool(Val, Result);
1198 case APValue::MemberPointer:
1199 Result = Val.getMemberPointerDecl();
1200 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001201 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001202 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001203 case APValue::Struct:
1204 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001205 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001206 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001207 }
1208
Richard Smith11562c52011-10-28 17:51:58 +00001209 llvm_unreachable("unknown APValue kind");
1210}
1211
1212static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1213 EvalInfo &Info) {
1214 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001215 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001216 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001217 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001218 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001219}
1220
Richard Smith357362d2011-12-13 06:39:58 +00001221template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001222static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001223 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001224 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001225 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001226}
1227
1228static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1229 QualType SrcType, const APFloat &Value,
1230 QualType DestType, APSInt &Result) {
1231 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001232 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001233 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001234
Richard Smith357362d2011-12-13 06:39:58 +00001235 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001236 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001237 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1238 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001239 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001240 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001241}
1242
Richard Smith357362d2011-12-13 06:39:58 +00001243static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1244 QualType SrcType, QualType DestType,
1245 APFloat &Result) {
1246 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001247 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001248 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1249 APFloat::rmNearestTiesToEven, &ignored)
1250 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001251 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001252 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001253}
1254
Richard Smith911e1422012-01-30 22:27:01 +00001255static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1256 QualType DestType, QualType SrcType,
1257 APSInt &Value) {
1258 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001259 APSInt Result = Value;
1260 // Figure out if this is a truncate, extend or noop cast.
1261 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001262 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001263 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001264 return Result;
1265}
1266
Richard Smith357362d2011-12-13 06:39:58 +00001267static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1268 QualType SrcType, const APSInt &Value,
1269 QualType DestType, APFloat &Result) {
1270 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1271 if (Result.convertFromAPInt(Value, Value.isSigned(),
1272 APFloat::rmNearestTiesToEven)
1273 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001274 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001275 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001276}
1277
Eli Friedman803acb32011-12-22 03:51:45 +00001278static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1279 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001280 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001281 if (!Evaluate(SVal, Info, E))
1282 return false;
1283 if (SVal.isInt()) {
1284 Res = SVal.getInt();
1285 return true;
1286 }
1287 if (SVal.isFloat()) {
1288 Res = SVal.getFloat().bitcastToAPInt();
1289 return true;
1290 }
1291 if (SVal.isVector()) {
1292 QualType VecTy = E->getType();
1293 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1294 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1295 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1296 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1297 Res = llvm::APInt::getNullValue(VecSize);
1298 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1299 APValue &Elt = SVal.getVectorElt(i);
1300 llvm::APInt EltAsInt;
1301 if (Elt.isInt()) {
1302 EltAsInt = Elt.getInt();
1303 } else if (Elt.isFloat()) {
1304 EltAsInt = Elt.getFloat().bitcastToAPInt();
1305 } else {
1306 // Don't try to handle vectors of anything other than int or float
1307 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001308 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001309 return false;
1310 }
1311 unsigned BaseEltSize = EltAsInt.getBitWidth();
1312 if (BigEndian)
1313 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1314 else
1315 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1316 }
1317 return true;
1318 }
1319 // Give up if the input isn't an int, float, or vector. For example, we
1320 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001321 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001322 return false;
1323}
1324
Richard Smith43e77732013-05-07 04:50:00 +00001325/// Perform the given integer operation, which is known to need at most BitWidth
1326/// bits, and check for overflow in the original type (if that type was not an
1327/// unsigned type).
1328template<typename Operation>
1329static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1330 const APSInt &LHS, const APSInt &RHS,
1331 unsigned BitWidth, Operation Op) {
1332 if (LHS.isUnsigned())
1333 return Op(LHS, RHS);
1334
1335 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1336 APSInt Result = Value.trunc(LHS.getBitWidth());
1337 if (Result.extend(BitWidth) != Value) {
1338 if (Info.getIntOverflowCheckMode())
1339 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1340 diag::warn_integer_constant_overflow)
1341 << Result.toString(10) << E->getType();
1342 else
1343 HandleOverflow(Info, E, Value, E->getType());
1344 }
1345 return Result;
1346}
1347
1348/// Perform the given binary integer operation.
1349static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1350 BinaryOperatorKind Opcode, APSInt RHS,
1351 APSInt &Result) {
1352 switch (Opcode) {
1353 default:
1354 Info.Diag(E);
1355 return false;
1356 case BO_Mul:
1357 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1358 std::multiplies<APSInt>());
1359 return true;
1360 case BO_Add:
1361 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1362 std::plus<APSInt>());
1363 return true;
1364 case BO_Sub:
1365 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1366 std::minus<APSInt>());
1367 return true;
1368 case BO_And: Result = LHS & RHS; return true;
1369 case BO_Xor: Result = LHS ^ RHS; return true;
1370 case BO_Or: Result = LHS | RHS; return true;
1371 case BO_Div:
1372 case BO_Rem:
1373 if (RHS == 0) {
1374 Info.Diag(E, diag::note_expr_divide_by_zero);
1375 return false;
1376 }
1377 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1378 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1379 LHS.isSigned() && LHS.isMinSignedValue())
1380 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1381 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1382 return true;
1383 case BO_Shl: {
1384 if (Info.getLangOpts().OpenCL)
1385 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1386 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1387 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1388 RHS.isUnsigned());
1389 else if (RHS.isSigned() && RHS.isNegative()) {
1390 // During constant-folding, a negative shift is an opposite shift. Such
1391 // a shift is not a constant expression.
1392 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1393 RHS = -RHS;
1394 goto shift_right;
1395 }
1396 shift_left:
1397 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1398 // the shifted type.
1399 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1400 if (SA != RHS) {
1401 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1402 << RHS << E->getType() << LHS.getBitWidth();
1403 } else if (LHS.isSigned()) {
1404 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1405 // operand, and must not overflow the corresponding unsigned type.
1406 if (LHS.isNegative())
1407 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1408 else if (LHS.countLeadingZeros() < SA)
1409 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1410 }
1411 Result = LHS << SA;
1412 return true;
1413 }
1414 case BO_Shr: {
1415 if (Info.getLangOpts().OpenCL)
1416 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1417 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1418 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1419 RHS.isUnsigned());
1420 else if (RHS.isSigned() && RHS.isNegative()) {
1421 // During constant-folding, a negative shift is an opposite shift. Such a
1422 // shift is not a constant expression.
1423 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1424 RHS = -RHS;
1425 goto shift_left;
1426 }
1427 shift_right:
1428 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1429 // shifted type.
1430 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1431 if (SA != RHS)
1432 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1433 << RHS << E->getType() << LHS.getBitWidth();
1434 Result = LHS >> SA;
1435 return true;
1436 }
1437
1438 case BO_LT: Result = LHS < RHS; return true;
1439 case BO_GT: Result = LHS > RHS; return true;
1440 case BO_LE: Result = LHS <= RHS; return true;
1441 case BO_GE: Result = LHS >= RHS; return true;
1442 case BO_EQ: Result = LHS == RHS; return true;
1443 case BO_NE: Result = LHS != RHS; return true;
1444 }
1445}
1446
Richard Smith861b5b52013-05-07 23:34:45 +00001447/// Perform the given binary floating-point operation, in-place, on LHS.
1448static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1449 APFloat &LHS, BinaryOperatorKind Opcode,
1450 const APFloat &RHS) {
1451 switch (Opcode) {
1452 default:
1453 Info.Diag(E);
1454 return false;
1455 case BO_Mul:
1456 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1457 break;
1458 case BO_Add:
1459 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1460 break;
1461 case BO_Sub:
1462 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1463 break;
1464 case BO_Div:
1465 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1466 break;
1467 }
1468
1469 if (LHS.isInfinity() || LHS.isNaN())
1470 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1471 return true;
1472}
1473
Richard Smitha8105bc2012-01-06 16:39:00 +00001474/// Cast an lvalue referring to a base subobject to a derived class, by
1475/// truncating the lvalue's path to the given length.
1476static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1477 const RecordDecl *TruncatedType,
1478 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001479 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001480
1481 // Check we actually point to a derived class object.
1482 if (TruncatedElements == D.Entries.size())
1483 return true;
1484 assert(TruncatedElements >= D.MostDerivedPathLength &&
1485 "not casting to a derived class");
1486 if (!Result.checkSubobject(Info, E, CSK_Derived))
1487 return false;
1488
1489 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001490 const RecordDecl *RD = TruncatedType;
1491 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001492 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001493 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1494 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001495 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001496 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001497 else
Richard Smithd62306a2011-11-10 06:34:14 +00001498 Result.Offset -= Layout.getBaseClassOffset(Base);
1499 RD = Base;
1500 }
Richard Smith027bf112011-11-17 22:56:20 +00001501 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001502 return true;
1503}
1504
John McCalld7bca762012-05-01 00:38:49 +00001505static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001506 const CXXRecordDecl *Derived,
1507 const CXXRecordDecl *Base,
1508 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001509 if (!RL) {
1510 if (Derived->isInvalidDecl()) return false;
1511 RL = &Info.Ctx.getASTRecordLayout(Derived);
1512 }
1513
Richard Smithd62306a2011-11-10 06:34:14 +00001514 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001515 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001516 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001517}
1518
Richard Smitha8105bc2012-01-06 16:39:00 +00001519static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001520 const CXXRecordDecl *DerivedDecl,
1521 const CXXBaseSpecifier *Base) {
1522 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1523
John McCalld7bca762012-05-01 00:38:49 +00001524 if (!Base->isVirtual())
1525 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001526
Richard Smitha8105bc2012-01-06 16:39:00 +00001527 SubobjectDesignator &D = Obj.Designator;
1528 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001529 return false;
1530
Richard Smitha8105bc2012-01-06 16:39:00 +00001531 // Extract most-derived object and corresponding type.
1532 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1533 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1534 return false;
1535
1536 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001537 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001538 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1539 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001540 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001541 return true;
1542}
1543
1544/// Update LVal to refer to the given field, which must be a member of the type
1545/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001546static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001547 const FieldDecl *FD,
1548 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001549 if (!RL) {
1550 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001551 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001552 }
Richard Smithd62306a2011-11-10 06:34:14 +00001553
1554 unsigned I = FD->getFieldIndex();
1555 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001556 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001557 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001558}
1559
Richard Smith1b78b3d2012-01-25 22:15:11 +00001560/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001561static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001562 LValue &LVal,
1563 const IndirectFieldDecl *IFD) {
1564 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1565 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001566 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1567 return false;
1568 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001569}
1570
Richard Smithd62306a2011-11-10 06:34:14 +00001571/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001572static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1573 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001574 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1575 // extension.
1576 if (Type->isVoidType() || Type->isFunctionType()) {
1577 Size = CharUnits::One();
1578 return true;
1579 }
1580
1581 if (!Type->isConstantSizeType()) {
1582 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001583 // FIXME: Better diagnostic.
1584 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001585 return false;
1586 }
1587
1588 Size = Info.Ctx.getTypeSizeInChars(Type);
1589 return true;
1590}
1591
1592/// Update a pointer value to model pointer arithmetic.
1593/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001594/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001595/// \param LVal - The pointer value to be updated.
1596/// \param EltTy - The pointee type represented by LVal.
1597/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001598static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1599 LValue &LVal, QualType EltTy,
1600 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001601 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001602 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001603 return false;
1604
1605 // Compute the new offset in the appropriate width.
1606 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001607 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001608 return true;
1609}
1610
Richard Smith66c96992012-02-18 22:04:06 +00001611/// Update an lvalue to refer to a component of a complex number.
1612/// \param Info - Information about the ongoing evaluation.
1613/// \param LVal - The lvalue to be updated.
1614/// \param EltTy - The complex number's component type.
1615/// \param Imag - False for the real component, true for the imaginary.
1616static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1617 LValue &LVal, QualType EltTy,
1618 bool Imag) {
1619 if (Imag) {
1620 CharUnits SizeOfComponent;
1621 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1622 return false;
1623 LVal.Offset += SizeOfComponent;
1624 }
1625 LVal.addComplex(Info, E, EltTy, Imag);
1626 return true;
1627}
1628
Richard Smith27908702011-10-24 17:54:18 +00001629/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001630///
1631/// \param Info Information about the ongoing evaluation.
1632/// \param E An expression to be used when printing diagnostics.
1633/// \param VD The variable whose initializer should be obtained.
1634/// \param Frame The frame in which the variable was created. Must be null
1635/// if this variable is not local to the evaluation.
1636/// \param Result Filled in with a pointer to the value of the variable.
1637static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1638 const VarDecl *VD, CallStackFrame *Frame,
1639 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001640 // If this is a parameter to an active constexpr function call, perform
1641 // argument substitution.
1642 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001643 // Assume arguments of a potential constant expression are unknown
1644 // constant expressions.
1645 if (Info.CheckingPotentialConstantExpression)
1646 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001647 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001648 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001649 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001650 }
Richard Smith3229b742013-05-05 21:17:10 +00001651 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001652 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001653 }
Richard Smith27908702011-10-24 17:54:18 +00001654
Richard Smithd9f663b2013-04-22 15:31:51 +00001655 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001656 if (Frame) {
1657 Result = &Frame->Temporaries[VD];
Richard Smithd9f663b2013-04-22 15:31:51 +00001658 // If we've carried on past an unevaluatable local variable initializer,
1659 // we can't go any further. This can happen during potential constant
1660 // expression checking.
Richard Smith3229b742013-05-05 21:17:10 +00001661 return !Result->isUninit();
Richard Smithd9f663b2013-04-22 15:31:51 +00001662 }
1663
Richard Smithd0b4dd62011-12-19 06:19:21 +00001664 // Dig out the initializer, and use the declaration which it's attached to.
1665 const Expr *Init = VD->getAnyInitializer(VD);
1666 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001667 // If we're checking a potential constant expression, the variable could be
1668 // initialized later.
1669 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001670 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001671 return false;
1672 }
1673
Richard Smithd62306a2011-11-10 06:34:14 +00001674 // If we're currently evaluating the initializer of this declaration, use that
1675 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001676 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001677 Result = Info.EvaluatingDeclValue;
1678 return !Result->isUninit();
Richard Smithd62306a2011-11-10 06:34:14 +00001679 }
1680
Richard Smithcecf1842011-11-01 21:06:14 +00001681 // Never evaluate the initializer of a weak variable. We can't be sure that
1682 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001683 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001684 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001685 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001686 }
Richard Smithcecf1842011-11-01 21:06:14 +00001687
Richard Smithd0b4dd62011-12-19 06:19:21 +00001688 // Check that we can fold the initializer. In C++, we will have already done
1689 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001690 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001691 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001692 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001693 Notes.size() + 1) << VD;
1694 Info.Note(VD->getLocation(), diag::note_declared_at);
1695 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001696 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001697 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001698 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001699 Notes.size() + 1) << VD;
1700 Info.Note(VD->getLocation(), diag::note_declared_at);
1701 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001702 }
Richard Smith27908702011-10-24 17:54:18 +00001703
Richard Smith3229b742013-05-05 21:17:10 +00001704 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001705 return true;
Richard Smith27908702011-10-24 17:54:18 +00001706}
1707
Richard Smith11562c52011-10-28 17:51:58 +00001708static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001709 Qualifiers Quals = T.getQualifiers();
1710 return Quals.hasConst() && !Quals.hasVolatile();
1711}
1712
Richard Smithe97cbd72011-11-11 04:05:33 +00001713/// Get the base index of the given base class within an APValue representing
1714/// the given derived class.
1715static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1716 const CXXRecordDecl *Base) {
1717 Base = Base->getCanonicalDecl();
1718 unsigned Index = 0;
1719 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1720 E = Derived->bases_end(); I != E; ++I, ++Index) {
1721 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1722 return Index;
1723 }
1724
1725 llvm_unreachable("base class missing from derived class's bases list");
1726}
1727
Richard Smith3da88fa2013-04-26 14:36:30 +00001728/// Extract the value of a character from a string literal.
1729static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1730 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00001731 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00001732 const StringLiteral *S = cast<StringLiteral>(Lit);
1733 const ConstantArrayType *CAT =
1734 Info.Ctx.getAsConstantArrayType(S->getType());
1735 assert(CAT && "string literal isn't an array");
1736 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00001737 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001738
1739 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001740 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001741 if (Index < S->getLength())
1742 Value = S->getCodeUnit(Index);
1743 return Value;
1744}
1745
Richard Smith3da88fa2013-04-26 14:36:30 +00001746// Expand a string literal into an array of characters.
1747static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1748 APValue &Result) {
1749 const StringLiteral *S = cast<StringLiteral>(Lit);
1750 const ConstantArrayType *CAT =
1751 Info.Ctx.getAsConstantArrayType(S->getType());
1752 assert(CAT && "string literal isn't an array");
1753 QualType CharType = CAT->getElementType();
1754 assert(CharType->isIntegerType() && "unexpected character type");
1755
1756 unsigned Elts = CAT->getSize().getZExtValue();
1757 Result = APValue(APValue::UninitArray(),
1758 std::min(S->getLength(), Elts), Elts);
1759 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1760 CharType->isUnsignedIntegerType());
1761 if (Result.hasArrayFiller())
1762 Result.getArrayFiller() = APValue(Value);
1763 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1764 Value = S->getCodeUnit(I);
1765 Result.getArrayInitializedElt(I) = APValue(Value);
1766 }
1767}
1768
1769// Expand an array so that it has more than Index filled elements.
1770static void expandArray(APValue &Array, unsigned Index) {
1771 unsigned Size = Array.getArraySize();
1772 assert(Index < Size);
1773
1774 // Always at least double the number of elements for which we store a value.
1775 unsigned OldElts = Array.getArrayInitializedElts();
1776 unsigned NewElts = std::max(Index+1, OldElts * 2);
1777 NewElts = std::min(Size, std::max(NewElts, 8u));
1778
1779 // Copy the data across.
1780 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1781 for (unsigned I = 0; I != OldElts; ++I)
1782 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1783 for (unsigned I = OldElts; I != NewElts; ++I)
1784 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1785 if (NewValue.hasArrayFiller())
1786 NewValue.getArrayFiller() = Array.getArrayFiller();
1787 Array.swap(NewValue);
1788}
1789
Richard Smith861b5b52013-05-07 23:34:45 +00001790/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00001791enum AccessKinds {
1792 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00001793 AK_Assign,
1794 AK_Increment,
1795 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00001796};
1797
Richard Smith3229b742013-05-05 21:17:10 +00001798/// A handle to a complete object (an object that is not a subobject of
1799/// another object).
1800struct CompleteObject {
1801 /// The value of the complete object.
1802 APValue *Value;
1803 /// The type of the complete object.
1804 QualType Type;
1805
1806 CompleteObject() : Value(0) {}
1807 CompleteObject(APValue *Value, QualType Type)
1808 : Value(Value), Type(Type) {
1809 assert(Value && "missing value for complete object");
1810 }
1811
1812 operator bool() const { return Value; }
1813};
1814
Richard Smith3da88fa2013-04-26 14:36:30 +00001815/// Find the designated sub-object of an rvalue.
1816template<typename SubobjectHandler>
1817typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00001818findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00001819 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001820 if (Sub.Invalid)
1821 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00001822 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00001823 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001824 if (Info.getLangOpts().CPlusPlus11)
1825 Info.Diag(E, diag::note_constexpr_access_past_end)
1826 << handler.AccessKind;
1827 else
1828 Info.Diag(E);
1829 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001830 }
Richard Smith6804be52011-11-11 08:28:03 +00001831 if (Sub.Entries.empty())
Richard Smith3229b742013-05-05 21:17:10 +00001832 return handler.found(*Obj.Value, Obj.Type);
1833 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
Richard Smith253c2a32012-01-27 01:14:48 +00001834 // This object might be initialized later.
Richard Smith3da88fa2013-04-26 14:36:30 +00001835 return handler.failed();
Richard Smithf3e9e432011-11-07 09:22:26 +00001836
Richard Smith3229b742013-05-05 21:17:10 +00001837 APValue *O = Obj.Value;
1838 QualType ObjType = Obj.Type;
Richard Smithd62306a2011-11-10 06:34:14 +00001839 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001840 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001841 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001842 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001843 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001844 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001845 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001846 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001847 // Note, it should not be possible to form a pointer with a valid
1848 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00001849 if (Info.getLangOpts().CPlusPlus11)
1850 Info.Diag(E, diag::note_constexpr_access_past_end)
1851 << handler.AccessKind;
1852 else
1853 Info.Diag(E);
1854 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001855 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001856
1857 ObjType = CAT->getElementType();
1858
Richard Smith14a94132012-02-17 03:35:37 +00001859 // An array object is represented as either an Array APValue or as an
1860 // LValue which refers to a string literal.
1861 if (O->isLValue()) {
1862 assert(I == N - 1 && "extracting subobject of character?");
1863 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00001864 if (handler.AccessKind != AK_Read)
1865 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1866 *O);
1867 else
1868 return handler.foundString(*O, ObjType, Index);
1869 }
1870
1871 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001872 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00001873 else if (handler.AccessKind != AK_Read) {
1874 expandArray(*O, Index);
1875 O = &O->getArrayInitializedElt(Index);
1876 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00001877 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00001878 } else if (ObjType->isAnyComplexType()) {
1879 // Next subobject is a complex number.
1880 uint64_t Index = Sub.Entries[I].ArrayIndex;
1881 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001882 if (Info.getLangOpts().CPlusPlus11)
1883 Info.Diag(E, diag::note_constexpr_access_past_end)
1884 << handler.AccessKind;
1885 else
1886 Info.Diag(E);
1887 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00001888 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001889
1890 bool WasConstQualified = ObjType.isConstQualified();
1891 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1892 if (WasConstQualified)
1893 ObjType.addConst();
1894
Richard Smith66c96992012-02-18 22:04:06 +00001895 assert(I == N - 1 && "extracting subobject of scalar?");
1896 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001897 return handler.found(Index ? O->getComplexIntImag()
1898 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001899 } else {
1900 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00001901 return handler.found(Index ? O->getComplexFloatImag()
1902 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00001903 }
Richard Smithd62306a2011-11-10 06:34:14 +00001904 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001905 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001906 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001907 << Field;
1908 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00001909 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00001910 }
1911
Richard Smithd62306a2011-11-10 06:34:14 +00001912 // Next subobject is a class, struct or union field.
1913 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1914 if (RD->isUnion()) {
1915 const FieldDecl *UnionField = O->getUnionField();
1916 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001917 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00001918 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1919 << handler.AccessKind << Field << !UnionField << UnionField;
1920 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001921 }
Richard Smithd62306a2011-11-10 06:34:14 +00001922 O = &O->getUnionValue();
1923 } else
1924 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00001925
1926 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00001927 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00001928 if (WasConstQualified && !Field->isMutable())
1929 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00001930
1931 if (ObjType.isVolatileQualified()) {
1932 if (Info.getLangOpts().CPlusPlus) {
1933 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00001934 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1935 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00001936 Info.Note(Field->getLocation(), diag::note_declared_at);
1937 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001938 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001939 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001940 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00001941 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001942 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001943 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001944 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1945 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1946 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00001947
1948 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00001949 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00001950 if (WasConstQualified)
1951 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00001952 }
Richard Smithd62306a2011-11-10 06:34:14 +00001953
Richard Smithf57d8cb2011-12-09 22:58:01 +00001954 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001955 if (!Info.CheckingPotentialConstantExpression)
Richard Smith3da88fa2013-04-26 14:36:30 +00001956 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1957 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00001958 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001959 }
1960
Richard Smith3da88fa2013-04-26 14:36:30 +00001961 return handler.found(*O, ObjType);
1962}
1963
Benjamin Kramer62498ab2013-04-26 22:01:47 +00001964namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00001965struct ExtractSubobjectHandler {
1966 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00001967 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00001968
1969 static const AccessKinds AccessKind = AK_Read;
1970
1971 typedef bool result_type;
1972 bool failed() { return false; }
1973 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001974 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00001975 return true;
1976 }
1977 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001978 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001979 return true;
1980 }
1981 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00001982 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00001983 return true;
1984 }
1985 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00001986 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00001987 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
1988 return true;
1989 }
1990};
Richard Smith3229b742013-05-05 21:17:10 +00001991} // end anonymous namespace
1992
Richard Smith3da88fa2013-04-26 14:36:30 +00001993const AccessKinds ExtractSubobjectHandler::AccessKind;
1994
1995/// Extract the designated sub-object of an rvalue.
1996static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00001997 const CompleteObject &Obj,
1998 const SubobjectDesignator &Sub,
1999 APValue &Result) {
2000 ExtractSubobjectHandler Handler = { Info, Result };
2001 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002002}
2003
Richard Smith3229b742013-05-05 21:17:10 +00002004namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002005struct ModifySubobjectHandler {
2006 EvalInfo &Info;
2007 APValue &NewVal;
2008 const Expr *E;
2009
2010 typedef bool result_type;
2011 static const AccessKinds AccessKind = AK_Assign;
2012
2013 bool checkConst(QualType QT) {
2014 // Assigning to a const object has undefined behavior.
2015 if (QT.isConstQualified()) {
2016 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2017 return false;
2018 }
2019 return true;
2020 }
2021
2022 bool failed() { return false; }
2023 bool found(APValue &Subobj, QualType SubobjType) {
2024 if (!checkConst(SubobjType))
2025 return false;
2026 // We've been given ownership of NewVal, so just swap it in.
2027 Subobj.swap(NewVal);
2028 return true;
2029 }
2030 bool found(APSInt &Value, QualType SubobjType) {
2031 if (!checkConst(SubobjType))
2032 return false;
2033 if (!NewVal.isInt()) {
2034 // Maybe trying to write a cast pointer value into a complex?
2035 Info.Diag(E);
2036 return false;
2037 }
2038 Value = NewVal.getInt();
2039 return true;
2040 }
2041 bool found(APFloat &Value, QualType SubobjType) {
2042 if (!checkConst(SubobjType))
2043 return false;
2044 Value = NewVal.getFloat();
2045 return true;
2046 }
2047 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2048 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2049 }
2050};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002051} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002052
Richard Smith3229b742013-05-05 21:17:10 +00002053const AccessKinds ModifySubobjectHandler::AccessKind;
2054
Richard Smith3da88fa2013-04-26 14:36:30 +00002055/// Update the designated sub-object of an rvalue to the given value.
2056static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002057 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002058 const SubobjectDesignator &Sub,
2059 APValue &NewVal) {
2060 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002061 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002062}
2063
Richard Smith84f6dcf2012-02-02 01:16:57 +00002064/// Find the position where two subobject designators diverge, or equivalently
2065/// the length of the common initial subsequence.
2066static unsigned FindDesignatorMismatch(QualType ObjType,
2067 const SubobjectDesignator &A,
2068 const SubobjectDesignator &B,
2069 bool &WasArrayIndex) {
2070 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2071 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002072 if (!ObjType.isNull() &&
2073 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002074 // Next subobject is an array element.
2075 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2076 WasArrayIndex = true;
2077 return I;
2078 }
Richard Smith66c96992012-02-18 22:04:06 +00002079 if (ObjType->isAnyComplexType())
2080 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2081 else
2082 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002083 } else {
2084 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2085 WasArrayIndex = false;
2086 return I;
2087 }
2088 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2089 // Next subobject is a field.
2090 ObjType = FD->getType();
2091 else
2092 // Next subobject is a base class.
2093 ObjType = QualType();
2094 }
2095 }
2096 WasArrayIndex = false;
2097 return I;
2098}
2099
2100/// Determine whether the given subobject designators refer to elements of the
2101/// same array object.
2102static bool AreElementsOfSameArray(QualType ObjType,
2103 const SubobjectDesignator &A,
2104 const SubobjectDesignator &B) {
2105 if (A.Entries.size() != B.Entries.size())
2106 return false;
2107
2108 bool IsArray = A.MostDerivedArraySize != 0;
2109 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2110 // A is a subobject of the array element.
2111 return false;
2112
2113 // If A (and B) designates an array element, the last entry will be the array
2114 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2115 // of length 1' case, and the entire path must match.
2116 bool WasArrayIndex;
2117 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2118 return CommonLength >= A.Entries.size() - IsArray;
2119}
2120
Richard Smith3229b742013-05-05 21:17:10 +00002121/// Find the complete object to which an LValue refers.
2122CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2123 const LValue &LVal, QualType LValType) {
2124 if (!LVal.Base) {
2125 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2126 return CompleteObject();
2127 }
2128
2129 CallStackFrame *Frame = 0;
2130 if (LVal.CallIndex) {
2131 Frame = Info.getCallFrame(LVal.CallIndex);
2132 if (!Frame) {
2133 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2134 << AK << LVal.Base.is<const ValueDecl*>();
2135 NoteLValueLocation(Info, LVal.Base);
2136 return CompleteObject();
2137 }
Richard Smith3229b742013-05-05 21:17:10 +00002138 }
2139
2140 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2141 // is not a constant expression (even if the object is non-volatile). We also
2142 // apply this rule to C++98, in order to conform to the expected 'volatile'
2143 // semantics.
2144 if (LValType.isVolatileQualified()) {
2145 if (Info.getLangOpts().CPlusPlus)
2146 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2147 << AK << LValType;
2148 else
2149 Info.Diag(E);
2150 return CompleteObject();
2151 }
2152
2153 // Compute value storage location and type of base object.
2154 APValue *BaseVal = 0;
2155 QualType BaseType;
2156
2157 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2158 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2159 // In C++11, constexpr, non-volatile variables initialized with constant
2160 // expressions are constant expressions too. Inside constexpr functions,
2161 // parameters are constant expressions even if they're non-const.
2162 // In C++1y, objects local to a constant expression (those with a Frame) are
2163 // both readable and writable inside constant expressions.
2164 // In C, such things can also be folded, although they are not ICEs.
2165 const VarDecl *VD = dyn_cast<VarDecl>(D);
2166 if (VD) {
2167 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2168 VD = VDef;
2169 }
2170 if (!VD || VD->isInvalidDecl()) {
2171 Info.Diag(E);
2172 return CompleteObject();
2173 }
2174
2175 // Accesses of volatile-qualified objects are not allowed.
2176 BaseType = VD->getType();
2177 if (BaseType.isVolatileQualified()) {
2178 if (Info.getLangOpts().CPlusPlus) {
2179 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2180 << AK << 1 << VD;
2181 Info.Note(VD->getLocation(), diag::note_declared_at);
2182 } else {
2183 Info.Diag(E);
2184 }
2185 return CompleteObject();
2186 }
2187
2188 // Unless we're looking at a local variable or argument in a constexpr call,
2189 // the variable we're reading must be const.
2190 if (!Frame) {
Richard Smith7525ff62013-05-09 07:14:00 +00002191 if (Info.getLangOpts().CPlusPlus1y &&
2192 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2193 // OK, we can read and modify an object if we're in the process of
2194 // evaluating its initializer, because its lifetime began in this
2195 // evaluation.
2196 } else if (AK != AK_Read) {
2197 // All the remaining cases only permit reading.
2198 Info.Diag(E, diag::note_constexpr_modify_global);
2199 return CompleteObject();
2200 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002201 // OK, we can read this variable.
2202 } else if (BaseType->isIntegralOrEnumerationType()) {
2203 if (!BaseType.isConstQualified()) {
2204 if (Info.getLangOpts().CPlusPlus) {
2205 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2206 Info.Note(VD->getLocation(), diag::note_declared_at);
2207 } else {
2208 Info.Diag(E);
2209 }
2210 return CompleteObject();
2211 }
2212 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2213 // We support folding of const floating-point types, in order to make
2214 // static const data members of such types (supported as an extension)
2215 // more useful.
2216 if (Info.getLangOpts().CPlusPlus11) {
2217 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2218 Info.Note(VD->getLocation(), diag::note_declared_at);
2219 } else {
2220 Info.CCEDiag(E);
2221 }
2222 } else {
2223 // FIXME: Allow folding of values of any literal type in all languages.
2224 if (Info.getLangOpts().CPlusPlus11) {
2225 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2226 Info.Note(VD->getLocation(), diag::note_declared_at);
2227 } else {
2228 Info.Diag(E);
2229 }
2230 return CompleteObject();
2231 }
2232 }
2233
2234 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2235 return CompleteObject();
2236 } else {
2237 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2238
2239 if (!Frame) {
2240 Info.Diag(E);
2241 return CompleteObject();
2242 }
2243
2244 BaseType = Base->getType();
2245 BaseVal = &Frame->Temporaries[Base];
2246
2247 // Volatile temporary objects cannot be accessed in constant expressions.
2248 if (BaseType.isVolatileQualified()) {
2249 if (Info.getLangOpts().CPlusPlus) {
2250 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2251 << AK << 0;
2252 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2253 } else {
2254 Info.Diag(E);
2255 }
2256 return CompleteObject();
2257 }
2258 }
2259
Richard Smith7525ff62013-05-09 07:14:00 +00002260 // During the construction of an object, it is not yet 'const'.
2261 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2262 // and this doesn't do quite the right thing for const subobjects of the
2263 // object under construction.
2264 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2265 BaseType = Info.Ctx.getCanonicalType(BaseType);
2266 BaseType.removeLocalConst();
2267 }
2268
Richard Smith3229b742013-05-05 21:17:10 +00002269 // In C++1y, we can't safely access any mutable state when checking a
2270 // potential constant expression.
2271 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2272 Info.CheckingPotentialConstantExpression)
2273 return CompleteObject();
2274
2275 return CompleteObject(BaseVal, BaseType);
2276}
2277
Richard Smith243ef902013-05-05 23:31:59 +00002278/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2279/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2280/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002281///
2282/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002283/// \param Conv - The expression for which we are performing the conversion.
2284/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002285/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2286/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002287/// \param LVal - The glvalue on which we are attempting to perform this action.
2288/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002289static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002290 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002291 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002292 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002293 return false;
2294
Richard Smith3229b742013-05-05 21:17:10 +00002295 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002296 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002297 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2298 !Type.isVolatileQualified()) {
2299 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2300 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2301 // initializer until now for such expressions. Such an expression can't be
2302 // an ICE in C, so this only matters for fold.
2303 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2304 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002305 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002306 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002307 }
Richard Smith3229b742013-05-05 21:17:10 +00002308 APValue Lit;
2309 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2310 return false;
2311 CompleteObject LitObj(&Lit, Base->getType());
2312 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2313 } else if (isa<StringLiteral>(Base)) {
2314 // We represent a string literal array as an lvalue pointing at the
2315 // corresponding expression, rather than building an array of chars.
2316 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2317 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2318 CompleteObject StrObj(&Str, Base->getType());
2319 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002320 }
Richard Smith11562c52011-10-28 17:51:58 +00002321 }
2322
Richard Smith3229b742013-05-05 21:17:10 +00002323 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2324 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002325}
2326
2327/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002328static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002329 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002330 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002331 return false;
2332
Richard Smith3229b742013-05-05 21:17:10 +00002333 if (!Info.getLangOpts().CPlusPlus1y) {
2334 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002335 return false;
2336 }
2337
Richard Smith3229b742013-05-05 21:17:10 +00002338 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2339 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002340}
2341
Richard Smith243ef902013-05-05 23:31:59 +00002342static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2343 return T->isSignedIntegerType() &&
2344 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2345}
2346
2347namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002348struct CompoundAssignSubobjectHandler {
2349 EvalInfo &Info;
2350 const Expr *E;
2351 QualType PromotedLHSType;
2352 BinaryOperatorKind Opcode;
2353 const APValue &RHS;
2354
2355 static const AccessKinds AccessKind = AK_Assign;
2356
2357 typedef bool result_type;
2358
2359 bool checkConst(QualType QT) {
2360 // Assigning to a const object has undefined behavior.
2361 if (QT.isConstQualified()) {
2362 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2363 return false;
2364 }
2365 return true;
2366 }
2367
2368 bool failed() { return false; }
2369 bool found(APValue &Subobj, QualType SubobjType) {
2370 switch (Subobj.getKind()) {
2371 case APValue::Int:
2372 return found(Subobj.getInt(), SubobjType);
2373 case APValue::Float:
2374 return found(Subobj.getFloat(), SubobjType);
2375 case APValue::ComplexInt:
2376 case APValue::ComplexFloat:
2377 // FIXME: Implement complex compound assignment.
2378 Info.Diag(E);
2379 return false;
2380 case APValue::LValue:
2381 return foundPointer(Subobj, SubobjType);
2382 default:
2383 // FIXME: can this happen?
2384 Info.Diag(E);
2385 return false;
2386 }
2387 }
2388 bool found(APSInt &Value, QualType SubobjType) {
2389 if (!checkConst(SubobjType))
2390 return false;
2391
2392 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2393 // We don't support compound assignment on integer-cast-to-pointer
2394 // values.
2395 Info.Diag(E);
2396 return false;
2397 }
2398
2399 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2400 SubobjType, Value);
2401 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2402 return false;
2403 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2404 return true;
2405 }
2406 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002407 return checkConst(SubobjType) &&
2408 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2409 Value) &&
2410 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2411 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002412 }
2413 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2414 if (!checkConst(SubobjType))
2415 return false;
2416
2417 QualType PointeeType;
2418 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2419 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002420
2421 if (PointeeType.isNull() || !RHS.isInt() ||
2422 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002423 Info.Diag(E);
2424 return false;
2425 }
2426
Richard Smith861b5b52013-05-07 23:34:45 +00002427 int64_t Offset = getExtValue(RHS.getInt());
2428 if (Opcode == BO_Sub)
2429 Offset = -Offset;
2430
2431 LValue LVal;
2432 LVal.setFrom(Info.Ctx, Subobj);
2433 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2434 return false;
2435 LVal.moveInto(Subobj);
2436 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002437 }
2438 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2439 llvm_unreachable("shouldn't encounter string elements here");
2440 }
2441};
2442} // end anonymous namespace
2443
2444const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2445
2446/// Perform a compound assignment of LVal <op>= RVal.
2447static bool handleCompoundAssignment(
2448 EvalInfo &Info, const Expr *E,
2449 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2450 BinaryOperatorKind Opcode, const APValue &RVal) {
2451 if (LVal.Designator.Invalid)
2452 return false;
2453
2454 if (!Info.getLangOpts().CPlusPlus1y) {
2455 Info.Diag(E);
2456 return false;
2457 }
2458
2459 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2460 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2461 RVal };
2462 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2463}
2464
2465namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002466struct IncDecSubobjectHandler {
2467 EvalInfo &Info;
2468 const Expr *E;
2469 AccessKinds AccessKind;
2470 APValue *Old;
2471
2472 typedef bool result_type;
2473
2474 bool checkConst(QualType QT) {
2475 // Assigning to a const object has undefined behavior.
2476 if (QT.isConstQualified()) {
2477 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2478 return false;
2479 }
2480 return true;
2481 }
2482
2483 bool failed() { return false; }
2484 bool found(APValue &Subobj, QualType SubobjType) {
2485 // Stash the old value. Also clear Old, so we don't clobber it later
2486 // if we're post-incrementing a complex.
2487 if (Old) {
2488 *Old = Subobj;
2489 Old = 0;
2490 }
2491
2492 switch (Subobj.getKind()) {
2493 case APValue::Int:
2494 return found(Subobj.getInt(), SubobjType);
2495 case APValue::Float:
2496 return found(Subobj.getFloat(), SubobjType);
2497 case APValue::ComplexInt:
2498 return found(Subobj.getComplexIntReal(),
2499 SubobjType->castAs<ComplexType>()->getElementType()
2500 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2501 case APValue::ComplexFloat:
2502 return found(Subobj.getComplexFloatReal(),
2503 SubobjType->castAs<ComplexType>()->getElementType()
2504 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2505 case APValue::LValue:
2506 return foundPointer(Subobj, SubobjType);
2507 default:
2508 // FIXME: can this happen?
2509 Info.Diag(E);
2510 return false;
2511 }
2512 }
2513 bool found(APSInt &Value, QualType SubobjType) {
2514 if (!checkConst(SubobjType))
2515 return false;
2516
2517 if (!SubobjType->isIntegerType()) {
2518 // We don't support increment / decrement on integer-cast-to-pointer
2519 // values.
2520 Info.Diag(E);
2521 return false;
2522 }
2523
2524 if (Old) *Old = APValue(Value);
2525
2526 // bool arithmetic promotes to int, and the conversion back to bool
2527 // doesn't reduce mod 2^n, so special-case it.
2528 if (SubobjType->isBooleanType()) {
2529 if (AccessKind == AK_Increment)
2530 Value = 1;
2531 else
2532 Value = !Value;
2533 return true;
2534 }
2535
2536 bool WasNegative = Value.isNegative();
2537 if (AccessKind == AK_Increment) {
2538 ++Value;
2539
2540 if (!WasNegative && Value.isNegative() &&
2541 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2542 APSInt ActualValue(Value, /*IsUnsigned*/true);
2543 HandleOverflow(Info, E, ActualValue, SubobjType);
2544 }
2545 } else {
2546 --Value;
2547
2548 if (WasNegative && !Value.isNegative() &&
2549 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2550 unsigned BitWidth = Value.getBitWidth();
2551 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2552 ActualValue.setBit(BitWidth);
2553 HandleOverflow(Info, E, ActualValue, SubobjType);
2554 }
2555 }
2556 return true;
2557 }
2558 bool found(APFloat &Value, QualType SubobjType) {
2559 if (!checkConst(SubobjType))
2560 return false;
2561
2562 if (Old) *Old = APValue(Value);
2563
2564 APFloat One(Value.getSemantics(), 1);
2565 if (AccessKind == AK_Increment)
2566 Value.add(One, APFloat::rmNearestTiesToEven);
2567 else
2568 Value.subtract(One, APFloat::rmNearestTiesToEven);
2569 return true;
2570 }
2571 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2572 if (!checkConst(SubobjType))
2573 return false;
2574
2575 QualType PointeeType;
2576 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2577 PointeeType = PT->getPointeeType();
2578 else {
2579 Info.Diag(E);
2580 return false;
2581 }
2582
2583 LValue LVal;
2584 LVal.setFrom(Info.Ctx, Subobj);
2585 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2586 AccessKind == AK_Increment ? 1 : -1))
2587 return false;
2588 LVal.moveInto(Subobj);
2589 return true;
2590 }
2591 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2592 llvm_unreachable("shouldn't encounter string elements here");
2593 }
2594};
2595} // end anonymous namespace
2596
2597/// Perform an increment or decrement on LVal.
2598static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2599 QualType LValType, bool IsIncrement, APValue *Old) {
2600 if (LVal.Designator.Invalid)
2601 return false;
2602
2603 if (!Info.getLangOpts().CPlusPlus1y) {
2604 Info.Diag(E);
2605 return false;
2606 }
2607
2608 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2609 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2610 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2611 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2612}
2613
Richard Smithe97cbd72011-11-11 04:05:33 +00002614/// Build an lvalue for the object argument of a member function call.
2615static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2616 LValue &This) {
2617 if (Object->getType()->isPointerType())
2618 return EvaluatePointer(Object, This, Info);
2619
2620 if (Object->isGLValue())
2621 return EvaluateLValue(Object, This, Info);
2622
Richard Smithd9f663b2013-04-22 15:31:51 +00002623 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00002624 return EvaluateTemporary(Object, This, Info);
2625
2626 return false;
2627}
2628
2629/// HandleMemberPointerAccess - Evaluate a member access operation and build an
2630/// lvalue referring to the result.
2631///
2632/// \param Info - Information about the ongoing evaluation.
2633/// \param BO - The member pointer access operation.
2634/// \param LV - Filled in with a reference to the resulting object.
2635/// \param IncludeMember - Specifies whether the member itself is included in
2636/// the resulting LValue subobject designator. This is not possible when
2637/// creating a bound member function.
2638/// \return The field or method declaration to which the member pointer refers,
2639/// or 0 if evaluation fails.
2640static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2641 const BinaryOperator *BO,
2642 LValue &LV,
2643 bool IncludeMember = true) {
2644 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2645
Richard Smith253c2a32012-01-27 01:14:48 +00002646 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
2647 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00002648 return 0;
2649
2650 MemberPtr MemPtr;
2651 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
2652 return 0;
2653
2654 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2655 // member value, the behavior is undefined.
2656 if (!MemPtr.getDecl())
2657 return 0;
2658
Richard Smith253c2a32012-01-27 01:14:48 +00002659 if (!EvalObjOK)
2660 return 0;
2661
Richard Smith027bf112011-11-17 22:56:20 +00002662 if (MemPtr.isDerivedMember()) {
2663 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00002664 // The end of the derived-to-base path for the base object must match the
2665 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00002666 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00002667 LV.Designator.Entries.size())
2668 return 0;
2669 unsigned PathLengthToMember =
2670 LV.Designator.Entries.size() - MemPtr.Path.size();
2671 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2672 const CXXRecordDecl *LVDecl = getAsBaseClass(
2673 LV.Designator.Entries[PathLengthToMember + I]);
2674 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2675 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
2676 return 0;
2677 }
2678
2679 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002680 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
2681 PathLengthToMember))
2682 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002683 } else if (!MemPtr.Path.empty()) {
2684 // Extend the LValue path with the member pointer's path.
2685 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2686 MemPtr.Path.size() + IncludeMember);
2687
2688 // Walk down to the appropriate base class.
2689 QualType LVType = BO->getLHS()->getType();
2690 if (const PointerType *PT = LVType->getAs<PointerType>())
2691 LVType = PT->getPointeeType();
2692 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2693 assert(RD && "member pointer access on non-class-type expression");
2694 // The first class in the path is that of the lvalue.
2695 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2696 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00002697 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
2698 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002699 RD = Base;
2700 }
2701 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00002702 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
2703 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00002704 }
2705
2706 // Add the member. Note that we cannot build bound member functions here.
2707 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00002708 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2709 if (!HandleLValueMember(Info, BO, LV, FD))
2710 return 0;
2711 } else if (const IndirectFieldDecl *IFD =
2712 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2713 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2714 return 0;
2715 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002716 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002717 }
Richard Smith027bf112011-11-17 22:56:20 +00002718 }
2719
2720 return MemPtr.getDecl();
2721}
2722
2723/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2724/// the provided lvalue, which currently refers to the base object.
2725static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2726 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002727 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002728 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002729 return false;
2730
Richard Smitha8105bc2012-01-06 16:39:00 +00002731 QualType TargetQT = E->getType();
2732 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2733 TargetQT = PT->getPointeeType();
2734
2735 // Check this cast lands within the final derived-to-base subobject path.
2736 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
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;
2739 return false;
2740 }
2741
Richard Smith027bf112011-11-17 22:56:20 +00002742 // Check the type of the final cast. We don't need to check the path,
2743 // since a cast can only be formed if the path is unique.
2744 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002745 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2746 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002747 if (NewEntriesSize == D.MostDerivedPathLength)
2748 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2749 else
Richard Smith027bf112011-11-17 22:56:20 +00002750 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002751 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002752 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002753 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002754 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002755 }
Richard Smith027bf112011-11-17 22:56:20 +00002756
2757 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002758 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002759}
2760
Mike Stump876387b2009-10-27 22:09:17 +00002761namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002762enum EvalStmtResult {
2763 /// Evaluation failed.
2764 ESR_Failed,
2765 /// Hit a 'return' statement.
2766 ESR_Returned,
2767 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00002768 ESR_Succeeded,
2769 /// Hit a 'continue' statement.
2770 ESR_Continue,
2771 /// Hit a 'break' statement.
2772 ESR_Break
Richard Smith254a73d2011-10-28 22:34:42 +00002773};
2774}
2775
Richard Smithd9f663b2013-04-22 15:31:51 +00002776static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2777 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2778 // We don't need to evaluate the initializer for a static local.
2779 if (!VD->hasLocalStorage())
2780 return true;
2781
2782 LValue Result;
2783 Result.set(VD, Info.CurrentCall->Index);
2784 APValue &Val = Info.CurrentCall->Temporaries[VD];
2785
2786 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2787 // Wipe out any partially-computed value, to allow tracking that this
2788 // evaluation failed.
2789 Val = APValue();
2790 return false;
2791 }
2792 }
2793
2794 return true;
2795}
2796
Richard Smith4e18ca52013-05-06 05:56:11 +00002797/// Evaluate a condition (either a variable declaration or an expression).
2798static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2799 const Expr *Cond, bool &Result) {
2800 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2801 return false;
2802 return EvaluateAsBooleanCondition(Cond, Result, Info);
2803}
2804
2805static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
2806 const Stmt *S);
2807
2808/// Evaluate the body of a loop, and translate the result as appropriate.
2809static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
2810 const Stmt *Body) {
2811 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body)) {
2812 case ESR_Break:
2813 return ESR_Succeeded;
2814 case ESR_Succeeded:
2815 case ESR_Continue:
2816 return ESR_Continue;
2817 case ESR_Failed:
2818 case ESR_Returned:
2819 return ESR;
2820 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00002821 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00002822}
2823
Richard Smith254a73d2011-10-28 22:34:42 +00002824// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002825static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00002826 const Stmt *S) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00002827 if (!Info.nextStep(S))
2828 return ESR_Failed;
2829
Richard Smithd9f663b2013-04-22 15:31:51 +00002830 // FIXME: Mark all temporaries in the current frame as destroyed at
2831 // the end of each full-expression.
Richard Smith254a73d2011-10-28 22:34:42 +00002832 switch (S->getStmtClass()) {
2833 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00002834 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002835 // Don't bother evaluating beyond an expression-statement which couldn't
2836 // be evaluated.
Richard Smith4e18ca52013-05-06 05:56:11 +00002837 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00002838 return ESR_Failed;
2839 return ESR_Succeeded;
2840 }
2841
2842 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00002843 return ESR_Failed;
2844
2845 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00002846 return ESR_Succeeded;
2847
Richard Smithd9f663b2013-04-22 15:31:51 +00002848 case Stmt::DeclStmtClass: {
2849 const DeclStmt *DS = cast<DeclStmt>(S);
2850 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
2851 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
2852 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
2853 return ESR_Failed;
2854 return ESR_Succeeded;
2855 }
2856
Richard Smith357362d2011-12-13 06:39:58 +00002857 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002858 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithd9f663b2013-04-22 15:31:51 +00002859 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002860 return ESR_Failed;
2861 return ESR_Returned;
2862 }
Richard Smith254a73d2011-10-28 22:34:42 +00002863
2864 case Stmt::CompoundStmtClass: {
2865 const CompoundStmt *CS = cast<CompoundStmt>(S);
2866 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2867 BE = CS->body_end(); BI != BE; ++BI) {
2868 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2869 if (ESR != ESR_Succeeded)
2870 return ESR;
2871 }
2872 return ESR_Succeeded;
2873 }
Richard Smithd9f663b2013-04-22 15:31:51 +00002874
2875 case Stmt::IfStmtClass: {
2876 const IfStmt *IS = cast<IfStmt>(S);
2877
2878 // Evaluate the condition, as either a var decl or as an expression.
2879 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00002880 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00002881 return ESR_Failed;
2882
2883 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
2884 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
2885 if (ESR != ESR_Succeeded)
2886 return ESR;
2887 }
2888 return ESR_Succeeded;
2889 }
Richard Smith4e18ca52013-05-06 05:56:11 +00002890
2891 case Stmt::WhileStmtClass: {
2892 const WhileStmt *WS = cast<WhileStmt>(S);
2893 while (true) {
2894 bool Continue;
2895 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
2896 Continue))
2897 return ESR_Failed;
2898 if (!Continue)
2899 break;
2900
2901 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
2902 if (ESR != ESR_Continue)
2903 return ESR;
2904 }
2905 return ESR_Succeeded;
2906 }
2907
2908 case Stmt::DoStmtClass: {
2909 const DoStmt *DS = cast<DoStmt>(S);
2910 bool Continue;
2911 do {
2912 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody());
2913 if (ESR != ESR_Continue)
2914 return ESR;
2915
2916 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
2917 return ESR_Failed;
2918 } while (Continue);
2919 return ESR_Succeeded;
2920 }
2921
2922 case Stmt::ForStmtClass: {
2923 const ForStmt *FS = cast<ForStmt>(S);
2924 if (FS->getInit()) {
2925 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
2926 if (ESR != ESR_Succeeded)
2927 return ESR;
2928 }
2929 while (true) {
2930 bool Continue = true;
2931 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
2932 FS->getCond(), Continue))
2933 return ESR_Failed;
2934 if (!Continue)
2935 break;
2936
2937 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
2938 if (ESR != ESR_Continue)
2939 return ESR;
2940
2941 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
2942 return ESR_Failed;
2943 }
2944 return ESR_Succeeded;
2945 }
2946
Richard Smith896e0d72013-05-06 06:51:17 +00002947 case Stmt::CXXForRangeStmtClass: {
2948 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
2949
2950 // Initialize the __range variable.
2951 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
2952 if (ESR != ESR_Succeeded)
2953 return ESR;
2954
2955 // Create the __begin and __end iterators.
2956 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
2957 if (ESR != ESR_Succeeded)
2958 return ESR;
2959
2960 while (true) {
2961 // Condition: __begin != __end.
2962 bool Continue = true;
2963 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
2964 return ESR_Failed;
2965 if (!Continue)
2966 break;
2967
2968 // User's variable declaration, initialized by *__begin.
2969 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
2970 if (ESR != ESR_Succeeded)
2971 return ESR;
2972
2973 // Loop body.
2974 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
2975 if (ESR != ESR_Continue)
2976 return ESR;
2977
2978 // Increment: ++__begin
2979 if (!EvaluateIgnoredValue(Info, FS->getInc()))
2980 return ESR_Failed;
2981 }
2982
2983 return ESR_Succeeded;
2984 }
2985
Richard Smith4e18ca52013-05-06 05:56:11 +00002986 case Stmt::ContinueStmtClass:
2987 return ESR_Continue;
2988
2989 case Stmt::BreakStmtClass:
2990 return ESR_Break;
Richard Smith254a73d2011-10-28 22:34:42 +00002991 }
2992}
2993
Richard Smithcc36f692011-12-22 02:22:31 +00002994/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2995/// default constructor. If so, we'll fold it whether or not it's marked as
2996/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2997/// so we need special handling.
2998static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00002999 const CXXConstructorDecl *CD,
3000 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003001 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3002 return false;
3003
Richard Smith66e05fe2012-01-18 05:21:49 +00003004 // Value-initialization does not call a trivial default constructor, so such a
3005 // call is a core constant expression whether or not the constructor is
3006 // constexpr.
3007 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003008 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003009 // FIXME: If DiagDecl is an implicitly-declared special member function,
3010 // we should be much more explicit about why it's not constexpr.
3011 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3012 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3013 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003014 } else {
3015 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3016 }
3017 }
3018 return true;
3019}
3020
Richard Smith357362d2011-12-13 06:39:58 +00003021/// CheckConstexprFunction - Check that a function can be called in a constant
3022/// expression.
3023static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3024 const FunctionDecl *Declaration,
3025 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003026 // Potential constant expressions can contain calls to declared, but not yet
3027 // defined, constexpr functions.
3028 if (Info.CheckingPotentialConstantExpression && !Definition &&
3029 Declaration->isConstexpr())
3030 return false;
3031
Richard Smith357362d2011-12-13 06:39:58 +00003032 // Can we evaluate this function call?
3033 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3034 return true;
3035
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003036 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003037 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003038 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3039 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003040 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3041 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3042 << DiagDecl;
3043 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3044 } else {
3045 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3046 }
3047 return false;
3048}
3049
Richard Smithd62306a2011-11-10 06:34:14 +00003050namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003051typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003052}
3053
3054/// EvaluateArgs - Evaluate the arguments to a function call.
3055static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3056 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003057 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003058 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003059 I != E; ++I) {
3060 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3061 // If we're checking for a potential constant expression, evaluate all
3062 // initializers even if some of them fail.
3063 if (!Info.keepEvaluatingAfterFailure())
3064 return false;
3065 Success = false;
3066 }
3067 }
3068 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003069}
3070
Richard Smith254a73d2011-10-28 22:34:42 +00003071/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003072static bool HandleFunctionCall(SourceLocation CallLoc,
3073 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003074 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003075 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003076 ArgVector ArgValues(Args.size());
3077 if (!EvaluateArgs(Args, ArgValues, Info))
3078 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003079
Richard Smith253c2a32012-01-27 01:14:48 +00003080 if (!Info.CheckCallLimit(CallLoc))
3081 return false;
3082
3083 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003084
3085 // For a trivial copy or move assignment, perform an APValue copy. This is
3086 // essential for unions, where the operations performed by the assignment
3087 // operator cannot be represented as statements.
3088 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3089 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3090 assert(This &&
3091 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3092 LValue RHS;
3093 RHS.setFrom(Info.Ctx, ArgValues[0]);
3094 APValue RHSValue;
3095 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3096 RHS, RHSValue))
3097 return false;
3098 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3099 RHSValue))
3100 return false;
3101 This->moveInto(Result);
3102 return true;
3103 }
3104
Richard Smithd9f663b2013-04-22 15:31:51 +00003105 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003106 if (ESR == ESR_Succeeded) {
3107 if (Callee->getResultType()->isVoidType())
3108 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003109 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003110 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003111 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003112}
3113
Richard Smithd62306a2011-11-10 06:34:14 +00003114/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003115static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003116 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003117 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003118 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003119 ArgVector ArgValues(Args.size());
3120 if (!EvaluateArgs(Args, ArgValues, Info))
3121 return false;
3122
Richard Smith253c2a32012-01-27 01:14:48 +00003123 if (!Info.CheckCallLimit(CallLoc))
3124 return false;
3125
Richard Smith3607ffe2012-02-13 03:54:03 +00003126 const CXXRecordDecl *RD = Definition->getParent();
3127 if (RD->getNumVBases()) {
3128 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3129 return false;
3130 }
3131
Richard Smith253c2a32012-01-27 01:14:48 +00003132 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003133
3134 // If it's a delegating constructor, just delegate.
3135 if (Definition->isDelegatingConstructor()) {
3136 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithd9f663b2013-04-22 15:31:51 +00003137 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3138 return false;
3139 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003140 }
3141
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003142 // For a trivial copy or move constructor, perform an APValue copy. This is
3143 // essential for unions, where the operations performed by the constructor
3144 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003145 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003146 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3147 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003148 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003149 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003150 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003151 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003152 }
3153
3154 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003155 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003156 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3157 std::distance(RD->field_begin(), RD->field_end()));
3158
John McCalld7bca762012-05-01 00:38:49 +00003159 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003160 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3161
Richard Smith253c2a32012-01-27 01:14:48 +00003162 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003163 unsigned BasesSeen = 0;
3164#ifndef NDEBUG
3165 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3166#endif
3167 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3168 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00003169 LValue Subobject = This;
3170 APValue *Value = &Result;
3171
3172 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00003173 if ((*I)->isBaseInitializer()) {
3174 QualType BaseType((*I)->getBaseClass(), 0);
3175#ifndef NDEBUG
3176 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003177 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003178 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3179 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3180 "base class initializers not in expected order");
3181 ++BaseIt;
3182#endif
John McCalld7bca762012-05-01 00:38:49 +00003183 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3184 BaseType->getAsCXXRecordDecl(), &Layout))
3185 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003186 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00003187 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00003188 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3189 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003190 if (RD->isUnion()) {
3191 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003192 Value = &Result.getUnionValue();
3193 } else {
3194 Value = &Result.getStructField(FD->getFieldIndex());
3195 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00003196 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003197 // Walk the indirect field decl's chain to find the object to initialize,
3198 // and make sure we've initialized every step along it.
3199 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3200 CE = IFD->chain_end();
3201 C != CE; ++C) {
3202 FieldDecl *FD = cast<FieldDecl>(*C);
3203 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3204 // Switch the union field if it differs. This happens if we had
3205 // preceding zero-initialization, and we're now initializing a union
3206 // subobject other than the first.
3207 // FIXME: In this case, the values of the other subobjects are
3208 // specified, since zero-initialization sets all padding bits to zero.
3209 if (Value->isUninit() ||
3210 (Value->isUnion() && Value->getUnionField() != FD)) {
3211 if (CD->isUnion())
3212 *Value = APValue(FD);
3213 else
3214 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3215 std::distance(CD->field_begin(), CD->field_end()));
3216 }
John McCalld7bca762012-05-01 00:38:49 +00003217 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3218 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003219 if (CD->isUnion())
3220 Value = &Value->getUnionValue();
3221 else
3222 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003223 }
Richard Smithd62306a2011-11-10 06:34:14 +00003224 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003225 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003226 }
Richard Smith253c2a32012-01-27 01:14:48 +00003227
Richard Smith7525ff62013-05-09 07:14:00 +00003228 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit())) {
Richard Smith253c2a32012-01-27 01:14:48 +00003229 // If we're checking for a potential constant expression, evaluate all
3230 // initializers even if some of them fail.
3231 if (!Info.keepEvaluatingAfterFailure())
3232 return false;
3233 Success = false;
3234 }
Richard Smithd62306a2011-11-10 06:34:14 +00003235 }
3236
Richard Smithd9f663b2013-04-22 15:31:51 +00003237 return Success &&
3238 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003239}
3240
Eli Friedman9a156e52008-11-12 09:44:48 +00003241//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003242// Generic Evaluation
3243//===----------------------------------------------------------------------===//
3244namespace {
3245
Richard Smithf57d8cb2011-12-09 22:58:01 +00003246// FIXME: RetTy is always bool. Remove it.
3247template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00003248class ExprEvaluatorBase
3249 : public ConstStmtVisitor<Derived, RetTy> {
3250private:
Richard Smith2e312c82012-03-03 22:46:17 +00003251 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003252 return static_cast<Derived*>(this)->Success(V, E);
3253 }
Richard Smithfddd3842011-12-30 21:15:51 +00003254 RetTy DerivedZeroInitialization(const Expr *E) {
3255 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003256 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003257
Richard Smith17100ba2012-02-16 02:46:34 +00003258 // Check whether a conditional operator with a non-constant condition is a
3259 // potential constant expression. If neither arm is a potential constant
3260 // expression, then the conditional operator is not either.
3261 template<typename ConditionalOperator>
3262 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3263 assert(Info.CheckingPotentialConstantExpression);
3264
3265 // Speculatively evaluate both arms.
3266 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003267 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003268 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3269
3270 StmtVisitorTy::Visit(E->getFalseExpr());
3271 if (Diag.empty())
3272 return;
3273
3274 Diag.clear();
3275 StmtVisitorTy::Visit(E->getTrueExpr());
3276 if (Diag.empty())
3277 return;
3278 }
3279
3280 Error(E, diag::note_constexpr_conditional_never_const);
3281 }
3282
3283
3284 template<typename ConditionalOperator>
3285 bool HandleConditionalOperator(const ConditionalOperator *E) {
3286 bool BoolResult;
3287 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3288 if (Info.CheckingPotentialConstantExpression)
3289 CheckPotentialConstantConditional(E);
3290 return false;
3291 }
3292
3293 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3294 return StmtVisitorTy::Visit(EvalExpr);
3295 }
3296
Peter Collingbournee9200682011-05-13 03:29:01 +00003297protected:
3298 EvalInfo &Info;
3299 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3300 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3301
Richard Smith92b1ce02011-12-12 09:28:41 +00003302 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003303 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003304 }
3305
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003306 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3307
3308public:
3309 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3310
3311 EvalInfo &getEvalInfo() { return Info; }
3312
Richard Smithf57d8cb2011-12-09 22:58:01 +00003313 /// Report an evaluation error. This should only be called when an error is
3314 /// first discovered. When propagating an error, just return false.
3315 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003316 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003317 return false;
3318 }
3319 bool Error(const Expr *E) {
3320 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3321 }
3322
Peter Collingbournee9200682011-05-13 03:29:01 +00003323 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003324 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003325 }
3326 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003327 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003328 }
3329
3330 RetTy VisitParenExpr(const ParenExpr *E)
3331 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3332 RetTy VisitUnaryExtension(const UnaryOperator *E)
3333 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3334 RetTy VisitUnaryPlus(const UnaryOperator *E)
3335 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3336 RetTy VisitChooseExpr(const ChooseExpr *E)
3337 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
3338 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3339 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00003340 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3341 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00003342 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3343 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00003344 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3345 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00003346 // We cannot create any objects for which cleanups are required, so there is
3347 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3348 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3349 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003350
Richard Smith6d6ecc32011-12-12 12:46:16 +00003351 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3352 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3353 return static_cast<Derived*>(this)->VisitCastExpr(E);
3354 }
3355 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3356 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3357 return static_cast<Derived*>(this)->VisitCastExpr(E);
3358 }
3359
Richard Smith027bf112011-11-17 22:56:20 +00003360 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3361 switch (E->getOpcode()) {
3362 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003363 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003364
3365 case BO_Comma:
3366 VisitIgnoredValue(E->getLHS());
3367 return StmtVisitorTy::Visit(E->getRHS());
3368
3369 case BO_PtrMemD:
3370 case BO_PtrMemI: {
3371 LValue Obj;
3372 if (!HandleMemberPointerAccess(Info, E, Obj))
3373 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003374 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003375 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003376 return false;
3377 return DerivedSuccess(Result, E);
3378 }
3379 }
3380 }
3381
Peter Collingbournee9200682011-05-13 03:29:01 +00003382 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003383 // Evaluate and cache the common expression. We treat it as a temporary,
3384 // even though it's not quite the same thing.
3385 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3386 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003387 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003388
Richard Smith17100ba2012-02-16 02:46:34 +00003389 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003390 }
3391
3392 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003393 bool IsBcpCall = false;
3394 // If the condition (ignoring parens) is a __builtin_constant_p call,
3395 // the result is a constant expression if it can be folded without
3396 // side-effects. This is an important GNU extension. See GCC PR38377
3397 // for discussion.
3398 if (const CallExpr *CallCE =
3399 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3400 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3401 IsBcpCall = true;
3402
3403 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3404 // constant expression; we can't check whether it's potentially foldable.
3405 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3406 return false;
3407
3408 FoldConstant Fold(Info);
3409
Richard Smith17100ba2012-02-16 02:46:34 +00003410 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00003411 return false;
3412
3413 if (IsBcpCall)
3414 Fold.Fold(Info);
3415
3416 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00003417 }
3418
3419 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00003420 APValue &Value = Info.CurrentCall->Temporaries[E];
3421 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003422 const Expr *Source = E->getSourceExpr();
3423 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003424 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003425 if (Source == E) { // sanity checking.
3426 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003427 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00003428 }
3429 return StmtVisitorTy::Visit(Source);
3430 }
Richard Smith26d4cc12012-06-26 08:12:11 +00003431 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003432 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003433
Richard Smith254a73d2011-10-28 22:34:42 +00003434 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003435 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00003436 QualType CalleeType = Callee->getType();
3437
Richard Smith254a73d2011-10-28 22:34:42 +00003438 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00003439 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003440 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00003441 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00003442
Richard Smithe97cbd72011-11-11 04:05:33 +00003443 // Extract function decl and 'this' pointer from the callee.
3444 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003445 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00003446 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3447 // Explicit bound member calls, such as x.f() or p->g();
3448 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003449 return false;
3450 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00003451 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00003452 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00003453 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3454 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00003455 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3456 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00003457 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00003458 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003459 return Error(Callee);
3460
3461 FD = dyn_cast<FunctionDecl>(Member);
3462 if (!FD)
3463 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003464 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003465 LValue Call;
3466 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003467 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00003468
Richard Smitha8105bc2012-01-06 16:39:00 +00003469 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003470 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00003471 FD = dyn_cast_or_null<FunctionDecl>(
3472 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00003473 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003474 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00003475
3476 // Overloaded operator calls to member functions are represented as normal
3477 // calls with '*this' as the first argument.
3478 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3479 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003480 // FIXME: When selecting an implicit conversion for an overloaded
3481 // operator delete, we sometimes try to evaluate calls to conversion
3482 // operators without a 'this' parameter!
3483 if (Args.empty())
3484 return Error(E);
3485
Richard Smithe97cbd72011-11-11 04:05:33 +00003486 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3487 return false;
3488 This = &ThisVal;
3489 Args = Args.slice(1);
3490 }
3491
3492 // Don't call function pointers which have been cast to some other type.
3493 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003494 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00003495 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003496 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00003497
Richard Smith47b34932012-02-01 02:39:43 +00003498 if (This && !This->checkSubobject(Info, E, CSK_This))
3499 return false;
3500
Richard Smith3607ffe2012-02-13 03:54:03 +00003501 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3502 // calls to such functions in constant expressions.
3503 if (This && !HasQualifier &&
3504 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3505 return Error(E, diag::note_constexpr_virtual_call);
3506
Richard Smith357362d2011-12-13 06:39:58 +00003507 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00003508 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00003509 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00003510
Richard Smith357362d2011-12-13 06:39:58 +00003511 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003512 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3513 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003514 return false;
3515
Richard Smithb228a862012-02-15 02:18:13 +00003516 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00003517 }
3518
Richard Smith11562c52011-10-28 17:51:58 +00003519 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3520 return StmtVisitorTy::Visit(E->getInitializer());
3521 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003522 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00003523 if (E->getNumInits() == 0)
3524 return DerivedZeroInitialization(E);
3525 if (E->getNumInits() == 1)
3526 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00003527 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003528 }
3529 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003530 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003531 }
3532 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003533 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003534 }
Richard Smith027bf112011-11-17 22:56:20 +00003535 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003536 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003537 }
Richard Smith4ce706a2011-10-11 21:43:33 +00003538
Richard Smithd62306a2011-11-10 06:34:14 +00003539 /// A member expression where the object is a prvalue is itself a prvalue.
3540 RetTy VisitMemberExpr(const MemberExpr *E) {
3541 assert(!E->isArrow() && "missing call to bound member function?");
3542
Richard Smith2e312c82012-03-03 22:46:17 +00003543 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00003544 if (!Evaluate(Val, Info, E->getBase()))
3545 return false;
3546
3547 QualType BaseTy = E->getBase()->getType();
3548
3549 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003550 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003551 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00003552 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00003553 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3554
Richard Smith3229b742013-05-05 21:17:10 +00003555 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00003556 SubobjectDesignator Designator(BaseTy);
3557 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00003558
Richard Smith3229b742013-05-05 21:17:10 +00003559 APValue Result;
3560 return extractSubobject(Info, E, Obj, Designator, Result) &&
3561 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00003562 }
3563
Richard Smith11562c52011-10-28 17:51:58 +00003564 RetTy VisitCastExpr(const CastExpr *E) {
3565 switch (E->getCastKind()) {
3566 default:
3567 break;
3568
David Chisnallfa35df62012-01-16 17:27:18 +00003569 case CK_AtomicToNonAtomic:
3570 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00003571 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00003572 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00003573 return StmtVisitorTy::Visit(E->getSubExpr());
3574
3575 case CK_LValueToRValue: {
3576 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003577 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3578 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003579 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00003580 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00003581 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00003582 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003583 return false;
3584 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00003585 }
3586 }
3587
Richard Smithf57d8cb2011-12-09 22:58:01 +00003588 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003589 }
3590
Richard Smith243ef902013-05-05 23:31:59 +00003591 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3592 return VisitUnaryPostIncDec(UO);
3593 }
3594 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3595 return VisitUnaryPostIncDec(UO);
3596 }
3597 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3598 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3599 return Error(UO);
3600
3601 LValue LVal;
3602 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3603 return false;
3604 APValue RVal;
3605 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3606 UO->isIncrementOp(), &RVal))
3607 return false;
3608 return DerivedSuccess(RVal, UO);
3609 }
3610
Richard Smith4a678122011-10-24 18:44:57 +00003611 /// Visit a value which is evaluated, but whose value is ignored.
3612 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003613 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00003614 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003615};
3616
3617}
3618
3619//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003620// Common base class for lvalue and temporary evaluation.
3621//===----------------------------------------------------------------------===//
3622namespace {
3623template<class Derived>
3624class LValueExprEvaluatorBase
3625 : public ExprEvaluatorBase<Derived, bool> {
3626protected:
3627 LValue &Result;
3628 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3629 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3630
3631 bool Success(APValue::LValueBase B) {
3632 Result.set(B);
3633 return true;
3634 }
3635
3636public:
3637 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3638 ExprEvaluatorBaseTy(Info), Result(Result) {}
3639
Richard Smith2e312c82012-03-03 22:46:17 +00003640 bool Success(const APValue &V, const Expr *E) {
3641 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00003642 return true;
3643 }
Richard Smith027bf112011-11-17 22:56:20 +00003644
Richard Smith027bf112011-11-17 22:56:20 +00003645 bool VisitMemberExpr(const MemberExpr *E) {
3646 // Handle non-static data members.
3647 QualType BaseTy;
3648 if (E->isArrow()) {
3649 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3650 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00003651 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00003652 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003653 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00003654 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3655 return false;
3656 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003657 } else {
3658 if (!this->Visit(E->getBase()))
3659 return false;
3660 BaseTy = E->getBase()->getType();
3661 }
Richard Smith027bf112011-11-17 22:56:20 +00003662
Richard Smith1b78b3d2012-01-25 22:15:11 +00003663 const ValueDecl *MD = E->getMemberDecl();
3664 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3665 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3666 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3667 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00003668 if (!HandleLValueMember(this->Info, E, Result, FD))
3669 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003670 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00003671 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3672 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003673 } else
3674 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003675
Richard Smith1b78b3d2012-01-25 22:15:11 +00003676 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00003677 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00003678 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00003679 RefValue))
3680 return false;
3681 return Success(RefValue, E);
3682 }
3683 return true;
3684 }
3685
3686 bool VisitBinaryOperator(const BinaryOperator *E) {
3687 switch (E->getOpcode()) {
3688 default:
3689 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3690
3691 case BO_PtrMemD:
3692 case BO_PtrMemI:
3693 return HandleMemberPointerAccess(this->Info, E, Result);
3694 }
3695 }
3696
3697 bool VisitCastExpr(const CastExpr *E) {
3698 switch (E->getCastKind()) {
3699 default:
3700 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3701
3702 case CK_DerivedToBase:
3703 case CK_UncheckedDerivedToBase: {
3704 if (!this->Visit(E->getSubExpr()))
3705 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003706
3707 // Now figure out the necessary offset to add to the base LV to get from
3708 // the derived class to the base class.
3709 QualType Type = E->getSubExpr()->getType();
3710
3711 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3712 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003713 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00003714 *PathI))
3715 return false;
3716 Type = (*PathI)->getType();
3717 }
3718
3719 return true;
3720 }
3721 }
3722 }
3723};
3724}
3725
3726//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00003727// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003728//
3729// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3730// function designators (in C), decl references to void objects (in C), and
3731// temporaries (if building with -Wno-address-of-temporary).
3732//
3733// LValue evaluation produces values comprising a base expression of one of the
3734// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00003735// - Declarations
3736// * VarDecl
3737// * FunctionDecl
3738// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00003739// * CompoundLiteralExpr in C
3740// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00003741// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00003742// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00003743// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00003744// * ObjCEncodeExpr
3745// * AddrLabelExpr
3746// * BlockExpr
3747// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00003748// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00003749// * Any Expr, with a CallIndex indicating the function in which the temporary
3750// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00003751// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00003752//===----------------------------------------------------------------------===//
3753namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003754class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00003755 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00003756public:
Richard Smith027bf112011-11-17 22:56:20 +00003757 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3758 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003759
Richard Smith11562c52011-10-28 17:51:58 +00003760 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00003761 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00003762
Peter Collingbournee9200682011-05-13 03:29:01 +00003763 bool VisitDeclRefExpr(const DeclRefExpr *E);
3764 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003765 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003766 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3767 bool VisitMemberExpr(const MemberExpr *E);
3768 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3769 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00003770 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00003771 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003772 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3773 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00003774 bool VisitUnaryReal(const UnaryOperator *E);
3775 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00003776 bool VisitUnaryPreInc(const UnaryOperator *UO) {
3777 return VisitUnaryPreIncDec(UO);
3778 }
3779 bool VisitUnaryPreDec(const UnaryOperator *UO) {
3780 return VisitUnaryPreIncDec(UO);
3781 }
Richard Smith3229b742013-05-05 21:17:10 +00003782 bool VisitBinAssign(const BinaryOperator *BO);
3783 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00003784
Peter Collingbournee9200682011-05-13 03:29:01 +00003785 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00003786 switch (E->getCastKind()) {
3787 default:
Richard Smith027bf112011-11-17 22:56:20 +00003788 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00003789
Eli Friedmance3e02a2011-10-11 00:13:24 +00003790 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00003791 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00003792 if (!Visit(E->getSubExpr()))
3793 return false;
3794 Result.Designator.setInvalid();
3795 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00003796
Richard Smith027bf112011-11-17 22:56:20 +00003797 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00003798 if (!Visit(E->getSubExpr()))
3799 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003800 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00003801 }
3802 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003803};
3804} // end anonymous namespace
3805
Richard Smith11562c52011-10-28 17:51:58 +00003806/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00003807/// expressions which are not glvalues, in two cases:
3808/// * function designators in C, and
3809/// * "extern void" objects
3810static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
3811 assert(E->isGLValue() || E->getType()->isFunctionType() ||
3812 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003813 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003814}
3815
Peter Collingbournee9200682011-05-13 03:29:01 +00003816bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003817 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
3818 return Success(FD);
3819 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00003820 return VisitVarDecl(E, VD);
3821 return Error(E);
3822}
Richard Smith733237d2011-10-24 23:14:33 +00003823
Richard Smith11562c52011-10-28 17:51:58 +00003824bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith3229b742013-05-05 21:17:10 +00003825 CallStackFrame *Frame = 0;
3826 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
3827 Frame = Info.CurrentCall;
3828
Richard Smithfec09922011-11-01 16:57:24 +00003829 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00003830 if (Frame) {
3831 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00003832 return true;
3833 }
Richard Smithce40ad62011-11-12 22:28:03 +00003834 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00003835 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00003836
Richard Smith3229b742013-05-05 21:17:10 +00003837 APValue *V;
3838 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003839 return false;
Richard Smith3229b742013-05-05 21:17:10 +00003840 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00003841}
3842
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003843bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3844 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00003845 if (E->getType()->isRecordType())
3846 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00003847
Richard Smithb228a862012-02-15 02:18:13 +00003848 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00003849 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3850 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00003851}
3852
Peter Collingbournee9200682011-05-13 03:29:01 +00003853bool
3854LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003855 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3856 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3857 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00003858 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003859}
3860
Richard Smith6e525142011-12-27 12:18:28 +00003861bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00003862 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00003863 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00003864
3865 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
3866 << E->getExprOperand()->getType()
3867 << E->getExprOperand()->getSourceRange();
3868 return false;
Richard Smith6e525142011-12-27 12:18:28 +00003869}
3870
Francois Pichet0066db92012-04-16 04:08:35 +00003871bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3872 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00003873}
Francois Pichet0066db92012-04-16 04:08:35 +00003874
Peter Collingbournee9200682011-05-13 03:29:01 +00003875bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003876 // Handle static data members.
3877 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3878 VisitIgnoredValue(E->getBase());
3879 return VisitVarDecl(E, VD);
3880 }
3881
Richard Smith254a73d2011-10-28 22:34:42 +00003882 // Handle static member functions.
3883 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3884 if (MD->isStatic()) {
3885 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00003886 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00003887 }
3888 }
3889
Richard Smithd62306a2011-11-10 06:34:14 +00003890 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00003891 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003892}
3893
Peter Collingbournee9200682011-05-13 03:29:01 +00003894bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003895 // FIXME: Deal with vectors as array subscript bases.
3896 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003897 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003898
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003899 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00003900 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003901
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003902 APSInt Index;
3903 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00003904 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003905
Richard Smith861b5b52013-05-07 23:34:45 +00003906 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
3907 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003908}
Eli Friedman9a156e52008-11-12 09:44:48 +00003909
Peter Collingbournee9200682011-05-13 03:29:01 +00003910bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00003911 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00003912}
3913
Richard Smith66c96992012-02-18 22:04:06 +00003914bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3915 if (!Visit(E->getSubExpr()))
3916 return false;
3917 // __real is a no-op on scalar lvalues.
3918 if (E->getSubExpr()->getType()->isAnyComplexType())
3919 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3920 return true;
3921}
3922
3923bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3924 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3925 "lvalue __imag__ on scalar?");
3926 if (!Visit(E->getSubExpr()))
3927 return false;
3928 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3929 return true;
3930}
3931
Richard Smith243ef902013-05-05 23:31:59 +00003932bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
3933 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00003934 return Error(UO);
3935
3936 if (!this->Visit(UO->getSubExpr()))
3937 return false;
3938
Richard Smith243ef902013-05-05 23:31:59 +00003939 return handleIncDec(
3940 this->Info, UO, Result, UO->getSubExpr()->getType(),
3941 UO->isIncrementOp(), 0);
Richard Smith3229b742013-05-05 21:17:10 +00003942}
3943
3944bool LValueExprEvaluator::VisitCompoundAssignOperator(
3945 const CompoundAssignOperator *CAO) {
Richard Smith243ef902013-05-05 23:31:59 +00003946 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00003947 return Error(CAO);
3948
Richard Smith3229b742013-05-05 21:17:10 +00003949 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00003950
3951 // The overall lvalue result is the result of evaluating the LHS.
3952 if (!this->Visit(CAO->getLHS())) {
3953 if (Info.keepEvaluatingAfterFailure())
3954 Evaluate(RHS, this->Info, CAO->getRHS());
3955 return false;
3956 }
3957
Richard Smith3229b742013-05-05 21:17:10 +00003958 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
3959 return false;
3960
Richard Smith43e77732013-05-07 04:50:00 +00003961 return handleCompoundAssignment(
3962 this->Info, CAO,
3963 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
3964 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00003965}
3966
3967bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Richard Smith243ef902013-05-05 23:31:59 +00003968 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3969 return Error(E);
3970
Richard Smith3229b742013-05-05 21:17:10 +00003971 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00003972
3973 if (!this->Visit(E->getLHS())) {
3974 if (Info.keepEvaluatingAfterFailure())
3975 Evaluate(NewVal, this->Info, E->getRHS());
3976 return false;
3977 }
3978
Richard Smith3229b742013-05-05 21:17:10 +00003979 if (!Evaluate(NewVal, this->Info, E->getRHS()))
3980 return false;
Richard Smith243ef902013-05-05 23:31:59 +00003981
3982 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00003983 NewVal);
3984}
3985
Eli Friedman9a156e52008-11-12 09:44:48 +00003986//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003987// Pointer Evaluation
3988//===----------------------------------------------------------------------===//
3989
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003990namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003991class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003992 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00003993 LValue &Result;
3994
Peter Collingbournee9200682011-05-13 03:29:01 +00003995 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00003996 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00003997 return true;
3998 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003999public:
Mike Stump11289f42009-09-09 15:08:12 +00004000
John McCall45d55e42010-05-07 21:00:08 +00004001 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004002 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004003
Richard Smith2e312c82012-03-03 22:46:17 +00004004 bool Success(const APValue &V, const Expr *E) {
4005 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004006 return true;
4007 }
Richard Smithfddd3842011-12-30 21:15:51 +00004008 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004009 return Success((Expr*)0);
4010 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004011
John McCall45d55e42010-05-07 21:00:08 +00004012 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004013 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004014 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004015 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004016 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004017 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004018 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004019 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004020 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004021 bool VisitCallExpr(const CallExpr *E);
4022 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004023 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004024 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004025 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004026 }
Richard Smithd62306a2011-11-10 06:34:14 +00004027 bool VisitCXXThisExpr(const CXXThisExpr *E) {
4028 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004029 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004030 Result = *Info.CurrentCall->This;
4031 return true;
4032 }
John McCallc07a0c72011-02-17 10:25:35 +00004033
Eli Friedman449fe542009-03-23 04:56:01 +00004034 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004035};
Chris Lattner05706e882008-07-11 18:11:29 +00004036} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004037
John McCall45d55e42010-05-07 21:00:08 +00004038static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004039 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004040 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004041}
4042
John McCall45d55e42010-05-07 21:00:08 +00004043bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004044 if (E->getOpcode() != BO_Add &&
4045 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004046 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004047
Chris Lattner05706e882008-07-11 18:11:29 +00004048 const Expr *PExp = E->getLHS();
4049 const Expr *IExp = E->getRHS();
4050 if (IExp->getType()->isPointerType())
4051 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004052
Richard Smith253c2a32012-01-27 01:14:48 +00004053 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4054 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004055 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004056
John McCall45d55e42010-05-07 21:00:08 +00004057 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004058 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004059 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004060
4061 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004062 if (E->getOpcode() == BO_Sub)
4063 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004064
Ted Kremenek28831752012-08-23 20:46:57 +00004065 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004066 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4067 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004068}
Eli Friedman9a156e52008-11-12 09:44:48 +00004069
John McCall45d55e42010-05-07 21:00:08 +00004070bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4071 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004072}
Mike Stump11289f42009-09-09 15:08:12 +00004073
Peter Collingbournee9200682011-05-13 03:29:01 +00004074bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4075 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004076
Eli Friedman847a2bc2009-12-27 05:43:15 +00004077 switch (E->getCastKind()) {
4078 default:
4079 break;
4080
John McCalle3027922010-08-25 11:45:40 +00004081 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004082 case CK_CPointerToObjCPointerCast:
4083 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004084 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004085 if (!Visit(SubExpr))
4086 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004087 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4088 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4089 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004090 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004091 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004092 if (SubExpr->getType()->isVoidPointerType())
4093 CCEDiag(E, diag::note_constexpr_invalid_cast)
4094 << 3 << SubExpr->getType();
4095 else
4096 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4097 }
Richard Smith96e0c102011-11-04 02:25:55 +00004098 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004099
Anders Carlsson18275092010-10-31 20:41:46 +00004100 case CK_DerivedToBase:
4101 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004102 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004103 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004104 if (!Result.Base && Result.Offset.isZero())
4105 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004106
Richard Smithd62306a2011-11-10 06:34:14 +00004107 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004108 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00004109 QualType Type =
4110 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00004111
Richard Smithd62306a2011-11-10 06:34:14 +00004112 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00004113 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004114 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
4115 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00004116 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004117 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00004118 }
4119
Anders Carlsson18275092010-10-31 20:41:46 +00004120 return true;
4121 }
4122
Richard Smith027bf112011-11-17 22:56:20 +00004123 case CK_BaseToDerived:
4124 if (!Visit(E->getSubExpr()))
4125 return false;
4126 if (!Result.Base && Result.Offset.isZero())
4127 return true;
4128 return HandleBaseToDerivedCast(Info, E, Result);
4129
Richard Smith0b0a0b62011-10-29 20:57:55 +00004130 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004131 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004132 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004133
John McCalle3027922010-08-25 11:45:40 +00004134 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004135 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4136
Richard Smith2e312c82012-03-03 22:46:17 +00004137 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004138 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004139 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004140
John McCall45d55e42010-05-07 21:00:08 +00004141 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004142 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4143 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00004144 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004145 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004146 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004147 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004148 return true;
4149 } else {
4150 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004151 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004152 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004153 }
4154 }
John McCalle3027922010-08-25 11:45:40 +00004155 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004156 if (SubExpr->isGLValue()) {
4157 if (!EvaluateLValue(SubExpr, Result, Info))
4158 return false;
4159 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004160 Result.set(SubExpr, Info.CurrentCall->Index);
4161 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
4162 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004163 return false;
4164 }
Richard Smith96e0c102011-11-04 02:25:55 +00004165 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004166 if (const ConstantArrayType *CAT
4167 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4168 Result.addArray(Info, E, CAT);
4169 else
4170 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004171 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004172
John McCalle3027922010-08-25 11:45:40 +00004173 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004174 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004175 }
4176
Richard Smith11562c52011-10-28 17:51:58 +00004177 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004178}
Chris Lattner05706e882008-07-11 18:11:29 +00004179
Peter Collingbournee9200682011-05-13 03:29:01 +00004180bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004181 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004182 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004183
Peter Collingbournee9200682011-05-13 03:29:01 +00004184 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004185}
Chris Lattner05706e882008-07-11 18:11:29 +00004186
4187//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004188// Member Pointer Evaluation
4189//===----------------------------------------------------------------------===//
4190
4191namespace {
4192class MemberPointerExprEvaluator
4193 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4194 MemberPtr &Result;
4195
4196 bool Success(const ValueDecl *D) {
4197 Result = MemberPtr(D);
4198 return true;
4199 }
4200public:
4201
4202 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4203 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4204
Richard Smith2e312c82012-03-03 22:46:17 +00004205 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004206 Result.setFrom(V);
4207 return true;
4208 }
Richard Smithfddd3842011-12-30 21:15:51 +00004209 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004210 return Success((const ValueDecl*)0);
4211 }
4212
4213 bool VisitCastExpr(const CastExpr *E);
4214 bool VisitUnaryAddrOf(const UnaryOperator *E);
4215};
4216} // end anonymous namespace
4217
4218static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4219 EvalInfo &Info) {
4220 assert(E->isRValue() && E->getType()->isMemberPointerType());
4221 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4222}
4223
4224bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4225 switch (E->getCastKind()) {
4226 default:
4227 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4228
4229 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004230 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004231 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004232
4233 case CK_BaseToDerivedMemberPointer: {
4234 if (!Visit(E->getSubExpr()))
4235 return false;
4236 if (E->path_empty())
4237 return true;
4238 // Base-to-derived member pointer casts store the path in derived-to-base
4239 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4240 // the wrong end of the derived->base arc, so stagger the path by one class.
4241 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4242 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4243 PathI != PathE; ++PathI) {
4244 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4245 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4246 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004247 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004248 }
4249 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4250 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004251 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004252 return true;
4253 }
4254
4255 case CK_DerivedToBaseMemberPointer:
4256 if (!Visit(E->getSubExpr()))
4257 return false;
4258 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4259 PathE = E->path_end(); PathI != PathE; ++PathI) {
4260 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4261 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4262 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004263 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004264 }
4265 return true;
4266 }
4267}
4268
4269bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4270 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4271 // member can be formed.
4272 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4273}
4274
4275//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004276// Record Evaluation
4277//===----------------------------------------------------------------------===//
4278
4279namespace {
4280 class RecordExprEvaluator
4281 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4282 const LValue &This;
4283 APValue &Result;
4284 public:
4285
4286 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4287 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4288
Richard Smith2e312c82012-03-03 22:46:17 +00004289 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004290 Result = V;
4291 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00004292 }
Richard Smithfddd3842011-12-30 21:15:51 +00004293 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004294
Richard Smithe97cbd72011-11-11 04:05:33 +00004295 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00004296 bool VisitInitListExpr(const InitListExpr *E);
4297 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
4298 };
4299}
4300
Richard Smithfddd3842011-12-30 21:15:51 +00004301/// Perform zero-initialization on an object of non-union class type.
4302/// C++11 [dcl.init]p5:
4303/// To zero-initialize an object or reference of type T means:
4304/// [...]
4305/// -- if T is a (possibly cv-qualified) non-union class type,
4306/// each non-static data member and each base-class subobject is
4307/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00004308static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4309 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00004310 const LValue &This, APValue &Result) {
4311 assert(!RD->isUnion() && "Expected non-union class type");
4312 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4313 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4314 std::distance(RD->field_begin(), RD->field_end()));
4315
John McCalld7bca762012-05-01 00:38:49 +00004316 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004317 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4318
4319 if (CD) {
4320 unsigned Index = 0;
4321 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004322 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00004323 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4324 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004325 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4326 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004327 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00004328 Result.getStructBase(Index)))
4329 return false;
4330 }
4331 }
4332
Richard Smitha8105bc2012-01-06 16:39:00 +00004333 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4334 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00004335 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004336 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00004337 continue;
4338
4339 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004340 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004341 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004342
David Blaikie2d7c57e2012-04-30 02:36:29 +00004343 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004344 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00004345 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004346 return false;
4347 }
4348
4349 return true;
4350}
4351
4352bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4353 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004354 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00004355 if (RD->isUnion()) {
4356 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4357 // object's first non-static named data member is zero-initialized
4358 RecordDecl::field_iterator I = RD->field_begin();
4359 if (I == RD->field_end()) {
4360 Result = APValue((const FieldDecl*)0);
4361 return true;
4362 }
4363
4364 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00004365 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00004366 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00004367 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00004368 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00004369 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004370 }
4371
Richard Smith5d108602012-02-17 00:44:16 +00004372 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004373 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00004374 return false;
4375 }
4376
Richard Smitha8105bc2012-01-06 16:39:00 +00004377 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00004378}
4379
Richard Smithe97cbd72011-11-11 04:05:33 +00004380bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4381 switch (E->getCastKind()) {
4382 default:
4383 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4384
4385 case CK_ConstructorConversion:
4386 return Visit(E->getSubExpr());
4387
4388 case CK_DerivedToBase:
4389 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00004390 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004391 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00004392 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004393 if (!DerivedObject.isStruct())
4394 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00004395
4396 // Derived-to-base rvalue conversion: just slice off the derived part.
4397 APValue *Value = &DerivedObject;
4398 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4399 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4400 PathE = E->path_end(); PathI != PathE; ++PathI) {
4401 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4402 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4403 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4404 RD = Base;
4405 }
4406 Result = *Value;
4407 return true;
4408 }
4409 }
4410}
4411
Richard Smithd62306a2011-11-10 06:34:14 +00004412bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00004413 // Cannot constant-evaluate std::initializer_list inits.
4414 if (E->initializesStdInitializerList())
4415 return false;
4416
Richard Smithd62306a2011-11-10 06:34:14 +00004417 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00004418 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004419 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4420
4421 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00004422 const FieldDecl *Field = E->getInitializedFieldInUnion();
4423 Result = APValue(Field);
4424 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00004425 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00004426
4427 // If the initializer list for a union does not contain any elements, the
4428 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00004429 // FIXME: The element should be initialized from an initializer list.
4430 // Is this difference ever observable for initializer lists which
4431 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00004432 ImplicitValueInitExpr VIE(Field->getType());
4433 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4434
Richard Smithd62306a2011-11-10 06:34:14 +00004435 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00004436 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4437 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00004438
4439 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4440 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4441 isa<CXXDefaultInitExpr>(InitExpr));
4442
Richard Smithb228a862012-02-15 02:18:13 +00004443 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00004444 }
4445
4446 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4447 "initializer list for class with base classes");
4448 Result = APValue(APValue::UninitStruct(), 0,
4449 std::distance(RD->field_begin(), RD->field_end()));
4450 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00004451 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004452 for (RecordDecl::field_iterator Field = RD->field_begin(),
4453 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4454 // Anonymous bit-fields are not considered members of the class for
4455 // purposes of aggregate initialization.
4456 if (Field->isUnnamedBitfield())
4457 continue;
4458
4459 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00004460
Richard Smith253c2a32012-01-27 01:14:48 +00004461 bool HaveInit = ElementNo < E->getNumInits();
4462
4463 // FIXME: Diagnostics here should point to the end of the initializer
4464 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00004465 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00004466 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004467 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004468
4469 // Perform an implicit value-initialization for members beyond the end of
4470 // the initializer list.
4471 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00004472 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00004473
Richard Smith852c9db2013-04-20 22:23:05 +00004474 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4475 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4476 isa<CXXDefaultInitExpr>(Init));
4477
4478 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4479 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00004480 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00004481 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004482 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00004483 }
4484 }
4485
Richard Smith253c2a32012-01-27 01:14:48 +00004486 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004487}
4488
4489bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4490 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00004491 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4492
Richard Smithfddd3842011-12-30 21:15:51 +00004493 bool ZeroInit = E->requiresZeroInitialization();
4494 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004495 // If we've already performed zero-initialization, we're already done.
4496 if (!Result.isUninit())
4497 return true;
4498
Richard Smithfddd3842011-12-30 21:15:51 +00004499 if (ZeroInit)
4500 return ZeroInitialization(E);
4501
Richard Smithcc36f692011-12-22 02:22:31 +00004502 const CXXRecordDecl *RD = FD->getParent();
4503 if (RD->isUnion())
4504 Result = APValue((FieldDecl*)0);
4505 else
4506 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4507 std::distance(RD->field_begin(), RD->field_end()));
4508 return true;
4509 }
4510
Richard Smithd62306a2011-11-10 06:34:14 +00004511 const FunctionDecl *Definition = 0;
4512 FD->getBody(Definition);
4513
Richard Smith357362d2011-12-13 06:39:58 +00004514 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4515 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004516
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004517 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00004518 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00004519 if (const MaterializeTemporaryExpr *ME
4520 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4521 return Visit(ME->GetTemporaryExpr());
4522
Richard Smithfddd3842011-12-30 21:15:51 +00004523 if (ZeroInit && !ZeroInitialization(E))
4524 return false;
4525
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004526 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004527 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004528 cast<CXXConstructorDecl>(Definition), Info,
4529 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00004530}
4531
4532static bool EvaluateRecord(const Expr *E, const LValue &This,
4533 APValue &Result, EvalInfo &Info) {
4534 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00004535 "can't evaluate expression as a record rvalue");
4536 return RecordExprEvaluator(Info, This, Result).Visit(E);
4537}
4538
4539//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004540// Temporary Evaluation
4541//
4542// Temporaries are represented in the AST as rvalues, but generally behave like
4543// lvalues. The full-object of which the temporary is a subobject is implicitly
4544// materialized so that a reference can bind to it.
4545//===----------------------------------------------------------------------===//
4546namespace {
4547class TemporaryExprEvaluator
4548 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4549public:
4550 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4551 LValueExprEvaluatorBaseTy(Info, Result) {}
4552
4553 /// Visit an expression which constructs the value of this temporary.
4554 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00004555 Result.set(E, Info.CurrentCall->Index);
4556 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00004557 }
4558
4559 bool VisitCastExpr(const CastExpr *E) {
4560 switch (E->getCastKind()) {
4561 default:
4562 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4563
4564 case CK_ConstructorConversion:
4565 return VisitConstructExpr(E->getSubExpr());
4566 }
4567 }
4568 bool VisitInitListExpr(const InitListExpr *E) {
4569 return VisitConstructExpr(E);
4570 }
4571 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4572 return VisitConstructExpr(E);
4573 }
4574 bool VisitCallExpr(const CallExpr *E) {
4575 return VisitConstructExpr(E);
4576 }
4577};
4578} // end anonymous namespace
4579
4580/// Evaluate an expression of record type as a temporary.
4581static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004582 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00004583 return TemporaryExprEvaluator(Info, Result).Visit(E);
4584}
4585
4586//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004587// Vector Evaluation
4588//===----------------------------------------------------------------------===//
4589
4590namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004591 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00004592 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4593 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004594 public:
Mike Stump11289f42009-09-09 15:08:12 +00004595
Richard Smith2d406342011-10-22 21:10:00 +00004596 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4597 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004598
Richard Smith2d406342011-10-22 21:10:00 +00004599 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4600 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4601 // FIXME: remove this APValue copy.
4602 Result = APValue(V.data(), V.size());
4603 return true;
4604 }
Richard Smith2e312c82012-03-03 22:46:17 +00004605 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004606 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00004607 Result = V;
4608 return true;
4609 }
Richard Smithfddd3842011-12-30 21:15:51 +00004610 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004611
Richard Smith2d406342011-10-22 21:10:00 +00004612 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00004613 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00004614 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00004615 bool VisitInitListExpr(const InitListExpr *E);
4616 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004617 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00004618 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00004619 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004620 };
4621} // end anonymous namespace
4622
4623static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004624 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00004625 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004626}
4627
Richard Smith2d406342011-10-22 21:10:00 +00004628bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
4629 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004630 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004631
Richard Smith161f09a2011-12-06 22:44:34 +00004632 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00004633 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004634
Eli Friedmanc757de22011-03-25 00:43:55 +00004635 switch (E->getCastKind()) {
4636 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00004637 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00004638 if (SETy->isIntegerType()) {
4639 APSInt IntResult;
4640 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004641 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004642 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00004643 } else if (SETy->isRealFloatingType()) {
4644 APFloat F(0.0);
4645 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004646 return false;
Richard Smith2d406342011-10-22 21:10:00 +00004647 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00004648 } else {
Richard Smith2d406342011-10-22 21:10:00 +00004649 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004650 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00004651
4652 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00004653 SmallVector<APValue, 4> Elts(NElts, Val);
4654 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00004655 }
Eli Friedman803acb32011-12-22 03:51:45 +00004656 case CK_BitCast: {
4657 // Evaluate the operand into an APInt we can extract from.
4658 llvm::APInt SValInt;
4659 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4660 return false;
4661 // Extract the elements
4662 QualType EltTy = VTy->getElementType();
4663 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4664 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4665 SmallVector<APValue, 4> Elts;
4666 if (EltTy->isRealFloatingType()) {
4667 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00004668 unsigned FloatEltSize = EltSize;
4669 if (&Sem == &APFloat::x87DoubleExtended)
4670 FloatEltSize = 80;
4671 for (unsigned i = 0; i < NElts; i++) {
4672 llvm::APInt Elt;
4673 if (BigEndian)
4674 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4675 else
4676 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00004677 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00004678 }
4679 } else if (EltTy->isIntegerType()) {
4680 for (unsigned i = 0; i < NElts; i++) {
4681 llvm::APInt Elt;
4682 if (BigEndian)
4683 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4684 else
4685 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4686 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4687 }
4688 } else {
4689 return Error(E);
4690 }
4691 return Success(Elts, E);
4692 }
Eli Friedmanc757de22011-03-25 00:43:55 +00004693 default:
Richard Smith11562c52011-10-28 17:51:58 +00004694 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004695 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004696}
4697
Richard Smith2d406342011-10-22 21:10:00 +00004698bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004699VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004700 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004701 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00004702 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00004703
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004704 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004705 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004706
Eli Friedmanb9c71292012-01-03 23:24:20 +00004707 // The number of initializers can be less than the number of
4708 // vector elements. For OpenCL, this can be due to nested vector
4709 // initialization. For GCC compatibility, missing trailing elements
4710 // should be initialized with zeroes.
4711 unsigned CountInits = 0, CountElts = 0;
4712 while (CountElts < NumElements) {
4713 // Handle nested vector initialization.
4714 if (CountInits < NumInits
4715 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4716 APValue v;
4717 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4718 return Error(E);
4719 unsigned vlen = v.getVectorLength();
4720 for (unsigned j = 0; j < vlen; j++)
4721 Elements.push_back(v.getVectorElt(j));
4722 CountElts += vlen;
4723 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004724 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004725 if (CountInits < NumInits) {
4726 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004727 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004728 } else // trailing integer zero.
4729 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4730 Elements.push_back(APValue(sInt));
4731 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004732 } else {
4733 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00004734 if (CountInits < NumInits) {
4735 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00004736 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00004737 } else // trailing float zero.
4738 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4739 Elements.push_back(APValue(f));
4740 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00004741 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00004742 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004743 }
Richard Smith2d406342011-10-22 21:10:00 +00004744 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004745}
4746
Richard Smith2d406342011-10-22 21:10:00 +00004747bool
Richard Smithfddd3842011-12-30 21:15:51 +00004748VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00004749 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00004750 QualType EltTy = VT->getElementType();
4751 APValue ZeroElement;
4752 if (EltTy->isIntegerType())
4753 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4754 else
4755 ZeroElement =
4756 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4757
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004758 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00004759 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004760}
4761
Richard Smith2d406342011-10-22 21:10:00 +00004762bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00004763 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004764 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00004765}
4766
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004767//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00004768// Array Evaluation
4769//===----------------------------------------------------------------------===//
4770
4771namespace {
4772 class ArrayExprEvaluator
4773 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00004774 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00004775 APValue &Result;
4776 public:
4777
Richard Smithd62306a2011-11-10 06:34:14 +00004778 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
4779 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00004780
4781 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00004782 assert((V.isArray() || V.isLValue()) &&
4783 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00004784 Result = V;
4785 return true;
4786 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004787
Richard Smithfddd3842011-12-30 21:15:51 +00004788 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004789 const ConstantArrayType *CAT =
4790 Info.Ctx.getAsConstantArrayType(E->getType());
4791 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004792 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004793
4794 Result = APValue(APValue::UninitArray(), 0,
4795 CAT->getSize().getZExtValue());
4796 if (!Result.hasArrayFiller()) return true;
4797
Richard Smithfddd3842011-12-30 21:15:51 +00004798 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00004799 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004800 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00004801 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00004802 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00004803 }
4804
Richard Smithf3e9e432011-11-07 09:22:26 +00004805 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00004806 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00004807 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
4808 const LValue &Subobject,
4809 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00004810 };
4811} // end anonymous namespace
4812
Richard Smithd62306a2011-11-10 06:34:14 +00004813static bool EvaluateArray(const Expr *E, const LValue &This,
4814 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00004815 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00004816 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004817}
4818
4819bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4820 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
4821 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004822 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00004823
Richard Smithca2cfbf2011-12-22 01:07:19 +00004824 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
4825 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00004826 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00004827 LValue LV;
4828 if (!EvaluateLValue(E->getInit(0), LV, Info))
4829 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004830 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00004831 LV.moveInto(Val);
4832 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00004833 }
4834
Richard Smith253c2a32012-01-27 01:14:48 +00004835 bool Success = true;
4836
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004837 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
4838 "zero-initialized array shouldn't have any initialized elts");
4839 APValue Filler;
4840 if (Result.isArray() && Result.hasArrayFiller())
4841 Filler = Result.getArrayFiller();
4842
Richard Smith9543c5e2013-04-22 14:44:29 +00004843 unsigned NumEltsToInit = E->getNumInits();
4844 unsigned NumElts = CAT->getSize().getZExtValue();
4845 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
4846
4847 // If the initializer might depend on the array index, run it for each
4848 // array element. For now, just whitelist non-class value-initialization.
4849 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
4850 NumEltsToInit = NumElts;
4851
4852 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004853
4854 // If the array was previously zero-initialized, preserve the
4855 // zero-initialized values.
4856 if (!Filler.isUninit()) {
4857 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
4858 Result.getArrayInitializedElt(I) = Filler;
4859 if (Result.hasArrayFiller())
4860 Result.getArrayFiller() = Filler;
4861 }
4862
Richard Smithd62306a2011-11-10 06:34:14 +00004863 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00004864 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00004865 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
4866 const Expr *Init =
4867 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00004868 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00004869 Info, Subobject, Init) ||
4870 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00004871 CAT->getElementType(), 1)) {
4872 if (!Info.keepEvaluatingAfterFailure())
4873 return false;
4874 Success = false;
4875 }
Richard Smithd62306a2011-11-10 06:34:14 +00004876 }
Richard Smithf3e9e432011-11-07 09:22:26 +00004877
Richard Smith9543c5e2013-04-22 14:44:29 +00004878 if (!Result.hasArrayFiller())
4879 return Success;
4880
4881 // If we get here, we have a trivial filler, which we can just evaluate
4882 // once and splat over the rest of the array elements.
4883 assert(FillerExpr && "no array filler for incomplete init list");
4884 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
4885 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00004886}
4887
Richard Smith027bf112011-11-17 22:56:20 +00004888bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004889 return VisitCXXConstructExpr(E, This, &Result, E->getType());
4890}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004891
Richard Smith9543c5e2013-04-22 14:44:29 +00004892bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
4893 const LValue &Subobject,
4894 APValue *Value,
4895 QualType Type) {
4896 bool HadZeroInit = !Value->isUninit();
4897
4898 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
4899 unsigned N = CAT->getSize().getZExtValue();
4900
4901 // Preserve the array filler if we had prior zero-initialization.
4902 APValue Filler =
4903 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
4904 : APValue();
4905
4906 *Value = APValue(APValue::UninitArray(), N, N);
4907
4908 if (HadZeroInit)
4909 for (unsigned I = 0; I != N; ++I)
4910 Value->getArrayInitializedElt(I) = Filler;
4911
4912 // Initialize the elements.
4913 LValue ArrayElt = Subobject;
4914 ArrayElt.addArray(Info, E, CAT);
4915 for (unsigned I = 0; I != N; ++I)
4916 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
4917 CAT->getElementType()) ||
4918 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
4919 CAT->getElementType(), 1))
4920 return false;
4921
4922 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004923 }
Richard Smith027bf112011-11-17 22:56:20 +00004924
Richard Smith9543c5e2013-04-22 14:44:29 +00004925 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00004926 return Error(E);
4927
Richard Smith027bf112011-11-17 22:56:20 +00004928 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00004929
Richard Smithfddd3842011-12-30 21:15:51 +00004930 bool ZeroInit = E->requiresZeroInitialization();
4931 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00004932 if (HadZeroInit)
4933 return true;
4934
Richard Smithfddd3842011-12-30 21:15:51 +00004935 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004936 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004937 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00004938 }
4939
Richard Smithcc36f692011-12-22 02:22:31 +00004940 const CXXRecordDecl *RD = FD->getParent();
4941 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004942 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00004943 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004944 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00004945 APValue(APValue::UninitStruct(), RD->getNumBases(),
4946 std::distance(RD->field_begin(), RD->field_end()));
4947 return true;
4948 }
4949
Richard Smith027bf112011-11-17 22:56:20 +00004950 const FunctionDecl *Definition = 0;
4951 FD->getBody(Definition);
4952
Richard Smith357362d2011-12-13 06:39:58 +00004953 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4954 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004955
Richard Smith9eae7232012-01-12 18:54:33 +00004956 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00004957 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004958 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00004959 return false;
4960 }
4961
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004962 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00004963 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00004964 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00004965 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00004966}
4967
Richard Smithf3e9e432011-11-07 09:22:26 +00004968//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004969// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004970//
4971// As a GNU extension, we support casting pointers to sufficiently-wide integer
4972// types and back in constant folding. Integer values are thus represented
4973// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00004974//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004975
4976namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004977class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004978 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00004979 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004980public:
Richard Smith2e312c82012-03-03 22:46:17 +00004981 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004982 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004983
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004984 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004985 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00004986 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004987 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004988 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004989 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004990 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004991 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004992 return true;
4993 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004994 bool Success(const llvm::APSInt &SI, const Expr *E) {
4995 return Success(SI, E, Result);
4996 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004997
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004998 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004999 assert(E->getType()->isIntegralOrEnumerationType() &&
5000 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005001 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005002 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005003 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005004 Result.getInt().setIsUnsigned(
5005 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005006 return true;
5007 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005008 bool Success(const llvm::APInt &I, const Expr *E) {
5009 return Success(I, E, Result);
5010 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005011
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005012 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005013 assert(E->getType()->isIntegralOrEnumerationType() &&
5014 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005015 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005016 return true;
5017 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005018 bool Success(uint64_t Value, const Expr *E) {
5019 return Success(Value, E, Result);
5020 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005021
Ken Dyckdbc01912011-03-11 02:13:43 +00005022 bool Success(CharUnits Size, const Expr *E) {
5023 return Success(Size.getQuantity(), E);
5024 }
5025
Richard Smith2e312c82012-03-03 22:46:17 +00005026 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005027 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005028 Result = V;
5029 return true;
5030 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005031 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005032 }
Mike Stump11289f42009-09-09 15:08:12 +00005033
Richard Smithfddd3842011-12-30 21:15:51 +00005034 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005035
Peter Collingbournee9200682011-05-13 03:29:01 +00005036 //===--------------------------------------------------------------------===//
5037 // Visitor Methods
5038 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005039
Chris Lattner7174bf32008-07-12 00:38:25 +00005040 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005041 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005042 }
5043 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005044 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005045 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005046
5047 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5048 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005049 if (CheckReferencedDecl(E, E->getDecl()))
5050 return true;
5051
5052 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005053 }
5054 bool VisitMemberExpr(const MemberExpr *E) {
5055 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005056 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005057 return true;
5058 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005059
5060 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005061 }
5062
Peter Collingbournee9200682011-05-13 03:29:01 +00005063 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005064 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005065 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005066 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005067
Peter Collingbournee9200682011-05-13 03:29:01 +00005068 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005069 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005070
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005071 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005072 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005073 }
Mike Stump11289f42009-09-09 15:08:12 +00005074
Ted Kremeneke65b0862012-03-06 20:05:56 +00005075 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5076 return Success(E->getValue(), E);
5077 }
5078
Richard Smith4ce706a2011-10-11 21:43:33 +00005079 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005080 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005081 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005082 }
5083
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005084 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00005085 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005086 }
5087
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005088 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5089 return Success(E->getValue(), E);
5090 }
5091
Douglas Gregor29c42f22012-02-24 07:38:34 +00005092 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5093 return Success(E->getValue(), E);
5094 }
5095
John Wiegley6242b6a2011-04-28 00:16:57 +00005096 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5097 return Success(E->getValue(), E);
5098 }
5099
John Wiegleyf9f65842011-04-25 06:54:41 +00005100 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5101 return Success(E->getValue(), E);
5102 }
5103
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005104 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005105 bool VisitUnaryImag(const UnaryOperator *E);
5106
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005107 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005108 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005109
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005110private:
Ken Dyck160146e2010-01-27 17:10:57 +00005111 CharUnits GetAlignOfExpr(const Expr *E);
5112 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005113 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005114 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005115 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005116};
Chris Lattner05706e882008-07-11 18:11:29 +00005117} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005118
Richard Smith11562c52011-10-28 17:51:58 +00005119/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5120/// produce either the integer value or a pointer.
5121///
5122/// GCC has a heinous extension which folds casts between pointer types and
5123/// pointer-sized integral types. We support this by allowing the evaluation of
5124/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5125/// Some simple arithmetic on such values is supported (they are treated much
5126/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005127static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005128 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005129 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005130 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005131}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005132
Richard Smithf57d8cb2011-12-09 22:58:01 +00005133static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005134 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005135 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005136 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005137 if (!Val.isInt()) {
5138 // FIXME: It would be better to produce the diagnostic for casting
5139 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005140 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005141 return false;
5142 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005143 Result = Val.getInt();
5144 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005145}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005146
Richard Smithf57d8cb2011-12-09 22:58:01 +00005147/// Check whether the given declaration can be directly converted to an integral
5148/// rvalue. If not, no diagnostic is produced; there are other things we can
5149/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005150bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005151 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005152 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005153 // Check for signedness/width mismatches between E type and ECD value.
5154 bool SameSign = (ECD->getInitVal().isSigned()
5155 == E->getType()->isSignedIntegerOrEnumerationType());
5156 bool SameWidth = (ECD->getInitVal().getBitWidth()
5157 == Info.Ctx.getIntWidth(E->getType()));
5158 if (SameSign && SameWidth)
5159 return Success(ECD->getInitVal(), E);
5160 else {
5161 // Get rid of mismatch (otherwise Success assertions will fail)
5162 // by computing a new value matching the type of E.
5163 llvm::APSInt Val = ECD->getInitVal();
5164 if (!SameSign)
5165 Val.setIsSigned(!ECD->getInitVal().isSigned());
5166 if (!SameWidth)
5167 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5168 return Success(Val, E);
5169 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005170 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005171 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005172}
5173
Chris Lattner86ee2862008-10-06 06:40:35 +00005174/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5175/// as GCC.
5176static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5177 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005178 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005179 enum gcc_type_class {
5180 no_type_class = -1,
5181 void_type_class, integer_type_class, char_type_class,
5182 enumeral_type_class, boolean_type_class,
5183 pointer_type_class, reference_type_class, offset_type_class,
5184 real_type_class, complex_type_class,
5185 function_type_class, method_type_class,
5186 record_type_class, union_type_class,
5187 array_type_class, string_type_class,
5188 lang_type_class
5189 };
Mike Stump11289f42009-09-09 15:08:12 +00005190
5191 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005192 // ideal, however it is what gcc does.
5193 if (E->getNumArgs() == 0)
5194 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005195
Chris Lattner86ee2862008-10-06 06:40:35 +00005196 QualType ArgTy = E->getArg(0)->getType();
5197 if (ArgTy->isVoidType())
5198 return void_type_class;
5199 else if (ArgTy->isEnumeralType())
5200 return enumeral_type_class;
5201 else if (ArgTy->isBooleanType())
5202 return boolean_type_class;
5203 else if (ArgTy->isCharType())
5204 return string_type_class; // gcc doesn't appear to use char_type_class
5205 else if (ArgTy->isIntegerType())
5206 return integer_type_class;
5207 else if (ArgTy->isPointerType())
5208 return pointer_type_class;
5209 else if (ArgTy->isReferenceType())
5210 return reference_type_class;
5211 else if (ArgTy->isRealType())
5212 return real_type_class;
5213 else if (ArgTy->isComplexType())
5214 return complex_type_class;
5215 else if (ArgTy->isFunctionType())
5216 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005217 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005218 return record_type_class;
5219 else if (ArgTy->isUnionType())
5220 return union_type_class;
5221 else if (ArgTy->isArrayType())
5222 return array_type_class;
5223 else if (ArgTy->isUnionType())
5224 return union_type_class;
5225 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005226 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005227}
5228
Richard Smith5fab0c92011-12-28 19:48:30 +00005229/// EvaluateBuiltinConstantPForLValue - Determine the result of
5230/// __builtin_constant_p when applied to the given lvalue.
5231///
5232/// An lvalue is only "constant" if it is a pointer or reference to the first
5233/// character of a string literal.
5234template<typename LValue>
5235static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005236 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005237 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5238}
5239
5240/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5241/// GCC as we can manage.
5242static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5243 QualType ArgType = Arg->getType();
5244
5245 // __builtin_constant_p always has one operand. The rules which gcc follows
5246 // are not precisely documented, but are as follows:
5247 //
5248 // - If the operand is of integral, floating, complex or enumeration type,
5249 // and can be folded to a known value of that type, it returns 1.
5250 // - If the operand and can be folded to a pointer to the first character
5251 // of a string literal (or such a pointer cast to an integral type), it
5252 // returns 1.
5253 //
5254 // Otherwise, it returns 0.
5255 //
5256 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5257 // its support for this does not currently work.
5258 if (ArgType->isIntegralOrEnumerationType()) {
5259 Expr::EvalResult Result;
5260 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5261 return false;
5262
5263 APValue &V = Result.Val;
5264 if (V.getKind() == APValue::Int)
5265 return true;
5266
5267 return EvaluateBuiltinConstantPForLValue(V);
5268 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5269 return Arg->isEvaluatable(Ctx);
5270 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5271 LValue LV;
5272 Expr::EvalStatus Status;
5273 EvalInfo Info(Ctx, Status);
5274 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5275 : EvaluatePointer(Arg, LV, Info)) &&
5276 !Status.HasSideEffects)
5277 return EvaluateBuiltinConstantPForLValue(LV);
5278 }
5279
5280 // Anything else isn't considered to be sufficiently constant.
5281 return false;
5282}
5283
John McCall95007602010-05-10 23:27:23 +00005284/// Retrieves the "underlying object type" of the given expression,
5285/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00005286QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5287 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5288 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00005289 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00005290 } else if (const Expr *E = B.get<const Expr*>()) {
5291 if (isa<CompoundLiteralExpr>(E))
5292 return E->getType();
John McCall95007602010-05-10 23:27:23 +00005293 }
5294
5295 return QualType();
5296}
5297
Peter Collingbournee9200682011-05-13 03:29:01 +00005298bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00005299 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00005300
5301 {
5302 // The operand of __builtin_object_size is never evaluated for side-effects.
5303 // If there are any, but we can determine the pointed-to object anyway, then
5304 // ignore the side-effects.
5305 SpeculativeEvaluationRAII SpeculativeEval(Info);
5306 if (!EvaluatePointer(E->getArg(0), Base, Info))
5307 return false;
5308 }
John McCall95007602010-05-10 23:27:23 +00005309
5310 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00005311 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00005312
Richard Smithce40ad62011-11-12 22:28:03 +00005313 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00005314 if (T.isNull() ||
5315 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00005316 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00005317 T->isVariablyModifiedType() ||
5318 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005319 return Error(E);
John McCall95007602010-05-10 23:27:23 +00005320
5321 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5322 CharUnits Offset = Base.getLValueOffset();
5323
5324 if (!Offset.isNegative() && Offset <= Size)
5325 Size -= Offset;
5326 else
5327 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00005328 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00005329}
5330
Peter Collingbournee9200682011-05-13 03:29:01 +00005331bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00005332 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005333 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00005334 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005335
5336 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00005337 if (TryEvaluateBuiltinObjectSize(E))
5338 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00005339
Richard Smith0421ce72012-08-07 04:16:51 +00005340 // If evaluating the argument has side-effects, we can't determine the size
5341 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5342 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005343 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00005344 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00005345 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00005346 return Success(0, E);
5347 }
Mike Stump876387b2009-10-27 22:09:17 +00005348
Richard Smith01ade172012-05-23 04:13:20 +00005349 // Expression had no side effects, but we couldn't statically determine the
5350 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005351 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00005352 }
5353
Benjamin Kramera801f4a2012-10-06 14:42:22 +00005354 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00005355 case Builtin::BI__builtin_bswap32:
5356 case Builtin::BI__builtin_bswap64: {
5357 APSInt Val;
5358 if (!EvaluateInteger(E->getArg(0), Val, Info))
5359 return false;
5360
5361 return Success(Val.byteSwap(), E);
5362 }
5363
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005364 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005365 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00005366
Richard Smith5fab0c92011-12-28 19:48:30 +00005367 case Builtin::BI__builtin_constant_p:
5368 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00005369
Chris Lattnerd545ad12009-09-23 06:06:36 +00005370 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00005371 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00005372 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00005373 return Success(Operand, E);
5374 }
Eli Friedmand5c93992010-02-13 00:10:10 +00005375
5376 case Builtin::BI__builtin_expect:
5377 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00005378
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005379 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00005380 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005381 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00005382 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00005383 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5384 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00005385 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00005386 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005387 case Builtin::BI__builtin_strlen:
5388 // As an extension, we support strlen() and __builtin_strlen() as constant
5389 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00005390 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005391 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5392 // The string literal may have embedded null characters. Find the first
5393 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005394 StringRef Str = S->getString();
5395 StringRef::size_type Pos = Str.find(0);
5396 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00005397 Str = Str.substr(0, Pos);
5398
5399 return Success(Str.size(), E);
5400 }
5401
Richard Smithf57d8cb2011-12-09 22:58:01 +00005402 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005403
Richard Smith01ba47d2012-04-13 00:45:38 +00005404 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00005405 case Builtin::BI__atomic_is_lock_free:
5406 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00005407 APSInt SizeVal;
5408 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5409 return false;
5410
5411 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5412 // of two less than the maximum inline atomic width, we know it is
5413 // lock-free. If the size isn't a power of two, or greater than the
5414 // maximum alignment where we promote atomics, we know it is not lock-free
5415 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5416 // the answer can only be determined at runtime; for example, 16-byte
5417 // atomics have lock-free implementations on some, but not all,
5418 // x86-64 processors.
5419
5420 // Check power-of-two.
5421 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00005422 if (Size.isPowerOfTwo()) {
5423 // Check against inlining width.
5424 unsigned InlineWidthBits =
5425 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5426 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5427 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5428 Size == CharUnits::One() ||
5429 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5430 Expr::NPC_NeverValueDependent))
5431 // OK, we will inline appropriately-aligned operations of this size,
5432 // and _Atomic(T) is appropriately-aligned.
5433 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005434
Richard Smith01ba47d2012-04-13 00:45:38 +00005435 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5436 castAs<PointerType>()->getPointeeType();
5437 if (!PointeeType->isIncompleteType() &&
5438 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5439 // OK, we will inline operations on this object.
5440 return Success(1, E);
5441 }
5442 }
5443 }
Eli Friedmana4c26022011-10-17 21:44:23 +00005444
Richard Smith01ba47d2012-04-13 00:45:38 +00005445 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5446 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00005447 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005448 }
Chris Lattner7174bf32008-07-12 00:38:25 +00005449}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005450
Richard Smith8b3497e2011-10-31 01:37:14 +00005451static bool HasSameBase(const LValue &A, const LValue &B) {
5452 if (!A.getLValueBase())
5453 return !B.getLValueBase();
5454 if (!B.getLValueBase())
5455 return false;
5456
Richard Smithce40ad62011-11-12 22:28:03 +00005457 if (A.getLValueBase().getOpaqueValue() !=
5458 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005459 const Decl *ADecl = GetLValueBaseDecl(A);
5460 if (!ADecl)
5461 return false;
5462 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00005463 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00005464 return false;
5465 }
5466
5467 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00005468 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00005469}
5470
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005471namespace {
Richard Smith11562c52011-10-28 17:51:58 +00005472
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005473/// \brief Data recursive integer evaluator of certain binary operators.
5474///
5475/// We use a data recursive algorithm for binary operators so that we are able
5476/// to handle extreme cases of chained binary operators without causing stack
5477/// overflow.
5478class DataRecursiveIntBinOpEvaluator {
5479 struct EvalResult {
5480 APValue Val;
5481 bool Failed;
5482
5483 EvalResult() : Failed(false) { }
5484
5485 void swap(EvalResult &RHS) {
5486 Val.swap(RHS.Val);
5487 Failed = RHS.Failed;
5488 RHS.Failed = false;
5489 }
5490 };
5491
5492 struct Job {
5493 const Expr *E;
5494 EvalResult LHSResult; // meaningful only for binary operator expression.
5495 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5496
5497 Job() : StoredInfo(0) { }
5498 void startSpeculativeEval(EvalInfo &Info) {
5499 OldEvalStatus = Info.EvalStatus;
5500 Info.EvalStatus.Diag = 0;
5501 StoredInfo = &Info;
5502 }
5503 ~Job() {
5504 if (StoredInfo) {
5505 StoredInfo->EvalStatus = OldEvalStatus;
5506 }
5507 }
5508 private:
5509 EvalInfo *StoredInfo; // non-null if status changed.
5510 Expr::EvalStatus OldEvalStatus;
5511 };
5512
5513 SmallVector<Job, 16> Queue;
5514
5515 IntExprEvaluator &IntEval;
5516 EvalInfo &Info;
5517 APValue &FinalResult;
5518
5519public:
5520 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5521 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5522
5523 /// \brief True if \param E is a binary operator that we are going to handle
5524 /// data recursively.
5525 /// We handle binary operators that are comma, logical, or that have operands
5526 /// with integral or enumeration type.
5527 static bool shouldEnqueue(const BinaryOperator *E) {
5528 return E->getOpcode() == BO_Comma ||
5529 E->isLogicalOp() ||
5530 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5531 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00005532 }
5533
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005534 bool Traverse(const BinaryOperator *E) {
5535 enqueue(E);
5536 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00005537 while (!Queue.empty())
5538 process(PrevResult);
5539
5540 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005541
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005542 FinalResult.swap(PrevResult.Val);
5543 return true;
5544 }
5545
5546private:
5547 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5548 return IntEval.Success(Value, E, Result);
5549 }
5550 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
5551 return IntEval.Success(Value, E, Result);
5552 }
5553 bool Error(const Expr *E) {
5554 return IntEval.Error(E);
5555 }
5556 bool Error(const Expr *E, diag::kind D) {
5557 return IntEval.Error(E, D);
5558 }
5559
5560 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5561 return Info.CCEDiag(E, D);
5562 }
5563
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005564 // \brief Returns true if visiting the RHS is necessary, false otherwise.
5565 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005566 bool &SuppressRHSDiags);
5567
5568 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5569 const BinaryOperator *E, APValue &Result);
5570
5571 void EvaluateExpr(const Expr *E, EvalResult &Result) {
5572 Result.Failed = !Evaluate(Result.Val, Info, E);
5573 if (Result.Failed)
5574 Result.Val = APValue();
5575 }
5576
Richard Trieuba4d0872012-03-21 23:30:30 +00005577 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005578
5579 void enqueue(const Expr *E) {
5580 E = E->IgnoreParens();
5581 Queue.resize(Queue.size()+1);
5582 Queue.back().E = E;
5583 Queue.back().Kind = Job::AnyExprKind;
5584 }
5585};
5586
5587}
5588
5589bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005590 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005591 bool &SuppressRHSDiags) {
5592 if (E->getOpcode() == BO_Comma) {
5593 // Ignore LHS but note if we could not evaluate it.
5594 if (LHSResult.Failed)
5595 Info.EvalStatus.HasSideEffects = true;
5596 return true;
5597 }
5598
5599 if (E->isLogicalOp()) {
5600 bool lhsResult;
5601 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005602 // We were able to evaluate the LHS, see if we can get away with not
5603 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005604 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005605 Success(lhsResult, E, LHSResult.Val);
5606 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005607 }
5608 } else {
5609 // Since we weren't able to evaluate the left hand side, it
5610 // must have had side effects.
5611 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005612
5613 // We can't evaluate the LHS; however, sometimes the result
5614 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5615 // Don't ignore RHS and suppress diagnostics from this arm.
5616 SuppressRHSDiags = true;
5617 }
5618
5619 return true;
5620 }
5621
5622 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5623 E->getRHS()->getType()->isIntegralOrEnumerationType());
5624
5625 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005626 return false; // Ignore RHS;
5627
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005628 return true;
5629}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005630
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005631bool DataRecursiveIntBinOpEvaluator::
5632 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5633 const BinaryOperator *E, APValue &Result) {
5634 if (E->getOpcode() == BO_Comma) {
5635 if (RHSResult.Failed)
5636 return false;
5637 Result = RHSResult.Val;
5638 return true;
5639 }
5640
5641 if (E->isLogicalOp()) {
5642 bool lhsResult, rhsResult;
5643 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5644 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5645
5646 if (LHSIsOK) {
5647 if (RHSIsOK) {
5648 if (E->getOpcode() == BO_LOr)
5649 return Success(lhsResult || rhsResult, E, Result);
5650 else
5651 return Success(lhsResult && rhsResult, E, Result);
5652 }
5653 } else {
5654 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005655 // We can't evaluate the LHS; however, sometimes the result
5656 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5657 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005658 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005659 }
5660 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005661
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00005662 return false;
5663 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005664
5665 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5666 E->getRHS()->getType()->isIntegralOrEnumerationType());
5667
5668 if (LHSResult.Failed || RHSResult.Failed)
5669 return false;
5670
5671 const APValue &LHSVal = LHSResult.Val;
5672 const APValue &RHSVal = RHSResult.Val;
5673
5674 // Handle cases like (unsigned long)&a + 4.
5675 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5676 Result = LHSVal;
5677 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5678 RHSVal.getInt().getZExtValue());
5679 if (E->getOpcode() == BO_Add)
5680 Result.getLValueOffset() += AdditionalOffset;
5681 else
5682 Result.getLValueOffset() -= AdditionalOffset;
5683 return true;
5684 }
5685
5686 // Handle cases like 4 + (unsigned long)&a
5687 if (E->getOpcode() == BO_Add &&
5688 RHSVal.isLValue() && LHSVal.isInt()) {
5689 Result = RHSVal;
5690 Result.getLValueOffset() += CharUnits::fromQuantity(
5691 LHSVal.getInt().getZExtValue());
5692 return true;
5693 }
5694
5695 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5696 // Handle (intptr_t)&&A - (intptr_t)&&B.
5697 if (!LHSVal.getLValueOffset().isZero() ||
5698 !RHSVal.getLValueOffset().isZero())
5699 return false;
5700 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5701 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5702 if (!LHSExpr || !RHSExpr)
5703 return false;
5704 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5705 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5706 if (!LHSAddrExpr || !RHSAddrExpr)
5707 return false;
5708 // Make sure both labels come from the same function.
5709 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5710 RHSAddrExpr->getLabel()->getDeclContext())
5711 return false;
5712 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5713 return true;
5714 }
Richard Smith43e77732013-05-07 04:50:00 +00005715
5716 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005717 if (!LHSVal.isInt() || !RHSVal.isInt())
5718 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00005719
5720 // Set up the width and signedness manually, in case it can't be deduced
5721 // from the operation we're performing.
5722 // FIXME: Don't do this in the cases where we can deduce it.
5723 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
5724 E->getType()->isUnsignedIntegerOrEnumerationType());
5725 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
5726 RHSVal.getInt(), Value))
5727 return false;
5728 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005729}
5730
Richard Trieuba4d0872012-03-21 23:30:30 +00005731void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005732 Job &job = Queue.back();
5733
5734 switch (job.Kind) {
5735 case Job::AnyExprKind: {
5736 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5737 if (shouldEnqueue(Bop)) {
5738 job.Kind = Job::BinOpKind;
5739 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005740 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005741 }
5742 }
5743
5744 EvaluateExpr(job.E, Result);
5745 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005746 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005747 }
5748
5749 case Job::BinOpKind: {
5750 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005751 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005752 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005753 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005754 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005755 }
5756 if (SuppressRHSDiags)
5757 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00005758 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005759 job.Kind = Job::BinOpVisitedLHSKind;
5760 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00005761 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005762 }
5763
5764 case Job::BinOpVisitedLHSKind: {
5765 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5766 EvalResult RHS;
5767 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00005768 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005769 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00005770 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005771 }
5772 }
5773
5774 llvm_unreachable("Invalid Job::Kind!");
5775}
5776
5777bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5778 if (E->isAssignmentOp())
5779 return Error(E);
5780
5781 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
5782 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005783
Anders Carlssonacc79812008-11-16 07:17:21 +00005784 QualType LHSTy = E->getLHS()->getType();
5785 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005786
5787 if (LHSTy->isAnyComplexType()) {
5788 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00005789 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005790
Richard Smith253c2a32012-01-27 01:14:48 +00005791 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
5792 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005793 return false;
5794
Richard Smith253c2a32012-01-27 01:14:48 +00005795 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005796 return false;
5797
5798 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00005799 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005800 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00005801 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005802 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
5803
John McCalle3027922010-08-25 11:45:40 +00005804 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005805 return Success((CR_r == APFloat::cmpEqual &&
5806 CR_i == APFloat::cmpEqual), E);
5807 else {
John McCalle3027922010-08-25 11:45:40 +00005808 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005809 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00005810 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005811 CR_r == APFloat::cmpLessThan ||
5812 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00005813 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00005814 CR_i == APFloat::cmpLessThan ||
5815 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005816 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005817 } else {
John McCalle3027922010-08-25 11:45:40 +00005818 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005819 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5820 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5821 else {
John McCalle3027922010-08-25 11:45:40 +00005822 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005823 "Invalid compex comparison.");
5824 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5825 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5826 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00005827 }
5828 }
Mike Stump11289f42009-09-09 15:08:12 +00005829
Anders Carlssonacc79812008-11-16 07:17:21 +00005830 if (LHSTy->isRealFloatingType() &&
5831 RHSTy->isRealFloatingType()) {
5832 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00005833
Richard Smith253c2a32012-01-27 01:14:48 +00005834 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5835 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00005836 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005837
Richard Smith253c2a32012-01-27 01:14:48 +00005838 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00005839 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005840
Anders Carlssonacc79812008-11-16 07:17:21 +00005841 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00005842
Anders Carlssonacc79812008-11-16 07:17:21 +00005843 switch (E->getOpcode()) {
5844 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005845 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00005846 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005847 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00005848 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005849 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00005850 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005851 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005852 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00005853 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005854 E);
John McCalle3027922010-08-25 11:45:40 +00005855 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005856 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00005857 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00005858 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00005859 || CR == APFloat::cmpLessThan
5860 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00005861 }
Anders Carlssonacc79812008-11-16 07:17:21 +00005862 }
Mike Stump11289f42009-09-09 15:08:12 +00005863
Eli Friedmana38da572009-04-28 19:17:36 +00005864 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00005865 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005866 LValue LHSValue, RHSValue;
5867
5868 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
5869 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005870 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005871
Richard Smith253c2a32012-01-27 01:14:48 +00005872 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005873 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005874
Richard Smith8b3497e2011-10-31 01:37:14 +00005875 // Reject differing bases from the normal codepath; we special-case
5876 // comparisons to null.
5877 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005878 if (E->getOpcode() == BO_Sub) {
5879 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005880 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
5881 return false;
5882 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00005883 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005884 if (!LHSExpr || !RHSExpr)
5885 return false;
5886 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5887 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5888 if (!LHSAddrExpr || !RHSAddrExpr)
5889 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005890 // Make sure both labels come from the same function.
5891 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5892 RHSAddrExpr->getLabel()->getDeclContext())
5893 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005894 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005895 return true;
5896 }
Richard Smith83c68212011-10-31 05:11:32 +00005897 // Inequalities and subtractions between unrelated pointers have
5898 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00005899 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005900 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005901 // A constant address may compare equal to the address of a symbol.
5902 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00005903 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005904 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5905 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005906 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005907 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00005908 // distinct addresses. In clang, the result of such a comparison is
5909 // unspecified, so it is not a constant expression. However, we do know
5910 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00005911 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5912 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005913 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005914 // We can't tell whether weak symbols will end up pointing to the same
5915 // object.
5916 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005917 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005918 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00005919 // (Note that clang defaults to -fmerge-all-constants, which can
5920 // lead to inconsistent results for comparisons involving the address
5921 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00005922 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00005923 }
Eli Friedman64004332009-03-23 04:38:34 +00005924
Richard Smith1b470412012-02-01 08:10:20 +00005925 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5926 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5927
Richard Smith84f6dcf2012-02-02 01:16:57 +00005928 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5929 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5930
John McCalle3027922010-08-25 11:45:40 +00005931 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005932 // C++11 [expr.add]p6:
5933 // Unless both pointers point to elements of the same array object, or
5934 // one past the last element of the array object, the behavior is
5935 // undefined.
5936 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5937 !AreElementsOfSameArray(getType(LHSValue.Base),
5938 LHSDesignator, RHSDesignator))
5939 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5940
Chris Lattner882bdf22010-04-20 17:13:14 +00005941 QualType Type = E->getLHS()->getType();
5942 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005943
Richard Smithd62306a2011-11-10 06:34:14 +00005944 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00005945 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00005946 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005947
Richard Smith1b470412012-02-01 08:10:20 +00005948 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5949 // and produce incorrect results when it overflows. Such behavior
5950 // appears to be non-conforming, but is common, so perhaps we should
5951 // assume the standard intended for such cases to be undefined behavior
5952 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00005953
Richard Smith1b470412012-02-01 08:10:20 +00005954 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5955 // overflow in the final conversion to ptrdiff_t.
5956 APSInt LHS(
5957 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5958 APSInt RHS(
5959 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5960 APSInt ElemSize(
5961 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5962 APSInt TrueResult = (LHS - RHS) / ElemSize;
5963 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5964
5965 if (Result.extend(65) != TrueResult)
5966 HandleOverflow(Info, E, TrueResult, E->getType());
5967 return Success(Result, E);
5968 }
Richard Smithde21b242012-01-31 06:41:30 +00005969
5970 // C++11 [expr.rel]p3:
5971 // Pointers to void (after pointer conversions) can be compared, with a
5972 // result defined as follows: If both pointers represent the same
5973 // address or are both the null pointer value, the result is true if the
5974 // operator is <= or >= and false otherwise; otherwise the result is
5975 // unspecified.
5976 // We interpret this as applying to pointers to *cv* void.
5977 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00005978 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00005979 CCEDiag(E, diag::note_constexpr_void_comparison);
5980
Richard Smith84f6dcf2012-02-02 01:16:57 +00005981 // C++11 [expr.rel]p2:
5982 // - If two pointers point to non-static data members of the same object,
5983 // or to subobjects or array elements fo such members, recursively, the
5984 // pointer to the later declared member compares greater provided the
5985 // two members have the same access control and provided their class is
5986 // not a union.
5987 // [...]
5988 // - Otherwise pointer comparisons are unspecified.
5989 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5990 E->isRelationalOp()) {
5991 bool WasArrayIndex;
5992 unsigned Mismatch =
5993 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5994 RHSDesignator, WasArrayIndex);
5995 // At the point where the designators diverge, the comparison has a
5996 // specified value if:
5997 // - we are comparing array indices
5998 // - we are comparing fields of a union, or fields with the same access
5999 // Otherwise, the result is unspecified and thus the comparison is not a
6000 // constant expression.
6001 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6002 Mismatch < RHSDesignator.Entries.size()) {
6003 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6004 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6005 if (!LF && !RF)
6006 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6007 else if (!LF)
6008 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6009 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6010 << RF->getParent() << RF;
6011 else if (!RF)
6012 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6013 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6014 << LF->getParent() << LF;
6015 else if (!LF->getParent()->isUnion() &&
6016 LF->getAccess() != RF->getAccess())
6017 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6018 << LF << LF->getAccess() << RF << RF->getAccess()
6019 << LF->getParent();
6020 }
6021 }
6022
Eli Friedman6c31cb42012-04-16 04:30:08 +00006023 // The comparison here must be unsigned, and performed with the same
6024 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006025 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6026 uint64_t CompareLHS = LHSOffset.getQuantity();
6027 uint64_t CompareRHS = RHSOffset.getQuantity();
6028 assert(PtrSize <= 64 && "Unexpected pointer width");
6029 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6030 CompareLHS &= Mask;
6031 CompareRHS &= Mask;
6032
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006033 // If there is a base and this is a relational operator, we can only
6034 // compare pointers within the object in question; otherwise, the result
6035 // depends on where the object is located in memory.
6036 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6037 QualType BaseTy = getType(LHSValue.Base);
6038 if (BaseTy->isIncompleteType())
6039 return Error(E);
6040 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6041 uint64_t OffsetLimit = Size.getQuantity();
6042 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6043 return Error(E);
6044 }
6045
Richard Smith8b3497e2011-10-31 01:37:14 +00006046 switch (E->getOpcode()) {
6047 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006048 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6049 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6050 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6051 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6052 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6053 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006054 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006055 }
6056 }
Richard Smith7bb00672012-02-01 01:42:44 +00006057
6058 if (LHSTy->isMemberPointerType()) {
6059 assert(E->isEqualityOp() && "unexpected member pointer operation");
6060 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6061
6062 MemberPtr LHSValue, RHSValue;
6063
6064 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6065 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6066 return false;
6067
6068 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6069 return false;
6070
6071 // C++11 [expr.eq]p2:
6072 // If both operands are null, they compare equal. Otherwise if only one is
6073 // null, they compare unequal.
6074 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6075 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6076 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6077 }
6078
6079 // Otherwise if either is a pointer to a virtual member function, the
6080 // result is unspecified.
6081 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6082 if (MD->isVirtual())
6083 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6084 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6085 if (MD->isVirtual())
6086 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6087
6088 // Otherwise they compare equal if and only if they would refer to the
6089 // same member of the same most derived object or the same subobject if
6090 // they were dereferenced with a hypothetical object of the associated
6091 // class type.
6092 bool Equal = LHSValue == RHSValue;
6093 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6094 }
6095
Richard Smithab44d9b2012-02-14 22:35:28 +00006096 if (LHSTy->isNullPtrType()) {
6097 assert(E->isComparisonOp() && "unexpected nullptr operation");
6098 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6099 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6100 // are compared, the result is true of the operator is <=, >= or ==, and
6101 // false otherwise.
6102 BinaryOperator::Opcode Opcode = E->getOpcode();
6103 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6104 }
6105
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006106 assert((!LHSTy->isIntegralOrEnumerationType() ||
6107 !RHSTy->isIntegralOrEnumerationType()) &&
6108 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6109 // We can't continue from here for non-integral types.
6110 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00006111}
6112
Ken Dyck160146e2010-01-27 17:10:57 +00006113CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00006114 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6115 // result shall be the alignment of the referenced type."
6116 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6117 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00006118
6119 // __alignof is defined to return the preferred alignment.
6120 return Info.Ctx.toCharUnitsFromBits(
6121 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00006122}
6123
Ken Dyck160146e2010-01-27 17:10:57 +00006124CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00006125 E = E->IgnoreParens();
6126
John McCall768439e2013-05-06 07:40:34 +00006127 // The kinds of expressions that we have special-case logic here for
6128 // should be kept up to date with the special checks for those
6129 // expressions in Sema.
6130
Chris Lattner68061312009-01-24 21:53:27 +00006131 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00006132 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00006133 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006134 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6135 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00006136
Chris Lattner68061312009-01-24 21:53:27 +00006137 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00006138 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6139 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00006140
Chris Lattner24aeeab2009-01-24 21:09:06 +00006141 return GetAlignOfType(E->getType());
6142}
6143
6144
Peter Collingbournee190dee2011-03-11 19:24:49 +00006145/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6146/// a result as the expression's type.
6147bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6148 const UnaryExprOrTypeTraitExpr *E) {
6149 switch(E->getKind()) {
6150 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00006151 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00006152 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006153 else
Ken Dyckdbc01912011-03-11 02:13:43 +00006154 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00006155 }
Eli Friedman64004332009-03-23 04:38:34 +00006156
Peter Collingbournee190dee2011-03-11 19:24:49 +00006157 case UETT_VecStep: {
6158 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00006159
Peter Collingbournee190dee2011-03-11 19:24:49 +00006160 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00006161 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00006162
Peter Collingbournee190dee2011-03-11 19:24:49 +00006163 // The vec_step built-in functions that take a 3-component
6164 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6165 if (n == 3)
6166 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00006167
Peter Collingbournee190dee2011-03-11 19:24:49 +00006168 return Success(n, E);
6169 } else
6170 return Success(1, E);
6171 }
6172
6173 case UETT_SizeOf: {
6174 QualType SrcTy = E->getTypeOfArgument();
6175 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6176 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00006177 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6178 SrcTy = Ref->getPointeeType();
6179
Richard Smithd62306a2011-11-10 06:34:14 +00006180 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00006181 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00006182 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006183 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006184 }
6185 }
6186
6187 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006188}
6189
Peter Collingbournee9200682011-05-13 03:29:01 +00006190bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006191 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00006192 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00006193 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006194 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00006195 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00006196 for (unsigned i = 0; i != n; ++i) {
6197 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6198 switch (ON.getKind()) {
6199 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00006200 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00006201 APSInt IdxResult;
6202 if (!EvaluateInteger(Idx, IdxResult, Info))
6203 return false;
6204 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6205 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006206 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006207 CurrentType = AT->getElementType();
6208 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6209 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00006210 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006211 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006212
Douglas Gregor882211c2010-04-28 22:16:22 +00006213 case OffsetOfExpr::OffsetOfNode::Field: {
6214 FieldDecl *MemberDecl = ON.getField();
6215 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006216 if (!RT)
6217 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006218 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006219 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006220 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00006221 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00006222 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00006223 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00006224 CurrentType = MemberDecl->getType().getNonReferenceType();
6225 break;
6226 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006227
Douglas Gregor882211c2010-04-28 22:16:22 +00006228 case OffsetOfExpr::OffsetOfNode::Identifier:
6229 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00006230
Douglas Gregord1702062010-04-29 00:18:15 +00006231 case OffsetOfExpr::OffsetOfNode::Base: {
6232 CXXBaseSpecifier *BaseSpec = ON.getBase();
6233 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006234 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006235
6236 // Find the layout of the class whose base we are looking into.
6237 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00006238 if (!RT)
6239 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006240 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00006241 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00006242 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6243
6244 // Find the base class itself.
6245 CurrentType = BaseSpec->getType();
6246 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6247 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006248 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00006249
6250 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00006251 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00006252 break;
6253 }
Douglas Gregor882211c2010-04-28 22:16:22 +00006254 }
6255 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006256 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00006257}
6258
Chris Lattnere13042c2008-07-11 19:10:17 +00006259bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006260 switch (E->getOpcode()) {
6261 default:
6262 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6263 // See C99 6.6p3.
6264 return Error(E);
6265 case UO_Extension:
6266 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6267 // If so, we could clear the diagnostic ID.
6268 return Visit(E->getSubExpr());
6269 case UO_Plus:
6270 // The result is just the value.
6271 return Visit(E->getSubExpr());
6272 case UO_Minus: {
6273 if (!Visit(E->getSubExpr()))
6274 return false;
6275 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00006276 const APSInt &Value = Result.getInt();
6277 if (Value.isSigned() && Value.isMinSignedValue())
6278 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6279 E->getType());
6280 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006281 }
6282 case UO_Not: {
6283 if (!Visit(E->getSubExpr()))
6284 return false;
6285 if (!Result.isInt()) return Error(E);
6286 return Success(~Result.getInt(), E);
6287 }
6288 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00006289 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00006290 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00006291 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006292 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006293 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006294 }
Anders Carlsson9c181652008-07-08 14:35:21 +00006295}
Mike Stump11289f42009-09-09 15:08:12 +00006296
Chris Lattner477c4be2008-07-12 01:15:53 +00006297/// HandleCast - This is used to evaluate implicit or explicit casts where the
6298/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00006299bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6300 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006301 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00006302 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00006303
Eli Friedmanc757de22011-03-25 00:43:55 +00006304 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00006305 case CK_BaseToDerived:
6306 case CK_DerivedToBase:
6307 case CK_UncheckedDerivedToBase:
6308 case CK_Dynamic:
6309 case CK_ToUnion:
6310 case CK_ArrayToPointerDecay:
6311 case CK_FunctionToPointerDecay:
6312 case CK_NullToPointer:
6313 case CK_NullToMemberPointer:
6314 case CK_BaseToDerivedMemberPointer:
6315 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00006316 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00006317 case CK_ConstructorConversion:
6318 case CK_IntegralToPointer:
6319 case CK_ToVoid:
6320 case CK_VectorSplat:
6321 case CK_IntegralToFloating:
6322 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006323 case CK_CPointerToObjCPointerCast:
6324 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006325 case CK_AnyPointerToBlockPointerCast:
6326 case CK_ObjCObjectLValueCast:
6327 case CK_FloatingRealToComplex:
6328 case CK_FloatingComplexToReal:
6329 case CK_FloatingComplexCast:
6330 case CK_FloatingComplexToIntegralComplex:
6331 case CK_IntegralRealToComplex:
6332 case CK_IntegralComplexCast:
6333 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00006334 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006335 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006336 llvm_unreachable("invalid cast kind for integral value");
6337
Eli Friedman9faf2f92011-03-25 19:07:11 +00006338 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00006339 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006340 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00006341 case CK_ARCProduceObject:
6342 case CK_ARCConsumeObject:
6343 case CK_ARCReclaimReturnedObject:
6344 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006345 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006346 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006347
Richard Smith4ef685b2012-01-17 21:17:26 +00006348 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00006349 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006350 case CK_AtomicToNonAtomic:
6351 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00006352 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006353 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006354
6355 case CK_MemberPointerToBoolean:
6356 case CK_PointerToBoolean:
6357 case CK_IntegralToBoolean:
6358 case CK_FloatingToBoolean:
6359 case CK_FloatingComplexToBoolean:
6360 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006361 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00006362 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00006363 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006364 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006365 }
6366
Eli Friedmanc757de22011-03-25 00:43:55 +00006367 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00006368 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00006369 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00006370
Eli Friedman742421e2009-02-20 01:15:07 +00006371 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006372 // Allow casts of address-of-label differences if they are no-ops
6373 // or narrowing. (The narrowing case isn't actually guaranteed to
6374 // be constant-evaluatable except in some narrow cases which are hard
6375 // to detect here. We let it through on the assumption the user knows
6376 // what they are doing.)
6377 if (Result.isAddrLabelDiff())
6378 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00006379 // Only allow casts of lvalues if they are lossless.
6380 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6381 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006382
Richard Smith911e1422012-01-30 22:27:01 +00006383 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6384 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00006385 }
Mike Stump11289f42009-09-09 15:08:12 +00006386
Eli Friedmanc757de22011-03-25 00:43:55 +00006387 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006388 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6389
John McCall45d55e42010-05-07 21:00:08 +00006390 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00006391 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00006392 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00006393
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006394 if (LV.getLValueBase()) {
6395 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00006396 // FIXME: Allow a larger integer size than the pointer size, and allow
6397 // narrowing back down to pointer width in subsequent integral casts.
6398 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006399 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006400 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006401
Richard Smithcf74da72011-11-16 07:18:12 +00006402 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00006403 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00006404 return true;
6405 }
6406
Ken Dyck02990832010-01-15 12:37:54 +00006407 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6408 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00006409 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006410 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006411
Eli Friedmanc757de22011-03-25 00:43:55 +00006412 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00006413 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006414 if (!EvaluateComplex(SubExpr, C, Info))
6415 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00006416 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00006417 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00006418
Eli Friedmanc757de22011-03-25 00:43:55 +00006419 case CK_FloatingToIntegral: {
6420 APFloat F(0.0);
6421 if (!EvaluateFloat(SubExpr, F, Info))
6422 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00006423
Richard Smith357362d2011-12-13 06:39:58 +00006424 APSInt Value;
6425 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6426 return false;
6427 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006428 }
6429 }
Mike Stump11289f42009-09-09 15:08:12 +00006430
Eli Friedmanc757de22011-03-25 00:43:55 +00006431 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00006432}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006433
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006434bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6435 if (E->getSubExpr()->getType()->isAnyComplexType()) {
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.getComplexIntReal(), E);
6442 }
6443
6444 return Visit(E->getSubExpr());
6445}
6446
Eli Friedman4e7a2412009-02-27 04:45:43 +00006447bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006448 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00006449 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006450 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6451 return false;
6452 if (!LV.isComplexInt())
6453 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006454 return Success(LV.getComplexIntImag(), E);
6455 }
6456
Richard Smith4a678122011-10-24 18:44:57 +00006457 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00006458 return Success(0, E);
6459}
6460
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006461bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6462 return Success(E->getPackLength(), E);
6463}
6464
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006465bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6466 return Success(E->getValue(), E);
6467}
6468
Chris Lattner05706e882008-07-11 18:11:29 +00006469//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00006470// Float Evaluation
6471//===----------------------------------------------------------------------===//
6472
6473namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006474class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006475 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00006476 APFloat &Result;
6477public:
6478 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006479 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00006480
Richard Smith2e312c82012-03-03 22:46:17 +00006481 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006482 Result = V.getFloat();
6483 return true;
6484 }
Eli Friedman24c01542008-08-22 00:06:13 +00006485
Richard Smithfddd3842011-12-30 21:15:51 +00006486 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00006487 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6488 return true;
6489 }
6490
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006491 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006492
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006493 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00006494 bool VisitBinaryOperator(const BinaryOperator *E);
6495 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006496 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00006497
John McCallb1fb0d32010-05-07 22:08:54 +00006498 bool VisitUnaryReal(const UnaryOperator *E);
6499 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00006500
Richard Smithfddd3842011-12-30 21:15:51 +00006501 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00006502};
6503} // end anonymous namespace
6504
6505static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006506 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006507 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00006508}
6509
Jay Foad39c79802011-01-12 09:06:06 +00006510static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00006511 QualType ResultTy,
6512 const Expr *Arg,
6513 bool SNaN,
6514 llvm::APFloat &Result) {
6515 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6516 if (!S) return false;
6517
6518 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6519
6520 llvm::APInt fill;
6521
6522 // Treat empty strings as if they were zero.
6523 if (S->getString().empty())
6524 fill = llvm::APInt(32, 0);
6525 else if (S->getString().getAsInteger(0, fill))
6526 return false;
6527
6528 if (SNaN)
6529 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6530 else
6531 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6532 return true;
6533}
6534
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006535bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006536 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006537 default:
6538 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6539
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006540 case Builtin::BI__builtin_huge_val:
6541 case Builtin::BI__builtin_huge_valf:
6542 case Builtin::BI__builtin_huge_vall:
6543 case Builtin::BI__builtin_inf:
6544 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006545 case Builtin::BI__builtin_infl: {
6546 const llvm::fltSemantics &Sem =
6547 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00006548 Result = llvm::APFloat::getInf(Sem);
6549 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00006550 }
Mike Stump11289f42009-09-09 15:08:12 +00006551
John McCall16291492010-02-28 13:00:19 +00006552 case Builtin::BI__builtin_nans:
6553 case Builtin::BI__builtin_nansf:
6554 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006555 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6556 true, Result))
6557 return Error(E);
6558 return true;
John McCall16291492010-02-28 13:00:19 +00006559
Chris Lattner0b7282e2008-10-06 06:31:58 +00006560 case Builtin::BI__builtin_nan:
6561 case Builtin::BI__builtin_nanf:
6562 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00006563 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00006564 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00006565 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6566 false, Result))
6567 return Error(E);
6568 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006569
6570 case Builtin::BI__builtin_fabs:
6571 case Builtin::BI__builtin_fabsf:
6572 case Builtin::BI__builtin_fabsl:
6573 if (!EvaluateFloat(E->getArg(0), Result, Info))
6574 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006575
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006576 if (Result.isNegative())
6577 Result.changeSign();
6578 return true;
6579
Mike Stump11289f42009-09-09 15:08:12 +00006580 case Builtin::BI__builtin_copysign:
6581 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006582 case Builtin::BI__builtin_copysignl: {
6583 APFloat RHS(0.);
6584 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6585 !EvaluateFloat(E->getArg(1), RHS, Info))
6586 return false;
6587 Result.copySign(RHS);
6588 return true;
6589 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006590 }
6591}
6592
John McCallb1fb0d32010-05-07 22:08:54 +00006593bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006594 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6595 ComplexValue CV;
6596 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6597 return false;
6598 Result = CV.FloatReal;
6599 return true;
6600 }
6601
6602 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00006603}
6604
6605bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00006606 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6607 ComplexValue CV;
6608 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6609 return false;
6610 Result = CV.FloatImag;
6611 return true;
6612 }
6613
Richard Smith4a678122011-10-24 18:44:57 +00006614 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00006615 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6616 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00006617 return true;
6618}
6619
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006620bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006621 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006622 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006623 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00006624 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00006625 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00006626 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6627 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006628 Result.changeSign();
6629 return true;
6630 }
6631}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006632
Eli Friedman24c01542008-08-22 00:06:13 +00006633bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006634 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6635 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00006636
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00006637 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00006638 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6639 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00006640 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00006641 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
6642 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00006643}
6644
6645bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6646 Result = E->getValue();
6647 return true;
6648}
6649
Peter Collingbournee9200682011-05-13 03:29:01 +00006650bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6651 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00006652
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006653 switch (E->getCastKind()) {
6654 default:
Richard Smith11562c52011-10-28 17:51:58 +00006655 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006656
6657 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006658 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00006659 return EvaluateInteger(SubExpr, IntResult, Info) &&
6660 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6661 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006662 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006663
6664 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00006665 if (!Visit(SubExpr))
6666 return false;
Richard Smith357362d2011-12-13 06:39:58 +00006667 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6668 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006669 }
John McCalld7646252010-11-14 08:17:51 +00006670
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006671 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00006672 ComplexValue V;
6673 if (!EvaluateComplex(SubExpr, V, Info))
6674 return false;
6675 Result = V.getComplexFloatReal();
6676 return true;
6677 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00006678 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006679}
6680
Eli Friedman24c01542008-08-22 00:06:13 +00006681//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006682// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00006683//===----------------------------------------------------------------------===//
6684
6685namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006686class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00006687 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00006688 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00006689
Anders Carlsson537969c2008-11-16 20:27:53 +00006690public:
John McCall93d91dc2010-05-07 17:22:02 +00006691 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006692 : ExprEvaluatorBaseTy(info), Result(Result) {}
6693
Richard Smith2e312c82012-03-03 22:46:17 +00006694 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006695 Result.setFrom(V);
6696 return true;
6697 }
Mike Stump11289f42009-09-09 15:08:12 +00006698
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006699 bool ZeroInitialization(const Expr *E);
6700
Anders Carlsson537969c2008-11-16 20:27:53 +00006701 //===--------------------------------------------------------------------===//
6702 // Visitor Methods
6703 //===--------------------------------------------------------------------===//
6704
Peter Collingbournee9200682011-05-13 03:29:01 +00006705 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006706 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00006707 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006708 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006709 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006710};
6711} // end anonymous namespace
6712
John McCall93d91dc2010-05-07 17:22:02 +00006713static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6714 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006715 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006716 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00006717}
6718
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006719bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00006720 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006721 if (ElemTy->isRealFloatingType()) {
6722 Result.makeComplexFloat();
6723 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6724 Result.FloatReal = Zero;
6725 Result.FloatImag = Zero;
6726 } else {
6727 Result.makeComplexInt();
6728 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6729 Result.IntReal = Zero;
6730 Result.IntImag = Zero;
6731 }
6732 return true;
6733}
6734
Peter Collingbournee9200682011-05-13 03:29:01 +00006735bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6736 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006737
6738 if (SubExpr->getType()->isRealFloatingType()) {
6739 Result.makeComplexFloat();
6740 APFloat &Imag = Result.FloatImag;
6741 if (!EvaluateFloat(SubExpr, Imag, Info))
6742 return false;
6743
6744 Result.FloatReal = APFloat(Imag.getSemantics());
6745 return true;
6746 } else {
6747 assert(SubExpr->getType()->isIntegerType() &&
6748 "Unexpected imaginary literal.");
6749
6750 Result.makeComplexInt();
6751 APSInt &Imag = Result.IntImag;
6752 if (!EvaluateInteger(SubExpr, Imag, Info))
6753 return false;
6754
6755 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6756 return true;
6757 }
6758}
6759
Peter Collingbournee9200682011-05-13 03:29:01 +00006760bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006761
John McCallfcef3cf2010-12-14 17:51:41 +00006762 switch (E->getCastKind()) {
6763 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006764 case CK_BaseToDerived:
6765 case CK_DerivedToBase:
6766 case CK_UncheckedDerivedToBase:
6767 case CK_Dynamic:
6768 case CK_ToUnion:
6769 case CK_ArrayToPointerDecay:
6770 case CK_FunctionToPointerDecay:
6771 case CK_NullToPointer:
6772 case CK_NullToMemberPointer:
6773 case CK_BaseToDerivedMemberPointer:
6774 case CK_DerivedToBaseMemberPointer:
6775 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00006776 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00006777 case CK_ConstructorConversion:
6778 case CK_IntegralToPointer:
6779 case CK_PointerToIntegral:
6780 case CK_PointerToBoolean:
6781 case CK_ToVoid:
6782 case CK_VectorSplat:
6783 case CK_IntegralCast:
6784 case CK_IntegralToBoolean:
6785 case CK_IntegralToFloating:
6786 case CK_FloatingToIntegral:
6787 case CK_FloatingToBoolean:
6788 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00006789 case CK_CPointerToObjCPointerCast:
6790 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006791 case CK_AnyPointerToBlockPointerCast:
6792 case CK_ObjCObjectLValueCast:
6793 case CK_FloatingComplexToReal:
6794 case CK_FloatingComplexToBoolean:
6795 case CK_IntegralComplexToReal:
6796 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00006797 case CK_ARCProduceObject:
6798 case CK_ARCConsumeObject:
6799 case CK_ARCReclaimReturnedObject:
6800 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00006801 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00006802 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006803 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00006804 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00006805
John McCallfcef3cf2010-12-14 17:51:41 +00006806 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006807 case CK_AtomicToNonAtomic:
6808 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00006809 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00006810 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006811
6812 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00006813 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00006814 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006815 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00006816
6817 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006818 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00006819 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006820 return false;
6821
John McCallfcef3cf2010-12-14 17:51:41 +00006822 Result.makeComplexFloat();
6823 Result.FloatImag = APFloat(Real.getSemantics());
6824 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006825 }
6826
John McCallfcef3cf2010-12-14 17:51:41 +00006827 case CK_FloatingComplexCast: {
6828 if (!Visit(E->getSubExpr()))
6829 return false;
6830
6831 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6832 QualType From
6833 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6834
Richard Smith357362d2011-12-13 06:39:58 +00006835 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6836 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006837 }
6838
6839 case CK_FloatingComplexToIntegralComplex: {
6840 if (!Visit(E->getSubExpr()))
6841 return false;
6842
6843 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6844 QualType From
6845 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6846 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00006847 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6848 To, Result.IntReal) &&
6849 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6850 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006851 }
6852
6853 case CK_IntegralRealToComplex: {
6854 APSInt &Real = Result.IntReal;
6855 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6856 return false;
6857
6858 Result.makeComplexInt();
6859 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
6860 return true;
6861 }
6862
6863 case CK_IntegralComplexCast: {
6864 if (!Visit(E->getSubExpr()))
6865 return false;
6866
6867 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6868 QualType From
6869 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6870
Richard Smith911e1422012-01-30 22:27:01 +00006871 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
6872 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006873 return true;
6874 }
6875
6876 case CK_IntegralComplexToFloatingComplex: {
6877 if (!Visit(E->getSubExpr()))
6878 return false;
6879
Ted Kremenek28831752012-08-23 20:46:57 +00006880 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006881 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00006882 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006883 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00006884 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6885 To, Result.FloatReal) &&
6886 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6887 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006888 }
6889 }
6890
6891 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006892}
6893
John McCall93d91dc2010-05-07 17:22:02 +00006894bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006895 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00006896 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6897
Richard Smith253c2a32012-01-27 01:14:48 +00006898 bool LHSOK = Visit(E->getLHS());
6899 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00006900 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006901
John McCall93d91dc2010-05-07 17:22:02 +00006902 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00006903 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00006904 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006905
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006906 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6907 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006908 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006909 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006910 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006911 if (Result.isComplexFloat()) {
6912 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6913 APFloat::rmNearestTiesToEven);
6914 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6915 APFloat::rmNearestTiesToEven);
6916 } else {
6917 Result.getComplexIntReal() += RHS.getComplexIntReal();
6918 Result.getComplexIntImag() += RHS.getComplexIntImag();
6919 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006920 break;
John McCalle3027922010-08-25 11:45:40 +00006921 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006922 if (Result.isComplexFloat()) {
6923 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6924 APFloat::rmNearestTiesToEven);
6925 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6926 APFloat::rmNearestTiesToEven);
6927 } else {
6928 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6929 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6930 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006931 break;
John McCalle3027922010-08-25 11:45:40 +00006932 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006933 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00006934 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006935 APFloat &LHS_r = LHS.getComplexFloatReal();
6936 APFloat &LHS_i = LHS.getComplexFloatImag();
6937 APFloat &RHS_r = RHS.getComplexFloatReal();
6938 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00006939
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006940 APFloat Tmp = LHS_r;
6941 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6942 Result.getComplexFloatReal() = Tmp;
6943 Tmp = LHS_i;
6944 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6945 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6946
6947 Tmp = LHS_r;
6948 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6949 Result.getComplexFloatImag() = Tmp;
6950 Tmp = LHS_i;
6951 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6952 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6953 } else {
John McCall93d91dc2010-05-07 17:22:02 +00006954 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00006955 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006956 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6957 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00006958 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006959 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6960 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6961 }
6962 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006963 case BO_Div:
6964 if (Result.isComplexFloat()) {
6965 ComplexValue LHS = Result;
6966 APFloat &LHS_r = LHS.getComplexFloatReal();
6967 APFloat &LHS_i = LHS.getComplexFloatImag();
6968 APFloat &RHS_r = RHS.getComplexFloatReal();
6969 APFloat &RHS_i = RHS.getComplexFloatImag();
6970 APFloat &Res_r = Result.getComplexFloatReal();
6971 APFloat &Res_i = Result.getComplexFloatImag();
6972
6973 APFloat Den = RHS_r;
6974 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6975 APFloat Tmp = RHS_i;
6976 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6977 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6978
6979 Res_r = LHS_r;
6980 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6981 Tmp = LHS_i;
6982 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6983 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6984 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6985
6986 Res_i = LHS_i;
6987 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6988 Tmp = LHS_r;
6989 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6990 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6991 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6992 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006993 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6994 return Error(E, diag::note_expr_divide_by_zero);
6995
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006996 ComplexValue LHS = Result;
6997 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6998 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6999 Result.getComplexIntReal() =
7000 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7001 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7002 Result.getComplexIntImag() =
7003 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7004 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7005 }
7006 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007007 }
7008
John McCall93d91dc2010-05-07 17:22:02 +00007009 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007010}
7011
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007012bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7013 // Get the operand value into 'Result'.
7014 if (!Visit(E->getSubExpr()))
7015 return false;
7016
7017 switch (E->getOpcode()) {
7018 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007019 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007020 case UO_Extension:
7021 return true;
7022 case UO_Plus:
7023 // The result is always just the subexpr.
7024 return true;
7025 case UO_Minus:
7026 if (Result.isComplexFloat()) {
7027 Result.getComplexFloatReal().changeSign();
7028 Result.getComplexFloatImag().changeSign();
7029 }
7030 else {
7031 Result.getComplexIntReal() = -Result.getComplexIntReal();
7032 Result.getComplexIntImag() = -Result.getComplexIntImag();
7033 }
7034 return true;
7035 case UO_Not:
7036 if (Result.isComplexFloat())
7037 Result.getComplexFloatImag().changeSign();
7038 else
7039 Result.getComplexIntImag() = -Result.getComplexIntImag();
7040 return true;
7041 }
7042}
7043
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007044bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7045 if (E->getNumInits() == 2) {
7046 if (E->getType()->isComplexType()) {
7047 Result.makeComplexFloat();
7048 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7049 return false;
7050 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7051 return false;
7052 } else {
7053 Result.makeComplexInt();
7054 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7055 return false;
7056 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7057 return false;
7058 }
7059 return true;
7060 }
7061 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7062}
7063
Anders Carlsson537969c2008-11-16 20:27:53 +00007064//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00007065// Void expression evaluation, primarily for a cast to void on the LHS of a
7066// comma operator
7067//===----------------------------------------------------------------------===//
7068
7069namespace {
7070class VoidExprEvaluator
7071 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7072public:
7073 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7074
Richard Smith2e312c82012-03-03 22:46:17 +00007075 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00007076
7077 bool VisitCastExpr(const CastExpr *E) {
7078 switch (E->getCastKind()) {
7079 default:
7080 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7081 case CK_ToVoid:
7082 VisitIgnoredValue(E->getSubExpr());
7083 return true;
7084 }
7085 }
7086};
7087} // end anonymous namespace
7088
7089static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7090 assert(E->isRValue() && E->getType()->isVoidType());
7091 return VoidExprEvaluator(Info).Visit(E);
7092}
7093
7094//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00007095// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00007096//===----------------------------------------------------------------------===//
7097
Richard Smith2e312c82012-03-03 22:46:17 +00007098static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007099 // In C, function designators are not lvalues, but we evaluate them as if they
7100 // are.
7101 if (E->isGLValue() || E->getType()->isFunctionType()) {
7102 LValue LV;
7103 if (!EvaluateLValue(E, LV, Info))
7104 return false;
7105 LV.moveInto(Result);
7106 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007107 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007108 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007109 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00007110 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007111 return false;
John McCall45d55e42010-05-07 21:00:08 +00007112 } else if (E->getType()->hasPointerRepresentation()) {
7113 LValue LV;
7114 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007115 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007116 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00007117 } else if (E->getType()->isRealFloatingType()) {
7118 llvm::APFloat F(0.0);
7119 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007120 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007121 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00007122 } else if (E->getType()->isAnyComplexType()) {
7123 ComplexValue C;
7124 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007125 return false;
Richard Smith725810a2011-10-16 21:26:27 +00007126 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00007127 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00007128 MemberPtr P;
7129 if (!EvaluateMemberPointer(E, P, Info))
7130 return false;
7131 P.moveInto(Result);
7132 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00007133 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007134 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007135 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007136 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00007137 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007138 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00007139 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007140 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007141 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00007142 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
7143 return false;
7144 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00007145 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007146 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007147 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00007148 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00007149 if (!EvaluateVoid(E, Info))
7150 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007151 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007152 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00007153 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007154 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00007155 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00007156 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007157 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00007158
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00007159 return true;
7160}
7161
Richard Smithb228a862012-02-15 02:18:13 +00007162/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7163/// cases, the in-place evaluation is essential, since later initializers for
7164/// an object can indirectly refer to subobjects which were initialized earlier.
7165static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00007166 const Expr *E, bool AllowNonLiteralTypes) {
7167 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00007168 return false;
7169
7170 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00007171 // Evaluate arrays and record types in-place, so that later initializers can
7172 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00007173 if (E->getType()->isArrayType())
7174 return EvaluateArray(E, This, Result, Info);
7175 else if (E->getType()->isRecordType())
7176 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00007177 }
7178
7179 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00007180 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00007181}
7182
Richard Smithf57d8cb2011-12-09 22:58:01 +00007183/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
7184/// lvalue-to-rvalue cast if it is an lvalue.
7185static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00007186 if (!CheckLiteralType(Info, E))
7187 return false;
7188
Richard Smith2e312c82012-03-03 22:46:17 +00007189 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007190 return false;
7191
7192 if (E->isGLValue()) {
7193 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00007194 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00007195 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007196 return false;
7197 }
7198
Richard Smith2e312c82012-03-03 22:46:17 +00007199 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00007200 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007201}
Richard Smith11562c52011-10-28 17:51:58 +00007202
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007203static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7204 const ASTContext &Ctx, bool &IsConst) {
7205 // Fast-path evaluations of integer literals, since we sometimes see files
7206 // containing vast quantities of these.
7207 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7208 Result.Val = APValue(APSInt(L->getValue(),
7209 L->getType()->isUnsignedIntegerType()));
7210 IsConst = true;
7211 return true;
7212 }
7213
7214 // FIXME: Evaluating values of large array and record types can cause
7215 // performance problems. Only do so in C++11 for now.
7216 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7217 Exp->getType()->isRecordType()) &&
7218 !Ctx.getLangOpts().CPlusPlus11) {
7219 IsConst = false;
7220 return true;
7221 }
7222 return false;
7223}
7224
7225
Richard Smith7b553f12011-10-29 00:50:52 +00007226/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00007227/// any crazy technique (that has nothing to do with language standards) that
7228/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00007229/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7230/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00007231bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007232 bool IsConst;
7233 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7234 return IsConst;
7235
Richard Smithf57d8cb2011-12-09 22:58:01 +00007236 EvalInfo Info(Ctx, Result);
7237 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00007238}
7239
Jay Foad39c79802011-01-12 09:06:06 +00007240bool Expr::EvaluateAsBooleanCondition(bool &Result,
7241 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00007242 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00007243 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00007244 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00007245}
7246
Richard Smith5fab0c92011-12-28 19:48:30 +00007247bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7248 SideEffectsKind AllowSideEffects) const {
7249 if (!getType()->isIntegralOrEnumerationType())
7250 return false;
7251
Richard Smith11562c52011-10-28 17:51:58 +00007252 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00007253 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7254 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00007255 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007256
Richard Smith11562c52011-10-28 17:51:58 +00007257 Result = ExprResult.Val.getInt();
7258 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00007259}
7260
Jay Foad39c79802011-01-12 09:06:06 +00007261bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00007262 EvalInfo Info(Ctx, Result);
7263
John McCall45d55e42010-05-07 21:00:08 +00007264 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00007265 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7266 !CheckLValueConstantExpression(Info, getExprLoc(),
7267 Ctx.getLValueReferenceType(getType()), LV))
7268 return false;
7269
Richard Smith2e312c82012-03-03 22:46:17 +00007270 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00007271 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00007272}
7273
Richard Smithd0b4dd62011-12-19 06:19:21 +00007274bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7275 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007276 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00007277 // FIXME: Evaluating initializers for large array and record types can cause
7278 // performance problems. Only do so in C++11 for now.
7279 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007280 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00007281 return false;
7282
Richard Smithd0b4dd62011-12-19 06:19:21 +00007283 Expr::EvalStatus EStatus;
7284 EStatus.Diag = &Notes;
7285
7286 EvalInfo InitInfo(Ctx, EStatus);
7287 InitInfo.setEvaluatingDecl(VD, Value);
7288
7289 LValue LVal;
7290 LVal.set(VD);
7291
Richard Smithfddd3842011-12-30 21:15:51 +00007292 // C++11 [basic.start.init]p2:
7293 // Variables with static storage duration or thread storage duration shall be
7294 // zero-initialized before any other initialization takes place.
7295 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007296 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00007297 !VD->getType()->isReferenceType()) {
7298 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00007299 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00007300 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00007301 return false;
7302 }
7303
Richard Smith7525ff62013-05-09 07:14:00 +00007304 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
7305 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00007306 EStatus.HasSideEffects)
7307 return false;
7308
7309 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7310 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00007311}
7312
Richard Smith7b553f12011-10-29 00:50:52 +00007313/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7314/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00007315bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00007316 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00007317 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00007318}
Anders Carlsson59689ed2008-11-22 21:04:56 +00007319
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007320APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007321 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007322 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00007323 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00007324 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00007325 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00007326 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007327 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00007328
Anders Carlsson6736d1a22008-12-19 20:58:05 +00007329 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00007330}
John McCall864e3962010-05-07 05:32:02 +00007331
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007332void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7333 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7334 bool IsConst;
7335 EvalResult EvalResult;
7336 EvalResult.Diag = Diags;
7337 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7338 EvalInfo Info(Ctx, EvalResult, true);
7339 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7340 }
7341}
7342
Abramo Bagnaraf8199452010-05-14 17:07:14 +00007343 bool Expr::EvalResult::isGlobalLValue() const {
7344 assert(Val.isLValue());
7345 return IsGlobalLValue(Val.getLValueBase());
7346 }
7347
7348
John McCall864e3962010-05-07 05:32:02 +00007349/// isIntegerConstantExpr - this recursive routine will test if an expression is
7350/// an integer constant expression.
7351
7352/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7353/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00007354
7355// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00007356// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7357// and a (possibly null) SourceLocation indicating the location of the problem.
7358//
John McCall864e3962010-05-07 05:32:02 +00007359// Note that to reduce code duplication, this helper does no evaluation
7360// itself; the caller checks whether the expression is evaluatable, and
7361// in the rare cases where CheckICE actually cares about the evaluated
7362// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00007363
Dan Gohman28ade552010-07-26 21:25:24 +00007364namespace {
7365
Richard Smith9e575da2012-12-28 13:25:52 +00007366enum ICEKind {
7367 /// This expression is an ICE.
7368 IK_ICE,
7369 /// This expression is not an ICE, but if it isn't evaluated, it's
7370 /// a legal subexpression for an ICE. This return value is used to handle
7371 /// the comma operator in C99 mode, and non-constant subexpressions.
7372 IK_ICEIfUnevaluated,
7373 /// This expression is not an ICE, and is not a legal subexpression for one.
7374 IK_NotICE
7375};
7376
John McCall864e3962010-05-07 05:32:02 +00007377struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00007378 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00007379 SourceLocation Loc;
7380
Richard Smith9e575da2012-12-28 13:25:52 +00007381 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00007382};
7383
Dan Gohman28ade552010-07-26 21:25:24 +00007384}
7385
Richard Smith9e575da2012-12-28 13:25:52 +00007386static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7387
7388static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00007389
7390static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7391 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00007392 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00007393 !EVResult.Val.isInt())
7394 return ICEDiag(IK_NotICE, E->getLocStart());
7395
John McCall864e3962010-05-07 05:32:02 +00007396 return NoDiag();
7397}
7398
7399static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7400 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00007401 if (!E->getType()->isIntegralOrEnumerationType())
7402 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007403
7404 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00007405#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00007406#define STMT(Node, Base) case Expr::Node##Class:
7407#define EXPR(Node, Base)
7408#include "clang/AST/StmtNodes.inc"
7409 case Expr::PredefinedExprClass:
7410 case Expr::FloatingLiteralClass:
7411 case Expr::ImaginaryLiteralClass:
7412 case Expr::StringLiteralClass:
7413 case Expr::ArraySubscriptExprClass:
7414 case Expr::MemberExprClass:
7415 case Expr::CompoundAssignOperatorClass:
7416 case Expr::CompoundLiteralExprClass:
7417 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00007418 case Expr::DesignatedInitExprClass:
7419 case Expr::ImplicitValueInitExprClass:
7420 case Expr::ParenListExprClass:
7421 case Expr::VAArgExprClass:
7422 case Expr::AddrLabelExprClass:
7423 case Expr::StmtExprClass:
7424 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00007425 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00007426 case Expr::CXXDynamicCastExprClass:
7427 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00007428 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00007429 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007430 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00007431 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007432 case Expr::CXXThisExprClass:
7433 case Expr::CXXThrowExprClass:
7434 case Expr::CXXNewExprClass:
7435 case Expr::CXXDeleteExprClass:
7436 case Expr::CXXPseudoDestructorExprClass:
7437 case Expr::UnresolvedLookupExprClass:
7438 case Expr::DependentScopeDeclRefExprClass:
7439 case Expr::CXXConstructExprClass:
7440 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00007441 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00007442 case Expr::CXXTemporaryObjectExprClass:
7443 case Expr::CXXUnresolvedConstructExprClass:
7444 case Expr::CXXDependentScopeMemberExprClass:
7445 case Expr::UnresolvedMemberExprClass:
7446 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00007447 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007448 case Expr::ObjCArrayLiteralClass:
7449 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00007450 case Expr::ObjCEncodeExprClass:
7451 case Expr::ObjCMessageExprClass:
7452 case Expr::ObjCSelectorExprClass:
7453 case Expr::ObjCProtocolExprClass:
7454 case Expr::ObjCIvarRefExprClass:
7455 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007456 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00007457 case Expr::ObjCIsaExprClass:
7458 case Expr::ShuffleVectorExprClass:
7459 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00007460 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00007461 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00007462 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00007463 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00007464 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00007465 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00007466 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00007467 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00007468 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00007469 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00007470 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00007471 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00007472 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00007473
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007474 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00007475 case Expr::GNUNullExprClass:
7476 // GCC considers the GNU __null value to be an integral constant expression.
7477 return NoDiag();
7478
John McCall7c454bb2011-07-15 05:09:51 +00007479 case Expr::SubstNonTypeTemplateParmExprClass:
7480 return
7481 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7482
John McCall864e3962010-05-07 05:32:02 +00007483 case Expr::ParenExprClass:
7484 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00007485 case Expr::GenericSelectionExprClass:
7486 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007487 case Expr::IntegerLiteralClass:
7488 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00007489 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00007490 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00007491 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00007492 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00007493 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00007494 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00007495 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00007496 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007497 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00007498 return NoDiag();
7499 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00007500 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00007501 // C99 6.6/3 allows function calls within unevaluated subexpressions of
7502 // constant expressions, but they can never be ICEs because an ICE cannot
7503 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00007504 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007505 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00007506 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007507 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007508 }
Richard Smith6365c912012-02-24 22:12:32 +00007509 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007510 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
7511 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00007512 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007513 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00007514 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00007515 // Parameter variables are never constants. Without this check,
7516 // getAnyInitializer() can find a default argument, which leads
7517 // to chaos.
7518 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00007519 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007520
7521 // C++ 7.1.5.1p2
7522 // A variable of non-volatile const-qualified integral or enumeration
7523 // type initialized by an ICE can be used in ICEs.
7524 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00007525 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00007526 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00007527
Richard Smithd0b4dd62011-12-19 06:19:21 +00007528 const VarDecl *VD;
7529 // Look for a declaration of this variable that has an initializer, and
7530 // check whether it is an ICE.
7531 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7532 return NoDiag();
7533 else
Richard Smith9e575da2012-12-28 13:25:52 +00007534 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00007535 }
7536 }
Richard Smith9e575da2012-12-28 13:25:52 +00007537 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00007538 }
John McCall864e3962010-05-07 05:32:02 +00007539 case Expr::UnaryOperatorClass: {
7540 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7541 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007542 case UO_PostInc:
7543 case UO_PostDec:
7544 case UO_PreInc:
7545 case UO_PreDec:
7546 case UO_AddrOf:
7547 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00007548 // C99 6.6/3 allows increment and decrement within unevaluated
7549 // subexpressions of constant expressions, but they can never be ICEs
7550 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007551 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00007552 case UO_Extension:
7553 case UO_LNot:
7554 case UO_Plus:
7555 case UO_Minus:
7556 case UO_Not:
7557 case UO_Real:
7558 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00007559 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007560 }
Richard Smith9e575da2012-12-28 13:25:52 +00007561
John McCall864e3962010-05-07 05:32:02 +00007562 // OffsetOf falls through here.
7563 }
7564 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00007565 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7566 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7567 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7568 // compliance: we should warn earlier for offsetof expressions with
7569 // array subscripts that aren't ICEs, and if the array subscripts
7570 // are ICEs, the value of the offsetof must be an integer constant.
7571 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007572 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00007573 case Expr::UnaryExprOrTypeTraitExprClass: {
7574 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7575 if ((Exp->getKind() == UETT_SizeOf) &&
7576 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00007577 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007578 return NoDiag();
7579 }
7580 case Expr::BinaryOperatorClass: {
7581 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7582 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007583 case BO_PtrMemD:
7584 case BO_PtrMemI:
7585 case BO_Assign:
7586 case BO_MulAssign:
7587 case BO_DivAssign:
7588 case BO_RemAssign:
7589 case BO_AddAssign:
7590 case BO_SubAssign:
7591 case BO_ShlAssign:
7592 case BO_ShrAssign:
7593 case BO_AndAssign:
7594 case BO_XorAssign:
7595 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00007596 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7597 // constant expressions, but they can never be ICEs because an ICE cannot
7598 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00007599 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007600
John McCalle3027922010-08-25 11:45:40 +00007601 case BO_Mul:
7602 case BO_Div:
7603 case BO_Rem:
7604 case BO_Add:
7605 case BO_Sub:
7606 case BO_Shl:
7607 case BO_Shr:
7608 case BO_LT:
7609 case BO_GT:
7610 case BO_LE:
7611 case BO_GE:
7612 case BO_EQ:
7613 case BO_NE:
7614 case BO_And:
7615 case BO_Xor:
7616 case BO_Or:
7617 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00007618 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7619 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00007620 if (Exp->getOpcode() == BO_Div ||
7621 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00007622 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00007623 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00007624 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00007625 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007626 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00007627 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007628 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00007629 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00007630 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00007631 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007632 }
7633 }
7634 }
John McCalle3027922010-08-25 11:45:40 +00007635 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007636 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00007637 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7638 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00007639 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7640 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007641 } else {
7642 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00007643 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00007644 }
7645 }
Richard Smith9e575da2012-12-28 13:25:52 +00007646 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007647 }
John McCalle3027922010-08-25 11:45:40 +00007648 case BO_LAnd:
7649 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00007650 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7651 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007652 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00007653 // Rare case where the RHS has a comma "side-effect"; we need
7654 // to actually check the condition to see whether the side
7655 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00007656 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00007657 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00007658 return RHSResult;
7659 return NoDiag();
7660 }
7661
Richard Smith9e575da2012-12-28 13:25:52 +00007662 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00007663 }
7664 }
7665 }
7666 case Expr::ImplicitCastExprClass:
7667 case Expr::CStyleCastExprClass:
7668 case Expr::CXXFunctionalCastExprClass:
7669 case Expr::CXXStaticCastExprClass:
7670 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00007671 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007672 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00007673 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00007674 if (isa<ExplicitCastExpr>(E)) {
7675 if (const FloatingLiteral *FL
7676 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7677 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7678 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7679 APSInt IgnoredVal(DestWidth, !DestSigned);
7680 bool Ignored;
7681 // If the value does not fit in the destination type, the behavior is
7682 // undefined, so we are not required to treat it as a constant
7683 // expression.
7684 if (FL->getValue().convertToInteger(IgnoredVal,
7685 llvm::APFloat::rmTowardZero,
7686 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00007687 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00007688 return NoDiag();
7689 }
7690 }
Eli Friedman76d4e432011-09-29 21:49:34 +00007691 switch (cast<CastExpr>(E)->getCastKind()) {
7692 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007693 case CK_AtomicToNonAtomic:
7694 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00007695 case CK_NoOp:
7696 case CK_IntegralToBoolean:
7697 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00007698 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00007699 default:
Richard Smith9e575da2012-12-28 13:25:52 +00007700 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00007701 }
John McCall864e3962010-05-07 05:32:02 +00007702 }
John McCallc07a0c72011-02-17 10:25:35 +00007703 case Expr::BinaryConditionalOperatorClass: {
7704 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7705 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007706 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00007707 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007708 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7709 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7710 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00007711 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00007712 return FalseResult;
7713 }
John McCall864e3962010-05-07 05:32:02 +00007714 case Expr::ConditionalOperatorClass: {
7715 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7716 // If the condition (ignoring parens) is a __builtin_constant_p call,
7717 // then only the true side is actually considered in an integer constant
7718 // expression, and it is fully evaluated. This is an important GNU
7719 // extension. See GCC PR38377 for discussion.
7720 if (const CallExpr *CallCE
7721 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00007722 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7723 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00007724 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00007725 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007726 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007727
Richard Smithf57d8cb2011-12-09 22:58:01 +00007728 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7729 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00007730
Richard Smith9e575da2012-12-28 13:25:52 +00007731 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007732 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007733 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00007734 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007735 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00007736 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00007737 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00007738 return NoDiag();
7739 // Rare case where the diagnostics depend on which side is evaluated
7740 // Note that if we get here, CondResult is 0, and at least one of
7741 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00007742 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00007743 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00007744 return TrueResult;
7745 }
7746 case Expr::CXXDefaultArgExprClass:
7747 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00007748 case Expr::CXXDefaultInitExprClass:
7749 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00007750 case Expr::ChooseExprClass: {
7751 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
7752 }
7753 }
7754
David Blaikiee4d798f2012-01-20 21:50:17 +00007755 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00007756}
7757
Richard Smithf57d8cb2011-12-09 22:58:01 +00007758/// Evaluate an expression as a C++11 integral constant expression.
7759static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
7760 const Expr *E,
7761 llvm::APSInt *Value,
7762 SourceLocation *Loc) {
7763 if (!E->getType()->isIntegralOrEnumerationType()) {
7764 if (Loc) *Loc = E->getExprLoc();
7765 return false;
7766 }
7767
Richard Smith66e05fe2012-01-18 05:21:49 +00007768 APValue Result;
7769 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00007770 return false;
7771
Richard Smith66e05fe2012-01-18 05:21:49 +00007772 assert(Result.isInt() && "pointer cast to int is not an ICE");
7773 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00007774 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007775}
7776
Richard Smith92b1ce02011-12-12 09:28:41 +00007777bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007778 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007779 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
7780
Richard Smith9e575da2012-12-28 13:25:52 +00007781 ICEDiag D = CheckICE(this, Ctx);
7782 if (D.Kind != IK_ICE) {
7783 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00007784 return false;
7785 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007786 return true;
7787}
7788
7789bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
7790 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007791 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007792 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
7793
7794 if (!isIntegerConstantExpr(Ctx, Loc))
7795 return false;
7796 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00007797 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00007798 return true;
7799}
Richard Smith66e05fe2012-01-18 05:21:49 +00007800
Richard Smith98a0a492012-02-14 21:38:30 +00007801bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00007802 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00007803}
7804
Richard Smith66e05fe2012-01-18 05:21:49 +00007805bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7806 SourceLocation *Loc) const {
7807 // We support this checking in C++98 mode in order to diagnose compatibility
7808 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007809 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00007810
Richard Smith98a0a492012-02-14 21:38:30 +00007811 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00007812 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007813 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00007814 Status.Diag = &Diags;
7815 EvalInfo Info(Ctx, Status);
7816
7817 APValue Scratch;
7818 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
7819
7820 if (!Diags.empty()) {
7821 IsConstExpr = false;
7822 if (Loc) *Loc = Diags[0].first;
7823 } else if (!IsConstExpr) {
7824 // FIXME: This shouldn't happen.
7825 if (Loc) *Loc = getExprLoc();
7826 }
7827
7828 return IsConstExpr;
7829}
Richard Smith253c2a32012-01-27 01:14:48 +00007830
7831bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007832 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00007833 PartialDiagnosticAt> &Diags) {
7834 // FIXME: It would be useful to check constexpr function templates, but at the
7835 // moment the constant expression evaluator cannot cope with the non-rigorous
7836 // ASTs which we build for dependent expressions.
7837 if (FD->isDependentContext())
7838 return true;
7839
7840 Expr::EvalStatus Status;
7841 Status.Diag = &Diags;
7842
7843 EvalInfo Info(FD->getASTContext(), Status);
7844 Info.CheckingPotentialConstantExpression = true;
7845
7846 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7847 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
7848
Richard Smith7525ff62013-05-09 07:14:00 +00007849 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00007850 // is a temporary being used as the 'this' pointer.
7851 LValue This;
7852 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00007853 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00007854
Richard Smith253c2a32012-01-27 01:14:48 +00007855 ArrayRef<const Expr*> Args;
7856
7857 SourceLocation Loc = FD->getLocation();
7858
Richard Smith2e312c82012-03-03 22:46:17 +00007859 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00007860 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
7861 // Evaluate the call as a constant initializer, to allow the construction
7862 // of objects of non-literal types.
7863 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00007864 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00007865 } else
Richard Smith253c2a32012-01-27 01:14:48 +00007866 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
7867 Args, FD->getBody(), Info, Scratch);
7868
7869 return Diags.empty();
7870}