blob: c02df9a70ba183adc474b4a0a17b1d01419fc10a [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
66 return B.get<const Expr*>()->getType();
67 }
68
Richard Smithd62306a2011-11-10 06:34:14 +000069 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000070 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000071 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000072 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000073 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000075 return Value;
76 }
77
78 /// Get an LValue path entry, which is known to not be an array index, as a
79 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000080 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000081 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +000082 }
83 /// Get an LValue path entry, which is known to not be an array index, as a
84 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +000085 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000086 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +000087 }
88 /// Determine whether this LValue path entry for a base class names a virtual
89 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +000090 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000091 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +000092 }
93
Richard Smitha8105bc2012-01-06 16:39:00 +000094 /// Find the path length and type of the most-derived subobject in the given
95 /// path, and find the size of the containing array, if any.
96 static
97 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
98 ArrayRef<APValue::LValuePathEntry> Path,
99 uint64_t &ArraySize, QualType &Type) {
100 unsigned MostDerivedLength = 0;
101 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000103 if (Type->isArrayType()) {
104 const ConstantArrayType *CAT =
105 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
106 Type = CAT->getElementType();
107 ArraySize = CAT->getSize().getZExtValue();
108 MostDerivedLength = I + 1;
Richard Smith66c96992012-02-18 22:04:06 +0000109 } else if (Type->isAnyComplexType()) {
110 const ComplexType *CT = Type->castAs<ComplexType>();
111 Type = CT->getElementType();
112 ArraySize = 2;
113 MostDerivedLength = I + 1;
Richard Smitha8105bc2012-01-06 16:39:00 +0000114 } else if (const FieldDecl *FD = getAsField(Path[I])) {
115 Type = FD->getType();
116 ArraySize = 0;
117 MostDerivedLength = I + 1;
118 } else {
Richard Smith80815602011-11-07 05:07:52 +0000119 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000120 ArraySize = 0;
121 }
Richard Smith80815602011-11-07 05:07:52 +0000122 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000123 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000124 }
125
Richard Smitha8105bc2012-01-06 16:39:00 +0000126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000129 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000130 };
131
Richard Smith96e0c102011-11-04 02:25:55 +0000132 /// A path from a glvalue to a subobject of that glvalue.
133 struct SubobjectDesignator {
134 /// True if the subobject was named in a manner not supported by C++11. Such
135 /// lvalues can still be folded, but they are not core constant expressions
136 /// and we cannot perform lvalue-to-rvalue conversions on them.
137 bool Invalid : 1;
138
Richard Smitha8105bc2012-01-06 16:39:00 +0000139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000141
Richard Smitha8105bc2012-01-06 16:39:00 +0000142 /// The length of the path to the most-derived object of which this is a
143 /// subobject.
144 unsigned MostDerivedPathLength : 30;
145
146 /// The size of the array of which the most-derived object is an element, or
147 /// 0 if the most-derived object is not an array element.
148 uint64_t MostDerivedArraySize;
149
150 /// The type of the most derived object referred to by this address.
151 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000152
Richard Smith80815602011-11-07 05:07:52 +0000153 typedef APValue::LValuePathEntry PathEntry;
154
Richard Smith96e0c102011-11-04 02:25:55 +0000155 /// The entries on the path from the glvalue to the designated subobject.
156 SmallVector<PathEntry, 8> Entries;
157
Richard Smitha8105bc2012-01-06 16:39:00 +0000158 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000159
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 explicit SubobjectDesignator(QualType T)
161 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
162 MostDerivedArraySize(0), MostDerivedType(T) {}
163
164 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
165 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
166 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000167 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000169 ArrayRef<PathEntry> VEntries = V.getLValuePath();
170 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
175 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000176 }
177 }
178
Richard Smith96e0c102011-11-04 02:25:55 +0000179 void setInvalid() {
180 Invalid = true;
181 Entries.clear();
182 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000183
184 /// Determine whether this is a one-past-the-end pointer.
185 bool isOnePastTheEnd() const {
186 if (IsOnePastTheEnd)
187 return true;
188 if (MostDerivedArraySize &&
189 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
190 return true;
191 return false;
192 }
193
194 /// Check that this refers to a valid subobject.
195 bool isValidSubobject() const {
196 if (Invalid)
197 return false;
198 return !isOnePastTheEnd();
199 }
200 /// Check that this refers to a valid subobject, and if not, produce a
201 /// relevant diagnostic and set the designator as invalid.
202 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
203
204 /// Update this designator to refer to the first element within this array.
205 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000206 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000207 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000208 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000209
210 // This is a most-derived object.
211 MostDerivedType = CAT->getElementType();
212 MostDerivedArraySize = CAT->getSize().getZExtValue();
213 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000214 }
215 /// Update this designator to refer to the given base or member of this
216 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000218 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000221 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000222
223 // If this isn't a base class, it's a new most-derived object.
224 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
225 MostDerivedType = FD->getType();
226 MostDerivedArraySize = 0;
227 MostDerivedPathLength = Entries.size();
228 }
Richard Smith96e0c102011-11-04 02:25:55 +0000229 }
Richard Smith66c96992012-02-18 22:04:06 +0000230 /// Update this designator to refer to the given complex component.
231 void addComplexUnchecked(QualType EltTy, bool Imag) {
232 PathEntry Entry;
233 Entry.ArrayIndex = Imag;
234 Entries.push_back(Entry);
235
236 // This is technically a most-derived object, though in practice this
237 // is unlikely to matter.
238 MostDerivedType = EltTy;
239 MostDerivedArraySize = 2;
240 MostDerivedPathLength = Entries.size();
241 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000243 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000245 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000247 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250 setInvalid();
251 }
Richard Smith96e0c102011-11-04 02:25:55 +0000252 return;
253 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000254 // [expr.add]p4: For the purposes of these operators, a pointer to a
255 // nonarray object behaves the same as a pointer to the first element of
256 // an array of length one with the type of the object as its element type.
257 if (IsOnePastTheEnd && N == (uint64_t)-1)
258 IsOnePastTheEnd = false;
259 else if (!IsOnePastTheEnd && N == 1)
260 IsOnePastTheEnd = true;
261 else if (N != 0) {
262 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000263 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 }
Richard Smith96e0c102011-11-04 02:25:55 +0000265 }
266 };
267
Richard Smith254a73d2011-10-28 22:34:42 +0000268 /// A stack frame in the constexpr call stack.
269 struct CallStackFrame {
270 EvalInfo &Info;
271
272 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000273 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000274
Richard Smithf6f003a2011-12-16 19:06:07 +0000275 /// CallLoc - The location of the call expression for this call.
276 SourceLocation CallLoc;
277
278 /// Callee - The function which was called.
279 const FunctionDecl *Callee;
280
Richard Smithb228a862012-02-15 02:18:13 +0000281 /// Index - The call index of this call.
282 unsigned Index;
283
Richard Smithd62306a2011-11-10 06:34:14 +0000284 /// This - The binding for the this pointer in this call, if any.
285 const LValue *This;
286
Richard Smith254a73d2011-10-28 22:34:42 +0000287 /// ParmBindings - Parameter bindings for this function call, indexed by
288 /// parameters' function scope indices.
Richard Smith2e312c82012-03-03 22:46:17 +0000289 const 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.
293 typedef std::map<const Expr*, 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 Smith2e312c82012-03-03 22:46:17 +0000300 const APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000301 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000302 };
303
Richard Smith852c9db2013-04-20 22:23:05 +0000304 /// Temporarily override 'this'.
305 class ThisOverrideRAII {
306 public:
307 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
308 : Frame(Frame), OldThis(Frame.This) {
309 if (Enable)
310 Frame.This = NewThis;
311 }
312 ~ThisOverrideRAII() {
313 Frame.This = OldThis;
314 }
315 private:
316 CallStackFrame &Frame;
317 const LValue *OldThis;
318 };
319
Richard Smith92b1ce02011-12-12 09:28:41 +0000320 /// A partial diagnostic which we might know in advance that we are not going
321 /// to emit.
322 class OptionalDiagnostic {
323 PartialDiagnostic *Diag;
324
325 public:
326 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
327
328 template<typename T>
329 OptionalDiagnostic &operator<<(const T &v) {
330 if (Diag)
331 *Diag << v;
332 return *this;
333 }
Richard Smithfe800032012-01-31 04:08:20 +0000334
335 OptionalDiagnostic &operator<<(const APSInt &I) {
336 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000337 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000338 I.toString(Buffer);
339 *Diag << StringRef(Buffer.data(), Buffer.size());
340 }
341 return *this;
342 }
343
344 OptionalDiagnostic &operator<<(const APFloat &F) {
345 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000346 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000347 F.toString(Buffer);
348 *Diag << StringRef(Buffer.data(), Buffer.size());
349 }
350 return *this;
351 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000352 };
353
Richard Smithb228a862012-02-15 02:18:13 +0000354 /// EvalInfo - This is a private struct used by the evaluator to capture
355 /// information about a subexpression as it is folded. It retains information
356 /// about the AST context, but also maintains information about the folded
357 /// expression.
358 ///
359 /// If an expression could be evaluated, it is still possible it is not a C
360 /// "integer constant expression" or constant expression. If not, this struct
361 /// captures information about how and why not.
362 ///
363 /// One bit of information passed *into* the request for constant folding
364 /// indicates whether the subexpression is "evaluated" or not according to C
365 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
366 /// evaluate the expression regardless of what the RHS is, but C only allows
367 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000368 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000369 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000370
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000371 /// EvalStatus - Contains information about the evaluation.
372 Expr::EvalStatus &EvalStatus;
373
374 /// CurrentCall - The top of the constexpr call stack.
375 CallStackFrame *CurrentCall;
376
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000377 /// CallStackDepth - The number of calls in the call stack right now.
378 unsigned CallStackDepth;
379
Richard Smithb228a862012-02-15 02:18:13 +0000380 /// NextCallIndex - The next call index to assign.
381 unsigned NextCallIndex;
382
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000383 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000384 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000385 CallStackFrame BottomFrame;
386
Richard Smithd62306a2011-11-10 06:34:14 +0000387 /// EvaluatingDecl - This is the declaration whose initializer is being
388 /// evaluated, if any.
389 const VarDecl *EvaluatingDecl;
390
391 /// EvaluatingDeclValue - This is the value being constructed for the
392 /// declaration whose initializer is being evaluated, if any.
393 APValue *EvaluatingDeclValue;
394
Richard Smith357362d2011-12-13 06:39:58 +0000395 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
396 /// notes attached to it will also be stored, otherwise they will not be.
397 bool HasActiveDiagnostic;
398
Richard Smith253c2a32012-01-27 01:14:48 +0000399 /// CheckingPotentialConstantExpression - Are we checking whether the
400 /// expression is a potential constant expression? If so, some diagnostics
401 /// are suppressed.
402 bool CheckingPotentialConstantExpression;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000403
404 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000405
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000406 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
407 bool OverflowCheckMode=false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000408 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000409 CallStackDepth(0), NextCallIndex(1),
410 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith253c2a32012-01-27 01:14:48 +0000411 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000412 CheckingPotentialConstantExpression(false),
413 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000414
Richard Smithd62306a2011-11-10 06:34:14 +0000415 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
416 EvaluatingDecl = VD;
417 EvaluatingDeclValue = &Value;
418 }
419
David Blaikiebbafb8a2012-03-11 07:00:24 +0000420 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000421
Richard Smith357362d2011-12-13 06:39:58 +0000422 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000423 // Don't perform any constexpr calls (other than the call we're checking)
424 // when checking a potential constant expression.
425 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
426 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000427 if (NextCallIndex == 0) {
428 // NextCallIndex has wrapped around.
429 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
430 return false;
431 }
Richard Smith357362d2011-12-13 06:39:58 +0000432 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
433 return true;
434 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
435 << getLangOpts().ConstexprCallDepth;
436 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000437 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000438
Richard Smithb228a862012-02-15 02:18:13 +0000439 CallStackFrame *getCallFrame(unsigned CallIndex) {
440 assert(CallIndex && "no call index in getCallFrame");
441 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
442 // be null in this loop.
443 CallStackFrame *Frame = CurrentCall;
444 while (Frame->Index > CallIndex)
445 Frame = Frame->Caller;
446 return (Frame->Index == CallIndex) ? Frame : 0;
447 }
448
Richard Smith357362d2011-12-13 06:39:58 +0000449 private:
450 /// Add a diagnostic to the diagnostics list.
451 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
452 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
453 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
454 return EvalStatus.Diag->back().second;
455 }
456
Richard Smithf6f003a2011-12-16 19:06:07 +0000457 /// Add notes containing a call stack to the current point of evaluation.
458 void addCallStack(unsigned Limit);
459
Richard Smith357362d2011-12-13 06:39:58 +0000460 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000461 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000462 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
463 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000464 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000465 // If we have a prior diagnostic, it will be noting that the expression
466 // isn't a constant expression. This diagnostic is more important.
467 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000468 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000469 unsigned CallStackNotes = CallStackDepth - 1;
470 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
471 if (Limit)
472 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith253c2a32012-01-27 01:14:48 +0000473 if (CheckingPotentialConstantExpression)
474 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000475
Richard Smith357362d2011-12-13 06:39:58 +0000476 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000477 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000478 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
479 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000480 if (!CheckingPotentialConstantExpression)
481 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000482 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000483 }
Richard Smith357362d2011-12-13 06:39:58 +0000484 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000485 return OptionalDiagnostic();
486 }
487
Richard Smithce1ec5e2012-03-15 04:53:45 +0000488 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
489 = diag::note_invalid_subexpr_in_const_expr,
490 unsigned ExtraNotes = 0) {
491 if (EvalStatus.Diag)
492 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
493 HasActiveDiagnostic = false;
494 return OptionalDiagnostic();
495 }
496
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000497 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
498
Richard Smith92b1ce02011-12-12 09:28:41 +0000499 /// Diagnose that the evaluation does not produce a C++11 core constant
500 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000501 template<typename LocArg>
502 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000503 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000504 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000505 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000506 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
507 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000508 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000509 }
Richard Smith357362d2011-12-13 06:39:58 +0000510 return Diag(Loc, DiagId, ExtraNotes);
511 }
512
513 /// Add a note to a prior diagnostic.
514 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
515 if (!HasActiveDiagnostic)
516 return OptionalDiagnostic();
517 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000518 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000519
520 /// Add a stack of notes to a prior diagnostic.
521 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
522 if (HasActiveDiagnostic) {
523 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
524 Diags.begin(), Diags.end());
525 }
526 }
Richard Smith253c2a32012-01-27 01:14:48 +0000527
528 /// Should we continue evaluation as much as possible after encountering a
529 /// construct which can't be folded?
530 bool keepEvaluatingAfterFailure() {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000531 // Should return true in IntOverflowCheckMode, so that we check for
532 // overflow even if some subexpressions can't be evaluated as constants.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000533 return IntOverflowCheckMode ||
534 (CheckingPotentialConstantExpression &&
535 EvalStatus.Diag && EvalStatus.Diag->empty());
Richard Smith253c2a32012-01-27 01:14:48 +0000536 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000537 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000538
539 /// Object used to treat all foldable expressions as constant expressions.
540 struct FoldConstant {
541 bool Enabled;
542
543 explicit FoldConstant(EvalInfo &Info)
544 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
545 !Info.EvalStatus.HasSideEffects) {
546 }
547 // Treat the value we've computed since this object was created as constant.
548 void Fold(EvalInfo &Info) {
549 if (Enabled && !Info.EvalStatus.Diag->empty() &&
550 !Info.EvalStatus.HasSideEffects)
551 Info.EvalStatus.Diag->clear();
552 }
553 };
Richard Smith17100ba2012-02-16 02:46:34 +0000554
555 /// RAII object used to suppress diagnostics and side-effects from a
556 /// speculative evaluation.
557 class SpeculativeEvaluationRAII {
558 EvalInfo &Info;
559 Expr::EvalStatus Old;
560
561 public:
562 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000563 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000564 : Info(Info), Old(Info.EvalStatus) {
565 Info.EvalStatus.Diag = NewDiag;
566 }
567 ~SpeculativeEvaluationRAII() {
568 Info.EvalStatus = Old;
569 }
570 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000571}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000572
Richard Smitha8105bc2012-01-06 16:39:00 +0000573bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
574 CheckSubobjectKind CSK) {
575 if (Invalid)
576 return false;
577 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000578 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000579 << CSK;
580 setInvalid();
581 return false;
582 }
583 return true;
584}
585
586void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
587 const Expr *E, uint64_t N) {
588 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000589 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000590 << static_cast<int>(N) << /*array*/ 0
591 << static_cast<unsigned>(MostDerivedArraySize);
592 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000593 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000594 << static_cast<int>(N) << /*non-array*/ 1;
595 setInvalid();
596}
597
Richard Smithf6f003a2011-12-16 19:06:07 +0000598CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
599 const FunctionDecl *Callee, const LValue *This,
Richard Smith2e312c82012-03-03 22:46:17 +0000600 const APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000601 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000602 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000603 Info.CurrentCall = this;
604 ++Info.CallStackDepth;
605}
606
607CallStackFrame::~CallStackFrame() {
608 assert(Info.CurrentCall == this && "calls retired out of order");
609 --Info.CallStackDepth;
610 Info.CurrentCall = Caller;
611}
612
613/// Produce a string describing the given constexpr call.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000614static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000615 unsigned ArgIndex = 0;
616 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith74388b42012-02-04 00:33:54 +0000617 !isa<CXXConstructorDecl>(Frame->Callee) &&
618 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smithf6f003a2011-12-16 19:06:07 +0000619
620 if (!IsMemberCall)
621 Out << *Frame->Callee << '(';
622
623 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
624 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumib8efa1e2012-01-26 09:37:36 +0000625 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smithf6f003a2011-12-16 19:06:07 +0000626 Out << ", ";
627
628 const ParmVarDecl *Param = *I;
Richard Smith2e312c82012-03-03 22:46:17 +0000629 const APValue &Arg = Frame->Arguments[ArgIndex];
630 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smithf6f003a2011-12-16 19:06:07 +0000631
632 if (ArgIndex == 0 && IsMemberCall)
633 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000634 }
635
Richard Smithf6f003a2011-12-16 19:06:07 +0000636 Out << ')';
637}
638
639void EvalInfo::addCallStack(unsigned Limit) {
640 // Determine which calls to skip, if any.
641 unsigned ActiveCalls = CallStackDepth - 1;
642 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
643 if (Limit && Limit < ActiveCalls) {
644 SkipStart = Limit / 2 + Limit % 2;
645 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000646 }
647
Richard Smithf6f003a2011-12-16 19:06:07 +0000648 // Walk the call stack and add the diagnostics.
649 unsigned CallIdx = 0;
650 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
651 Frame = Frame->Caller, ++CallIdx) {
652 // Skip this call?
653 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
654 if (CallIdx == SkipStart) {
655 // Note that we're skipping calls.
656 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
657 << unsigned(ActiveCalls - Limit);
658 }
659 continue;
660 }
661
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000662 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000663 llvm::raw_svector_ostream Out(Buffer);
664 describeCall(Frame, Out);
665 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
666 }
667}
668
669namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000670 struct ComplexValue {
671 private:
672 bool IsInt;
673
674 public:
675 APSInt IntReal, IntImag;
676 APFloat FloatReal, FloatImag;
677
678 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
679
680 void makeComplexFloat() { IsInt = false; }
681 bool isComplexFloat() const { return !IsInt; }
682 APFloat &getComplexFloatReal() { return FloatReal; }
683 APFloat &getComplexFloatImag() { return FloatImag; }
684
685 void makeComplexInt() { IsInt = true; }
686 bool isComplexInt() const { return IsInt; }
687 APSInt &getComplexIntReal() { return IntReal; }
688 APSInt &getComplexIntImag() { return IntImag; }
689
Richard Smith2e312c82012-03-03 22:46:17 +0000690 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000691 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000692 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000693 else
Richard Smith2e312c82012-03-03 22:46:17 +0000694 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000695 }
Richard Smith2e312c82012-03-03 22:46:17 +0000696 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000697 assert(v.isComplexFloat() || v.isComplexInt());
698 if (v.isComplexFloat()) {
699 makeComplexFloat();
700 FloatReal = v.getComplexFloatReal();
701 FloatImag = v.getComplexFloatImag();
702 } else {
703 makeComplexInt();
704 IntReal = v.getComplexIntReal();
705 IntImag = v.getComplexIntImag();
706 }
707 }
John McCall93d91dc2010-05-07 17:22:02 +0000708 };
John McCall45d55e42010-05-07 21:00:08 +0000709
710 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000711 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000712 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000713 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000714 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000715
Richard Smithce40ad62011-11-12 22:28:03 +0000716 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000717 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000718 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000719 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000720 SubobjectDesignator &getLValueDesignator() { return Designator; }
721 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000722
Richard Smith2e312c82012-03-03 22:46:17 +0000723 void moveInto(APValue &V) const {
724 if (Designator.Invalid)
725 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
726 else
727 V = APValue(Base, Offset, Designator.Entries,
728 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000729 }
Richard Smith2e312c82012-03-03 22:46:17 +0000730 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000731 assert(V.isLValue());
732 Base = V.getLValueBase();
733 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000734 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000735 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000736 }
737
Richard Smithb228a862012-02-15 02:18:13 +0000738 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000739 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000740 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000741 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000742 Designator = SubobjectDesignator(getType(B));
743 }
744
745 // Check that this LValue is not based on a null pointer. If it is, produce
746 // a diagnostic and mark the designator as invalid.
747 bool checkNullPointer(EvalInfo &Info, const Expr *E,
748 CheckSubobjectKind CSK) {
749 if (Designator.Invalid)
750 return false;
751 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000752 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000753 << CSK;
754 Designator.setInvalid();
755 return false;
756 }
757 return true;
758 }
759
760 // Check this LValue refers to an object. If not, set the designator to be
761 // invalid and emit a diagnostic.
762 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000763 // Outside C++11, do not build a designator referring to a subobject of
764 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000765 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000766 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000767 return checkNullPointer(Info, E, CSK) &&
768 Designator.checkSubobject(Info, E, CSK);
769 }
770
771 void addDecl(EvalInfo &Info, const Expr *E,
772 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000773 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
774 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000775 }
776 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000777 if (checkSubobject(Info, E, CSK_ArrayToPointer))
778 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000779 }
Richard Smith66c96992012-02-18 22:04:06 +0000780 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000781 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
782 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000783 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000784 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000785 if (checkNullPointer(Info, E, CSK_ArrayIndex))
786 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000787 }
John McCall45d55e42010-05-07 21:00:08 +0000788 };
Richard Smith027bf112011-11-17 22:56:20 +0000789
790 struct MemberPtr {
791 MemberPtr() {}
792 explicit MemberPtr(const ValueDecl *Decl) :
793 DeclAndIsDerivedMember(Decl, false), Path() {}
794
795 /// The member or (direct or indirect) field referred to by this member
796 /// pointer, or 0 if this is a null member pointer.
797 const ValueDecl *getDecl() const {
798 return DeclAndIsDerivedMember.getPointer();
799 }
800 /// Is this actually a member of some type derived from the relevant class?
801 bool isDerivedMember() const {
802 return DeclAndIsDerivedMember.getInt();
803 }
804 /// Get the class which the declaration actually lives in.
805 const CXXRecordDecl *getContainingRecord() const {
806 return cast<CXXRecordDecl>(
807 DeclAndIsDerivedMember.getPointer()->getDeclContext());
808 }
809
Richard Smith2e312c82012-03-03 22:46:17 +0000810 void moveInto(APValue &V) const {
811 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000812 }
Richard Smith2e312c82012-03-03 22:46:17 +0000813 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000814 assert(V.isMemberPointer());
815 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
816 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
817 Path.clear();
818 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
819 Path.insert(Path.end(), P.begin(), P.end());
820 }
821
822 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
823 /// whether the member is a member of some class derived from the class type
824 /// of the member pointer.
825 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
826 /// Path - The path of base/derived classes from the member declaration's
827 /// class (exclusive) to the class type of the member pointer (inclusive).
828 SmallVector<const CXXRecordDecl*, 4> Path;
829
830 /// Perform a cast towards the class of the Decl (either up or down the
831 /// hierarchy).
832 bool castBack(const CXXRecordDecl *Class) {
833 assert(!Path.empty());
834 const CXXRecordDecl *Expected;
835 if (Path.size() >= 2)
836 Expected = Path[Path.size() - 2];
837 else
838 Expected = getContainingRecord();
839 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
840 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
841 // if B does not contain the original member and is not a base or
842 // derived class of the class containing the original member, the result
843 // of the cast is undefined.
844 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
845 // (D::*). We consider that to be a language defect.
846 return false;
847 }
848 Path.pop_back();
849 return true;
850 }
851 /// Perform a base-to-derived member pointer cast.
852 bool castToDerived(const CXXRecordDecl *Derived) {
853 if (!getDecl())
854 return true;
855 if (!isDerivedMember()) {
856 Path.push_back(Derived);
857 return true;
858 }
859 if (!castBack(Derived))
860 return false;
861 if (Path.empty())
862 DeclAndIsDerivedMember.setInt(false);
863 return true;
864 }
865 /// Perform a derived-to-base member pointer cast.
866 bool castToBase(const CXXRecordDecl *Base) {
867 if (!getDecl())
868 return true;
869 if (Path.empty())
870 DeclAndIsDerivedMember.setInt(true);
871 if (isDerivedMember()) {
872 Path.push_back(Base);
873 return true;
874 }
875 return castBack(Base);
876 }
877 };
Richard Smith357362d2011-12-13 06:39:58 +0000878
Richard Smith7bb00672012-02-01 01:42:44 +0000879 /// Compare two member pointers, which are assumed to be of the same type.
880 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
881 if (!LHS.getDecl() || !RHS.getDecl())
882 return !LHS.getDecl() && !RHS.getDecl();
883 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
884 return false;
885 return LHS.Path == RHS.Path;
886 }
887
Richard Smith357362d2011-12-13 06:39:58 +0000888 /// Kinds of constant expression checking, for diagnostics.
889 enum CheckConstantExpressionKind {
890 CCEK_Constant, ///< A normal constant.
891 CCEK_ReturnValue, ///< A constexpr function return value.
892 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
893 };
John McCall93d91dc2010-05-07 17:22:02 +0000894}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000895
Richard Smith2e312c82012-03-03 22:46:17 +0000896static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000897static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
898 const LValue &This, const Expr *E,
899 CheckConstantExpressionKind CCEK = CCEK_Constant,
900 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000901static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
902static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000903static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
904 EvalInfo &Info);
905static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000906static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000907static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000908 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000909static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000910static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000911
912//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000913// Misc utilities
914//===----------------------------------------------------------------------===//
915
Richard Smithd62306a2011-11-10 06:34:14 +0000916/// Should this call expression be treated as a string literal?
917static bool IsStringLiteralCall(const CallExpr *E) {
918 unsigned Builtin = E->isBuiltinCall();
919 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
920 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
921}
922
Richard Smithce40ad62011-11-12 22:28:03 +0000923static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000924 // C++11 [expr.const]p3 An address constant expression is a prvalue core
925 // constant expression of pointer type that evaluates to...
926
927 // ... a null pointer value, or a prvalue core constant expression of type
928 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000929 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000930
Richard Smithce40ad62011-11-12 22:28:03 +0000931 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
932 // ... the address of an object with static storage duration,
933 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
934 return VD->hasGlobalStorage();
935 // ... the address of a function,
936 return isa<FunctionDecl>(D);
937 }
938
939 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000940 switch (E->getStmtClass()) {
941 default:
942 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000943 case Expr::CompoundLiteralExprClass: {
944 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
945 return CLE->isFileScope() && CLE->isLValue();
946 }
Richard Smithd62306a2011-11-10 06:34:14 +0000947 // A string literal has static storage duration.
948 case Expr::StringLiteralClass:
949 case Expr::PredefinedExprClass:
950 case Expr::ObjCStringLiteralClass:
951 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000952 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000953 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000954 return true;
955 case Expr::CallExprClass:
956 return IsStringLiteralCall(cast<CallExpr>(E));
957 // For GCC compatibility, &&label has static storage duration.
958 case Expr::AddrLabelExprClass:
959 return true;
960 // A Block literal expression may be used as the initialization value for
961 // Block variables at global or local static scope.
962 case Expr::BlockExprClass:
963 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000964 case Expr::ImplicitValueInitExprClass:
965 // FIXME:
966 // We can never form an lvalue with an implicit value initialization as its
967 // base through expression evaluation, so these only appear in one case: the
968 // implicit variable declaration we invent when checking whether a constexpr
969 // constructor can produce a constant expression. We must assume that such
970 // an expression might be a global lvalue.
971 return true;
Richard Smithd62306a2011-11-10 06:34:14 +0000972 }
John McCall95007602010-05-10 23:27:23 +0000973}
974
Richard Smithb228a862012-02-15 02:18:13 +0000975static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
976 assert(Base && "no location for a null lvalue");
977 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
978 if (VD)
979 Info.Note(VD->getLocation(), diag::note_declared_at);
980 else
Ted Kremenek28831752012-08-23 20:46:57 +0000981 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +0000982 diag::note_constexpr_temporary_here);
983}
984
Richard Smith80815602011-11-07 05:07:52 +0000985/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +0000986/// value for an address or reference constant expression. Return true if we
987/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +0000988static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
989 QualType Type, const LValue &LVal) {
990 bool IsReferenceType = Type->isReferenceType();
991
Richard Smith357362d2011-12-13 06:39:58 +0000992 APValue::LValueBase Base = LVal.getLValueBase();
993 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
994
Richard Smith0dea49e2012-02-18 04:58:18 +0000995 // Check that the object is a global. Note that the fake 'this' object we
996 // manufacture when checking potential constant expressions is conservatively
997 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +0000998 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000999 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001000 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001001 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1002 << IsReferenceType << !Designator.Entries.empty()
1003 << !!VD << VD;
1004 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001005 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001006 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001007 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001008 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001009 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001010 }
Richard Smithb228a862012-02-15 02:18:13 +00001011 assert((Info.CheckingPotentialConstantExpression ||
1012 LVal.getLValueCallIndex() == 0) &&
1013 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001014
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001015 // Check if this is a thread-local variable.
1016 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1017 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001018 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001019 return false;
1020 }
1021 }
1022
Richard Smitha8105bc2012-01-06 16:39:00 +00001023 // Allow address constant expressions to be past-the-end pointers. This is
1024 // an extension: the standard requires them to point to an object.
1025 if (!IsReferenceType)
1026 return true;
1027
1028 // A reference constant expression must refer to an object.
1029 if (!Base) {
1030 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001031 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001032 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001033 }
1034
Richard Smith357362d2011-12-13 06:39:58 +00001035 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001036 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001037 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001038 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001039 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001040 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001041 }
1042
Richard Smith80815602011-11-07 05:07:52 +00001043 return true;
1044}
1045
Richard Smithfddd3842011-12-30 21:15:51 +00001046/// Check that this core constant expression is of literal type, and if not,
1047/// produce an appropriate diagnostic.
1048static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1049 if (!E->isRValue() || E->getType()->isLiteralType())
1050 return true;
1051
1052 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001053 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001054 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001055 << E->getType();
1056 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001057 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001058 return false;
1059}
1060
Richard Smith0b0a0b62011-10-29 20:57:55 +00001061/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001062/// constant expression. If not, report an appropriate diagnostic. Does not
1063/// check that the expression is of literal type.
1064static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1065 QualType Type, const APValue &Value) {
1066 // Core issue 1454: For a literal constant expression of array or class type,
1067 // each subobject of its value shall have been initialized by a constant
1068 // expression.
1069 if (Value.isArray()) {
1070 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1071 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1072 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1073 Value.getArrayInitializedElt(I)))
1074 return false;
1075 }
1076 if (!Value.hasArrayFiller())
1077 return true;
1078 return CheckConstantExpression(Info, DiagLoc, EltTy,
1079 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001080 }
Richard Smithb228a862012-02-15 02:18:13 +00001081 if (Value.isUnion() && Value.getUnionField()) {
1082 return CheckConstantExpression(Info, DiagLoc,
1083 Value.getUnionField()->getType(),
1084 Value.getUnionValue());
1085 }
1086 if (Value.isStruct()) {
1087 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1088 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1089 unsigned BaseIndex = 0;
1090 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1091 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1092 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1093 Value.getStructBase(BaseIndex)))
1094 return false;
1095 }
1096 }
1097 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1098 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001099 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1100 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001101 return false;
1102 }
1103 }
1104
1105 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001106 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001107 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001108 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1109 }
1110
1111 // Everything else is fine.
1112 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001113}
1114
Richard Smith83c68212011-10-31 05:11:32 +00001115const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001116 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001117}
1118
1119static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001120 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001121}
1122
Richard Smithcecf1842011-11-01 21:06:14 +00001123static bool IsWeakLValue(const LValue &Value) {
1124 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001125 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001126}
1127
Richard Smith2e312c82012-03-03 22:46:17 +00001128static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001129 // A null base expression indicates a null pointer. These are always
1130 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001131 if (!Value.getLValueBase()) {
1132 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001133 return true;
1134 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001135
Richard Smith027bf112011-11-17 22:56:20 +00001136 // We have a non-null base. These are generally known to be true, but if it's
1137 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001138 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001139 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001140 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001141}
1142
Richard Smith2e312c82012-03-03 22:46:17 +00001143static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001144 switch (Val.getKind()) {
1145 case APValue::Uninitialized:
1146 return false;
1147 case APValue::Int:
1148 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001149 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001150 case APValue::Float:
1151 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001152 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001153 case APValue::ComplexInt:
1154 Result = Val.getComplexIntReal().getBoolValue() ||
1155 Val.getComplexIntImag().getBoolValue();
1156 return true;
1157 case APValue::ComplexFloat:
1158 Result = !Val.getComplexFloatReal().isZero() ||
1159 !Val.getComplexFloatImag().isZero();
1160 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001161 case APValue::LValue:
1162 return EvalPointerValueAsBool(Val, Result);
1163 case APValue::MemberPointer:
1164 Result = Val.getMemberPointerDecl();
1165 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001166 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001167 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001168 case APValue::Struct:
1169 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001170 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001171 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001172 }
1173
Richard Smith11562c52011-10-28 17:51:58 +00001174 llvm_unreachable("unknown APValue kind");
1175}
1176
1177static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1178 EvalInfo &Info) {
1179 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001180 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001181 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001182 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001183 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001184}
1185
Richard Smith357362d2011-12-13 06:39:58 +00001186template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001187static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001188 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001189 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001190 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001191}
1192
1193static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1194 QualType SrcType, const APFloat &Value,
1195 QualType DestType, APSInt &Result) {
1196 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001197 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001198 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001199
Richard Smith357362d2011-12-13 06:39:58 +00001200 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001201 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001202 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1203 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001204 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001205 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001206}
1207
Richard Smith357362d2011-12-13 06:39:58 +00001208static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1209 QualType SrcType, QualType DestType,
1210 APFloat &Result) {
1211 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001212 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001213 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1214 APFloat::rmNearestTiesToEven, &ignored)
1215 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001216 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001217 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001218}
1219
Richard Smith911e1422012-01-30 22:27:01 +00001220static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1221 QualType DestType, QualType SrcType,
1222 APSInt &Value) {
1223 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001224 APSInt Result = Value;
1225 // Figure out if this is a truncate, extend or noop cast.
1226 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001227 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001228 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001229 return Result;
1230}
1231
Richard Smith357362d2011-12-13 06:39:58 +00001232static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1233 QualType SrcType, const APSInt &Value,
1234 QualType DestType, APFloat &Result) {
1235 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1236 if (Result.convertFromAPInt(Value, Value.isSigned(),
1237 APFloat::rmNearestTiesToEven)
1238 & APFloat::opOverflow)
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
Eli Friedman803acb32011-12-22 03:51:45 +00001243static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1244 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001245 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001246 if (!Evaluate(SVal, Info, E))
1247 return false;
1248 if (SVal.isInt()) {
1249 Res = SVal.getInt();
1250 return true;
1251 }
1252 if (SVal.isFloat()) {
1253 Res = SVal.getFloat().bitcastToAPInt();
1254 return true;
1255 }
1256 if (SVal.isVector()) {
1257 QualType VecTy = E->getType();
1258 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1259 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1260 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1261 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1262 Res = llvm::APInt::getNullValue(VecSize);
1263 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1264 APValue &Elt = SVal.getVectorElt(i);
1265 llvm::APInt EltAsInt;
1266 if (Elt.isInt()) {
1267 EltAsInt = Elt.getInt();
1268 } else if (Elt.isFloat()) {
1269 EltAsInt = Elt.getFloat().bitcastToAPInt();
1270 } else {
1271 // Don't try to handle vectors of anything other than int or float
1272 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001273 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001274 return false;
1275 }
1276 unsigned BaseEltSize = EltAsInt.getBitWidth();
1277 if (BigEndian)
1278 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1279 else
1280 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1281 }
1282 return true;
1283 }
1284 // Give up if the input isn't an int, float, or vector. For example, we
1285 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001286 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001287 return false;
1288}
1289
Richard Smitha8105bc2012-01-06 16:39:00 +00001290/// Cast an lvalue referring to a base subobject to a derived class, by
1291/// truncating the lvalue's path to the given length.
1292static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1293 const RecordDecl *TruncatedType,
1294 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001295 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001296
1297 // Check we actually point to a derived class object.
1298 if (TruncatedElements == D.Entries.size())
1299 return true;
1300 assert(TruncatedElements >= D.MostDerivedPathLength &&
1301 "not casting to a derived class");
1302 if (!Result.checkSubobject(Info, E, CSK_Derived))
1303 return false;
1304
1305 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001306 const RecordDecl *RD = TruncatedType;
1307 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001308 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001309 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1310 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001311 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001312 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001313 else
Richard Smithd62306a2011-11-10 06:34:14 +00001314 Result.Offset -= Layout.getBaseClassOffset(Base);
1315 RD = Base;
1316 }
Richard Smith027bf112011-11-17 22:56:20 +00001317 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001318 return true;
1319}
1320
John McCalld7bca762012-05-01 00:38:49 +00001321static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001322 const CXXRecordDecl *Derived,
1323 const CXXRecordDecl *Base,
1324 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001325 if (!RL) {
1326 if (Derived->isInvalidDecl()) return false;
1327 RL = &Info.Ctx.getASTRecordLayout(Derived);
1328 }
1329
Richard Smithd62306a2011-11-10 06:34:14 +00001330 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001331 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001332 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001333}
1334
Richard Smitha8105bc2012-01-06 16:39:00 +00001335static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001336 const CXXRecordDecl *DerivedDecl,
1337 const CXXBaseSpecifier *Base) {
1338 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1339
John McCalld7bca762012-05-01 00:38:49 +00001340 if (!Base->isVirtual())
1341 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001342
Richard Smitha8105bc2012-01-06 16:39:00 +00001343 SubobjectDesignator &D = Obj.Designator;
1344 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001345 return false;
1346
Richard Smitha8105bc2012-01-06 16:39:00 +00001347 // Extract most-derived object and corresponding type.
1348 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1349 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1350 return false;
1351
1352 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001353 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001354 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1355 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001356 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001357 return true;
1358}
1359
1360/// Update LVal to refer to the given field, which must be a member of the type
1361/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001362static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001363 const FieldDecl *FD,
1364 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001365 if (!RL) {
1366 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001367 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001368 }
Richard Smithd62306a2011-11-10 06:34:14 +00001369
1370 unsigned I = FD->getFieldIndex();
1371 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001372 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001373 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001374}
1375
Richard Smith1b78b3d2012-01-25 22:15:11 +00001376/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001377static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001378 LValue &LVal,
1379 const IndirectFieldDecl *IFD) {
1380 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1381 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001382 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1383 return false;
1384 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001385}
1386
Richard Smithd62306a2011-11-10 06:34:14 +00001387/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001388static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1389 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001390 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1391 // extension.
1392 if (Type->isVoidType() || Type->isFunctionType()) {
1393 Size = CharUnits::One();
1394 return true;
1395 }
1396
1397 if (!Type->isConstantSizeType()) {
1398 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001399 // FIXME: Better diagnostic.
1400 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001401 return false;
1402 }
1403
1404 Size = Info.Ctx.getTypeSizeInChars(Type);
1405 return true;
1406}
1407
1408/// Update a pointer value to model pointer arithmetic.
1409/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001410/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001411/// \param LVal - The pointer value to be updated.
1412/// \param EltTy - The pointee type represented by LVal.
1413/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001414static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1415 LValue &LVal, QualType EltTy,
1416 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001417 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001418 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001419 return false;
1420
1421 // Compute the new offset in the appropriate width.
1422 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001423 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001424 return true;
1425}
1426
Richard Smith66c96992012-02-18 22:04:06 +00001427/// Update an lvalue to refer to a component of a complex number.
1428/// \param Info - Information about the ongoing evaluation.
1429/// \param LVal - The lvalue to be updated.
1430/// \param EltTy - The complex number's component type.
1431/// \param Imag - False for the real component, true for the imaginary.
1432static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1433 LValue &LVal, QualType EltTy,
1434 bool Imag) {
1435 if (Imag) {
1436 CharUnits SizeOfComponent;
1437 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1438 return false;
1439 LVal.Offset += SizeOfComponent;
1440 }
1441 LVal.addComplex(Info, E, EltTy, Imag);
1442 return true;
1443}
1444
Richard Smith27908702011-10-24 17:54:18 +00001445/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001446static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1447 const VarDecl *VD,
Richard Smith2e312c82012-03-03 22:46:17 +00001448 CallStackFrame *Frame, APValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001449 // If this is a parameter to an active constexpr function call, perform
1450 // argument substitution.
1451 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001452 // Assume arguments of a potential constant expression are unknown
1453 // constant expressions.
1454 if (Info.CheckingPotentialConstantExpression)
1455 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001456 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001457 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001458 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001459 }
Richard Smithfec09922011-11-01 16:57:24 +00001460 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1461 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001462 }
Richard Smith27908702011-10-24 17:54:18 +00001463
Richard Smithd0b4dd62011-12-19 06:19:21 +00001464 // Dig out the initializer, and use the declaration which it's attached to.
1465 const Expr *Init = VD->getAnyInitializer(VD);
1466 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001467 // If we're checking a potential constant expression, the variable could be
1468 // initialized later.
1469 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001470 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001471 return false;
1472 }
1473
Richard Smithd62306a2011-11-10 06:34:14 +00001474 // If we're currently evaluating the initializer of this declaration, use that
1475 // in-flight value.
1476 if (Info.EvaluatingDecl == VD) {
Richard Smith2e312c82012-03-03 22:46:17 +00001477 Result = *Info.EvaluatingDeclValue;
Richard Smithd62306a2011-11-10 06:34:14 +00001478 return !Result.isUninit();
1479 }
1480
Richard Smithcecf1842011-11-01 21:06:14 +00001481 // Never evaluate the initializer of a weak variable. We can't be sure that
1482 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001483 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001484 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001485 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001486 }
Richard Smithcecf1842011-11-01 21:06:14 +00001487
Richard Smithd0b4dd62011-12-19 06:19:21 +00001488 // Check that we can fold the initializer. In C++, we will have already done
1489 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001490 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001491 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001492 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001493 Notes.size() + 1) << VD;
1494 Info.Note(VD->getLocation(), diag::note_declared_at);
1495 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001496 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001497 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001498 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001499 Notes.size() + 1) << VD;
1500 Info.Note(VD->getLocation(), diag::note_declared_at);
1501 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001502 }
Richard Smith27908702011-10-24 17:54:18 +00001503
Richard Smith2e312c82012-03-03 22:46:17 +00001504 Result = *VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001505 return true;
Richard Smith27908702011-10-24 17:54:18 +00001506}
1507
Richard Smith11562c52011-10-28 17:51:58 +00001508static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001509 Qualifiers Quals = T.getQualifiers();
1510 return Quals.hasConst() && !Quals.hasVolatile();
1511}
1512
Richard Smithe97cbd72011-11-11 04:05:33 +00001513/// Get the base index of the given base class within an APValue representing
1514/// the given derived class.
1515static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1516 const CXXRecordDecl *Base) {
1517 Base = Base->getCanonicalDecl();
1518 unsigned Index = 0;
1519 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1520 E = Derived->bases_end(); I != E; ++I, ++Index) {
1521 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1522 return Index;
1523 }
1524
1525 llvm_unreachable("base class missing from derived class's bases list");
1526}
1527
Richard Smith9ec1e482012-04-15 02:50:59 +00001528/// Extract the value of a character from a string literal. CharType is used to
1529/// determine the expected signedness of the result -- a string literal used to
1530/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1531/// of the wrong signedness.
Richard Smith14a94132012-02-17 03:35:37 +00001532static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smith9ec1e482012-04-15 02:50:59 +00001533 uint64_t Index, QualType CharType) {
Richard Smith14a94132012-02-17 03:35:37 +00001534 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1535 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1536 assert(S && "unexpected string literal expression kind");
Richard Smith9ec1e482012-04-15 02:50:59 +00001537 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001538
1539 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001540 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001541 if (Index < S->getLength())
1542 Value = S->getCodeUnit(Index);
1543 return Value;
1544}
1545
Richard Smithf3e9e432011-11-07 09:22:26 +00001546/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001547static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith2e312c82012-03-03 22:46:17 +00001548 APValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001549 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001550 if (Sub.Invalid)
1551 // A diagnostic will have already been produced.
Richard Smithf3e9e432011-11-07 09:22:26 +00001552 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00001553 if (Sub.isOnePastTheEnd()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001554 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001555 (unsigned)diag::note_constexpr_read_past_end :
1556 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001557 return false;
1558 }
Richard Smith6804be52011-11-11 08:28:03 +00001559 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001560 return true;
Richard Smith253c2a32012-01-27 01:14:48 +00001561 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1562 // This object might be initialized later.
1563 return false;
Richard Smithf3e9e432011-11-07 09:22:26 +00001564
Richard Smith4e9e5232012-03-10 00:28:11 +00001565 APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001566 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001567 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001568 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001569 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001570 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001571 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001572 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001573 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001574 // Note, it should not be possible to form a pointer with a valid
1575 // designator which points more than one past the end of the array.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001576 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001577 (unsigned)diag::note_constexpr_read_past_end :
1578 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001579 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001580 }
Richard Smith14a94132012-02-17 03:35:37 +00001581 // An array object is represented as either an Array APValue or as an
1582 // LValue which refers to a string literal.
1583 if (O->isLValue()) {
1584 assert(I == N - 1 && "extracting subobject of character?");
1585 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith2e312c82012-03-03 22:46:17 +00001586 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smith9ec1e482012-04-15 02:50:59 +00001587 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smith14a94132012-02-17 03:35:37 +00001588 return true;
1589 } else if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001590 O = &O->getArrayInitializedElt(Index);
1591 else
1592 O = &O->getArrayFiller();
1593 ObjType = CAT->getElementType();
Richard Smith66c96992012-02-18 22:04:06 +00001594 } else if (ObjType->isAnyComplexType()) {
1595 // Next subobject is a complex number.
1596 uint64_t Index = Sub.Entries[I].ArrayIndex;
1597 if (Index > 1) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001598 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Richard Smith66c96992012-02-18 22:04:06 +00001599 (unsigned)diag::note_constexpr_read_past_end :
1600 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1601 return false;
1602 }
1603 assert(I == N - 1 && "extracting subobject of scalar?");
1604 if (O->isComplexInt()) {
Richard Smith2e312c82012-03-03 22:46:17 +00001605 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith66c96992012-02-18 22:04:06 +00001606 : O->getComplexIntReal());
1607 } else {
1608 assert(O->isComplexFloat());
Richard Smith2e312c82012-03-03 22:46:17 +00001609 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith66c96992012-02-18 22:04:06 +00001610 : O->getComplexFloatReal());
1611 }
1612 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001613 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith5a294e62012-02-09 03:29:58 +00001614 if (Field->isMutable()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001615 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001616 << Field;
1617 Info.Note(Field->getLocation(), diag::note_declared_at);
1618 return false;
1619 }
1620
Richard Smithd62306a2011-11-10 06:34:14 +00001621 // Next subobject is a class, struct or union field.
1622 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1623 if (RD->isUnion()) {
1624 const FieldDecl *UnionField = O->getUnionField();
1625 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001626 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001627 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smithf2b681b2011-12-21 05:04:46 +00001628 << Field << !UnionField << UnionField;
Richard Smithd62306a2011-11-10 06:34:14 +00001629 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001630 }
Richard Smithd62306a2011-11-10 06:34:14 +00001631 O = &O->getUnionValue();
1632 } else
1633 O = &O->getStructField(Field->getFieldIndex());
1634 ObjType = Field->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001635
1636 if (ObjType.isVolatileQualified()) {
1637 if (Info.getLangOpts().CPlusPlus) {
1638 // FIXME: Include a description of the path to the volatile subobject.
Richard Smithce1ec5e2012-03-15 04:53:45 +00001639 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smithf2b681b2011-12-21 05:04:46 +00001640 << 2 << Field;
1641 Info.Note(Field->getLocation(), diag::note_declared_at);
1642 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001643 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001644 }
1645 return false;
1646 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001647 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001648 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001649 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1650 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1651 O = &O->getStructBase(getBaseIndex(Derived, Base));
1652 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001653 }
Richard Smithd62306a2011-11-10 06:34:14 +00001654
Richard Smithf57d8cb2011-12-09 22:58:01 +00001655 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001656 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001657 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smithd62306a2011-11-10 06:34:14 +00001658 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001659 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001660 }
1661
Richard Smith4e9e5232012-03-10 00:28:11 +00001662 // This may look super-stupid, but it serves an important purpose: if we just
1663 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1664 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1665 // object, which is destroyed by Tmp's destructor.
1666 APValue Tmp;
1667 O->swap(Tmp);
1668 Obj.swap(Tmp);
Richard Smithf3e9e432011-11-07 09:22:26 +00001669 return true;
1670}
1671
Richard Smith84f6dcf2012-02-02 01:16:57 +00001672/// Find the position where two subobject designators diverge, or equivalently
1673/// the length of the common initial subsequence.
1674static unsigned FindDesignatorMismatch(QualType ObjType,
1675 const SubobjectDesignator &A,
1676 const SubobjectDesignator &B,
1677 bool &WasArrayIndex) {
1678 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1679 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00001680 if (!ObjType.isNull() &&
1681 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00001682 // Next subobject is an array element.
1683 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1684 WasArrayIndex = true;
1685 return I;
1686 }
Richard Smith66c96992012-02-18 22:04:06 +00001687 if (ObjType->isAnyComplexType())
1688 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1689 else
1690 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00001691 } else {
1692 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1693 WasArrayIndex = false;
1694 return I;
1695 }
1696 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1697 // Next subobject is a field.
1698 ObjType = FD->getType();
1699 else
1700 // Next subobject is a base class.
1701 ObjType = QualType();
1702 }
1703 }
1704 WasArrayIndex = false;
1705 return I;
1706}
1707
1708/// Determine whether the given subobject designators refer to elements of the
1709/// same array object.
1710static bool AreElementsOfSameArray(QualType ObjType,
1711 const SubobjectDesignator &A,
1712 const SubobjectDesignator &B) {
1713 if (A.Entries.size() != B.Entries.size())
1714 return false;
1715
1716 bool IsArray = A.MostDerivedArraySize != 0;
1717 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1718 // A is a subobject of the array element.
1719 return false;
1720
1721 // If A (and B) designates an array element, the last entry will be the array
1722 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1723 // of length 1' case, and the entire path must match.
1724 bool WasArrayIndex;
1725 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1726 return CommonLength >= A.Entries.size() - IsArray;
1727}
1728
Richard Smithd62306a2011-11-10 06:34:14 +00001729/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1730/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1731/// for looking up the glvalue referred to by an entity of reference type.
1732///
1733/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001734/// \param Conv - The expression for which we are performing the conversion.
1735/// Used for diagnostics.
Richard Smithc82fae62012-02-05 01:23:16 +00001736/// \param Type - The type we expect this conversion to produce, before
1737/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smithd62306a2011-11-10 06:34:14 +00001738/// \param LVal - The glvalue on which we are attempting to perform this action.
1739/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001740static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1741 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00001742 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001743 if (LVal.Designator.Invalid)
1744 // A diagnostic will have already been produced.
1745 return false;
1746
Richard Smithce40ad62011-11-12 22:28:03 +00001747 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith11562c52011-10-28 17:51:58 +00001748
Richard Smithf57d8cb2011-12-09 22:58:01 +00001749 if (!LVal.Base) {
1750 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithce1ec5e2012-03-15 04:53:45 +00001751 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001752 return false;
1753 }
1754
Richard Smithb228a862012-02-15 02:18:13 +00001755 CallStackFrame *Frame = 0;
1756 if (LVal.CallIndex) {
1757 Frame = Info.getCallFrame(LVal.CallIndex);
1758 if (!Frame) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001759 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smithb228a862012-02-15 02:18:13 +00001760 NoteLValueLocation(Info, LVal.Base);
1761 return false;
1762 }
1763 }
1764
Richard Smithf2b681b2011-12-21 05:04:46 +00001765 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1766 // is not a constant expression (even if the object is non-volatile). We also
1767 // apply this rule to C++98, in order to conform to the expected 'volatile'
1768 // semantics.
1769 if (Type.isVolatileQualified()) {
1770 if (Info.getLangOpts().CPlusPlus)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001771 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smithf2b681b2011-12-21 05:04:46 +00001772 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001773 Info.Diag(Conv);
Richard Smith11562c52011-10-28 17:51:58 +00001774 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001775 }
Richard Smith11562c52011-10-28 17:51:58 +00001776
Richard Smithce40ad62011-11-12 22:28:03 +00001777 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001778 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1779 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001780 // expressions are constant expressions too. Inside constexpr functions,
1781 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001782 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001783 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001784 if (VD) {
1785 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1786 VD = VDef;
1787 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001788 if (!VD || VD->isInvalidDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001789 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00001790 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001791 }
1792
Richard Smithf2b681b2011-12-21 05:04:46 +00001793 // DR1313: If the object is volatile-qualified but the glvalue was not,
1794 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001795 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001796 if (VT.isVolatileQualified()) {
1797 if (Info.getLangOpts().CPlusPlus) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001798 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001799 Info.Note(VD->getLocation(), diag::note_declared_at);
1800 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001801 Info.Diag(Conv);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001802 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001803 return false;
1804 }
1805
1806 if (!isa<ParmVarDecl>(VD)) {
1807 if (VD->isConstexpr()) {
1808 // OK, we can read this variable.
1809 } else if (VT->isIntegralOrEnumerationType()) {
1810 if (!VT.isConstQualified()) {
1811 if (Info.getLangOpts().CPlusPlus) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001812 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001813 Info.Note(VD->getLocation(), diag::note_declared_at);
1814 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001815 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001816 }
1817 return false;
1818 }
1819 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1820 // We support folding of const floating-point types, in order to make
1821 // static const data members of such types (supported as an extension)
1822 // more useful.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001823 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001824 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001825 Info.Note(VD->getLocation(), diag::note_declared_at);
1826 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001827 Info.CCEDiag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001828 }
1829 } else {
1830 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001831 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001832 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001833 Info.Note(VD->getLocation(), diag::note_declared_at);
1834 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001835 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001836 }
Richard Smith96e0c102011-11-04 02:25:55 +00001837 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001838 }
Richard Smith96e0c102011-11-04 02:25:55 +00001839 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001840
Richard Smithf57d8cb2011-12-09 22:58:01 +00001841 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001842 return false;
1843
Richard Smith0b0a0b62011-10-29 20:57:55 +00001844 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001845 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001846
1847 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1848 // conversion. This happens when the declaration and the lvalue should be
1849 // considered synonymous, for instance when initializing an array of char
1850 // from a string literal. Continue as if the initializer lvalue was the
1851 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001852 assert(RVal.getLValueOffset().isZero() &&
1853 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001854 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithb228a862012-02-15 02:18:13 +00001855
1856 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1857 Frame = Info.getCallFrame(CallIndex);
1858 if (!Frame) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001859 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smithb228a862012-02-15 02:18:13 +00001860 NoteLValueLocation(Info, RVal.getLValueBase());
1861 return false;
1862 }
1863 } else {
1864 Frame = 0;
1865 }
Richard Smith11562c52011-10-28 17:51:58 +00001866 }
1867
Richard Smithf2b681b2011-12-21 05:04:46 +00001868 // Volatile temporary objects cannot be read in constant expressions.
1869 if (Base->getType().isVolatileQualified()) {
1870 if (Info.getLangOpts().CPlusPlus) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001871 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smithf2b681b2011-12-21 05:04:46 +00001872 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1873 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001874 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001875 }
1876 return false;
1877 }
1878
Richard Smithf3e9e432011-11-07 09:22:26 +00001879 if (Frame) {
1880 // If this is a temporary expression with a nontrivial initializer, grab the
1881 // value from the relevant stack frame.
1882 RVal = Frame->Temporaries[Base];
1883 } else if (const CompoundLiteralExpr *CLE
1884 = dyn_cast<CompoundLiteralExpr>(Base)) {
1885 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1886 // initializer until now for such expressions. Such an expression can't be
1887 // an ICE in C, so this only matters for fold.
1888 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1889 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1890 return false;
Richard Smith14a94132012-02-17 03:35:37 +00001891 } else if (isa<StringLiteral>(Base)) {
1892 // We represent a string literal array as an lvalue pointing at the
1893 // corresponding expression, rather than building an array of chars.
1894 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith2e312c82012-03-03 22:46:17 +00001895 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001896 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001897 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001898 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001899 }
Richard Smith96e0c102011-11-04 02:25:55 +00001900
Richard Smithf57d8cb2011-12-09 22:58:01 +00001901 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1902 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001903}
1904
Richard Smithe97cbd72011-11-11 04:05:33 +00001905/// Build an lvalue for the object argument of a member function call.
1906static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1907 LValue &This) {
1908 if (Object->getType()->isPointerType())
1909 return EvaluatePointer(Object, This, Info);
1910
1911 if (Object->isGLValue())
1912 return EvaluateLValue(Object, This, Info);
1913
Richard Smith027bf112011-11-17 22:56:20 +00001914 if (Object->getType()->isLiteralType())
1915 return EvaluateTemporary(Object, This, Info);
1916
1917 return false;
1918}
1919
1920/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1921/// lvalue referring to the result.
1922///
1923/// \param Info - Information about the ongoing evaluation.
1924/// \param BO - The member pointer access operation.
1925/// \param LV - Filled in with a reference to the resulting object.
1926/// \param IncludeMember - Specifies whether the member itself is included in
1927/// the resulting LValue subobject designator. This is not possible when
1928/// creating a bound member function.
1929/// \return The field or method declaration to which the member pointer refers,
1930/// or 0 if evaluation fails.
1931static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1932 const BinaryOperator *BO,
1933 LValue &LV,
1934 bool IncludeMember = true) {
1935 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1936
Richard Smith253c2a32012-01-27 01:14:48 +00001937 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1938 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00001939 return 0;
1940
1941 MemberPtr MemPtr;
1942 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1943 return 0;
1944
1945 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1946 // member value, the behavior is undefined.
1947 if (!MemPtr.getDecl())
1948 return 0;
1949
Richard Smith253c2a32012-01-27 01:14:48 +00001950 if (!EvalObjOK)
1951 return 0;
1952
Richard Smith027bf112011-11-17 22:56:20 +00001953 if (MemPtr.isDerivedMember()) {
1954 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00001955 // The end of the derived-to-base path for the base object must match the
1956 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00001957 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00001958 LV.Designator.Entries.size())
1959 return 0;
1960 unsigned PathLengthToMember =
1961 LV.Designator.Entries.size() - MemPtr.Path.size();
1962 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1963 const CXXRecordDecl *LVDecl = getAsBaseClass(
1964 LV.Designator.Entries[PathLengthToMember + I]);
1965 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1966 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1967 return 0;
1968 }
1969
1970 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00001971 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1972 PathLengthToMember))
1973 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00001974 } else if (!MemPtr.Path.empty()) {
1975 // Extend the LValue path with the member pointer's path.
1976 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1977 MemPtr.Path.size() + IncludeMember);
1978
1979 // Walk down to the appropriate base class.
1980 QualType LVType = BO->getLHS()->getType();
1981 if (const PointerType *PT = LVType->getAs<PointerType>())
1982 LVType = PT->getPointeeType();
1983 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1984 assert(RD && "member pointer access on non-class-type expression");
1985 // The first class in the path is that of the lvalue.
1986 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1987 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00001988 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1989 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00001990 RD = Base;
1991 }
1992 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00001993 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1994 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00001995 }
1996
1997 // Add the member. Note that we cannot build bound member functions here.
1998 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00001999 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2000 if (!HandleLValueMember(Info, BO, LV, FD))
2001 return 0;
2002 } else if (const IndirectFieldDecl *IFD =
2003 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2004 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2005 return 0;
2006 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002007 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002008 }
Richard Smith027bf112011-11-17 22:56:20 +00002009 }
2010
2011 return MemPtr.getDecl();
2012}
2013
2014/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2015/// the provided lvalue, which currently refers to the base object.
2016static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2017 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002018 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002019 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002020 return false;
2021
Richard Smitha8105bc2012-01-06 16:39:00 +00002022 QualType TargetQT = E->getType();
2023 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2024 TargetQT = PT->getPointeeType();
2025
2026 // Check this cast lands within the final derived-to-base subobject path.
2027 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002028 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002029 << D.MostDerivedType << TargetQT;
2030 return false;
2031 }
2032
Richard Smith027bf112011-11-17 22:56:20 +00002033 // Check the type of the final cast. We don't need to check the path,
2034 // since a cast can only be formed if the path is unique.
2035 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002036 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2037 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002038 if (NewEntriesSize == D.MostDerivedPathLength)
2039 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2040 else
Richard Smith027bf112011-11-17 22:56:20 +00002041 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002042 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002043 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002044 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002045 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002046 }
Richard Smith027bf112011-11-17 22:56:20 +00002047
2048 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002049 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002050}
2051
Mike Stump876387b2009-10-27 22:09:17 +00002052namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002053enum EvalStmtResult {
2054 /// Evaluation failed.
2055 ESR_Failed,
2056 /// Hit a 'return' statement.
2057 ESR_Returned,
2058 /// Evaluation succeeded.
2059 ESR_Succeeded
2060};
2061}
2062
2063// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002064static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00002065 const Stmt *S) {
2066 switch (S->getStmtClass()) {
2067 default:
2068 return ESR_Failed;
2069
2070 case Stmt::NullStmtClass:
2071 case Stmt::DeclStmtClass:
2072 return ESR_Succeeded;
2073
Richard Smith357362d2011-12-13 06:39:58 +00002074 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002075 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithb228a862012-02-15 02:18:13 +00002076 if (!Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002077 return ESR_Failed;
2078 return ESR_Returned;
2079 }
Richard Smith254a73d2011-10-28 22:34:42 +00002080
2081 case Stmt::CompoundStmtClass: {
2082 const CompoundStmt *CS = cast<CompoundStmt>(S);
2083 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2084 BE = CS->body_end(); BI != BE; ++BI) {
2085 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2086 if (ESR != ESR_Succeeded)
2087 return ESR;
2088 }
2089 return ESR_Succeeded;
2090 }
2091 }
2092}
2093
Richard Smithcc36f692011-12-22 02:22:31 +00002094/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2095/// default constructor. If so, we'll fold it whether or not it's marked as
2096/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2097/// so we need special handling.
2098static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00002099 const CXXConstructorDecl *CD,
2100 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00002101 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2102 return false;
2103
Richard Smith66e05fe2012-01-18 05:21:49 +00002104 // Value-initialization does not call a trivial default constructor, so such a
2105 // call is a core constant expression whether or not the constructor is
2106 // constexpr.
2107 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002108 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00002109 // FIXME: If DiagDecl is an implicitly-declared special member function,
2110 // we should be much more explicit about why it's not constexpr.
2111 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2112 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2113 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00002114 } else {
2115 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2116 }
2117 }
2118 return true;
2119}
2120
Richard Smith357362d2011-12-13 06:39:58 +00002121/// CheckConstexprFunction - Check that a function can be called in a constant
2122/// expression.
2123static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2124 const FunctionDecl *Declaration,
2125 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00002126 // Potential constant expressions can contain calls to declared, but not yet
2127 // defined, constexpr functions.
2128 if (Info.CheckingPotentialConstantExpression && !Definition &&
2129 Declaration->isConstexpr())
2130 return false;
2131
Richard Smith357362d2011-12-13 06:39:58 +00002132 // Can we evaluate this function call?
2133 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2134 return true;
2135
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002136 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00002137 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002138 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2139 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00002140 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2141 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2142 << DiagDecl;
2143 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2144 } else {
2145 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2146 }
2147 return false;
2148}
2149
Richard Smithd62306a2011-11-10 06:34:14 +00002150namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00002151typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00002152}
2153
2154/// EvaluateArgs - Evaluate the arguments to a function call.
2155static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2156 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00002157 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002158 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00002159 I != E; ++I) {
2160 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2161 // If we're checking for a potential constant expression, evaluate all
2162 // initializers even if some of them fail.
2163 if (!Info.keepEvaluatingAfterFailure())
2164 return false;
2165 Success = false;
2166 }
2167 }
2168 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00002169}
2170
Richard Smith254a73d2011-10-28 22:34:42 +00002171/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00002172static bool HandleFunctionCall(SourceLocation CallLoc,
2173 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002174 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00002175 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002176 ArgVector ArgValues(Args.size());
2177 if (!EvaluateArgs(Args, ArgValues, Info))
2178 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00002179
Richard Smith253c2a32012-01-27 01:14:48 +00002180 if (!Info.CheckCallLimit(CallLoc))
2181 return false;
2182
2183 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00002184 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2185}
2186
Richard Smithd62306a2011-11-10 06:34:14 +00002187/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00002188static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00002189 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00002190 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00002191 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002192 ArgVector ArgValues(Args.size());
2193 if (!EvaluateArgs(Args, ArgValues, Info))
2194 return false;
2195
Richard Smith253c2a32012-01-27 01:14:48 +00002196 if (!Info.CheckCallLimit(CallLoc))
2197 return false;
2198
Richard Smith3607ffe2012-02-13 03:54:03 +00002199 const CXXRecordDecl *RD = Definition->getParent();
2200 if (RD->getNumVBases()) {
2201 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2202 return false;
2203 }
2204
Richard Smith253c2a32012-01-27 01:14:48 +00002205 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00002206
2207 // If it's a delegating constructor, just delegate.
2208 if (Definition->isDelegatingConstructor()) {
2209 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithb228a862012-02-15 02:18:13 +00002210 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smithd62306a2011-11-10 06:34:14 +00002211 }
2212
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002213 // For a trivial copy or move constructor, perform an APValue copy. This is
2214 // essential for unions, where the operations performed by the constructor
2215 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002216 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00002217 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2218 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002219 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00002220 RHS.setFrom(Info.Ctx, ArgValues[0]);
2221 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2222 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002223 }
2224
2225 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00002226 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00002227 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2228 std::distance(RD->field_begin(), RD->field_end()));
2229
John McCalld7bca762012-05-01 00:38:49 +00002230 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002231 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2232
Richard Smith253c2a32012-01-27 01:14:48 +00002233 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002234 unsigned BasesSeen = 0;
2235#ifndef NDEBUG
2236 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2237#endif
2238 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2239 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00002240 LValue Subobject = This;
2241 APValue *Value = &Result;
2242
2243 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00002244 if ((*I)->isBaseInitializer()) {
2245 QualType BaseType((*I)->getBaseClass(), 0);
2246#ifndef NDEBUG
2247 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00002248 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00002249 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2250 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2251 "base class initializers not in expected order");
2252 ++BaseIt;
2253#endif
John McCalld7bca762012-05-01 00:38:49 +00002254 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2255 BaseType->getAsCXXRecordDecl(), &Layout))
2256 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00002257 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00002258 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00002259 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2260 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002261 if (RD->isUnion()) {
2262 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00002263 Value = &Result.getUnionValue();
2264 } else {
2265 Value = &Result.getStructField(FD->getFieldIndex());
2266 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00002267 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002268 // Walk the indirect field decl's chain to find the object to initialize,
2269 // and make sure we've initialized every step along it.
2270 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2271 CE = IFD->chain_end();
2272 C != CE; ++C) {
2273 FieldDecl *FD = cast<FieldDecl>(*C);
2274 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2275 // Switch the union field if it differs. This happens if we had
2276 // preceding zero-initialization, and we're now initializing a union
2277 // subobject other than the first.
2278 // FIXME: In this case, the values of the other subobjects are
2279 // specified, since zero-initialization sets all padding bits to zero.
2280 if (Value->isUninit() ||
2281 (Value->isUnion() && Value->getUnionField() != FD)) {
2282 if (CD->isUnion())
2283 *Value = APValue(FD);
2284 else
2285 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2286 std::distance(CD->field_begin(), CD->field_end()));
2287 }
John McCalld7bca762012-05-01 00:38:49 +00002288 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2289 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002290 if (CD->isUnion())
2291 Value = &Value->getUnionValue();
2292 else
2293 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00002294 }
Richard Smithd62306a2011-11-10 06:34:14 +00002295 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002296 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00002297 }
Richard Smith253c2a32012-01-27 01:14:48 +00002298
Richard Smithb228a862012-02-15 02:18:13 +00002299 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2300 (*I)->isBaseInitializer()
Richard Smith253c2a32012-01-27 01:14:48 +00002301 ? CCEK_Constant : CCEK_MemberInit)) {
2302 // If we're checking for a potential constant expression, evaluate all
2303 // initializers even if some of them fail.
2304 if (!Info.keepEvaluatingAfterFailure())
2305 return false;
2306 Success = false;
2307 }
Richard Smithd62306a2011-11-10 06:34:14 +00002308 }
2309
Richard Smith253c2a32012-01-27 01:14:48 +00002310 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00002311}
2312
Eli Friedman9a156e52008-11-12 09:44:48 +00002313//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00002314// Generic Evaluation
2315//===----------------------------------------------------------------------===//
2316namespace {
2317
Richard Smithf57d8cb2011-12-09 22:58:01 +00002318// FIXME: RetTy is always bool. Remove it.
2319template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00002320class ExprEvaluatorBase
2321 : public ConstStmtVisitor<Derived, RetTy> {
2322private:
Richard Smith2e312c82012-03-03 22:46:17 +00002323 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002324 return static_cast<Derived*>(this)->Success(V, E);
2325 }
Richard Smithfddd3842011-12-30 21:15:51 +00002326 RetTy DerivedZeroInitialization(const Expr *E) {
2327 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002328 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002329
Richard Smith17100ba2012-02-16 02:46:34 +00002330 // Check whether a conditional operator with a non-constant condition is a
2331 // potential constant expression. If neither arm is a potential constant
2332 // expression, then the conditional operator is not either.
2333 template<typename ConditionalOperator>
2334 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2335 assert(Info.CheckingPotentialConstantExpression);
2336
2337 // Speculatively evaluate both arms.
2338 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002339 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00002340 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2341
2342 StmtVisitorTy::Visit(E->getFalseExpr());
2343 if (Diag.empty())
2344 return;
2345
2346 Diag.clear();
2347 StmtVisitorTy::Visit(E->getTrueExpr());
2348 if (Diag.empty())
2349 return;
2350 }
2351
2352 Error(E, diag::note_constexpr_conditional_never_const);
2353 }
2354
2355
2356 template<typename ConditionalOperator>
2357 bool HandleConditionalOperator(const ConditionalOperator *E) {
2358 bool BoolResult;
2359 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2360 if (Info.CheckingPotentialConstantExpression)
2361 CheckPotentialConstantConditional(E);
2362 return false;
2363 }
2364
2365 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2366 return StmtVisitorTy::Visit(EvalExpr);
2367 }
2368
Peter Collingbournee9200682011-05-13 03:29:01 +00002369protected:
2370 EvalInfo &Info;
2371 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2372 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2373
Richard Smith92b1ce02011-12-12 09:28:41 +00002374 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002375 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002376 }
2377
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00002378 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2379
2380public:
2381 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2382
2383 EvalInfo &getEvalInfo() { return Info; }
2384
Richard Smithf57d8cb2011-12-09 22:58:01 +00002385 /// Report an evaluation error. This should only be called when an error is
2386 /// first discovered. When propagating an error, just return false.
2387 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002388 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002389 return false;
2390 }
2391 bool Error(const Expr *E) {
2392 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2393 }
2394
Peter Collingbournee9200682011-05-13 03:29:01 +00002395 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00002396 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00002397 }
2398 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002399 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002400 }
2401
2402 RetTy VisitParenExpr(const ParenExpr *E)
2403 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2404 RetTy VisitUnaryExtension(const UnaryOperator *E)
2405 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2406 RetTy VisitUnaryPlus(const UnaryOperator *E)
2407 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2408 RetTy VisitChooseExpr(const ChooseExpr *E)
2409 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2410 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2411 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00002412 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2413 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00002414 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2415 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00002416 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
2417 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00002418 // We cannot create any objects for which cleanups are required, so there is
2419 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2420 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2421 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002422
Richard Smith6d6ecc32011-12-12 12:46:16 +00002423 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2424 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2425 return static_cast<Derived*>(this)->VisitCastExpr(E);
2426 }
2427 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2428 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2429 return static_cast<Derived*>(this)->VisitCastExpr(E);
2430 }
2431
Richard Smith027bf112011-11-17 22:56:20 +00002432 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2433 switch (E->getOpcode()) {
2434 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00002435 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002436
2437 case BO_Comma:
2438 VisitIgnoredValue(E->getLHS());
2439 return StmtVisitorTy::Visit(E->getRHS());
2440
2441 case BO_PtrMemD:
2442 case BO_PtrMemI: {
2443 LValue Obj;
2444 if (!HandleMemberPointerAccess(Info, E, Obj))
2445 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00002446 APValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002447 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002448 return false;
2449 return DerivedSuccess(Result, E);
2450 }
2451 }
2452 }
2453
Peter Collingbournee9200682011-05-13 03:29:01 +00002454 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00002455 // Evaluate and cache the common expression. We treat it as a temporary,
2456 // even though it's not quite the same thing.
2457 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2458 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002459 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002460
Richard Smith17100ba2012-02-16 02:46:34 +00002461 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002462 }
2463
2464 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002465 bool IsBcpCall = false;
2466 // If the condition (ignoring parens) is a __builtin_constant_p call,
2467 // the result is a constant expression if it can be folded without
2468 // side-effects. This is an important GNU extension. See GCC PR38377
2469 // for discussion.
2470 if (const CallExpr *CallCE =
2471 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2472 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2473 IsBcpCall = true;
2474
2475 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2476 // constant expression; we can't check whether it's potentially foldable.
2477 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2478 return false;
2479
2480 FoldConstant Fold(Info);
2481
Richard Smith17100ba2012-02-16 02:46:34 +00002482 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00002483 return false;
2484
2485 if (IsBcpCall)
2486 Fold.Fold(Info);
2487
2488 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00002489 }
2490
2491 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00002492 APValue &Value = Info.CurrentCall->Temporaries[E];
2493 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002494 const Expr *Source = E->getSourceExpr();
2495 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002496 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002497 if (Source == E) { // sanity checking.
2498 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002499 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002500 }
2501 return StmtVisitorTy::Visit(Source);
2502 }
Richard Smith26d4cc12012-06-26 08:12:11 +00002503 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002504 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002505
Richard Smith254a73d2011-10-28 22:34:42 +00002506 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002507 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002508 QualType CalleeType = Callee->getType();
2509
Richard Smith254a73d2011-10-28 22:34:42 +00002510 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002511 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002512 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00002513 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00002514
Richard Smithe97cbd72011-11-11 04:05:33 +00002515 // Extract function decl and 'this' pointer from the callee.
2516 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002517 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002518 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2519 // Explicit bound member calls, such as x.f() or p->g();
2520 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002521 return false;
2522 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002523 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00002524 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00002525 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2526 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002527 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2528 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002529 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002530 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002531 return Error(Callee);
2532
2533 FD = dyn_cast<FunctionDecl>(Member);
2534 if (!FD)
2535 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002536 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002537 LValue Call;
2538 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002539 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002540
Richard Smitha8105bc2012-01-06 16:39:00 +00002541 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002542 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002543 FD = dyn_cast_or_null<FunctionDecl>(
2544 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002545 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002546 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002547
2548 // Overloaded operator calls to member functions are represented as normal
2549 // calls with '*this' as the first argument.
2550 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2551 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002552 // FIXME: When selecting an implicit conversion for an overloaded
2553 // operator delete, we sometimes try to evaluate calls to conversion
2554 // operators without a 'this' parameter!
2555 if (Args.empty())
2556 return Error(E);
2557
Richard Smithe97cbd72011-11-11 04:05:33 +00002558 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2559 return false;
2560 This = &ThisVal;
2561 Args = Args.slice(1);
2562 }
2563
2564 // Don't call function pointers which have been cast to some other type.
2565 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002566 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002567 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002568 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002569
Richard Smith47b34932012-02-01 02:39:43 +00002570 if (This && !This->checkSubobject(Info, E, CSK_This))
2571 return false;
2572
Richard Smith3607ffe2012-02-13 03:54:03 +00002573 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2574 // calls to such functions in constant expressions.
2575 if (This && !HasQualifier &&
2576 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2577 return Error(E, diag::note_constexpr_virtual_call);
2578
Richard Smith357362d2011-12-13 06:39:58 +00002579 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002580 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00002581 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002582
Richard Smith357362d2011-12-13 06:39:58 +00002583 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00002584 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2585 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002586 return false;
2587
Richard Smithb228a862012-02-15 02:18:13 +00002588 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00002589 }
2590
Richard Smith11562c52011-10-28 17:51:58 +00002591 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2592 return StmtVisitorTy::Visit(E->getInitializer());
2593 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002594 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00002595 if (E->getNumInits() == 0)
2596 return DerivedZeroInitialization(E);
2597 if (E->getNumInits() == 1)
2598 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00002599 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002600 }
2601 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002602 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002603 }
2604 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002605 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002606 }
Richard Smith027bf112011-11-17 22:56:20 +00002607 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002608 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002609 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002610
Richard Smithd62306a2011-11-10 06:34:14 +00002611 /// A member expression where the object is a prvalue is itself a prvalue.
2612 RetTy VisitMemberExpr(const MemberExpr *E) {
2613 assert(!E->isArrow() && "missing call to bound member function?");
2614
Richard Smith2e312c82012-03-03 22:46:17 +00002615 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00002616 if (!Evaluate(Val, Info, E->getBase()))
2617 return false;
2618
2619 QualType BaseTy = E->getBase()->getType();
2620
2621 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002622 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002623 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00002624 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00002625 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2626
Richard Smitha8105bc2012-01-06 16:39:00 +00002627 SubobjectDesignator Designator(BaseTy);
2628 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00002629
Richard Smithf57d8cb2011-12-09 22:58:01 +00002630 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002631 DerivedSuccess(Val, E);
2632 }
2633
Richard Smith11562c52011-10-28 17:51:58 +00002634 RetTy VisitCastExpr(const CastExpr *E) {
2635 switch (E->getCastKind()) {
2636 default:
2637 break;
2638
David Chisnallfa35df62012-01-16 17:27:18 +00002639 case CK_AtomicToNonAtomic:
2640 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00002641 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00002642 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00002643 return StmtVisitorTy::Visit(E->getSubExpr());
2644
2645 case CK_LValueToRValue: {
2646 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002647 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2648 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00002649 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00002650 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2651 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2652 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002653 return false;
2654 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002655 }
2656 }
2657
Richard Smithf57d8cb2011-12-09 22:58:01 +00002658 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002659 }
2660
Richard Smith4a678122011-10-24 18:44:57 +00002661 /// Visit a value which is evaluated, but whose value is ignored.
2662 void VisitIgnoredValue(const Expr *E) {
Richard Smith2e312c82012-03-03 22:46:17 +00002663 APValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002664 if (!Evaluate(Scratch, Info, E))
2665 Info.EvalStatus.HasSideEffects = true;
2666 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002667};
2668
2669}
2670
2671//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002672// Common base class for lvalue and temporary evaluation.
2673//===----------------------------------------------------------------------===//
2674namespace {
2675template<class Derived>
2676class LValueExprEvaluatorBase
2677 : public ExprEvaluatorBase<Derived, bool> {
2678protected:
2679 LValue &Result;
2680 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2681 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2682
2683 bool Success(APValue::LValueBase B) {
2684 Result.set(B);
2685 return true;
2686 }
2687
2688public:
2689 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2690 ExprEvaluatorBaseTy(Info), Result(Result) {}
2691
Richard Smith2e312c82012-03-03 22:46:17 +00002692 bool Success(const APValue &V, const Expr *E) {
2693 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00002694 return true;
2695 }
Richard Smith027bf112011-11-17 22:56:20 +00002696
Richard Smith027bf112011-11-17 22:56:20 +00002697 bool VisitMemberExpr(const MemberExpr *E) {
2698 // Handle non-static data members.
2699 QualType BaseTy;
2700 if (E->isArrow()) {
2701 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2702 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00002703 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002704 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002705 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002706 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2707 return false;
2708 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002709 } else {
2710 if (!this->Visit(E->getBase()))
2711 return false;
2712 BaseTy = E->getBase()->getType();
2713 }
Richard Smith027bf112011-11-17 22:56:20 +00002714
Richard Smith1b78b3d2012-01-25 22:15:11 +00002715 const ValueDecl *MD = E->getMemberDecl();
2716 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2717 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2718 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2719 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00002720 if (!HandleLValueMember(this->Info, E, Result, FD))
2721 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002722 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00002723 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2724 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002725 } else
2726 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002727
Richard Smith1b78b3d2012-01-25 22:15:11 +00002728 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00002729 APValue RefValue;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002730 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002731 RefValue))
2732 return false;
2733 return Success(RefValue, E);
2734 }
2735 return true;
2736 }
2737
2738 bool VisitBinaryOperator(const BinaryOperator *E) {
2739 switch (E->getOpcode()) {
2740 default:
2741 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2742
2743 case BO_PtrMemD:
2744 case BO_PtrMemI:
2745 return HandleMemberPointerAccess(this->Info, E, Result);
2746 }
2747 }
2748
2749 bool VisitCastExpr(const CastExpr *E) {
2750 switch (E->getCastKind()) {
2751 default:
2752 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2753
2754 case CK_DerivedToBase:
2755 case CK_UncheckedDerivedToBase: {
2756 if (!this->Visit(E->getSubExpr()))
2757 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002758
2759 // Now figure out the necessary offset to add to the base LV to get from
2760 // the derived class to the base class.
2761 QualType Type = E->getSubExpr()->getType();
2762
2763 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2764 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002765 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00002766 *PathI))
2767 return false;
2768 Type = (*PathI)->getType();
2769 }
2770
2771 return true;
2772 }
2773 }
2774 }
2775};
2776}
2777
2778//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002779// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002780//
2781// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2782// function designators (in C), decl references to void objects (in C), and
2783// temporaries (if building with -Wno-address-of-temporary).
2784//
2785// LValue evaluation produces values comprising a base expression of one of the
2786// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002787// - Declarations
2788// * VarDecl
2789// * FunctionDecl
2790// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002791// * CompoundLiteralExpr in C
2792// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00002793// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00002794// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002795// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002796// * ObjCEncodeExpr
2797// * AddrLabelExpr
2798// * BlockExpr
2799// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002800// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00002801// * Any Expr, with a CallIndex indicating the function in which the temporary
2802// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00002803// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002804//===----------------------------------------------------------------------===//
2805namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002806class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002807 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002808public:
Richard Smith027bf112011-11-17 22:56:20 +00002809 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2810 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002811
Richard Smith11562c52011-10-28 17:51:58 +00002812 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2813
Peter Collingbournee9200682011-05-13 03:29:01 +00002814 bool VisitDeclRefExpr(const DeclRefExpr *E);
2815 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002816 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002817 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2818 bool VisitMemberExpr(const MemberExpr *E);
2819 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2820 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00002821 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00002822 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002823 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2824 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00002825 bool VisitUnaryReal(const UnaryOperator *E);
2826 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002827
Peter Collingbournee9200682011-05-13 03:29:01 +00002828 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002829 switch (E->getCastKind()) {
2830 default:
Richard Smith027bf112011-11-17 22:56:20 +00002831 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002832
Eli Friedmance3e02a2011-10-11 00:13:24 +00002833 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002834 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002835 if (!Visit(E->getSubExpr()))
2836 return false;
2837 Result.Designator.setInvalid();
2838 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002839
Richard Smith027bf112011-11-17 22:56:20 +00002840 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002841 if (!Visit(E->getSubExpr()))
2842 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002843 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002844 }
2845 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002846};
2847} // end anonymous namespace
2848
Richard Smith11562c52011-10-28 17:51:58 +00002849/// Evaluate an expression as an lvalue. This can be legitimately called on
2850/// expressions which are not glvalues, in a few cases:
2851/// * function designators in C,
2852/// * "extern void" objects,
2853/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002854static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002855 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2856 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2857 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002858 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002859}
2860
Peter Collingbournee9200682011-05-13 03:29:01 +00002861bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002862 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2863 return Success(FD);
2864 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002865 return VisitVarDecl(E, VD);
2866 return Error(E);
2867}
Richard Smith733237d2011-10-24 23:14:33 +00002868
Richard Smith11562c52011-10-28 17:51:58 +00002869bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002870 if (!VD->getType()->isReferenceType()) {
2871 if (isa<ParmVarDecl>(VD)) {
Richard Smithb228a862012-02-15 02:18:13 +00002872 Result.set(VD, Info.CurrentCall->Index);
Richard Smithfec09922011-11-01 16:57:24 +00002873 return true;
2874 }
Richard Smithce40ad62011-11-12 22:28:03 +00002875 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002876 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002877
Richard Smith2e312c82012-03-03 22:46:17 +00002878 APValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002879 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2880 return false;
2881 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002882}
2883
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002884bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2885 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00002886 if (E->getType()->isRecordType())
2887 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00002888
Richard Smithb228a862012-02-15 02:18:13 +00002889 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00002890 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2891 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002892}
2893
Peter Collingbournee9200682011-05-13 03:29:01 +00002894bool
2895LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002896 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2897 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2898 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002899 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002900}
2901
Richard Smith6e525142011-12-27 12:18:28 +00002902bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00002903 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00002904 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00002905
2906 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
2907 << E->getExprOperand()->getType()
2908 << E->getExprOperand()->getSourceRange();
2909 return false;
Richard Smith6e525142011-12-27 12:18:28 +00002910}
2911
Francois Pichet0066db92012-04-16 04:08:35 +00002912bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2913 return Success(E);
2914}
2915
Peter Collingbournee9200682011-05-13 03:29:01 +00002916bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002917 // Handle static data members.
2918 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2919 VisitIgnoredValue(E->getBase());
2920 return VisitVarDecl(E, VD);
2921 }
2922
Richard Smith254a73d2011-10-28 22:34:42 +00002923 // Handle static member functions.
2924 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2925 if (MD->isStatic()) {
2926 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002927 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002928 }
2929 }
2930
Richard Smithd62306a2011-11-10 06:34:14 +00002931 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002932 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002933}
2934
Peter Collingbournee9200682011-05-13 03:29:01 +00002935bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002936 // FIXME: Deal with vectors as array subscript bases.
2937 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002938 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002939
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002940 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002941 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002942
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002943 APSInt Index;
2944 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002945 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002946 int64_t IndexValue
2947 = Index.isSigned() ? Index.getSExtValue()
2948 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002949
Richard Smitha8105bc2012-01-06 16:39:00 +00002950 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002951}
Eli Friedman9a156e52008-11-12 09:44:48 +00002952
Peter Collingbournee9200682011-05-13 03:29:01 +00002953bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00002954 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002955}
2956
Richard Smith66c96992012-02-18 22:04:06 +00002957bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2958 if (!Visit(E->getSubExpr()))
2959 return false;
2960 // __real is a no-op on scalar lvalues.
2961 if (E->getSubExpr()->getType()->isAnyComplexType())
2962 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
2963 return true;
2964}
2965
2966bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
2967 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
2968 "lvalue __imag__ on scalar?");
2969 if (!Visit(E->getSubExpr()))
2970 return false;
2971 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
2972 return true;
2973}
2974
Eli Friedman9a156e52008-11-12 09:44:48 +00002975//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002976// Pointer Evaluation
2977//===----------------------------------------------------------------------===//
2978
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002979namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002980class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002981 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002982 LValue &Result;
2983
Peter Collingbournee9200682011-05-13 03:29:01 +00002984 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002985 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002986 return true;
2987 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002988public:
Mike Stump11289f42009-09-09 15:08:12 +00002989
John McCall45d55e42010-05-07 21:00:08 +00002990 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002991 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002992
Richard Smith2e312c82012-03-03 22:46:17 +00002993 bool Success(const APValue &V, const Expr *E) {
2994 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00002995 return true;
2996 }
Richard Smithfddd3842011-12-30 21:15:51 +00002997 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002998 return Success((Expr*)0);
2999 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003000
John McCall45d55e42010-05-07 21:00:08 +00003001 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003002 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00003003 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003004 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00003005 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00003006 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00003007 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003008 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00003009 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003010 bool VisitCallExpr(const CallExpr *E);
3011 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00003012 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00003013 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003014 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00003015 }
Richard Smithd62306a2011-11-10 06:34:14 +00003016 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3017 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003018 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003019 Result = *Info.CurrentCall->This;
3020 return true;
3021 }
John McCallc07a0c72011-02-17 10:25:35 +00003022
Eli Friedman449fe542009-03-23 04:56:01 +00003023 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003024};
Chris Lattner05706e882008-07-11 18:11:29 +00003025} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003026
John McCall45d55e42010-05-07 21:00:08 +00003027static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003028 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00003029 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00003030}
3031
John McCall45d55e42010-05-07 21:00:08 +00003032bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003033 if (E->getOpcode() != BO_Add &&
3034 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00003035 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00003036
Chris Lattner05706e882008-07-11 18:11:29 +00003037 const Expr *PExp = E->getLHS();
3038 const Expr *IExp = E->getRHS();
3039 if (IExp->getType()->isPointerType())
3040 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00003041
Richard Smith253c2a32012-01-27 01:14:48 +00003042 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3043 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00003044 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003045
John McCall45d55e42010-05-07 21:00:08 +00003046 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00003047 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00003048 return false;
3049 int64_t AdditionalOffset
3050 = Offset.isSigned() ? Offset.getSExtValue()
3051 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00003052 if (E->getOpcode() == BO_Sub)
3053 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00003054
Ted Kremenek28831752012-08-23 20:46:57 +00003055 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00003056 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3057 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00003058}
Eli Friedman9a156e52008-11-12 09:44:48 +00003059
John McCall45d55e42010-05-07 21:00:08 +00003060bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3061 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003062}
Mike Stump11289f42009-09-09 15:08:12 +00003063
Peter Collingbournee9200682011-05-13 03:29:01 +00003064bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3065 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00003066
Eli Friedman847a2bc2009-12-27 05:43:15 +00003067 switch (E->getCastKind()) {
3068 default:
3069 break;
3070
John McCalle3027922010-08-25 11:45:40 +00003071 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003072 case CK_CPointerToObjCPointerCast:
3073 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00003074 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00003075 if (!Visit(SubExpr))
3076 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00003077 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3078 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3079 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00003080 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00003081 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00003082 if (SubExpr->getType()->isVoidPointerType())
3083 CCEDiag(E, diag::note_constexpr_invalid_cast)
3084 << 3 << SubExpr->getType();
3085 else
3086 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3087 }
Richard Smith96e0c102011-11-04 02:25:55 +00003088 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00003089
Anders Carlsson18275092010-10-31 20:41:46 +00003090 case CK_DerivedToBase:
3091 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003092 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00003093 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003094 if (!Result.Base && Result.Offset.isZero())
3095 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00003096
Richard Smithd62306a2011-11-10 06:34:14 +00003097 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00003098 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00003099 QualType Type =
3100 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00003101
Richard Smithd62306a2011-11-10 06:34:14 +00003102 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00003103 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003104 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3105 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00003106 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003107 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00003108 }
3109
Anders Carlsson18275092010-10-31 20:41:46 +00003110 return true;
3111 }
3112
Richard Smith027bf112011-11-17 22:56:20 +00003113 case CK_BaseToDerived:
3114 if (!Visit(E->getSubExpr()))
3115 return false;
3116 if (!Result.Base && Result.Offset.isZero())
3117 return true;
3118 return HandleBaseToDerivedCast(Info, E, Result);
3119
Richard Smith0b0a0b62011-10-29 20:57:55 +00003120 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003121 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003122 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00003123
John McCalle3027922010-08-25 11:45:40 +00003124 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003125 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3126
Richard Smith2e312c82012-03-03 22:46:17 +00003127 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00003128 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00003129 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00003130
John McCall45d55e42010-05-07 21:00:08 +00003131 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003132 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3133 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00003134 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003135 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00003136 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00003137 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00003138 return true;
3139 } else {
3140 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00003141 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00003142 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00003143 }
3144 }
John McCalle3027922010-08-25 11:45:40 +00003145 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00003146 if (SubExpr->isGLValue()) {
3147 if (!EvaluateLValue(SubExpr, Result, Info))
3148 return false;
3149 } else {
Richard Smithb228a862012-02-15 02:18:13 +00003150 Result.set(SubExpr, Info.CurrentCall->Index);
3151 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3152 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00003153 return false;
3154 }
Richard Smith96e0c102011-11-04 02:25:55 +00003155 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00003156 if (const ConstantArrayType *CAT
3157 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3158 Result.addArray(Info, E, CAT);
3159 else
3160 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00003161 return true;
Richard Smithdd785442011-10-31 20:57:44 +00003162
John McCalle3027922010-08-25 11:45:40 +00003163 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00003164 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003165 }
3166
Richard Smith11562c52011-10-28 17:51:58 +00003167 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00003168}
Chris Lattner05706e882008-07-11 18:11:29 +00003169
Peter Collingbournee9200682011-05-13 03:29:01 +00003170bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003171 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00003172 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00003173
Peter Collingbournee9200682011-05-13 03:29:01 +00003174 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003175}
Chris Lattner05706e882008-07-11 18:11:29 +00003176
3177//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003178// Member Pointer Evaluation
3179//===----------------------------------------------------------------------===//
3180
3181namespace {
3182class MemberPointerExprEvaluator
3183 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3184 MemberPtr &Result;
3185
3186 bool Success(const ValueDecl *D) {
3187 Result = MemberPtr(D);
3188 return true;
3189 }
3190public:
3191
3192 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3193 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3194
Richard Smith2e312c82012-03-03 22:46:17 +00003195 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003196 Result.setFrom(V);
3197 return true;
3198 }
Richard Smithfddd3842011-12-30 21:15:51 +00003199 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003200 return Success((const ValueDecl*)0);
3201 }
3202
3203 bool VisitCastExpr(const CastExpr *E);
3204 bool VisitUnaryAddrOf(const UnaryOperator *E);
3205};
3206} // end anonymous namespace
3207
3208static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3209 EvalInfo &Info) {
3210 assert(E->isRValue() && E->getType()->isMemberPointerType());
3211 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3212}
3213
3214bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3215 switch (E->getCastKind()) {
3216 default:
3217 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3218
3219 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003220 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003221 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003222
3223 case CK_BaseToDerivedMemberPointer: {
3224 if (!Visit(E->getSubExpr()))
3225 return false;
3226 if (E->path_empty())
3227 return true;
3228 // Base-to-derived member pointer casts store the path in derived-to-base
3229 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3230 // the wrong end of the derived->base arc, so stagger the path by one class.
3231 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3232 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3233 PathI != PathE; ++PathI) {
3234 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3235 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3236 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003237 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003238 }
3239 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3240 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003241 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003242 return true;
3243 }
3244
3245 case CK_DerivedToBaseMemberPointer:
3246 if (!Visit(E->getSubExpr()))
3247 return false;
3248 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3249 PathE = E->path_end(); PathI != PathE; ++PathI) {
3250 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3251 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3252 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003253 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003254 }
3255 return true;
3256 }
3257}
3258
3259bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3260 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3261 // member can be formed.
3262 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3263}
3264
3265//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00003266// Record Evaluation
3267//===----------------------------------------------------------------------===//
3268
3269namespace {
3270 class RecordExprEvaluator
3271 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3272 const LValue &This;
3273 APValue &Result;
3274 public:
3275
3276 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3277 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3278
Richard Smith2e312c82012-03-03 22:46:17 +00003279 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003280 Result = V;
3281 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00003282 }
Richard Smithfddd3842011-12-30 21:15:51 +00003283 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003284
Richard Smithe97cbd72011-11-11 04:05:33 +00003285 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003286 bool VisitInitListExpr(const InitListExpr *E);
3287 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3288 };
3289}
3290
Richard Smithfddd3842011-12-30 21:15:51 +00003291/// Perform zero-initialization on an object of non-union class type.
3292/// C++11 [dcl.init]p5:
3293/// To zero-initialize an object or reference of type T means:
3294/// [...]
3295/// -- if T is a (possibly cv-qualified) non-union class type,
3296/// each non-static data member and each base-class subobject is
3297/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00003298static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3299 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00003300 const LValue &This, APValue &Result) {
3301 assert(!RD->isUnion() && "Expected non-union class type");
3302 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3303 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3304 std::distance(RD->field_begin(), RD->field_end()));
3305
John McCalld7bca762012-05-01 00:38:49 +00003306 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003307 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3308
3309 if (CD) {
3310 unsigned Index = 0;
3311 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003312 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00003313 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3314 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003315 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3316 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003317 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00003318 Result.getStructBase(Index)))
3319 return false;
3320 }
3321 }
3322
Richard Smitha8105bc2012-01-06 16:39:00 +00003323 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3324 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00003325 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00003326 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00003327 continue;
3328
3329 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003330 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003331 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003332
David Blaikie2d7c57e2012-04-30 02:36:29 +00003333 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003334 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00003335 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00003336 return false;
3337 }
3338
3339 return true;
3340}
3341
3342bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3343 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003344 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003345 if (RD->isUnion()) {
3346 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3347 // object's first non-static named data member is zero-initialized
3348 RecordDecl::field_iterator I = RD->field_begin();
3349 if (I == RD->field_end()) {
3350 Result = APValue((const FieldDecl*)0);
3351 return true;
3352 }
3353
3354 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003355 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00003356 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00003357 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00003358 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003359 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00003360 }
3361
Richard Smith5d108602012-02-17 00:44:16 +00003362 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003363 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00003364 return false;
3365 }
3366
Richard Smitha8105bc2012-01-06 16:39:00 +00003367 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00003368}
3369
Richard Smithe97cbd72011-11-11 04:05:33 +00003370bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3371 switch (E->getCastKind()) {
3372 default:
3373 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3374
3375 case CK_ConstructorConversion:
3376 return Visit(E->getSubExpr());
3377
3378 case CK_DerivedToBase:
3379 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00003380 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003381 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00003382 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003383 if (!DerivedObject.isStruct())
3384 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00003385
3386 // Derived-to-base rvalue conversion: just slice off the derived part.
3387 APValue *Value = &DerivedObject;
3388 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3389 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3390 PathE = E->path_end(); PathI != PathE; ++PathI) {
3391 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3392 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3393 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3394 RD = Base;
3395 }
3396 Result = *Value;
3397 return true;
3398 }
3399 }
3400}
3401
Richard Smithd62306a2011-11-10 06:34:14 +00003402bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00003403 // Cannot constant-evaluate std::initializer_list inits.
3404 if (E->initializesStdInitializerList())
3405 return false;
3406
Richard Smithd62306a2011-11-10 06:34:14 +00003407 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003408 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003409 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3410
3411 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00003412 const FieldDecl *Field = E->getInitializedFieldInUnion();
3413 Result = APValue(Field);
3414 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00003415 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00003416
3417 // If the initializer list for a union does not contain any elements, the
3418 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00003419 // FIXME: The element should be initialized from an initializer list.
3420 // Is this difference ever observable for initializer lists which
3421 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00003422 ImplicitValueInitExpr VIE(Field->getType());
3423 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3424
Richard Smithd62306a2011-11-10 06:34:14 +00003425 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003426 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3427 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00003428
3429 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
3430 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
3431 isa<CXXDefaultInitExpr>(InitExpr));
3432
Richard Smithb228a862012-02-15 02:18:13 +00003433 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00003434 }
3435
3436 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3437 "initializer list for class with base classes");
3438 Result = APValue(APValue::UninitStruct(), 0,
3439 std::distance(RD->field_begin(), RD->field_end()));
3440 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00003441 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003442 for (RecordDecl::field_iterator Field = RD->field_begin(),
3443 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3444 // Anonymous bit-fields are not considered members of the class for
3445 // purposes of aggregate initialization.
3446 if (Field->isUnnamedBitfield())
3447 continue;
3448
3449 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00003450
Richard Smith253c2a32012-01-27 01:14:48 +00003451 bool HaveInit = ElementNo < E->getNumInits();
3452
3453 // FIXME: Diagnostics here should point to the end of the initializer
3454 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00003455 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00003456 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003457 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003458
3459 // Perform an implicit value-initialization for members beyond the end of
3460 // the initializer list.
3461 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00003462 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00003463
Richard Smith852c9db2013-04-20 22:23:05 +00003464 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
3465 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
3466 isa<CXXDefaultInitExpr>(Init));
3467
3468 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
3469 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00003470 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00003471 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003472 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00003473 }
3474 }
3475
Richard Smith253c2a32012-01-27 01:14:48 +00003476 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003477}
3478
3479bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3480 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00003481 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3482
Richard Smithfddd3842011-12-30 21:15:51 +00003483 bool ZeroInit = E->requiresZeroInitialization();
3484 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00003485 // If we've already performed zero-initialization, we're already done.
3486 if (!Result.isUninit())
3487 return true;
3488
Richard Smithfddd3842011-12-30 21:15:51 +00003489 if (ZeroInit)
3490 return ZeroInitialization(E);
3491
Richard Smithcc36f692011-12-22 02:22:31 +00003492 const CXXRecordDecl *RD = FD->getParent();
3493 if (RD->isUnion())
3494 Result = APValue((FieldDecl*)0);
3495 else
3496 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3497 std::distance(RD->field_begin(), RD->field_end()));
3498 return true;
3499 }
3500
Richard Smithd62306a2011-11-10 06:34:14 +00003501 const FunctionDecl *Definition = 0;
3502 FD->getBody(Definition);
3503
Richard Smith357362d2011-12-13 06:39:58 +00003504 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3505 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003506
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003507 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00003508 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00003509 if (const MaterializeTemporaryExpr *ME
3510 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3511 return Visit(ME->GetTemporaryExpr());
3512
Richard Smithfddd3842011-12-30 21:15:51 +00003513 if (ZeroInit && !ZeroInitialization(E))
3514 return false;
3515
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003516 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00003517 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003518 cast<CXXConstructorDecl>(Definition), Info,
3519 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00003520}
3521
3522static bool EvaluateRecord(const Expr *E, const LValue &This,
3523 APValue &Result, EvalInfo &Info) {
3524 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00003525 "can't evaluate expression as a record rvalue");
3526 return RecordExprEvaluator(Info, This, Result).Visit(E);
3527}
3528
3529//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003530// Temporary Evaluation
3531//
3532// Temporaries are represented in the AST as rvalues, but generally behave like
3533// lvalues. The full-object of which the temporary is a subobject is implicitly
3534// materialized so that a reference can bind to it.
3535//===----------------------------------------------------------------------===//
3536namespace {
3537class TemporaryExprEvaluator
3538 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3539public:
3540 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3541 LValueExprEvaluatorBaseTy(Info, Result) {}
3542
3543 /// Visit an expression which constructs the value of this temporary.
3544 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003545 Result.set(E, Info.CurrentCall->Index);
3546 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00003547 }
3548
3549 bool VisitCastExpr(const CastExpr *E) {
3550 switch (E->getCastKind()) {
3551 default:
3552 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3553
3554 case CK_ConstructorConversion:
3555 return VisitConstructExpr(E->getSubExpr());
3556 }
3557 }
3558 bool VisitInitListExpr(const InitListExpr *E) {
3559 return VisitConstructExpr(E);
3560 }
3561 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3562 return VisitConstructExpr(E);
3563 }
3564 bool VisitCallExpr(const CallExpr *E) {
3565 return VisitConstructExpr(E);
3566 }
3567};
3568} // end anonymous namespace
3569
3570/// Evaluate an expression of record type as a temporary.
3571static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003572 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00003573 return TemporaryExprEvaluator(Info, Result).Visit(E);
3574}
3575
3576//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003577// Vector Evaluation
3578//===----------------------------------------------------------------------===//
3579
3580namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003581 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00003582 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3583 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003584 public:
Mike Stump11289f42009-09-09 15:08:12 +00003585
Richard Smith2d406342011-10-22 21:10:00 +00003586 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3587 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003588
Richard Smith2d406342011-10-22 21:10:00 +00003589 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3590 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3591 // FIXME: remove this APValue copy.
3592 Result = APValue(V.data(), V.size());
3593 return true;
3594 }
Richard Smith2e312c82012-03-03 22:46:17 +00003595 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00003596 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00003597 Result = V;
3598 return true;
3599 }
Richard Smithfddd3842011-12-30 21:15:51 +00003600 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003601
Richard Smith2d406342011-10-22 21:10:00 +00003602 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00003603 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00003604 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003605 bool VisitInitListExpr(const InitListExpr *E);
3606 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003607 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003608 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003609 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003610 };
3611} // end anonymous namespace
3612
3613static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003614 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003615 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003616}
3617
Richard Smith2d406342011-10-22 21:10:00 +00003618bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3619 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003620 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003621
Richard Smith161f09a2011-12-06 22:44:34 +00003622 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003623 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003624
Eli Friedmanc757de22011-03-25 00:43:55 +00003625 switch (E->getCastKind()) {
3626 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003627 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003628 if (SETy->isIntegerType()) {
3629 APSInt IntResult;
3630 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003631 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003632 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00003633 } else if (SETy->isRealFloatingType()) {
3634 APFloat F(0.0);
3635 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003636 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003637 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00003638 } else {
Richard Smith2d406342011-10-22 21:10:00 +00003639 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003640 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003641
3642 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00003643 SmallVector<APValue, 4> Elts(NElts, Val);
3644 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00003645 }
Eli Friedman803acb32011-12-22 03:51:45 +00003646 case CK_BitCast: {
3647 // Evaluate the operand into an APInt we can extract from.
3648 llvm::APInt SValInt;
3649 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3650 return false;
3651 // Extract the elements
3652 QualType EltTy = VTy->getElementType();
3653 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3654 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3655 SmallVector<APValue, 4> Elts;
3656 if (EltTy->isRealFloatingType()) {
3657 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00003658 unsigned FloatEltSize = EltSize;
3659 if (&Sem == &APFloat::x87DoubleExtended)
3660 FloatEltSize = 80;
3661 for (unsigned i = 0; i < NElts; i++) {
3662 llvm::APInt Elt;
3663 if (BigEndian)
3664 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3665 else
3666 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00003667 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00003668 }
3669 } else if (EltTy->isIntegerType()) {
3670 for (unsigned i = 0; i < NElts; i++) {
3671 llvm::APInt Elt;
3672 if (BigEndian)
3673 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3674 else
3675 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3676 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3677 }
3678 } else {
3679 return Error(E);
3680 }
3681 return Success(Elts, E);
3682 }
Eli Friedmanc757de22011-03-25 00:43:55 +00003683 default:
Richard Smith11562c52011-10-28 17:51:58 +00003684 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003685 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003686}
3687
Richard Smith2d406342011-10-22 21:10:00 +00003688bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003689VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003690 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003691 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00003692 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003693
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003694 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003695 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003696
Eli Friedmanb9c71292012-01-03 23:24:20 +00003697 // The number of initializers can be less than the number of
3698 // vector elements. For OpenCL, this can be due to nested vector
3699 // initialization. For GCC compatibility, missing trailing elements
3700 // should be initialized with zeroes.
3701 unsigned CountInits = 0, CountElts = 0;
3702 while (CountElts < NumElements) {
3703 // Handle nested vector initialization.
3704 if (CountInits < NumInits
3705 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3706 APValue v;
3707 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3708 return Error(E);
3709 unsigned vlen = v.getVectorLength();
3710 for (unsigned j = 0; j < vlen; j++)
3711 Elements.push_back(v.getVectorElt(j));
3712 CountElts += vlen;
3713 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003714 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003715 if (CountInits < NumInits) {
3716 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00003717 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00003718 } else // trailing integer zero.
3719 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3720 Elements.push_back(APValue(sInt));
3721 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003722 } else {
3723 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003724 if (CountInits < NumInits) {
3725 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00003726 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00003727 } else // trailing float zero.
3728 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3729 Elements.push_back(APValue(f));
3730 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00003731 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00003732 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003733 }
Richard Smith2d406342011-10-22 21:10:00 +00003734 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003735}
3736
Richard Smith2d406342011-10-22 21:10:00 +00003737bool
Richard Smithfddd3842011-12-30 21:15:51 +00003738VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003739 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003740 QualType EltTy = VT->getElementType();
3741 APValue ZeroElement;
3742 if (EltTy->isIntegerType())
3743 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3744 else
3745 ZeroElement =
3746 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3747
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003748 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003749 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003750}
3751
Richard Smith2d406342011-10-22 21:10:00 +00003752bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003753 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003754 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003755}
3756
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003757//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003758// Array Evaluation
3759//===----------------------------------------------------------------------===//
3760
3761namespace {
3762 class ArrayExprEvaluator
3763 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003764 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003765 APValue &Result;
3766 public:
3767
Richard Smithd62306a2011-11-10 06:34:14 +00003768 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3769 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003770
3771 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00003772 assert((V.isArray() || V.isLValue()) &&
3773 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00003774 Result = V;
3775 return true;
3776 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003777
Richard Smithfddd3842011-12-30 21:15:51 +00003778 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003779 const ConstantArrayType *CAT =
3780 Info.Ctx.getAsConstantArrayType(E->getType());
3781 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003782 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003783
3784 Result = APValue(APValue::UninitArray(), 0,
3785 CAT->getSize().getZExtValue());
3786 if (!Result.hasArrayFiller()) return true;
3787
Richard Smithfddd3842011-12-30 21:15:51 +00003788 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00003789 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003790 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00003791 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00003792 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00003793 }
3794
Richard Smithf3e9e432011-11-07 09:22:26 +00003795 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003796 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00003797 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
3798 const LValue &Subobject,
3799 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00003800 };
3801} // end anonymous namespace
3802
Richard Smithd62306a2011-11-10 06:34:14 +00003803static bool EvaluateArray(const Expr *E, const LValue &This,
3804 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00003805 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003806 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003807}
3808
3809bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3810 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3811 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003812 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003813
Richard Smithca2cfbf2011-12-22 01:07:19 +00003814 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3815 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00003816 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00003817 LValue LV;
3818 if (!EvaluateLValue(E->getInit(0), LV, Info))
3819 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003820 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00003821 LV.moveInto(Val);
3822 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00003823 }
3824
Richard Smith253c2a32012-01-27 01:14:48 +00003825 bool Success = true;
3826
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003827 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
3828 "zero-initialized array shouldn't have any initialized elts");
3829 APValue Filler;
3830 if (Result.isArray() && Result.hasArrayFiller())
3831 Filler = Result.getArrayFiller();
3832
Richard Smith9543c5e2013-04-22 14:44:29 +00003833 unsigned NumEltsToInit = E->getNumInits();
3834 unsigned NumElts = CAT->getSize().getZExtValue();
3835 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
3836
3837 // If the initializer might depend on the array index, run it for each
3838 // array element. For now, just whitelist non-class value-initialization.
3839 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
3840 NumEltsToInit = NumElts;
3841
3842 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003843
3844 // If the array was previously zero-initialized, preserve the
3845 // zero-initialized values.
3846 if (!Filler.isUninit()) {
3847 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
3848 Result.getArrayInitializedElt(I) = Filler;
3849 if (Result.hasArrayFiller())
3850 Result.getArrayFiller() = Filler;
3851 }
3852
Richard Smithd62306a2011-11-10 06:34:14 +00003853 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003854 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00003855 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
3856 const Expr *Init =
3857 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00003858 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00003859 Info, Subobject, Init) ||
3860 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00003861 CAT->getElementType(), 1)) {
3862 if (!Info.keepEvaluatingAfterFailure())
3863 return false;
3864 Success = false;
3865 }
Richard Smithd62306a2011-11-10 06:34:14 +00003866 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003867
Richard Smith9543c5e2013-04-22 14:44:29 +00003868 if (!Result.hasArrayFiller())
3869 return Success;
3870
3871 // If we get here, we have a trivial filler, which we can just evaluate
3872 // once and splat over the rest of the array elements.
3873 assert(FillerExpr && "no array filler for incomplete init list");
3874 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
3875 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00003876}
3877
Richard Smith027bf112011-11-17 22:56:20 +00003878bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00003879 return VisitCXXConstructExpr(E, This, &Result, E->getType());
3880}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003881
Richard Smith9543c5e2013-04-22 14:44:29 +00003882bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
3883 const LValue &Subobject,
3884 APValue *Value,
3885 QualType Type) {
3886 bool HadZeroInit = !Value->isUninit();
3887
3888 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
3889 unsigned N = CAT->getSize().getZExtValue();
3890
3891 // Preserve the array filler if we had prior zero-initialization.
3892 APValue Filler =
3893 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
3894 : APValue();
3895
3896 *Value = APValue(APValue::UninitArray(), N, N);
3897
3898 if (HadZeroInit)
3899 for (unsigned I = 0; I != N; ++I)
3900 Value->getArrayInitializedElt(I) = Filler;
3901
3902 // Initialize the elements.
3903 LValue ArrayElt = Subobject;
3904 ArrayElt.addArray(Info, E, CAT);
3905 for (unsigned I = 0; I != N; ++I)
3906 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
3907 CAT->getElementType()) ||
3908 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
3909 CAT->getElementType(), 1))
3910 return false;
3911
3912 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003913 }
Richard Smith027bf112011-11-17 22:56:20 +00003914
Richard Smith9543c5e2013-04-22 14:44:29 +00003915 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00003916 return Error(E);
3917
Richard Smith027bf112011-11-17 22:56:20 +00003918 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00003919
Richard Smithfddd3842011-12-30 21:15:51 +00003920 bool ZeroInit = E->requiresZeroInitialization();
3921 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00003922 if (HadZeroInit)
3923 return true;
3924
Richard Smithfddd3842011-12-30 21:15:51 +00003925 if (ZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00003926 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003927 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00003928 }
3929
Richard Smithcc36f692011-12-22 02:22:31 +00003930 const CXXRecordDecl *RD = FD->getParent();
3931 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003932 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00003933 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003934 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00003935 APValue(APValue::UninitStruct(), RD->getNumBases(),
3936 std::distance(RD->field_begin(), RD->field_end()));
3937 return true;
3938 }
3939
Richard Smith027bf112011-11-17 22:56:20 +00003940 const FunctionDecl *Definition = 0;
3941 FD->getBody(Definition);
3942
Richard Smith357362d2011-12-13 06:39:58 +00003943 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3944 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003945
Richard Smith9eae7232012-01-12 18:54:33 +00003946 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00003947 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003948 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00003949 return false;
3950 }
3951
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003952 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00003953 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003954 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003955 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00003956}
3957
Richard Smithf3e9e432011-11-07 09:22:26 +00003958//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003959// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003960//
3961// As a GNU extension, we support casting pointers to sufficiently-wide integer
3962// types and back in constant folding. Integer values are thus represented
3963// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003964//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003965
3966namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003967class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003968 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00003969 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003970public:
Richard Smith2e312c82012-03-03 22:46:17 +00003971 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003972 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003973
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003974 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003975 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003976 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003977 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003978 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003979 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003980 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00003981 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003982 return true;
3983 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003984 bool Success(const llvm::APSInt &SI, const Expr *E) {
3985 return Success(SI, E, Result);
3986 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003987
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003988 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003989 assert(E->getType()->isIntegralOrEnumerationType() &&
3990 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003991 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003992 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00003993 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003994 Result.getInt().setIsUnsigned(
3995 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003996 return true;
3997 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003998 bool Success(const llvm::APInt &I, const Expr *E) {
3999 return Success(I, E, Result);
4000 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004001
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004002 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00004003 assert(E->getType()->isIntegralOrEnumerationType() &&
4004 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00004005 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004006 return true;
4007 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004008 bool Success(uint64_t Value, const Expr *E) {
4009 return Success(Value, E, Result);
4010 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004011
Ken Dyckdbc01912011-03-11 02:13:43 +00004012 bool Success(CharUnits Size, const Expr *E) {
4013 return Success(Size.getQuantity(), E);
4014 }
4015
Richard Smith2e312c82012-03-03 22:46:17 +00004016 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004017 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00004018 Result = V;
4019 return true;
4020 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004021 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004022 }
Mike Stump11289f42009-09-09 15:08:12 +00004023
Richard Smithfddd3842011-12-30 21:15:51 +00004024 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00004025
Peter Collingbournee9200682011-05-13 03:29:01 +00004026 //===--------------------------------------------------------------------===//
4027 // Visitor Methods
4028 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004029
Chris Lattner7174bf32008-07-12 00:38:25 +00004030 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004031 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004032 }
4033 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004034 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004035 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004036
4037 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4038 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004039 if (CheckReferencedDecl(E, E->getDecl()))
4040 return true;
4041
4042 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004043 }
4044 bool VisitMemberExpr(const MemberExpr *E) {
4045 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00004046 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004047 return true;
4048 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004049
4050 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004051 }
4052
Peter Collingbournee9200682011-05-13 03:29:01 +00004053 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004054 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00004055 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004056 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00004057
Peter Collingbournee9200682011-05-13 03:29:01 +00004058 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004059 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00004060
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004061 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004062 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004063 }
Mike Stump11289f42009-09-09 15:08:12 +00004064
Ted Kremeneke65b0862012-03-06 20:05:56 +00004065 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4066 return Success(E->getValue(), E);
4067 }
4068
Richard Smith4ce706a2011-10-11 21:43:33 +00004069 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00004070 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004071 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004072 }
4073
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004074 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004075 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004076 }
4077
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004078 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4079 return Success(E->getValue(), E);
4080 }
4081
Douglas Gregor29c42f22012-02-24 07:38:34 +00004082 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4083 return Success(E->getValue(), E);
4084 }
4085
John Wiegley6242b6a2011-04-28 00:16:57 +00004086 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4087 return Success(E->getValue(), E);
4088 }
4089
John Wiegleyf9f65842011-04-25 06:54:41 +00004090 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4091 return Success(E->getValue(), E);
4092 }
4093
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004094 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004095 bool VisitUnaryImag(const UnaryOperator *E);
4096
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004097 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004098 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004099
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004100private:
Ken Dyck160146e2010-01-27 17:10:57 +00004101 CharUnits GetAlignOfExpr(const Expr *E);
4102 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00004103 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00004104 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004105 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00004106};
Chris Lattner05706e882008-07-11 18:11:29 +00004107} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004108
Richard Smith11562c52011-10-28 17:51:58 +00004109/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4110/// produce either the integer value or a pointer.
4111///
4112/// GCC has a heinous extension which folds casts between pointer types and
4113/// pointer-sized integral types. We support this by allowing the evaluation of
4114/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4115/// Some simple arithmetic on such values is supported (they are treated much
4116/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00004117static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00004118 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004119 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004120 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00004121}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004122
Richard Smithf57d8cb2011-12-09 22:58:01 +00004123static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00004124 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004125 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00004126 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004127 if (!Val.isInt()) {
4128 // FIXME: It would be better to produce the diagnostic for casting
4129 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00004130 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004131 return false;
4132 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004133 Result = Val.getInt();
4134 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004135}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004136
Richard Smithf57d8cb2011-12-09 22:58:01 +00004137/// Check whether the given declaration can be directly converted to an integral
4138/// rvalue. If not, no diagnostic is produced; there are other things we can
4139/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004140bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00004141 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004142 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004143 // Check for signedness/width mismatches between E type and ECD value.
4144 bool SameSign = (ECD->getInitVal().isSigned()
4145 == E->getType()->isSignedIntegerOrEnumerationType());
4146 bool SameWidth = (ECD->getInitVal().getBitWidth()
4147 == Info.Ctx.getIntWidth(E->getType()));
4148 if (SameSign && SameWidth)
4149 return Success(ECD->getInitVal(), E);
4150 else {
4151 // Get rid of mismatch (otherwise Success assertions will fail)
4152 // by computing a new value matching the type of E.
4153 llvm::APSInt Val = ECD->getInitVal();
4154 if (!SameSign)
4155 Val.setIsSigned(!ECD->getInitVal().isSigned());
4156 if (!SameWidth)
4157 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4158 return Success(Val, E);
4159 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004160 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004161 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00004162}
4163
Chris Lattner86ee2862008-10-06 06:40:35 +00004164/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4165/// as GCC.
4166static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4167 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004168 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00004169 enum gcc_type_class {
4170 no_type_class = -1,
4171 void_type_class, integer_type_class, char_type_class,
4172 enumeral_type_class, boolean_type_class,
4173 pointer_type_class, reference_type_class, offset_type_class,
4174 real_type_class, complex_type_class,
4175 function_type_class, method_type_class,
4176 record_type_class, union_type_class,
4177 array_type_class, string_type_class,
4178 lang_type_class
4179 };
Mike Stump11289f42009-09-09 15:08:12 +00004180
4181 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00004182 // ideal, however it is what gcc does.
4183 if (E->getNumArgs() == 0)
4184 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00004185
Chris Lattner86ee2862008-10-06 06:40:35 +00004186 QualType ArgTy = E->getArg(0)->getType();
4187 if (ArgTy->isVoidType())
4188 return void_type_class;
4189 else if (ArgTy->isEnumeralType())
4190 return enumeral_type_class;
4191 else if (ArgTy->isBooleanType())
4192 return boolean_type_class;
4193 else if (ArgTy->isCharType())
4194 return string_type_class; // gcc doesn't appear to use char_type_class
4195 else if (ArgTy->isIntegerType())
4196 return integer_type_class;
4197 else if (ArgTy->isPointerType())
4198 return pointer_type_class;
4199 else if (ArgTy->isReferenceType())
4200 return reference_type_class;
4201 else if (ArgTy->isRealType())
4202 return real_type_class;
4203 else if (ArgTy->isComplexType())
4204 return complex_type_class;
4205 else if (ArgTy->isFunctionType())
4206 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00004207 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00004208 return record_type_class;
4209 else if (ArgTy->isUnionType())
4210 return union_type_class;
4211 else if (ArgTy->isArrayType())
4212 return array_type_class;
4213 else if (ArgTy->isUnionType())
4214 return union_type_class;
4215 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00004216 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00004217}
4218
Richard Smith5fab0c92011-12-28 19:48:30 +00004219/// EvaluateBuiltinConstantPForLValue - Determine the result of
4220/// __builtin_constant_p when applied to the given lvalue.
4221///
4222/// An lvalue is only "constant" if it is a pointer or reference to the first
4223/// character of a string literal.
4224template<typename LValue>
4225static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00004226 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00004227 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4228}
4229
4230/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4231/// GCC as we can manage.
4232static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4233 QualType ArgType = Arg->getType();
4234
4235 // __builtin_constant_p always has one operand. The rules which gcc follows
4236 // are not precisely documented, but are as follows:
4237 //
4238 // - If the operand is of integral, floating, complex or enumeration type,
4239 // and can be folded to a known value of that type, it returns 1.
4240 // - If the operand and can be folded to a pointer to the first character
4241 // of a string literal (or such a pointer cast to an integral type), it
4242 // returns 1.
4243 //
4244 // Otherwise, it returns 0.
4245 //
4246 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4247 // its support for this does not currently work.
4248 if (ArgType->isIntegralOrEnumerationType()) {
4249 Expr::EvalResult Result;
4250 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4251 return false;
4252
4253 APValue &V = Result.Val;
4254 if (V.getKind() == APValue::Int)
4255 return true;
4256
4257 return EvaluateBuiltinConstantPForLValue(V);
4258 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4259 return Arg->isEvaluatable(Ctx);
4260 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4261 LValue LV;
4262 Expr::EvalStatus Status;
4263 EvalInfo Info(Ctx, Status);
4264 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4265 : EvaluatePointer(Arg, LV, Info)) &&
4266 !Status.HasSideEffects)
4267 return EvaluateBuiltinConstantPForLValue(LV);
4268 }
4269
4270 // Anything else isn't considered to be sufficiently constant.
4271 return false;
4272}
4273
John McCall95007602010-05-10 23:27:23 +00004274/// Retrieves the "underlying object type" of the given expression,
4275/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00004276QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4277 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4278 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00004279 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00004280 } else if (const Expr *E = B.get<const Expr*>()) {
4281 if (isa<CompoundLiteralExpr>(E))
4282 return E->getType();
John McCall95007602010-05-10 23:27:23 +00004283 }
4284
4285 return QualType();
4286}
4287
Peter Collingbournee9200682011-05-13 03:29:01 +00004288bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00004289 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00004290
4291 {
4292 // The operand of __builtin_object_size is never evaluated for side-effects.
4293 // If there are any, but we can determine the pointed-to object anyway, then
4294 // ignore the side-effects.
4295 SpeculativeEvaluationRAII SpeculativeEval(Info);
4296 if (!EvaluatePointer(E->getArg(0), Base, Info))
4297 return false;
4298 }
John McCall95007602010-05-10 23:27:23 +00004299
4300 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00004301 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00004302
Richard Smithce40ad62011-11-12 22:28:03 +00004303 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00004304 if (T.isNull() ||
4305 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00004306 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00004307 T->isVariablyModifiedType() ||
4308 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004309 return Error(E);
John McCall95007602010-05-10 23:27:23 +00004310
4311 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4312 CharUnits Offset = Base.getLValueOffset();
4313
4314 if (!Offset.isNegative() && Offset <= Size)
4315 Size -= Offset;
4316 else
4317 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00004318 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00004319}
4320
Peter Collingbournee9200682011-05-13 03:29:01 +00004321bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00004322 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004323 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00004324 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004325
4326 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00004327 if (TryEvaluateBuiltinObjectSize(E))
4328 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00004329
Richard Smith0421ce72012-08-07 04:16:51 +00004330 // If evaluating the argument has side-effects, we can't determine the size
4331 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4332 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004333 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00004334 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00004335 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00004336 return Success(0, E);
4337 }
Mike Stump876387b2009-10-27 22:09:17 +00004338
Richard Smith01ade172012-05-23 04:13:20 +00004339 // Expression had no side effects, but we couldn't statically determine the
4340 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004341 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004342 }
4343
Benjamin Kramera801f4a2012-10-06 14:42:22 +00004344 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00004345 case Builtin::BI__builtin_bswap32:
4346 case Builtin::BI__builtin_bswap64: {
4347 APSInt Val;
4348 if (!EvaluateInteger(E->getArg(0), Val, Info))
4349 return false;
4350
4351 return Success(Val.byteSwap(), E);
4352 }
4353
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004354 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004355 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00004356
Richard Smith5fab0c92011-12-28 19:48:30 +00004357 case Builtin::BI__builtin_constant_p:
4358 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00004359
Chris Lattnerd545ad12009-09-23 06:06:36 +00004360 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00004361 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00004362 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00004363 return Success(Operand, E);
4364 }
Eli Friedmand5c93992010-02-13 00:10:10 +00004365
4366 case Builtin::BI__builtin_expect:
4367 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00004368
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004369 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00004370 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004371 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00004372 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00004373 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4374 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00004375 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00004376 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004377 case Builtin::BI__builtin_strlen:
4378 // As an extension, we support strlen() and __builtin_strlen() as constant
4379 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00004380 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004381 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4382 // The string literal may have embedded null characters. Find the first
4383 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004384 StringRef Str = S->getString();
4385 StringRef::size_type Pos = Str.find(0);
4386 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004387 Str = Str.substr(0, Pos);
4388
4389 return Success(Str.size(), E);
4390 }
4391
Richard Smithf57d8cb2011-12-09 22:58:01 +00004392 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004393
Richard Smith01ba47d2012-04-13 00:45:38 +00004394 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00004395 case Builtin::BI__atomic_is_lock_free:
4396 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00004397 APSInt SizeVal;
4398 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4399 return false;
4400
4401 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4402 // of two less than the maximum inline atomic width, we know it is
4403 // lock-free. If the size isn't a power of two, or greater than the
4404 // maximum alignment where we promote atomics, we know it is not lock-free
4405 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4406 // the answer can only be determined at runtime; for example, 16-byte
4407 // atomics have lock-free implementations on some, but not all,
4408 // x86-64 processors.
4409
4410 // Check power-of-two.
4411 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00004412 if (Size.isPowerOfTwo()) {
4413 // Check against inlining width.
4414 unsigned InlineWidthBits =
4415 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4416 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4417 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4418 Size == CharUnits::One() ||
4419 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4420 Expr::NPC_NeverValueDependent))
4421 // OK, we will inline appropriately-aligned operations of this size,
4422 // and _Atomic(T) is appropriately-aligned.
4423 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004424
Richard Smith01ba47d2012-04-13 00:45:38 +00004425 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4426 castAs<PointerType>()->getPointeeType();
4427 if (!PointeeType->isIncompleteType() &&
4428 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4429 // OK, we will inline operations on this object.
4430 return Success(1, E);
4431 }
4432 }
4433 }
Eli Friedmana4c26022011-10-17 21:44:23 +00004434
Richard Smith01ba47d2012-04-13 00:45:38 +00004435 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4436 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004437 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004438 }
Chris Lattner7174bf32008-07-12 00:38:25 +00004439}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004440
Richard Smith8b3497e2011-10-31 01:37:14 +00004441static bool HasSameBase(const LValue &A, const LValue &B) {
4442 if (!A.getLValueBase())
4443 return !B.getLValueBase();
4444 if (!B.getLValueBase())
4445 return false;
4446
Richard Smithce40ad62011-11-12 22:28:03 +00004447 if (A.getLValueBase().getOpaqueValue() !=
4448 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00004449 const Decl *ADecl = GetLValueBaseDecl(A);
4450 if (!ADecl)
4451 return false;
4452 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00004453 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00004454 return false;
4455 }
4456
4457 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00004458 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00004459}
4460
Richard Smithc8042322012-02-01 05:53:12 +00004461/// Perform the given integer operation, which is known to need at most BitWidth
4462/// bits, and check for overflow in the original type (if that type was not an
4463/// unsigned type).
4464template<typename Operation>
4465static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4466 const APSInt &LHS, const APSInt &RHS,
4467 unsigned BitWidth, Operation Op) {
4468 if (LHS.isUnsigned())
4469 return Op(LHS, RHS);
4470
4471 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4472 APSInt Result = Value.trunc(LHS.getBitWidth());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00004473 if (Result.extend(BitWidth) != Value) {
4474 if (Info.getIntOverflowCheckMode())
4475 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
4476 diag::warn_integer_constant_overflow)
4477 << Result.toString(10) << E->getType();
4478 else
4479 HandleOverflow(Info, E, Value, E->getType());
4480 }
Richard Smithc8042322012-02-01 05:53:12 +00004481 return Result;
4482}
4483
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004484namespace {
Richard Smith11562c52011-10-28 17:51:58 +00004485
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004486/// \brief Data recursive integer evaluator of certain binary operators.
4487///
4488/// We use a data recursive algorithm for binary operators so that we are able
4489/// to handle extreme cases of chained binary operators without causing stack
4490/// overflow.
4491class DataRecursiveIntBinOpEvaluator {
4492 struct EvalResult {
4493 APValue Val;
4494 bool Failed;
4495
4496 EvalResult() : Failed(false) { }
4497
4498 void swap(EvalResult &RHS) {
4499 Val.swap(RHS.Val);
4500 Failed = RHS.Failed;
4501 RHS.Failed = false;
4502 }
4503 };
4504
4505 struct Job {
4506 const Expr *E;
4507 EvalResult LHSResult; // meaningful only for binary operator expression.
4508 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4509
4510 Job() : StoredInfo(0) { }
4511 void startSpeculativeEval(EvalInfo &Info) {
4512 OldEvalStatus = Info.EvalStatus;
4513 Info.EvalStatus.Diag = 0;
4514 StoredInfo = &Info;
4515 }
4516 ~Job() {
4517 if (StoredInfo) {
4518 StoredInfo->EvalStatus = OldEvalStatus;
4519 }
4520 }
4521 private:
4522 EvalInfo *StoredInfo; // non-null if status changed.
4523 Expr::EvalStatus OldEvalStatus;
4524 };
4525
4526 SmallVector<Job, 16> Queue;
4527
4528 IntExprEvaluator &IntEval;
4529 EvalInfo &Info;
4530 APValue &FinalResult;
4531
4532public:
4533 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4534 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4535
4536 /// \brief True if \param E is a binary operator that we are going to handle
4537 /// data recursively.
4538 /// We handle binary operators that are comma, logical, or that have operands
4539 /// with integral or enumeration type.
4540 static bool shouldEnqueue(const BinaryOperator *E) {
4541 return E->getOpcode() == BO_Comma ||
4542 E->isLogicalOp() ||
4543 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4544 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00004545 }
4546
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004547 bool Traverse(const BinaryOperator *E) {
4548 enqueue(E);
4549 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00004550 while (!Queue.empty())
4551 process(PrevResult);
4552
4553 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004554
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004555 FinalResult.swap(PrevResult.Val);
4556 return true;
4557 }
4558
4559private:
4560 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4561 return IntEval.Success(Value, E, Result);
4562 }
4563 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4564 return IntEval.Success(Value, E, Result);
4565 }
4566 bool Error(const Expr *E) {
4567 return IntEval.Error(E);
4568 }
4569 bool Error(const Expr *E, diag::kind D) {
4570 return IntEval.Error(E, D);
4571 }
4572
4573 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4574 return Info.CCEDiag(E, D);
4575 }
4576
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004577 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4578 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004579 bool &SuppressRHSDiags);
4580
4581 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4582 const BinaryOperator *E, APValue &Result);
4583
4584 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4585 Result.Failed = !Evaluate(Result.Val, Info, E);
4586 if (Result.Failed)
4587 Result.Val = APValue();
4588 }
4589
Richard Trieuba4d0872012-03-21 23:30:30 +00004590 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004591
4592 void enqueue(const Expr *E) {
4593 E = E->IgnoreParens();
4594 Queue.resize(Queue.size()+1);
4595 Queue.back().E = E;
4596 Queue.back().Kind = Job::AnyExprKind;
4597 }
4598};
4599
4600}
4601
4602bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004603 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004604 bool &SuppressRHSDiags) {
4605 if (E->getOpcode() == BO_Comma) {
4606 // Ignore LHS but note if we could not evaluate it.
4607 if (LHSResult.Failed)
4608 Info.EvalStatus.HasSideEffects = true;
4609 return true;
4610 }
4611
4612 if (E->isLogicalOp()) {
4613 bool lhsResult;
4614 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004615 // We were able to evaluate the LHS, see if we can get away with not
4616 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004617 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004618 Success(lhsResult, E, LHSResult.Val);
4619 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004620 }
4621 } else {
4622 // Since we weren't able to evaluate the left hand side, it
4623 // must have had side effects.
4624 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004625
4626 // We can't evaluate the LHS; however, sometimes the result
4627 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4628 // Don't ignore RHS and suppress diagnostics from this arm.
4629 SuppressRHSDiags = true;
4630 }
4631
4632 return true;
4633 }
4634
4635 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4636 E->getRHS()->getType()->isIntegralOrEnumerationType());
4637
4638 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004639 return false; // Ignore RHS;
4640
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004641 return true;
4642}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004643
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004644bool DataRecursiveIntBinOpEvaluator::
4645 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4646 const BinaryOperator *E, APValue &Result) {
4647 if (E->getOpcode() == BO_Comma) {
4648 if (RHSResult.Failed)
4649 return false;
4650 Result = RHSResult.Val;
4651 return true;
4652 }
4653
4654 if (E->isLogicalOp()) {
4655 bool lhsResult, rhsResult;
4656 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4657 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4658
4659 if (LHSIsOK) {
4660 if (RHSIsOK) {
4661 if (E->getOpcode() == BO_LOr)
4662 return Success(lhsResult || rhsResult, E, Result);
4663 else
4664 return Success(lhsResult && rhsResult, E, Result);
4665 }
4666 } else {
4667 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004668 // We can't evaluate the LHS; however, sometimes the result
4669 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4670 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004671 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004672 }
4673 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004674
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004675 return false;
4676 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004677
4678 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4679 E->getRHS()->getType()->isIntegralOrEnumerationType());
4680
4681 if (LHSResult.Failed || RHSResult.Failed)
4682 return false;
4683
4684 const APValue &LHSVal = LHSResult.Val;
4685 const APValue &RHSVal = RHSResult.Val;
4686
4687 // Handle cases like (unsigned long)&a + 4.
4688 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4689 Result = LHSVal;
4690 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4691 RHSVal.getInt().getZExtValue());
4692 if (E->getOpcode() == BO_Add)
4693 Result.getLValueOffset() += AdditionalOffset;
4694 else
4695 Result.getLValueOffset() -= AdditionalOffset;
4696 return true;
4697 }
4698
4699 // Handle cases like 4 + (unsigned long)&a
4700 if (E->getOpcode() == BO_Add &&
4701 RHSVal.isLValue() && LHSVal.isInt()) {
4702 Result = RHSVal;
4703 Result.getLValueOffset() += CharUnits::fromQuantity(
4704 LHSVal.getInt().getZExtValue());
4705 return true;
4706 }
4707
4708 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4709 // Handle (intptr_t)&&A - (intptr_t)&&B.
4710 if (!LHSVal.getLValueOffset().isZero() ||
4711 !RHSVal.getLValueOffset().isZero())
4712 return false;
4713 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4714 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4715 if (!LHSExpr || !RHSExpr)
4716 return false;
4717 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4718 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4719 if (!LHSAddrExpr || !RHSAddrExpr)
4720 return false;
4721 // Make sure both labels come from the same function.
4722 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4723 RHSAddrExpr->getLabel()->getDeclContext())
4724 return false;
4725 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4726 return true;
4727 }
4728
4729 // All the following cases expect both operands to be an integer
4730 if (!LHSVal.isInt() || !RHSVal.isInt())
4731 return Error(E);
4732
4733 const APSInt &LHS = LHSVal.getInt();
4734 APSInt RHS = RHSVal.getInt();
4735
4736 switch (E->getOpcode()) {
4737 default:
4738 return Error(E);
4739 case BO_Mul:
4740 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4741 LHS.getBitWidth() * 2,
4742 std::multiplies<APSInt>()), E,
4743 Result);
4744 case BO_Add:
4745 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4746 LHS.getBitWidth() + 1,
4747 std::plus<APSInt>()), E, Result);
4748 case BO_Sub:
4749 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4750 LHS.getBitWidth() + 1,
4751 std::minus<APSInt>()), E, Result);
4752 case BO_And: return Success(LHS & RHS, E, Result);
4753 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4754 case BO_Or: return Success(LHS | RHS, E, Result);
4755 case BO_Div:
4756 case BO_Rem:
4757 if (RHS == 0)
4758 return Error(E, diag::note_expr_divide_by_zero);
4759 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4760 // not actually undefined behavior in C++11 due to a language defect.
4761 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4762 LHS.isSigned() && LHS.isMinSignedValue())
4763 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4764 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4765 Result);
4766 case BO_Shl: {
David Tweed042e0882013-01-07 16:43:27 +00004767 if (Info.getLangOpts().OpenCL)
4768 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00004769 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00004770 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
4771 RHS.isUnsigned());
4772 else if (RHS.isSigned() && RHS.isNegative()) {
4773 // During constant-folding, a negative shift is an opposite shift. Such
4774 // a shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004775 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4776 RHS = -RHS;
4777 goto shift_right;
4778 }
4779
4780 shift_left:
4781 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4782 // the shifted type.
4783 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4784 if (SA != RHS) {
4785 CCEDiag(E, diag::note_constexpr_large_shift)
4786 << RHS << E->getType() << LHS.getBitWidth();
4787 } else if (LHS.isSigned()) {
4788 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4789 // operand, and must not overflow the corresponding unsigned type.
4790 if (LHS.isNegative())
4791 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4792 else if (LHS.countLeadingZeros() < SA)
4793 CCEDiag(E, diag::note_constexpr_lshift_discards);
4794 }
4795
4796 return Success(LHS << SA, E, Result);
4797 }
4798 case BO_Shr: {
David Tweed042e0882013-01-07 16:43:27 +00004799 if (Info.getLangOpts().OpenCL)
4800 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00004801 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00004802 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
4803 RHS.isUnsigned());
4804 else if (RHS.isSigned() && RHS.isNegative()) {
4805 // During constant-folding, a negative shift is an opposite shift. Such a
4806 // shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004807 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4808 RHS = -RHS;
4809 goto shift_left;
4810 }
4811
4812 shift_right:
4813 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4814 // shifted type.
4815 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4816 if (SA != RHS)
4817 CCEDiag(E, diag::note_constexpr_large_shift)
4818 << RHS << E->getType() << LHS.getBitWidth();
4819
4820 return Success(LHS >> SA, E, Result);
4821 }
4822
4823 case BO_LT: return Success(LHS < RHS, E, Result);
4824 case BO_GT: return Success(LHS > RHS, E, Result);
4825 case BO_LE: return Success(LHS <= RHS, E, Result);
4826 case BO_GE: return Success(LHS >= RHS, E, Result);
4827 case BO_EQ: return Success(LHS == RHS, E, Result);
4828 case BO_NE: return Success(LHS != RHS, E, Result);
4829 }
4830}
4831
Richard Trieuba4d0872012-03-21 23:30:30 +00004832void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004833 Job &job = Queue.back();
4834
4835 switch (job.Kind) {
4836 case Job::AnyExprKind: {
4837 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4838 if (shouldEnqueue(Bop)) {
4839 job.Kind = Job::BinOpKind;
4840 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00004841 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004842 }
4843 }
4844
4845 EvaluateExpr(job.E, Result);
4846 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00004847 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004848 }
4849
4850 case Job::BinOpKind: {
4851 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004852 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004853 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004854 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00004855 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004856 }
4857 if (SuppressRHSDiags)
4858 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004859 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004860 job.Kind = Job::BinOpVisitedLHSKind;
4861 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00004862 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004863 }
4864
4865 case Job::BinOpVisitedLHSKind: {
4866 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4867 EvalResult RHS;
4868 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00004869 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004870 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00004871 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004872 }
4873 }
4874
4875 llvm_unreachable("Invalid Job::Kind!");
4876}
4877
4878bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4879 if (E->isAssignmentOp())
4880 return Error(E);
4881
4882 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4883 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004884
Anders Carlssonacc79812008-11-16 07:17:21 +00004885 QualType LHSTy = E->getLHS()->getType();
4886 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004887
4888 if (LHSTy->isAnyComplexType()) {
4889 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00004890 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004891
Richard Smith253c2a32012-01-27 01:14:48 +00004892 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4893 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004894 return false;
4895
Richard Smith253c2a32012-01-27 01:14:48 +00004896 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004897 return false;
4898
4899 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00004900 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004901 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00004902 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004903 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4904
John McCalle3027922010-08-25 11:45:40 +00004905 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004906 return Success((CR_r == APFloat::cmpEqual &&
4907 CR_i == APFloat::cmpEqual), E);
4908 else {
John McCalle3027922010-08-25 11:45:40 +00004909 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004910 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00004911 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004912 CR_r == APFloat::cmpLessThan ||
4913 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00004914 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004915 CR_i == APFloat::cmpLessThan ||
4916 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004917 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004918 } else {
John McCalle3027922010-08-25 11:45:40 +00004919 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004920 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4921 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4922 else {
John McCalle3027922010-08-25 11:45:40 +00004923 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004924 "Invalid compex comparison.");
4925 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4926 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4927 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004928 }
4929 }
Mike Stump11289f42009-09-09 15:08:12 +00004930
Anders Carlssonacc79812008-11-16 07:17:21 +00004931 if (LHSTy->isRealFloatingType() &&
4932 RHSTy->isRealFloatingType()) {
4933 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00004934
Richard Smith253c2a32012-01-27 01:14:48 +00004935 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4936 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00004937 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004938
Richard Smith253c2a32012-01-27 01:14:48 +00004939 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00004940 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004941
Anders Carlssonacc79812008-11-16 07:17:21 +00004942 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00004943
Anders Carlssonacc79812008-11-16 07:17:21 +00004944 switch (E->getOpcode()) {
4945 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004946 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00004947 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004948 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00004949 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004950 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00004951 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004952 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00004953 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00004954 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004955 E);
John McCalle3027922010-08-25 11:45:40 +00004956 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004957 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00004958 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00004959 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00004960 || CR == APFloat::cmpLessThan
4961 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00004962 }
Anders Carlssonacc79812008-11-16 07:17:21 +00004963 }
Mike Stump11289f42009-09-09 15:08:12 +00004964
Eli Friedmana38da572009-04-28 19:17:36 +00004965 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00004966 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004967 LValue LHSValue, RHSValue;
4968
4969 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4970 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004971 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004972
Richard Smith253c2a32012-01-27 01:14:48 +00004973 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004974 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004975
Richard Smith8b3497e2011-10-31 01:37:14 +00004976 // Reject differing bases from the normal codepath; we special-case
4977 // comparisons to null.
4978 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004979 if (E->getOpcode() == BO_Sub) {
4980 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004981 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4982 return false;
4983 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00004984 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004985 if (!LHSExpr || !RHSExpr)
4986 return false;
4987 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4988 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4989 if (!LHSAddrExpr || !RHSAddrExpr)
4990 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004991 // Make sure both labels come from the same function.
4992 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4993 RHSAddrExpr->getLabel()->getDeclContext())
4994 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004995 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004996 return true;
4997 }
Richard Smith83c68212011-10-31 05:11:32 +00004998 // Inequalities and subtractions between unrelated pointers have
4999 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00005000 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005001 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005002 // A constant address may compare equal to the address of a symbol.
5003 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00005004 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00005005 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5006 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005007 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005008 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00005009 // distinct addresses. In clang, the result of such a comparison is
5010 // unspecified, so it is not a constant expression. However, we do know
5011 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00005012 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5013 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005014 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005015 // We can't tell whether weak symbols will end up pointing to the same
5016 // object.
5017 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005018 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00005019 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00005020 // (Note that clang defaults to -fmerge-all-constants, which can
5021 // lead to inconsistent results for comparisons involving the address
5022 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00005023 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00005024 }
Eli Friedman64004332009-03-23 04:38:34 +00005025
Richard Smith1b470412012-02-01 08:10:20 +00005026 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5027 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5028
Richard Smith84f6dcf2012-02-02 01:16:57 +00005029 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5030 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5031
John McCalle3027922010-08-25 11:45:40 +00005032 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005033 // C++11 [expr.add]p6:
5034 // Unless both pointers point to elements of the same array object, or
5035 // one past the last element of the array object, the behavior is
5036 // undefined.
5037 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5038 !AreElementsOfSameArray(getType(LHSValue.Base),
5039 LHSDesignator, RHSDesignator))
5040 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5041
Chris Lattner882bdf22010-04-20 17:13:14 +00005042 QualType Type = E->getLHS()->getType();
5043 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005044
Richard Smithd62306a2011-11-10 06:34:14 +00005045 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00005046 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00005047 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005048
Richard Smith1b470412012-02-01 08:10:20 +00005049 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5050 // and produce incorrect results when it overflows. Such behavior
5051 // appears to be non-conforming, but is common, so perhaps we should
5052 // assume the standard intended for such cases to be undefined behavior
5053 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00005054
Richard Smith1b470412012-02-01 08:10:20 +00005055 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5056 // overflow in the final conversion to ptrdiff_t.
5057 APSInt LHS(
5058 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5059 APSInt RHS(
5060 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5061 APSInt ElemSize(
5062 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5063 APSInt TrueResult = (LHS - RHS) / ElemSize;
5064 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5065
5066 if (Result.extend(65) != TrueResult)
5067 HandleOverflow(Info, E, TrueResult, E->getType());
5068 return Success(Result, E);
5069 }
Richard Smithde21b242012-01-31 06:41:30 +00005070
5071 // C++11 [expr.rel]p3:
5072 // Pointers to void (after pointer conversions) can be compared, with a
5073 // result defined as follows: If both pointers represent the same
5074 // address or are both the null pointer value, the result is true if the
5075 // operator is <= or >= and false otherwise; otherwise the result is
5076 // unspecified.
5077 // We interpret this as applying to pointers to *cv* void.
5078 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00005079 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00005080 CCEDiag(E, diag::note_constexpr_void_comparison);
5081
Richard Smith84f6dcf2012-02-02 01:16:57 +00005082 // C++11 [expr.rel]p2:
5083 // - If two pointers point to non-static data members of the same object,
5084 // or to subobjects or array elements fo such members, recursively, the
5085 // pointer to the later declared member compares greater provided the
5086 // two members have the same access control and provided their class is
5087 // not a union.
5088 // [...]
5089 // - Otherwise pointer comparisons are unspecified.
5090 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5091 E->isRelationalOp()) {
5092 bool WasArrayIndex;
5093 unsigned Mismatch =
5094 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5095 RHSDesignator, WasArrayIndex);
5096 // At the point where the designators diverge, the comparison has a
5097 // specified value if:
5098 // - we are comparing array indices
5099 // - we are comparing fields of a union, or fields with the same access
5100 // Otherwise, the result is unspecified and thus the comparison is not a
5101 // constant expression.
5102 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5103 Mismatch < RHSDesignator.Entries.size()) {
5104 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5105 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5106 if (!LF && !RF)
5107 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5108 else if (!LF)
5109 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5110 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5111 << RF->getParent() << RF;
5112 else if (!RF)
5113 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5114 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5115 << LF->getParent() << LF;
5116 else if (!LF->getParent()->isUnion() &&
5117 LF->getAccess() != RF->getAccess())
5118 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5119 << LF << LF->getAccess() << RF << RF->getAccess()
5120 << LF->getParent();
5121 }
5122 }
5123
Eli Friedman6c31cb42012-04-16 04:30:08 +00005124 // The comparison here must be unsigned, and performed with the same
5125 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00005126 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5127 uint64_t CompareLHS = LHSOffset.getQuantity();
5128 uint64_t CompareRHS = RHSOffset.getQuantity();
5129 assert(PtrSize <= 64 && "Unexpected pointer width");
5130 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5131 CompareLHS &= Mask;
5132 CompareRHS &= Mask;
5133
Eli Friedman2f5b7c52012-04-16 19:23:57 +00005134 // If there is a base and this is a relational operator, we can only
5135 // compare pointers within the object in question; otherwise, the result
5136 // depends on where the object is located in memory.
5137 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5138 QualType BaseTy = getType(LHSValue.Base);
5139 if (BaseTy->isIncompleteType())
5140 return Error(E);
5141 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5142 uint64_t OffsetLimit = Size.getQuantity();
5143 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5144 return Error(E);
5145 }
5146
Richard Smith8b3497e2011-10-31 01:37:14 +00005147 switch (E->getOpcode()) {
5148 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00005149 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5150 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5151 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5152 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5153 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5154 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00005155 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005156 }
5157 }
Richard Smith7bb00672012-02-01 01:42:44 +00005158
5159 if (LHSTy->isMemberPointerType()) {
5160 assert(E->isEqualityOp() && "unexpected member pointer operation");
5161 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5162
5163 MemberPtr LHSValue, RHSValue;
5164
5165 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5166 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5167 return false;
5168
5169 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5170 return false;
5171
5172 // C++11 [expr.eq]p2:
5173 // If both operands are null, they compare equal. Otherwise if only one is
5174 // null, they compare unequal.
5175 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5176 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5177 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5178 }
5179
5180 // Otherwise if either is a pointer to a virtual member function, the
5181 // result is unspecified.
5182 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5183 if (MD->isVirtual())
5184 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5185 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5186 if (MD->isVirtual())
5187 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5188
5189 // Otherwise they compare equal if and only if they would refer to the
5190 // same member of the same most derived object or the same subobject if
5191 // they were dereferenced with a hypothetical object of the associated
5192 // class type.
5193 bool Equal = LHSValue == RHSValue;
5194 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5195 }
5196
Richard Smithab44d9b2012-02-14 22:35:28 +00005197 if (LHSTy->isNullPtrType()) {
5198 assert(E->isComparisonOp() && "unexpected nullptr operation");
5199 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5200 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5201 // are compared, the result is true of the operator is <=, >= or ==, and
5202 // false otherwise.
5203 BinaryOperator::Opcode Opcode = E->getOpcode();
5204 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5205 }
5206
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005207 assert((!LHSTy->isIntegralOrEnumerationType() ||
5208 !RHSTy->isIntegralOrEnumerationType()) &&
5209 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5210 // We can't continue from here for non-integral types.
5211 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00005212}
5213
Ken Dyck160146e2010-01-27 17:10:57 +00005214CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00005215 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5216 // result shall be the alignment of the referenced type."
5217 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5218 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00005219
5220 // __alignof is defined to return the preferred alignment.
5221 return Info.Ctx.toCharUnitsFromBits(
5222 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00005223}
5224
Ken Dyck160146e2010-01-27 17:10:57 +00005225CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00005226 E = E->IgnoreParens();
5227
5228 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00005229 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00005230 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005231 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5232 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00005233
Chris Lattner68061312009-01-24 21:53:27 +00005234 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005235 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5236 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00005237
Chris Lattner24aeeab2009-01-24 21:09:06 +00005238 return GetAlignOfType(E->getType());
5239}
5240
5241
Peter Collingbournee190dee2011-03-11 19:24:49 +00005242/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5243/// a result as the expression's type.
5244bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5245 const UnaryExprOrTypeTraitExpr *E) {
5246 switch(E->getKind()) {
5247 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00005248 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00005249 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005250 else
Ken Dyckdbc01912011-03-11 02:13:43 +00005251 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005252 }
Eli Friedman64004332009-03-23 04:38:34 +00005253
Peter Collingbournee190dee2011-03-11 19:24:49 +00005254 case UETT_VecStep: {
5255 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00005256
Peter Collingbournee190dee2011-03-11 19:24:49 +00005257 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00005258 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00005259
Peter Collingbournee190dee2011-03-11 19:24:49 +00005260 // The vec_step built-in functions that take a 3-component
5261 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5262 if (n == 3)
5263 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00005264
Peter Collingbournee190dee2011-03-11 19:24:49 +00005265 return Success(n, E);
5266 } else
5267 return Success(1, E);
5268 }
5269
5270 case UETT_SizeOf: {
5271 QualType SrcTy = E->getTypeOfArgument();
5272 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5273 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00005274 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5275 SrcTy = Ref->getPointeeType();
5276
Richard Smithd62306a2011-11-10 06:34:14 +00005277 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00005278 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00005279 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005280 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005281 }
5282 }
5283
5284 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005285}
5286
Peter Collingbournee9200682011-05-13 03:29:01 +00005287bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00005288 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00005289 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00005290 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005291 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00005292 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00005293 for (unsigned i = 0; i != n; ++i) {
5294 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5295 switch (ON.getKind()) {
5296 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00005297 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00005298 APSInt IdxResult;
5299 if (!EvaluateInteger(Idx, IdxResult, Info))
5300 return false;
5301 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5302 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005303 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005304 CurrentType = AT->getElementType();
5305 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5306 Result += IdxResult.getSExtValue() * ElementSize;
5307 break;
5308 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005309
Douglas Gregor882211c2010-04-28 22:16:22 +00005310 case OffsetOfExpr::OffsetOfNode::Field: {
5311 FieldDecl *MemberDecl = ON.getField();
5312 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005313 if (!RT)
5314 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005315 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005316 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00005317 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00005318 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00005319 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00005320 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00005321 CurrentType = MemberDecl->getType().getNonReferenceType();
5322 break;
5323 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005324
Douglas Gregor882211c2010-04-28 22:16:22 +00005325 case OffsetOfExpr::OffsetOfNode::Identifier:
5326 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00005327
Douglas Gregord1702062010-04-29 00:18:15 +00005328 case OffsetOfExpr::OffsetOfNode::Base: {
5329 CXXBaseSpecifier *BaseSpec = ON.getBase();
5330 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005331 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005332
5333 // Find the layout of the class whose base we are looking into.
5334 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005335 if (!RT)
5336 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005337 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005338 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00005339 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5340
5341 // Find the base class itself.
5342 CurrentType = BaseSpec->getType();
5343 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5344 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005345 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005346
5347 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00005348 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00005349 break;
5350 }
Douglas Gregor882211c2010-04-28 22:16:22 +00005351 }
5352 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005353 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005354}
5355
Chris Lattnere13042c2008-07-11 19:10:17 +00005356bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005357 switch (E->getOpcode()) {
5358 default:
5359 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5360 // See C99 6.6p3.
5361 return Error(E);
5362 case UO_Extension:
5363 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5364 // If so, we could clear the diagnostic ID.
5365 return Visit(E->getSubExpr());
5366 case UO_Plus:
5367 // The result is just the value.
5368 return Visit(E->getSubExpr());
5369 case UO_Minus: {
5370 if (!Visit(E->getSubExpr()))
5371 return false;
5372 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00005373 const APSInt &Value = Result.getInt();
5374 if (Value.isSigned() && Value.isMinSignedValue())
5375 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5376 E->getType());
5377 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005378 }
5379 case UO_Not: {
5380 if (!Visit(E->getSubExpr()))
5381 return false;
5382 if (!Result.isInt()) return Error(E);
5383 return Success(~Result.getInt(), E);
5384 }
5385 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00005386 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00005387 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00005388 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005389 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005390 }
Anders Carlsson9c181652008-07-08 14:35:21 +00005391 }
Anders Carlsson9c181652008-07-08 14:35:21 +00005392}
Mike Stump11289f42009-09-09 15:08:12 +00005393
Chris Lattner477c4be2008-07-12 01:15:53 +00005394/// HandleCast - This is used to evaluate implicit or explicit casts where the
5395/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00005396bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5397 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00005398 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00005399 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00005400
Eli Friedmanc757de22011-03-25 00:43:55 +00005401 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00005402 case CK_BaseToDerived:
5403 case CK_DerivedToBase:
5404 case CK_UncheckedDerivedToBase:
5405 case CK_Dynamic:
5406 case CK_ToUnion:
5407 case CK_ArrayToPointerDecay:
5408 case CK_FunctionToPointerDecay:
5409 case CK_NullToPointer:
5410 case CK_NullToMemberPointer:
5411 case CK_BaseToDerivedMemberPointer:
5412 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00005413 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00005414 case CK_ConstructorConversion:
5415 case CK_IntegralToPointer:
5416 case CK_ToVoid:
5417 case CK_VectorSplat:
5418 case CK_IntegralToFloating:
5419 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00005420 case CK_CPointerToObjCPointerCast:
5421 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00005422 case CK_AnyPointerToBlockPointerCast:
5423 case CK_ObjCObjectLValueCast:
5424 case CK_FloatingRealToComplex:
5425 case CK_FloatingComplexToReal:
5426 case CK_FloatingComplexCast:
5427 case CK_FloatingComplexToIntegralComplex:
5428 case CK_IntegralRealToComplex:
5429 case CK_IntegralComplexCast:
5430 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00005431 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005432 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005433 llvm_unreachable("invalid cast kind for integral value");
5434
Eli Friedman9faf2f92011-03-25 19:07:11 +00005435 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00005436 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005437 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00005438 case CK_ARCProduceObject:
5439 case CK_ARCConsumeObject:
5440 case CK_ARCReclaimReturnedObject:
5441 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00005442 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005443 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005444
Richard Smith4ef685b2012-01-17 21:17:26 +00005445 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00005446 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00005447 case CK_AtomicToNonAtomic:
5448 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00005449 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00005450 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005451
5452 case CK_MemberPointerToBoolean:
5453 case CK_PointerToBoolean:
5454 case CK_IntegralToBoolean:
5455 case CK_FloatingToBoolean:
5456 case CK_FloatingComplexToBoolean:
5457 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00005458 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00005459 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00005460 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005461 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005462 }
5463
Eli Friedmanc757de22011-03-25 00:43:55 +00005464 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00005465 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00005466 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00005467
Eli Friedman742421e2009-02-20 01:15:07 +00005468 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005469 // Allow casts of address-of-label differences if they are no-ops
5470 // or narrowing. (The narrowing case isn't actually guaranteed to
5471 // be constant-evaluatable except in some narrow cases which are hard
5472 // to detect here. We let it through on the assumption the user knows
5473 // what they are doing.)
5474 if (Result.isAddrLabelDiff())
5475 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00005476 // Only allow casts of lvalues if they are lossless.
5477 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5478 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005479
Richard Smith911e1422012-01-30 22:27:01 +00005480 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5481 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00005482 }
Mike Stump11289f42009-09-09 15:08:12 +00005483
Eli Friedmanc757de22011-03-25 00:43:55 +00005484 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005485 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5486
John McCall45d55e42010-05-07 21:00:08 +00005487 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00005488 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00005489 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00005490
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005491 if (LV.getLValueBase()) {
5492 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00005493 // FIXME: Allow a larger integer size than the pointer size, and allow
5494 // narrowing back down to pointer width in subsequent integral casts.
5495 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005496 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005497 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005498
Richard Smithcf74da72011-11-16 07:18:12 +00005499 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005500 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005501 return true;
5502 }
5503
Ken Dyck02990832010-01-15 12:37:54 +00005504 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5505 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00005506 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005507 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005508
Eli Friedmanc757de22011-03-25 00:43:55 +00005509 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00005510 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00005511 if (!EvaluateComplex(SubExpr, C, Info))
5512 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00005513 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00005514 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00005515
Eli Friedmanc757de22011-03-25 00:43:55 +00005516 case CK_FloatingToIntegral: {
5517 APFloat F(0.0);
5518 if (!EvaluateFloat(SubExpr, F, Info))
5519 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00005520
Richard Smith357362d2011-12-13 06:39:58 +00005521 APSInt Value;
5522 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5523 return false;
5524 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005525 }
5526 }
Mike Stump11289f42009-09-09 15:08:12 +00005527
Eli Friedmanc757de22011-03-25 00:43:55 +00005528 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00005529}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005530
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005531bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5532 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00005533 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005534 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5535 return false;
5536 if (!LV.isComplexInt())
5537 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005538 return Success(LV.getComplexIntReal(), E);
5539 }
5540
5541 return Visit(E->getSubExpr());
5542}
5543
Eli Friedman4e7a2412009-02-27 04:45:43 +00005544bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005545 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00005546 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005547 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5548 return false;
5549 if (!LV.isComplexInt())
5550 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005551 return Success(LV.getComplexIntImag(), E);
5552 }
5553
Richard Smith4a678122011-10-24 18:44:57 +00005554 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00005555 return Success(0, E);
5556}
5557
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005558bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5559 return Success(E->getPackLength(), E);
5560}
5561
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005562bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5563 return Success(E->getValue(), E);
5564}
5565
Chris Lattner05706e882008-07-11 18:11:29 +00005566//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00005567// Float Evaluation
5568//===----------------------------------------------------------------------===//
5569
5570namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005571class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005572 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00005573 APFloat &Result;
5574public:
5575 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005576 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00005577
Richard Smith2e312c82012-03-03 22:46:17 +00005578 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005579 Result = V.getFloat();
5580 return true;
5581 }
Eli Friedman24c01542008-08-22 00:06:13 +00005582
Richard Smithfddd3842011-12-30 21:15:51 +00005583 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00005584 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5585 return true;
5586 }
5587
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005588 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00005589
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005590 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00005591 bool VisitBinaryOperator(const BinaryOperator *E);
5592 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005593 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00005594
John McCallb1fb0d32010-05-07 22:08:54 +00005595 bool VisitUnaryReal(const UnaryOperator *E);
5596 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00005597
Richard Smithfddd3842011-12-30 21:15:51 +00005598 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00005599};
5600} // end anonymous namespace
5601
5602static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005603 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005604 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00005605}
5606
Jay Foad39c79802011-01-12 09:06:06 +00005607static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00005608 QualType ResultTy,
5609 const Expr *Arg,
5610 bool SNaN,
5611 llvm::APFloat &Result) {
5612 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5613 if (!S) return false;
5614
5615 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5616
5617 llvm::APInt fill;
5618
5619 // Treat empty strings as if they were zero.
5620 if (S->getString().empty())
5621 fill = llvm::APInt(32, 0);
5622 else if (S->getString().getAsInteger(0, fill))
5623 return false;
5624
5625 if (SNaN)
5626 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5627 else
5628 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5629 return true;
5630}
5631
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005632bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005633 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005634 default:
5635 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5636
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005637 case Builtin::BI__builtin_huge_val:
5638 case Builtin::BI__builtin_huge_valf:
5639 case Builtin::BI__builtin_huge_vall:
5640 case Builtin::BI__builtin_inf:
5641 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00005642 case Builtin::BI__builtin_infl: {
5643 const llvm::fltSemantics &Sem =
5644 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00005645 Result = llvm::APFloat::getInf(Sem);
5646 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00005647 }
Mike Stump11289f42009-09-09 15:08:12 +00005648
John McCall16291492010-02-28 13:00:19 +00005649 case Builtin::BI__builtin_nans:
5650 case Builtin::BI__builtin_nansf:
5651 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005652 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5653 true, Result))
5654 return Error(E);
5655 return true;
John McCall16291492010-02-28 13:00:19 +00005656
Chris Lattner0b7282e2008-10-06 06:31:58 +00005657 case Builtin::BI__builtin_nan:
5658 case Builtin::BI__builtin_nanf:
5659 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00005660 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00005661 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005662 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5663 false, Result))
5664 return Error(E);
5665 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005666
5667 case Builtin::BI__builtin_fabs:
5668 case Builtin::BI__builtin_fabsf:
5669 case Builtin::BI__builtin_fabsl:
5670 if (!EvaluateFloat(E->getArg(0), Result, Info))
5671 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005672
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005673 if (Result.isNegative())
5674 Result.changeSign();
5675 return true;
5676
Mike Stump11289f42009-09-09 15:08:12 +00005677 case Builtin::BI__builtin_copysign:
5678 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005679 case Builtin::BI__builtin_copysignl: {
5680 APFloat RHS(0.);
5681 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5682 !EvaluateFloat(E->getArg(1), RHS, Info))
5683 return false;
5684 Result.copySign(RHS);
5685 return true;
5686 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005687 }
5688}
5689
John McCallb1fb0d32010-05-07 22:08:54 +00005690bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00005691 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5692 ComplexValue CV;
5693 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5694 return false;
5695 Result = CV.FloatReal;
5696 return true;
5697 }
5698
5699 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00005700}
5701
5702bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00005703 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5704 ComplexValue CV;
5705 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5706 return false;
5707 Result = CV.FloatImag;
5708 return true;
5709 }
5710
Richard Smith4a678122011-10-24 18:44:57 +00005711 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00005712 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5713 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00005714 return true;
5715}
5716
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005717bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005718 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005719 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00005720 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00005721 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00005722 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00005723 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5724 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005725 Result.changeSign();
5726 return true;
5727 }
5728}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005729
Eli Friedman24c01542008-08-22 00:06:13 +00005730bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005731 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5732 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00005733
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005734 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00005735 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5736 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00005737 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005738 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedman24c01542008-08-22 00:06:13 +00005739 return false;
5740
5741 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005742 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00005743 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00005744 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005745 break;
John McCalle3027922010-08-25 11:45:40 +00005746 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00005747 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005748 break;
John McCalle3027922010-08-25 11:45:40 +00005749 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00005750 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005751 break;
John McCalle3027922010-08-25 11:45:40 +00005752 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00005753 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005754 break;
Eli Friedman24c01542008-08-22 00:06:13 +00005755 }
Richard Smithc8042322012-02-01 05:53:12 +00005756
5757 if (Result.isInfinity() || Result.isNaN())
5758 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5759 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00005760}
5761
5762bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5763 Result = E->getValue();
5764 return true;
5765}
5766
Peter Collingbournee9200682011-05-13 03:29:01 +00005767bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5768 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00005769
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005770 switch (E->getCastKind()) {
5771 default:
Richard Smith11562c52011-10-28 17:51:58 +00005772 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005773
5774 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00005775 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00005776 return EvaluateInteger(SubExpr, IntResult, Info) &&
5777 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5778 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005779 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005780
5781 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00005782 if (!Visit(SubExpr))
5783 return false;
Richard Smith357362d2011-12-13 06:39:58 +00005784 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5785 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005786 }
John McCalld7646252010-11-14 08:17:51 +00005787
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005788 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00005789 ComplexValue V;
5790 if (!EvaluateComplex(SubExpr, V, Info))
5791 return false;
5792 Result = V.getComplexFloatReal();
5793 return true;
5794 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005795 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005796}
5797
Eli Friedman24c01542008-08-22 00:06:13 +00005798//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005799// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00005800//===----------------------------------------------------------------------===//
5801
5802namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005803class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005804 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00005805 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00005806
Anders Carlsson537969c2008-11-16 20:27:53 +00005807public:
John McCall93d91dc2010-05-07 17:22:02 +00005808 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005809 : ExprEvaluatorBaseTy(info), Result(Result) {}
5810
Richard Smith2e312c82012-03-03 22:46:17 +00005811 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005812 Result.setFrom(V);
5813 return true;
5814 }
Mike Stump11289f42009-09-09 15:08:12 +00005815
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005816 bool ZeroInitialization(const Expr *E);
5817
Anders Carlsson537969c2008-11-16 20:27:53 +00005818 //===--------------------------------------------------------------------===//
5819 // Visitor Methods
5820 //===--------------------------------------------------------------------===//
5821
Peter Collingbournee9200682011-05-13 03:29:01 +00005822 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005823 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00005824 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005825 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005826 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00005827};
5828} // end anonymous namespace
5829
John McCall93d91dc2010-05-07 17:22:02 +00005830static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5831 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005832 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005833 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00005834}
5835
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005836bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00005837 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005838 if (ElemTy->isRealFloatingType()) {
5839 Result.makeComplexFloat();
5840 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5841 Result.FloatReal = Zero;
5842 Result.FloatImag = Zero;
5843 } else {
5844 Result.makeComplexInt();
5845 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5846 Result.IntReal = Zero;
5847 Result.IntImag = Zero;
5848 }
5849 return true;
5850}
5851
Peter Collingbournee9200682011-05-13 03:29:01 +00005852bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5853 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005854
5855 if (SubExpr->getType()->isRealFloatingType()) {
5856 Result.makeComplexFloat();
5857 APFloat &Imag = Result.FloatImag;
5858 if (!EvaluateFloat(SubExpr, Imag, Info))
5859 return false;
5860
5861 Result.FloatReal = APFloat(Imag.getSemantics());
5862 return true;
5863 } else {
5864 assert(SubExpr->getType()->isIntegerType() &&
5865 "Unexpected imaginary literal.");
5866
5867 Result.makeComplexInt();
5868 APSInt &Imag = Result.IntImag;
5869 if (!EvaluateInteger(SubExpr, Imag, Info))
5870 return false;
5871
5872 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5873 return true;
5874 }
5875}
5876
Peter Collingbournee9200682011-05-13 03:29:01 +00005877bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005878
John McCallfcef3cf2010-12-14 17:51:41 +00005879 switch (E->getCastKind()) {
5880 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00005881 case CK_BaseToDerived:
5882 case CK_DerivedToBase:
5883 case CK_UncheckedDerivedToBase:
5884 case CK_Dynamic:
5885 case CK_ToUnion:
5886 case CK_ArrayToPointerDecay:
5887 case CK_FunctionToPointerDecay:
5888 case CK_NullToPointer:
5889 case CK_NullToMemberPointer:
5890 case CK_BaseToDerivedMemberPointer:
5891 case CK_DerivedToBaseMemberPointer:
5892 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00005893 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00005894 case CK_ConstructorConversion:
5895 case CK_IntegralToPointer:
5896 case CK_PointerToIntegral:
5897 case CK_PointerToBoolean:
5898 case CK_ToVoid:
5899 case CK_VectorSplat:
5900 case CK_IntegralCast:
5901 case CK_IntegralToBoolean:
5902 case CK_IntegralToFloating:
5903 case CK_FloatingToIntegral:
5904 case CK_FloatingToBoolean:
5905 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00005906 case CK_CPointerToObjCPointerCast:
5907 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00005908 case CK_AnyPointerToBlockPointerCast:
5909 case CK_ObjCObjectLValueCast:
5910 case CK_FloatingComplexToReal:
5911 case CK_FloatingComplexToBoolean:
5912 case CK_IntegralComplexToReal:
5913 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00005914 case CK_ARCProduceObject:
5915 case CK_ARCConsumeObject:
5916 case CK_ARCReclaimReturnedObject:
5917 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00005918 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00005919 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005920 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00005921 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00005922
John McCallfcef3cf2010-12-14 17:51:41 +00005923 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00005924 case CK_AtomicToNonAtomic:
5925 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00005926 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00005927 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00005928
5929 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005930 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00005931 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005932 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00005933
5934 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005935 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00005936 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005937 return false;
5938
John McCallfcef3cf2010-12-14 17:51:41 +00005939 Result.makeComplexFloat();
5940 Result.FloatImag = APFloat(Real.getSemantics());
5941 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005942 }
5943
John McCallfcef3cf2010-12-14 17:51:41 +00005944 case CK_FloatingComplexCast: {
5945 if (!Visit(E->getSubExpr()))
5946 return false;
5947
5948 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5949 QualType From
5950 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5951
Richard Smith357362d2011-12-13 06:39:58 +00005952 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5953 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005954 }
5955
5956 case CK_FloatingComplexToIntegralComplex: {
5957 if (!Visit(E->getSubExpr()))
5958 return false;
5959
5960 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5961 QualType From
5962 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5963 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00005964 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5965 To, Result.IntReal) &&
5966 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5967 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005968 }
5969
5970 case CK_IntegralRealToComplex: {
5971 APSInt &Real = Result.IntReal;
5972 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5973 return false;
5974
5975 Result.makeComplexInt();
5976 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5977 return true;
5978 }
5979
5980 case CK_IntegralComplexCast: {
5981 if (!Visit(E->getSubExpr()))
5982 return false;
5983
5984 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5985 QualType From
5986 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5987
Richard Smith911e1422012-01-30 22:27:01 +00005988 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5989 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005990 return true;
5991 }
5992
5993 case CK_IntegralComplexToFloatingComplex: {
5994 if (!Visit(E->getSubExpr()))
5995 return false;
5996
Ted Kremenek28831752012-08-23 20:46:57 +00005997 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005998 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00005999 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00006000 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00006001 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6002 To, Result.FloatReal) &&
6003 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6004 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00006005 }
6006 }
6007
6008 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00006009}
6010
John McCall93d91dc2010-05-07 17:22:02 +00006011bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006012 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00006013 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6014
Richard Smith253c2a32012-01-27 01:14:48 +00006015 bool LHSOK = Visit(E->getLHS());
6016 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00006017 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006018
John McCall93d91dc2010-05-07 17:22:02 +00006019 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00006020 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00006021 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006022
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006023 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6024 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006025 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006026 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006027 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006028 if (Result.isComplexFloat()) {
6029 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6030 APFloat::rmNearestTiesToEven);
6031 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6032 APFloat::rmNearestTiesToEven);
6033 } else {
6034 Result.getComplexIntReal() += RHS.getComplexIntReal();
6035 Result.getComplexIntImag() += RHS.getComplexIntImag();
6036 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006037 break;
John McCalle3027922010-08-25 11:45:40 +00006038 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006039 if (Result.isComplexFloat()) {
6040 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6041 APFloat::rmNearestTiesToEven);
6042 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6043 APFloat::rmNearestTiesToEven);
6044 } else {
6045 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6046 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6047 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006048 break;
John McCalle3027922010-08-25 11:45:40 +00006049 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006050 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00006051 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006052 APFloat &LHS_r = LHS.getComplexFloatReal();
6053 APFloat &LHS_i = LHS.getComplexFloatImag();
6054 APFloat &RHS_r = RHS.getComplexFloatReal();
6055 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00006056
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006057 APFloat Tmp = LHS_r;
6058 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6059 Result.getComplexFloatReal() = Tmp;
6060 Tmp = LHS_i;
6061 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6062 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6063
6064 Tmp = LHS_r;
6065 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6066 Result.getComplexFloatImag() = Tmp;
6067 Tmp = LHS_i;
6068 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6069 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6070 } else {
John McCall93d91dc2010-05-07 17:22:02 +00006071 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00006072 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006073 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6074 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00006075 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006076 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6077 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6078 }
6079 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006080 case BO_Div:
6081 if (Result.isComplexFloat()) {
6082 ComplexValue LHS = Result;
6083 APFloat &LHS_r = LHS.getComplexFloatReal();
6084 APFloat &LHS_i = LHS.getComplexFloatImag();
6085 APFloat &RHS_r = RHS.getComplexFloatReal();
6086 APFloat &RHS_i = RHS.getComplexFloatImag();
6087 APFloat &Res_r = Result.getComplexFloatReal();
6088 APFloat &Res_i = Result.getComplexFloatImag();
6089
6090 APFloat Den = RHS_r;
6091 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6092 APFloat Tmp = RHS_i;
6093 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6094 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6095
6096 Res_r = LHS_r;
6097 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6098 Tmp = LHS_i;
6099 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6100 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6101 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6102
6103 Res_i = LHS_i;
6104 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6105 Tmp = LHS_r;
6106 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6107 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6108 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6109 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006110 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6111 return Error(E, diag::note_expr_divide_by_zero);
6112
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006113 ComplexValue LHS = Result;
6114 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6115 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6116 Result.getComplexIntReal() =
6117 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6118 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6119 Result.getComplexIntImag() =
6120 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6121 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6122 }
6123 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006124 }
6125
John McCall93d91dc2010-05-07 17:22:02 +00006126 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006127}
6128
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006129bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6130 // Get the operand value into 'Result'.
6131 if (!Visit(E->getSubExpr()))
6132 return false;
6133
6134 switch (E->getOpcode()) {
6135 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006136 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006137 case UO_Extension:
6138 return true;
6139 case UO_Plus:
6140 // The result is always just the subexpr.
6141 return true;
6142 case UO_Minus:
6143 if (Result.isComplexFloat()) {
6144 Result.getComplexFloatReal().changeSign();
6145 Result.getComplexFloatImag().changeSign();
6146 }
6147 else {
6148 Result.getComplexIntReal() = -Result.getComplexIntReal();
6149 Result.getComplexIntImag() = -Result.getComplexIntImag();
6150 }
6151 return true;
6152 case UO_Not:
6153 if (Result.isComplexFloat())
6154 Result.getComplexFloatImag().changeSign();
6155 else
6156 Result.getComplexIntImag() = -Result.getComplexIntImag();
6157 return true;
6158 }
6159}
6160
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006161bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6162 if (E->getNumInits() == 2) {
6163 if (E->getType()->isComplexType()) {
6164 Result.makeComplexFloat();
6165 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6166 return false;
6167 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6168 return false;
6169 } else {
6170 Result.makeComplexInt();
6171 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6172 return false;
6173 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6174 return false;
6175 }
6176 return true;
6177 }
6178 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6179}
6180
Anders Carlsson537969c2008-11-16 20:27:53 +00006181//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00006182// Void expression evaluation, primarily for a cast to void on the LHS of a
6183// comma operator
6184//===----------------------------------------------------------------------===//
6185
6186namespace {
6187class VoidExprEvaluator
6188 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6189public:
6190 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6191
Richard Smith2e312c82012-03-03 22:46:17 +00006192 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00006193
6194 bool VisitCastExpr(const CastExpr *E) {
6195 switch (E->getCastKind()) {
6196 default:
6197 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6198 case CK_ToVoid:
6199 VisitIgnoredValue(E->getSubExpr());
6200 return true;
6201 }
6202 }
6203};
6204} // end anonymous namespace
6205
6206static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6207 assert(E->isRValue() && E->getType()->isVoidType());
6208 return VoidExprEvaluator(Info).Visit(E);
6209}
6210
6211//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00006212// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00006213//===----------------------------------------------------------------------===//
6214
Richard Smith2e312c82012-03-03 22:46:17 +00006215static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006216 // In C, function designators are not lvalues, but we evaluate them as if they
6217 // are.
6218 if (E->isGLValue() || E->getType()->isFunctionType()) {
6219 LValue LV;
6220 if (!EvaluateLValue(E, LV, Info))
6221 return false;
6222 LV.moveInto(Result);
6223 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006224 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006225 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006226 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006227 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006228 return false;
John McCall45d55e42010-05-07 21:00:08 +00006229 } else if (E->getType()->hasPointerRepresentation()) {
6230 LValue LV;
6231 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006232 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006233 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00006234 } else if (E->getType()->isRealFloatingType()) {
6235 llvm::APFloat F(0.0);
6236 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006237 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006238 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00006239 } else if (E->getType()->isAnyComplexType()) {
6240 ComplexValue C;
6241 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006242 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006243 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00006244 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00006245 MemberPtr P;
6246 if (!EvaluateMemberPointer(E, P, Info))
6247 return false;
6248 P.moveInto(Result);
6249 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00006250 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006251 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006252 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006253 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00006254 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006255 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00006256 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006257 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006258 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006259 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6260 return false;
6261 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00006262 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006263 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006264 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00006265 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00006266 if (!EvaluateVoid(E, Info))
6267 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006268 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006269 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00006270 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006271 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006272 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00006273 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006274 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006275
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00006276 return true;
6277}
6278
Richard Smithb228a862012-02-15 02:18:13 +00006279/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6280/// cases, the in-place evaluation is essential, since later initializers for
6281/// an object can indirectly refer to subobjects which were initialized earlier.
6282static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6283 const Expr *E, CheckConstantExpressionKind CCEK,
6284 bool AllowNonLiteralTypes) {
Richard Smith6331c402012-02-13 22:16:19 +00006285 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00006286 return false;
6287
6288 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00006289 // Evaluate arrays and record types in-place, so that later initializers can
6290 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00006291 if (E->getType()->isArrayType())
6292 return EvaluateArray(E, This, Result, Info);
6293 else if (E->getType()->isRecordType())
6294 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00006295 }
6296
6297 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00006298 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00006299}
6300
Richard Smithf57d8cb2011-12-09 22:58:01 +00006301/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6302/// lvalue-to-rvalue cast if it is an lvalue.
6303static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00006304 if (!CheckLiteralType(Info, E))
6305 return false;
6306
Richard Smith2e312c82012-03-03 22:46:17 +00006307 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006308 return false;
6309
6310 if (E->isGLValue()) {
6311 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00006312 LV.setFrom(Info.Ctx, Result);
6313 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006314 return false;
6315 }
6316
Richard Smith2e312c82012-03-03 22:46:17 +00006317 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00006318 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006319}
Richard Smith11562c52011-10-28 17:51:58 +00006320
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006321static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
6322 const ASTContext &Ctx, bool &IsConst) {
6323 // Fast-path evaluations of integer literals, since we sometimes see files
6324 // containing vast quantities of these.
6325 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
6326 Result.Val = APValue(APSInt(L->getValue(),
6327 L->getType()->isUnsignedIntegerType()));
6328 IsConst = true;
6329 return true;
6330 }
6331
6332 // FIXME: Evaluating values of large array and record types can cause
6333 // performance problems. Only do so in C++11 for now.
6334 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
6335 Exp->getType()->isRecordType()) &&
6336 !Ctx.getLangOpts().CPlusPlus11) {
6337 IsConst = false;
6338 return true;
6339 }
6340 return false;
6341}
6342
6343
Richard Smith7b553f12011-10-29 00:50:52 +00006344/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00006345/// any crazy technique (that has nothing to do with language standards) that
6346/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00006347/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6348/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00006349bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006350 bool IsConst;
6351 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
6352 return IsConst;
6353
Richard Smithf57d8cb2011-12-09 22:58:01 +00006354 EvalInfo Info(Ctx, Result);
6355 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00006356}
6357
Jay Foad39c79802011-01-12 09:06:06 +00006358bool Expr::EvaluateAsBooleanCondition(bool &Result,
6359 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00006360 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00006361 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00006362 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00006363}
6364
Richard Smith5fab0c92011-12-28 19:48:30 +00006365bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6366 SideEffectsKind AllowSideEffects) const {
6367 if (!getType()->isIntegralOrEnumerationType())
6368 return false;
6369
Richard Smith11562c52011-10-28 17:51:58 +00006370 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00006371 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6372 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00006373 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006374
Richard Smith11562c52011-10-28 17:51:58 +00006375 Result = ExprResult.Val.getInt();
6376 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00006377}
6378
Jay Foad39c79802011-01-12 09:06:06 +00006379bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00006380 EvalInfo Info(Ctx, Result);
6381
John McCall45d55e42010-05-07 21:00:08 +00006382 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006383 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6384 !CheckLValueConstantExpression(Info, getExprLoc(),
6385 Ctx.getLValueReferenceType(getType()), LV))
6386 return false;
6387
Richard Smith2e312c82012-03-03 22:46:17 +00006388 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00006389 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00006390}
6391
Richard Smithd0b4dd62011-12-19 06:19:21 +00006392bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6393 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006394 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00006395 // FIXME: Evaluating initializers for large array and record types can cause
6396 // performance problems. Only do so in C++11 for now.
6397 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006398 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00006399 return false;
6400
Richard Smithd0b4dd62011-12-19 06:19:21 +00006401 Expr::EvalStatus EStatus;
6402 EStatus.Diag = &Notes;
6403
6404 EvalInfo InitInfo(Ctx, EStatus);
6405 InitInfo.setEvaluatingDecl(VD, Value);
6406
6407 LValue LVal;
6408 LVal.set(VD);
6409
Richard Smithfddd3842011-12-30 21:15:51 +00006410 // C++11 [basic.start.init]p2:
6411 // Variables with static storage duration or thread storage duration shall be
6412 // zero-initialized before any other initialization takes place.
6413 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006414 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00006415 !VD->getType()->isReferenceType()) {
6416 ImplicitValueInitExpr VIE(VD->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006417 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6418 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00006419 return false;
6420 }
6421
Richard Smithb228a862012-02-15 02:18:13 +00006422 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6423 /*AllowNonLiteralTypes=*/true) ||
6424 EStatus.HasSideEffects)
6425 return false;
6426
6427 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6428 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00006429}
6430
Richard Smith7b553f12011-10-29 00:50:52 +00006431/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6432/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00006433bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00006434 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00006435 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00006436}
Anders Carlsson59689ed2008-11-22 21:04:56 +00006437
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00006438APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006439 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006440 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00006441 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00006442 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00006443 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00006444 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006445 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00006446
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006447 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00006448}
John McCall864e3962010-05-07 05:32:02 +00006449
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006450void Expr::EvaluateForOverflow(const ASTContext &Ctx,
6451 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
6452 bool IsConst;
6453 EvalResult EvalResult;
6454 EvalResult.Diag = Diags;
6455 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
6456 EvalInfo Info(Ctx, EvalResult, true);
6457 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
6458 }
6459}
6460
Abramo Bagnaraf8199452010-05-14 17:07:14 +00006461 bool Expr::EvalResult::isGlobalLValue() const {
6462 assert(Val.isLValue());
6463 return IsGlobalLValue(Val.getLValueBase());
6464 }
6465
6466
John McCall864e3962010-05-07 05:32:02 +00006467/// isIntegerConstantExpr - this recursive routine will test if an expression is
6468/// an integer constant expression.
6469
6470/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6471/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00006472
6473// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00006474// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
6475// and a (possibly null) SourceLocation indicating the location of the problem.
6476//
John McCall864e3962010-05-07 05:32:02 +00006477// Note that to reduce code duplication, this helper does no evaluation
6478// itself; the caller checks whether the expression is evaluatable, and
6479// in the rare cases where CheckICE actually cares about the evaluated
6480// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00006481
Dan Gohman28ade552010-07-26 21:25:24 +00006482namespace {
6483
Richard Smith9e575da2012-12-28 13:25:52 +00006484enum ICEKind {
6485 /// This expression is an ICE.
6486 IK_ICE,
6487 /// This expression is not an ICE, but if it isn't evaluated, it's
6488 /// a legal subexpression for an ICE. This return value is used to handle
6489 /// the comma operator in C99 mode, and non-constant subexpressions.
6490 IK_ICEIfUnevaluated,
6491 /// This expression is not an ICE, and is not a legal subexpression for one.
6492 IK_NotICE
6493};
6494
John McCall864e3962010-05-07 05:32:02 +00006495struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00006496 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00006497 SourceLocation Loc;
6498
Richard Smith9e575da2012-12-28 13:25:52 +00006499 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00006500};
6501
Dan Gohman28ade552010-07-26 21:25:24 +00006502}
6503
Richard Smith9e575da2012-12-28 13:25:52 +00006504static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
6505
6506static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00006507
6508static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6509 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00006510 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00006511 !EVResult.Val.isInt())
6512 return ICEDiag(IK_NotICE, E->getLocStart());
6513
John McCall864e3962010-05-07 05:32:02 +00006514 return NoDiag();
6515}
6516
6517static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6518 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00006519 if (!E->getType()->isIntegralOrEnumerationType())
6520 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006521
6522 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00006523#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00006524#define STMT(Node, Base) case Expr::Node##Class:
6525#define EXPR(Node, Base)
6526#include "clang/AST/StmtNodes.inc"
6527 case Expr::PredefinedExprClass:
6528 case Expr::FloatingLiteralClass:
6529 case Expr::ImaginaryLiteralClass:
6530 case Expr::StringLiteralClass:
6531 case Expr::ArraySubscriptExprClass:
6532 case Expr::MemberExprClass:
6533 case Expr::CompoundAssignOperatorClass:
6534 case Expr::CompoundLiteralExprClass:
6535 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00006536 case Expr::DesignatedInitExprClass:
6537 case Expr::ImplicitValueInitExprClass:
6538 case Expr::ParenListExprClass:
6539 case Expr::VAArgExprClass:
6540 case Expr::AddrLabelExprClass:
6541 case Expr::StmtExprClass:
6542 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00006543 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00006544 case Expr::CXXDynamicCastExprClass:
6545 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00006546 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00006547 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00006548 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00006549 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00006550 case Expr::CXXThisExprClass:
6551 case Expr::CXXThrowExprClass:
6552 case Expr::CXXNewExprClass:
6553 case Expr::CXXDeleteExprClass:
6554 case Expr::CXXPseudoDestructorExprClass:
6555 case Expr::UnresolvedLookupExprClass:
6556 case Expr::DependentScopeDeclRefExprClass:
6557 case Expr::CXXConstructExprClass:
6558 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00006559 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00006560 case Expr::CXXTemporaryObjectExprClass:
6561 case Expr::CXXUnresolvedConstructExprClass:
6562 case Expr::CXXDependentScopeMemberExprClass:
6563 case Expr::UnresolvedMemberExprClass:
6564 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00006565 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006566 case Expr::ObjCArrayLiteralClass:
6567 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00006568 case Expr::ObjCEncodeExprClass:
6569 case Expr::ObjCMessageExprClass:
6570 case Expr::ObjCSelectorExprClass:
6571 case Expr::ObjCProtocolExprClass:
6572 case Expr::ObjCIvarRefExprClass:
6573 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006574 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00006575 case Expr::ObjCIsaExprClass:
6576 case Expr::ShuffleVectorExprClass:
6577 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00006578 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00006579 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00006580 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00006581 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00006582 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00006583 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00006584 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00006585 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00006586 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00006587 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00006588 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00006589 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00006590 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00006591
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006592 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00006593 case Expr::GNUNullExprClass:
6594 // GCC considers the GNU __null value to be an integral constant expression.
6595 return NoDiag();
6596
John McCall7c454bb2011-07-15 05:09:51 +00006597 case Expr::SubstNonTypeTemplateParmExprClass:
6598 return
6599 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6600
John McCall864e3962010-05-07 05:32:02 +00006601 case Expr::ParenExprClass:
6602 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00006603 case Expr::GenericSelectionExprClass:
6604 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00006605 case Expr::IntegerLiteralClass:
6606 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006607 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00006608 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00006609 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00006610 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00006611 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00006612 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00006613 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00006614 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006615 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00006616 return NoDiag();
6617 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00006618 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00006619 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6620 // constant expressions, but they can never be ICEs because an ICE cannot
6621 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00006622 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006623 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00006624 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006625 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006626 }
Richard Smith6365c912012-02-24 22:12:32 +00006627 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00006628 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6629 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00006630 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006631 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00006632 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00006633 // Parameter variables are never constants. Without this check,
6634 // getAnyInitializer() can find a default argument, which leads
6635 // to chaos.
6636 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00006637 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00006638
6639 // C++ 7.1.5.1p2
6640 // A variable of non-volatile const-qualified integral or enumeration
6641 // type initialized by an ICE can be used in ICEs.
6642 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00006643 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00006644 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00006645
Richard Smithd0b4dd62011-12-19 06:19:21 +00006646 const VarDecl *VD;
6647 // Look for a declaration of this variable that has an initializer, and
6648 // check whether it is an ICE.
6649 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6650 return NoDiag();
6651 else
Richard Smith9e575da2012-12-28 13:25:52 +00006652 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00006653 }
6654 }
Richard Smith9e575da2012-12-28 13:25:52 +00006655 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00006656 }
John McCall864e3962010-05-07 05:32:02 +00006657 case Expr::UnaryOperatorClass: {
6658 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6659 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00006660 case UO_PostInc:
6661 case UO_PostDec:
6662 case UO_PreInc:
6663 case UO_PreDec:
6664 case UO_AddrOf:
6665 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00006666 // C99 6.6/3 allows increment and decrement within unevaluated
6667 // subexpressions of constant expressions, but they can never be ICEs
6668 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00006669 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00006670 case UO_Extension:
6671 case UO_LNot:
6672 case UO_Plus:
6673 case UO_Minus:
6674 case UO_Not:
6675 case UO_Real:
6676 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00006677 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00006678 }
Richard Smith9e575da2012-12-28 13:25:52 +00006679
John McCall864e3962010-05-07 05:32:02 +00006680 // OffsetOf falls through here.
6681 }
6682 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00006683 // Note that per C99, offsetof must be an ICE. And AFAIK, using
6684 // EvaluateAsRValue matches the proposed gcc behavior for cases like
6685 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
6686 // compliance: we should warn earlier for offsetof expressions with
6687 // array subscripts that aren't ICEs, and if the array subscripts
6688 // are ICEs, the value of the offsetof must be an integer constant.
6689 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00006690 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00006691 case Expr::UnaryExprOrTypeTraitExprClass: {
6692 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6693 if ((Exp->getKind() == UETT_SizeOf) &&
6694 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00006695 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006696 return NoDiag();
6697 }
6698 case Expr::BinaryOperatorClass: {
6699 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6700 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00006701 case BO_PtrMemD:
6702 case BO_PtrMemI:
6703 case BO_Assign:
6704 case BO_MulAssign:
6705 case BO_DivAssign:
6706 case BO_RemAssign:
6707 case BO_AddAssign:
6708 case BO_SubAssign:
6709 case BO_ShlAssign:
6710 case BO_ShrAssign:
6711 case BO_AndAssign:
6712 case BO_XorAssign:
6713 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00006714 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6715 // constant expressions, but they can never be ICEs because an ICE cannot
6716 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00006717 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006718
John McCalle3027922010-08-25 11:45:40 +00006719 case BO_Mul:
6720 case BO_Div:
6721 case BO_Rem:
6722 case BO_Add:
6723 case BO_Sub:
6724 case BO_Shl:
6725 case BO_Shr:
6726 case BO_LT:
6727 case BO_GT:
6728 case BO_LE:
6729 case BO_GE:
6730 case BO_EQ:
6731 case BO_NE:
6732 case BO_And:
6733 case BO_Xor:
6734 case BO_Or:
6735 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00006736 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6737 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00006738 if (Exp->getOpcode() == BO_Div ||
6739 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00006740 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00006741 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00006742 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00006743 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00006744 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00006745 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006746 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00006747 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00006748 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00006749 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006750 }
6751 }
6752 }
John McCalle3027922010-08-25 11:45:40 +00006753 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006754 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00006755 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6756 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00006757 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
6758 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006759 } else {
6760 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00006761 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006762 }
6763 }
Richard Smith9e575da2012-12-28 13:25:52 +00006764 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00006765 }
John McCalle3027922010-08-25 11:45:40 +00006766 case BO_LAnd:
6767 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00006768 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6769 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006770 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00006771 // Rare case where the RHS has a comma "side-effect"; we need
6772 // to actually check the condition to see whether the side
6773 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00006774 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00006775 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00006776 return RHSResult;
6777 return NoDiag();
6778 }
6779
Richard Smith9e575da2012-12-28 13:25:52 +00006780 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00006781 }
6782 }
6783 }
6784 case Expr::ImplicitCastExprClass:
6785 case Expr::CStyleCastExprClass:
6786 case Expr::CXXFunctionalCastExprClass:
6787 case Expr::CXXStaticCastExprClass:
6788 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00006789 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006790 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00006791 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00006792 if (isa<ExplicitCastExpr>(E)) {
6793 if (const FloatingLiteral *FL
6794 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6795 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6796 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6797 APSInt IgnoredVal(DestWidth, !DestSigned);
6798 bool Ignored;
6799 // If the value does not fit in the destination type, the behavior is
6800 // undefined, so we are not required to treat it as a constant
6801 // expression.
6802 if (FL->getValue().convertToInteger(IgnoredVal,
6803 llvm::APFloat::rmTowardZero,
6804 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00006805 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00006806 return NoDiag();
6807 }
6808 }
Eli Friedman76d4e432011-09-29 21:49:34 +00006809 switch (cast<CastExpr>(E)->getCastKind()) {
6810 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006811 case CK_AtomicToNonAtomic:
6812 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00006813 case CK_NoOp:
6814 case CK_IntegralToBoolean:
6815 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00006816 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00006817 default:
Richard Smith9e575da2012-12-28 13:25:52 +00006818 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00006819 }
John McCall864e3962010-05-07 05:32:02 +00006820 }
John McCallc07a0c72011-02-17 10:25:35 +00006821 case Expr::BinaryConditionalOperatorClass: {
6822 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6823 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006824 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00006825 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006826 if (FalseResult.Kind == IK_NotICE) return FalseResult;
6827 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
6828 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00006829 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00006830 return FalseResult;
6831 }
John McCall864e3962010-05-07 05:32:02 +00006832 case Expr::ConditionalOperatorClass: {
6833 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6834 // If the condition (ignoring parens) is a __builtin_constant_p call,
6835 // then only the true side is actually considered in an integer constant
6836 // expression, and it is fully evaluated. This is an important GNU
6837 // extension. See GCC PR38377 for discussion.
6838 if (const CallExpr *CallCE
6839 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00006840 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6841 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00006842 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006843 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00006844 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00006845
Richard Smithf57d8cb2011-12-09 22:58:01 +00006846 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6847 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00006848
Richard Smith9e575da2012-12-28 13:25:52 +00006849 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00006850 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00006851 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00006852 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00006853 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00006854 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00006855 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00006856 return NoDiag();
6857 // Rare case where the diagnostics depend on which side is evaluated
6858 // Note that if we get here, CondResult is 0, and at least one of
6859 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00006860 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00006861 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00006862 return TrueResult;
6863 }
6864 case Expr::CXXDefaultArgExprClass:
6865 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00006866 case Expr::CXXDefaultInitExprClass:
6867 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00006868 case Expr::ChooseExprClass: {
6869 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6870 }
6871 }
6872
David Blaikiee4d798f2012-01-20 21:50:17 +00006873 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00006874}
6875
Richard Smithf57d8cb2011-12-09 22:58:01 +00006876/// Evaluate an expression as a C++11 integral constant expression.
6877static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6878 const Expr *E,
6879 llvm::APSInt *Value,
6880 SourceLocation *Loc) {
6881 if (!E->getType()->isIntegralOrEnumerationType()) {
6882 if (Loc) *Loc = E->getExprLoc();
6883 return false;
6884 }
6885
Richard Smith66e05fe2012-01-18 05:21:49 +00006886 APValue Result;
6887 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00006888 return false;
6889
Richard Smith66e05fe2012-01-18 05:21:49 +00006890 assert(Result.isInt() && "pointer cast to int is not an ICE");
6891 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00006892 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006893}
6894
Richard Smith92b1ce02011-12-12 09:28:41 +00006895bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006896 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006897 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6898
Richard Smith9e575da2012-12-28 13:25:52 +00006899 ICEDiag D = CheckICE(this, Ctx);
6900 if (D.Kind != IK_ICE) {
6901 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00006902 return false;
6903 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006904 return true;
6905}
6906
6907bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6908 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006909 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006910 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6911
6912 if (!isIntegerConstantExpr(Ctx, Loc))
6913 return false;
6914 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00006915 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00006916 return true;
6917}
Richard Smith66e05fe2012-01-18 05:21:49 +00006918
Richard Smith98a0a492012-02-14 21:38:30 +00006919bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00006920 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00006921}
6922
Richard Smith66e05fe2012-01-18 05:21:49 +00006923bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6924 SourceLocation *Loc) const {
6925 // We support this checking in C++98 mode in order to diagnose compatibility
6926 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006927 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00006928
Richard Smith98a0a492012-02-14 21:38:30 +00006929 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00006930 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006931 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00006932 Status.Diag = &Diags;
6933 EvalInfo Info(Ctx, Status);
6934
6935 APValue Scratch;
6936 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6937
6938 if (!Diags.empty()) {
6939 IsConstExpr = false;
6940 if (Loc) *Loc = Diags[0].first;
6941 } else if (!IsConstExpr) {
6942 // FIXME: This shouldn't happen.
6943 if (Loc) *Loc = getExprLoc();
6944 }
6945
6946 return IsConstExpr;
6947}
Richard Smith253c2a32012-01-27 01:14:48 +00006948
6949bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006950 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00006951 PartialDiagnosticAt> &Diags) {
6952 // FIXME: It would be useful to check constexpr function templates, but at the
6953 // moment the constant expression evaluator cannot cope with the non-rigorous
6954 // ASTs which we build for dependent expressions.
6955 if (FD->isDependentContext())
6956 return true;
6957
6958 Expr::EvalStatus Status;
6959 Status.Diag = &Diags;
6960
6961 EvalInfo Info(FD->getASTContext(), Status);
6962 Info.CheckingPotentialConstantExpression = true;
6963
6964 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6965 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6966
6967 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6968 // is a temporary being used as the 'this' pointer.
6969 LValue This;
6970 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00006971 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00006972
Richard Smith253c2a32012-01-27 01:14:48 +00006973 ArrayRef<const Expr*> Args;
6974
6975 SourceLocation Loc = FD->getLocation();
6976
Richard Smith2e312c82012-03-03 22:46:17 +00006977 APValue Scratch;
6978 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith253c2a32012-01-27 01:14:48 +00006979 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith2e312c82012-03-03 22:46:17 +00006980 else
Richard Smith253c2a32012-01-27 01:14:48 +00006981 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6982 Args, FD->getBody(), Info, Scratch);
6983
6984 return Diags.empty();
6985}