blob: d2d651c97f4dcb4ce68635ab67d1b351ddcce8bd [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-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 Smith745f5142012-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 Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000038#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000039#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000040#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000041#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000042#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000047#include <cstring>
48
Anders Carlssonc44eec62008-07-03 04:20:39 +000049using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000050using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000051using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000052
Chris Lattner87eae5e2008-07-11 22:52:41 +000053/// EvalInfo - This is a private struct used by the evaluator to capture
54/// information about a subexpression as it is folded. It retains information
55/// about the AST context, but also maintains information about the folded
56/// expression.
57///
58/// If an expression could be evaluated, it is still possible it is not a C
59/// "integer constant expression" or constant expression. If not, this struct
60/// captures information about how and why not.
61///
62/// One bit of information passed *into* the request for constant folding
63/// indicates whether the subexpression is "evaluated" or not according to C
64/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
65/// evaluate the expression regardless of what the RHS is, but C only allows
66/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000067namespace {
Richard Smith180f4792011-11-10 06:34:14 +000068 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000069 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000070 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000071
Richard Smith1bf9a9e2011-11-12 22:28:03 +000072 QualType getType(APValue::LValueBase B) {
73 if (!B) return QualType();
74 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
75 return D->getType();
76 return B.get<const Expr*>()->getType();
77 }
78
Richard Smith180f4792011-11-10 06:34:14 +000079 /// Get an LValue path entry, which is known to not be an array index, as a
80 /// field declaration.
81 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
82 APValue::BaseOrMemberType Value;
83 Value.setFromOpaqueValue(E.BaseOrMember);
84 return dyn_cast<FieldDecl>(Value.getPointer());
85 }
86 /// Get an LValue path entry, which is known to not be an array index, as a
87 /// base class declaration.
88 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
89 APValue::BaseOrMemberType Value;
90 Value.setFromOpaqueValue(E.BaseOrMember);
91 return dyn_cast<CXXRecordDecl>(Value.getPointer());
92 }
93 /// Determine whether this LValue path entry for a base class names a virtual
94 /// base class.
95 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
96 APValue::BaseOrMemberType Value;
97 Value.setFromOpaqueValue(E.BaseOrMember);
98 return Value.getInt();
99 }
100
Richard Smithb4e85ed2012-01-06 16:39:00 +0000101 /// Find the path length and type of the most-derived subobject in the given
102 /// path, and find the size of the containing array, if any.
103 static
104 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
105 ArrayRef<APValue::LValuePathEntry> Path,
106 uint64_t &ArraySize, QualType &Type) {
107 unsigned MostDerivedLength = 0;
108 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000109 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000110 if (Type->isArrayType()) {
111 const ConstantArrayType *CAT =
112 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
113 Type = CAT->getElementType();
114 ArraySize = CAT->getSize().getZExtValue();
115 MostDerivedLength = I + 1;
116 } else if (const FieldDecl *FD = getAsField(Path[I])) {
117 Type = FD->getType();
118 ArraySize = 0;
119 MostDerivedLength = I + 1;
120 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000121 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000122 ArraySize = 0;
123 }
Richard Smith9a17a682011-11-07 05:07:52 +0000124 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000125 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000126 }
127
Richard Smithb4e85ed2012-01-06 16:39:00 +0000128 // The order of this enum is important for diagnostics.
129 enum CheckSubobjectKind {
130 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex
131 };
132
Richard Smith0a3bdb62011-11-04 02:25:55 +0000133 /// A path from a glvalue to a subobject of that glvalue.
134 struct SubobjectDesignator {
135 /// True if the subobject was named in a manner not supported by C++11. Such
136 /// lvalues can still be folded, but they are not core constant expressions
137 /// and we cannot perform lvalue-to-rvalue conversions on them.
138 bool Invalid : 1;
139
Richard Smithb4e85ed2012-01-06 16:39:00 +0000140 /// Is this a pointer one past the end of an object?
141 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000142
Richard Smithb4e85ed2012-01-06 16:39:00 +0000143 /// The length of the path to the most-derived object of which this is a
144 /// subobject.
145 unsigned MostDerivedPathLength : 30;
146
147 /// The size of the array of which the most-derived object is an element, or
148 /// 0 if the most-derived object is not an array element.
149 uint64_t MostDerivedArraySize;
150
151 /// The type of the most derived object referred to by this address.
152 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000153
Richard Smith9a17a682011-11-07 05:07:52 +0000154 typedef APValue::LValuePathEntry PathEntry;
155
Richard Smith0a3bdb62011-11-04 02:25:55 +0000156 /// The entries on the path from the glvalue to the designated subobject.
157 SmallVector<PathEntry, 8> Entries;
158
Richard Smithb4e85ed2012-01-06 16:39:00 +0000159 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000160
Richard Smithb4e85ed2012-01-06 16:39:00 +0000161 explicit SubobjectDesignator(QualType T)
162 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
163 MostDerivedArraySize(0), MostDerivedType(T) {}
164
165 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
166 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
167 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000168 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000169 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000170 ArrayRef<PathEntry> VEntries = V.getLValuePath();
171 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
172 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000173 MostDerivedPathLength =
174 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
175 V.getLValuePath(), MostDerivedArraySize,
176 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000177 }
178 }
179
Richard Smith0a3bdb62011-11-04 02:25:55 +0000180 void setInvalid() {
181 Invalid = true;
182 Entries.clear();
183 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000184
185 /// Determine whether this is a one-past-the-end pointer.
186 bool isOnePastTheEnd() const {
187 if (IsOnePastTheEnd)
188 return true;
189 if (MostDerivedArraySize &&
190 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
191 return true;
192 return false;
193 }
194
195 /// Check that this refers to a valid subobject.
196 bool isValidSubobject() const {
197 if (Invalid)
198 return false;
199 return !isOnePastTheEnd();
200 }
201 /// Check that this refers to a valid subobject, and if not, produce a
202 /// relevant diagnostic and set the designator as invalid.
203 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
204
205 /// Update this designator to refer to the first element within this array.
206 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000207 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000208 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000209 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000210
211 // This is a most-derived object.
212 MostDerivedType = CAT->getElementType();
213 MostDerivedArraySize = CAT->getSize().getZExtValue();
214 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000215 }
216 /// Update this designator to refer to the given base or member of this
217 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000218 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000219 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000220 APValue::BaseOrMemberType Value(D, Virtual);
221 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000222 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000223
224 // If this isn't a base class, it's a new most-derived object.
225 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
226 MostDerivedType = FD->getType();
227 MostDerivedArraySize = 0;
228 MostDerivedPathLength = Entries.size();
229 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000230 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000231 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000232 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000233 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000234 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000235 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000236 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000237 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
238 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
239 setInvalid();
240 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000241 return;
242 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000243 // [expr.add]p4: For the purposes of these operators, a pointer to a
244 // nonarray object behaves the same as a pointer to the first element of
245 // an array of length one with the type of the object as its element type.
246 if (IsOnePastTheEnd && N == (uint64_t)-1)
247 IsOnePastTheEnd = false;
248 else if (!IsOnePastTheEnd && N == 1)
249 IsOnePastTheEnd = true;
250 else if (N != 0) {
251 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000252 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000253 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000254 }
255 };
256
Richard Smith47a1eed2011-10-29 20:57:55 +0000257 /// A core constant value. This can be the value of any constant expression,
258 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000259 ///
260 /// For an LValue, the base and offset are stored in the APValue subobject,
261 /// but the other information is stored in the SubobjectDesignator. For all
262 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000263 class CCValue : public APValue {
264 typedef llvm::APSInt APSInt;
265 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000266 /// If the value is a reference or pointer into a parameter or temporary,
267 /// this is the corresponding call stack frame.
268 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000269 /// If the value is a reference or pointer, this is a description of how the
270 /// subobject was specified.
271 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000272 public:
Richard Smith177dce72011-11-01 16:57:24 +0000273 struct GlobalValue {};
274
Richard Smith47a1eed2011-10-29 20:57:55 +0000275 CCValue() {}
276 explicit CCValue(const APSInt &I) : APValue(I) {}
277 explicit CCValue(const APFloat &F) : APValue(F) {}
278 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
279 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
280 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000281 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000282 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000283 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000284 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000285 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
286 APValue(V), CallFrame(0), Designator(Ctx, V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000287 CCValue(const ValueDecl *D, bool IsDerivedMember,
288 ArrayRef<const CXXRecordDecl*> Path) :
289 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000290 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
291 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000292
Richard Smith177dce72011-11-01 16:57:24 +0000293 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000294 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000295 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000296 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000297 SubobjectDesignator &getLValueDesignator() {
298 assert(getKind() == LValue);
299 return Designator;
300 }
301 const SubobjectDesignator &getLValueDesignator() const {
302 return const_cast<CCValue*>(this)->getLValueDesignator();
303 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000304 };
305
Richard Smithd0dccea2011-10-28 22:34:42 +0000306 /// A stack frame in the constexpr call stack.
307 struct CallStackFrame {
308 EvalInfo &Info;
309
310 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000311 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000312
Richard Smith08d6e032011-12-16 19:06:07 +0000313 /// CallLoc - The location of the call expression for this call.
314 SourceLocation CallLoc;
315
316 /// Callee - The function which was called.
317 const FunctionDecl *Callee;
318
Richard Smith180f4792011-11-10 06:34:14 +0000319 /// This - The binding for the this pointer in this call, if any.
320 const LValue *This;
321
Richard Smithd0dccea2011-10-28 22:34:42 +0000322 /// ParmBindings - Parameter bindings for this function call, indexed by
323 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000324 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000325
Richard Smithbd552ef2011-10-31 05:52:43 +0000326 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
327 typedef MapTy::const_iterator temp_iterator;
328 /// Temporaries - Temporary lvalues materialized within this stack frame.
329 MapTy Temporaries;
330
Richard Smith08d6e032011-12-16 19:06:07 +0000331 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
332 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000333 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000334 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000335 };
336
Richard Smithdd1f29b2011-12-12 09:28:41 +0000337 /// A partial diagnostic which we might know in advance that we are not going
338 /// to emit.
339 class OptionalDiagnostic {
340 PartialDiagnostic *Diag;
341
342 public:
343 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
344
345 template<typename T>
346 OptionalDiagnostic &operator<<(const T &v) {
347 if (Diag)
348 *Diag << v;
349 return *this;
350 }
351 };
352
Richard Smithbd552ef2011-10-31 05:52:43 +0000353 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000354 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000355
356 /// EvalStatus - Contains information about the evaluation.
357 Expr::EvalStatus &EvalStatus;
358
359 /// CurrentCall - The top of the constexpr call stack.
360 CallStackFrame *CurrentCall;
361
Richard Smithbd552ef2011-10-31 05:52:43 +0000362 /// CallStackDepth - The number of calls in the call stack right now.
363 unsigned CallStackDepth;
364
365 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
366 /// OpaqueValues - Values used as the common expression in a
367 /// BinaryConditionalOperator.
368 MapTy OpaqueValues;
369
370 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000371 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000372 CallStackFrame BottomFrame;
373
Richard Smith180f4792011-11-10 06:34:14 +0000374 /// EvaluatingDecl - This is the declaration whose initializer is being
375 /// evaluated, if any.
376 const VarDecl *EvaluatingDecl;
377
378 /// EvaluatingDeclValue - This is the value being constructed for the
379 /// declaration whose initializer is being evaluated, if any.
380 APValue *EvaluatingDeclValue;
381
Richard Smithc1c5f272011-12-13 06:39:58 +0000382 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
383 /// notes attached to it will also be stored, otherwise they will not be.
384 bool HasActiveDiagnostic;
385
Richard Smith745f5142012-01-27 01:14:48 +0000386 /// CheckingPotentialConstantExpression - Are we checking whether the
387 /// expression is a potential constant expression? If so, some diagnostics
388 /// are suppressed.
389 bool CheckingPotentialConstantExpression;
390
Richard Smithbd552ef2011-10-31 05:52:43 +0000391
392 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000393 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000394 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000395 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
396 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000397
Richard Smithbd552ef2011-10-31 05:52:43 +0000398 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
399 MapTy::const_iterator i = OpaqueValues.find(e);
400 if (i == OpaqueValues.end()) return 0;
401 return &i->second;
402 }
403
Richard Smith180f4792011-11-10 06:34:14 +0000404 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
405 EvaluatingDecl = VD;
406 EvaluatingDeclValue = &Value;
407 }
408
Richard Smithc18c4232011-11-21 19:36:32 +0000409 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
410
Richard Smithc1c5f272011-12-13 06:39:58 +0000411 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000412 // Don't perform any constexpr calls (other than the call we're checking)
413 // when checking a potential constant expression.
414 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
415 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +0000416 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
417 return true;
418 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
419 << getLangOpts().ConstexprCallDepth;
420 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000421 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000422
Richard Smithc1c5f272011-12-13 06:39:58 +0000423 private:
424 /// Add a diagnostic to the diagnostics list.
425 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
426 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
427 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
428 return EvalStatus.Diag->back().second;
429 }
430
Richard Smith08d6e032011-12-16 19:06:07 +0000431 /// Add notes containing a call stack to the current point of evaluation.
432 void addCallStack(unsigned Limit);
433
Richard Smithc1c5f272011-12-13 06:39:58 +0000434 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000435 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000436 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
437 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000438 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000439 // If we have a prior diagnostic, it will be noting that the expression
440 // isn't a constant expression. This diagnostic is more important.
441 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000442 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000443 unsigned CallStackNotes = CallStackDepth - 1;
444 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
445 if (Limit)
446 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000447 if (CheckingPotentialConstantExpression)
448 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000449
Richard Smithc1c5f272011-12-13 06:39:58 +0000450 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000451 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000452 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
453 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000454 if (!CheckingPotentialConstantExpression)
455 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000456 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000457 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000458 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000459 return OptionalDiagnostic();
460 }
461
462 /// Diagnose that the evaluation does not produce a C++11 core constant
463 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000464 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
465 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000466 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000467 // Don't override a previous diagnostic.
468 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
469 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000470 return Diag(Loc, DiagId, ExtraNotes);
471 }
472
473 /// Add a note to a prior diagnostic.
474 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
475 if (!HasActiveDiagnostic)
476 return OptionalDiagnostic();
477 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000478 }
Richard Smith099e7f62011-12-19 06:19:21 +0000479
480 /// Add a stack of notes to a prior diagnostic.
481 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
482 if (HasActiveDiagnostic) {
483 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
484 Diags.begin(), Diags.end());
485 }
486 }
Richard Smith745f5142012-01-27 01:14:48 +0000487
488 /// Should we continue evaluation as much as possible after encountering a
489 /// construct which can't be folded?
490 bool keepEvaluatingAfterFailure() {
491 return CheckingPotentialConstantExpression && EvalStatus.Diag->empty();
492 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000493 };
Richard Smith08d6e032011-12-16 19:06:07 +0000494}
Richard Smithbd552ef2011-10-31 05:52:43 +0000495
Richard Smithb4e85ed2012-01-06 16:39:00 +0000496bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
497 CheckSubobjectKind CSK) {
498 if (Invalid)
499 return false;
500 if (isOnePastTheEnd()) {
501 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
502 << CSK;
503 setInvalid();
504 return false;
505 }
506 return true;
507}
508
509void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
510 const Expr *E, uint64_t N) {
511 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
512 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
513 << static_cast<int>(N) << /*array*/ 0
514 << static_cast<unsigned>(MostDerivedArraySize);
515 else
516 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
517 << static_cast<int>(N) << /*non-array*/ 1;
518 setInvalid();
519}
520
Richard Smith08d6e032011-12-16 19:06:07 +0000521CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
522 const FunctionDecl *Callee, const LValue *This,
523 const CCValue *Arguments)
524 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
525 This(This), Arguments(Arguments) {
526 Info.CurrentCall = this;
527 ++Info.CallStackDepth;
528}
529
530CallStackFrame::~CallStackFrame() {
531 assert(Info.CurrentCall == this && "calls retired out of order");
532 --Info.CallStackDepth;
533 Info.CurrentCall = Caller;
534}
535
536/// Produce a string describing the given constexpr call.
537static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
538 unsigned ArgIndex = 0;
539 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
540 !isa<CXXConstructorDecl>(Frame->Callee);
541
542 if (!IsMemberCall)
543 Out << *Frame->Callee << '(';
544
545 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
546 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000547 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000548 Out << ", ";
549
550 const ParmVarDecl *Param = *I;
551 const CCValue &Arg = Frame->Arguments[ArgIndex];
552 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
553 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
554 else {
555 // Deliberately slice off the frame to form an APValue we can print.
556 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
557 Arg.getLValueDesignator().Entries,
Richard Smithb4e85ed2012-01-06 16:39:00 +0000558 Arg.getLValueDesignator().IsOnePastTheEnd);
Richard Smith08d6e032011-12-16 19:06:07 +0000559 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
560 }
561
562 if (ArgIndex == 0 && IsMemberCall)
563 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000564 }
565
Richard Smith08d6e032011-12-16 19:06:07 +0000566 Out << ')';
567}
568
569void EvalInfo::addCallStack(unsigned Limit) {
570 // Determine which calls to skip, if any.
571 unsigned ActiveCalls = CallStackDepth - 1;
572 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
573 if (Limit && Limit < ActiveCalls) {
574 SkipStart = Limit / 2 + Limit % 2;
575 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000576 }
577
Richard Smith08d6e032011-12-16 19:06:07 +0000578 // Walk the call stack and add the diagnostics.
579 unsigned CallIdx = 0;
580 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
581 Frame = Frame->Caller, ++CallIdx) {
582 // Skip this call?
583 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
584 if (CallIdx == SkipStart) {
585 // Note that we're skipping calls.
586 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
587 << unsigned(ActiveCalls - Limit);
588 }
589 continue;
590 }
591
592 llvm::SmallVector<char, 128> Buffer;
593 llvm::raw_svector_ostream Out(Buffer);
594 describeCall(Frame, Out);
595 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
596 }
597}
598
599namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000600 struct ComplexValue {
601 private:
602 bool IsInt;
603
604 public:
605 APSInt IntReal, IntImag;
606 APFloat FloatReal, FloatImag;
607
608 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
609
610 void makeComplexFloat() { IsInt = false; }
611 bool isComplexFloat() const { return !IsInt; }
612 APFloat &getComplexFloatReal() { return FloatReal; }
613 APFloat &getComplexFloatImag() { return FloatImag; }
614
615 void makeComplexInt() { IsInt = true; }
616 bool isComplexInt() const { return IsInt; }
617 APSInt &getComplexIntReal() { return IntReal; }
618 APSInt &getComplexIntImag() { return IntImag; }
619
Richard Smith47a1eed2011-10-29 20:57:55 +0000620 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000621 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000622 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000623 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000624 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000625 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000626 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000627 assert(v.isComplexFloat() || v.isComplexInt());
628 if (v.isComplexFloat()) {
629 makeComplexFloat();
630 FloatReal = v.getComplexFloatReal();
631 FloatImag = v.getComplexFloatImag();
632 } else {
633 makeComplexInt();
634 IntReal = v.getComplexIntReal();
635 IntImag = v.getComplexIntImag();
636 }
637 }
John McCallf4cf1a12010-05-07 17:22:02 +0000638 };
John McCallefdb83e2010-05-07 21:00:08 +0000639
640 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000641 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000642 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000643 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000644 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000645
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000646 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000647 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000648 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000649 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000650 SubobjectDesignator &getLValueDesignator() { return Designator; }
651 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000652
Richard Smith47a1eed2011-10-29 20:57:55 +0000653 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000654 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000655 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000656 void setFrom(const CCValue &V) {
657 assert(V.isLValue());
658 Base = V.getLValueBase();
659 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000660 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000661 Designator = V.getLValueDesignator();
662 }
663
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000664 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
665 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000666 Offset = CharUnits::Zero();
667 Frame = F;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000668 Designator = SubobjectDesignator(getType(B));
669 }
670
671 // Check that this LValue is not based on a null pointer. If it is, produce
672 // a diagnostic and mark the designator as invalid.
673 bool checkNullPointer(EvalInfo &Info, const Expr *E,
674 CheckSubobjectKind CSK) {
675 if (Designator.Invalid)
676 return false;
677 if (!Base) {
678 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
679 << CSK;
680 Designator.setInvalid();
681 return false;
682 }
683 return true;
684 }
685
686 // Check this LValue refers to an object. If not, set the designator to be
687 // invalid and emit a diagnostic.
688 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
689 return checkNullPointer(Info, E, CSK) &&
690 Designator.checkSubobject(Info, E, CSK);
691 }
692
693 void addDecl(EvalInfo &Info, const Expr *E,
694 const Decl *D, bool Virtual = false) {
695 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
696 Designator.addDeclUnchecked(D, Virtual);
697 }
698 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
699 checkSubobject(Info, E, CSK_ArrayToPointer);
700 Designator.addArrayUnchecked(CAT);
701 }
702 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
703 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
704 return;
705 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000706 }
John McCallefdb83e2010-05-07 21:00:08 +0000707 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000708
709 struct MemberPtr {
710 MemberPtr() {}
711 explicit MemberPtr(const ValueDecl *Decl) :
712 DeclAndIsDerivedMember(Decl, false), Path() {}
713
714 /// The member or (direct or indirect) field referred to by this member
715 /// pointer, or 0 if this is a null member pointer.
716 const ValueDecl *getDecl() const {
717 return DeclAndIsDerivedMember.getPointer();
718 }
719 /// Is this actually a member of some type derived from the relevant class?
720 bool isDerivedMember() const {
721 return DeclAndIsDerivedMember.getInt();
722 }
723 /// Get the class which the declaration actually lives in.
724 const CXXRecordDecl *getContainingRecord() const {
725 return cast<CXXRecordDecl>(
726 DeclAndIsDerivedMember.getPointer()->getDeclContext());
727 }
728
729 void moveInto(CCValue &V) const {
730 V = CCValue(getDecl(), isDerivedMember(), Path);
731 }
732 void setFrom(const CCValue &V) {
733 assert(V.isMemberPointer());
734 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
735 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
736 Path.clear();
737 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
738 Path.insert(Path.end(), P.begin(), P.end());
739 }
740
741 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
742 /// whether the member is a member of some class derived from the class type
743 /// of the member pointer.
744 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
745 /// Path - The path of base/derived classes from the member declaration's
746 /// class (exclusive) to the class type of the member pointer (inclusive).
747 SmallVector<const CXXRecordDecl*, 4> Path;
748
749 /// Perform a cast towards the class of the Decl (either up or down the
750 /// hierarchy).
751 bool castBack(const CXXRecordDecl *Class) {
752 assert(!Path.empty());
753 const CXXRecordDecl *Expected;
754 if (Path.size() >= 2)
755 Expected = Path[Path.size() - 2];
756 else
757 Expected = getContainingRecord();
758 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
759 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
760 // if B does not contain the original member and is not a base or
761 // derived class of the class containing the original member, the result
762 // of the cast is undefined.
763 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
764 // (D::*). We consider that to be a language defect.
765 return false;
766 }
767 Path.pop_back();
768 return true;
769 }
770 /// Perform a base-to-derived member pointer cast.
771 bool castToDerived(const CXXRecordDecl *Derived) {
772 if (!getDecl())
773 return true;
774 if (!isDerivedMember()) {
775 Path.push_back(Derived);
776 return true;
777 }
778 if (!castBack(Derived))
779 return false;
780 if (Path.empty())
781 DeclAndIsDerivedMember.setInt(false);
782 return true;
783 }
784 /// Perform a derived-to-base member pointer cast.
785 bool castToBase(const CXXRecordDecl *Base) {
786 if (!getDecl())
787 return true;
788 if (Path.empty())
789 DeclAndIsDerivedMember.setInt(true);
790 if (isDerivedMember()) {
791 Path.push_back(Base);
792 return true;
793 }
794 return castBack(Base);
795 }
796 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000797
798 /// Kinds of constant expression checking, for diagnostics.
799 enum CheckConstantExpressionKind {
800 CCEK_Constant, ///< A normal constant.
801 CCEK_ReturnValue, ///< A constexpr function return value.
802 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
803 };
John McCallf4cf1a12010-05-07 17:22:02 +0000804}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000805
Richard Smith47a1eed2011-10-29 20:57:55 +0000806static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000807static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000808 const LValue &This, const Expr *E,
809 CheckConstantExpressionKind CCEK
810 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000811static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
812static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000813static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
814 EvalInfo &Info);
815static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000816static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000817static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000818 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000819static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000820static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000821
822//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000823// Misc utilities
824//===----------------------------------------------------------------------===//
825
Richard Smith180f4792011-11-10 06:34:14 +0000826/// Should this call expression be treated as a string literal?
827static bool IsStringLiteralCall(const CallExpr *E) {
828 unsigned Builtin = E->isBuiltinCall();
829 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
830 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
831}
832
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000833static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000834 // C++11 [expr.const]p3 An address constant expression is a prvalue core
835 // constant expression of pointer type that evaluates to...
836
837 // ... a null pointer value, or a prvalue core constant expression of type
838 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000839 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000840
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000841 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
842 // ... the address of an object with static storage duration,
843 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
844 return VD->hasGlobalStorage();
845 // ... the address of a function,
846 return isa<FunctionDecl>(D);
847 }
848
849 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000850 switch (E->getStmtClass()) {
851 default:
852 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000853 case Expr::CompoundLiteralExprClass:
854 return cast<CompoundLiteralExpr>(E)->isFileScope();
855 // A string literal has static storage duration.
856 case Expr::StringLiteralClass:
857 case Expr::PredefinedExprClass:
858 case Expr::ObjCStringLiteralClass:
859 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000860 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000861 return true;
862 case Expr::CallExprClass:
863 return IsStringLiteralCall(cast<CallExpr>(E));
864 // For GCC compatibility, &&label has static storage duration.
865 case Expr::AddrLabelExprClass:
866 return true;
867 // A Block literal expression may be used as the initialization value for
868 // Block variables at global or local static scope.
869 case Expr::BlockExprClass:
870 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000871 case Expr::ImplicitValueInitExprClass:
872 // FIXME:
873 // We can never form an lvalue with an implicit value initialization as its
874 // base through expression evaluation, so these only appear in one case: the
875 // implicit variable declaration we invent when checking whether a constexpr
876 // constructor can produce a constant expression. We must assume that such
877 // an expression might be a global lvalue.
878 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000879 }
John McCall42c8f872010-05-10 23:27:23 +0000880}
881
Richard Smith9a17a682011-11-07 05:07:52 +0000882/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000883/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000884/// either LValue or CCValue. Return true if we can fold this expression,
885/// whether or not it's a constant expression.
Richard Smith9a17a682011-11-07 05:07:52 +0000886template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000887static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000888 const T &LVal, APValue &Value,
889 CheckConstantExpressionKind CCEK) {
890 APValue::LValueBase Base = LVal.getLValueBase();
891 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
892
893 if (!IsGlobalLValue(Base)) {
894 if (Info.getLangOpts().CPlusPlus0x) {
895 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
896 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
897 << E->isGLValue() << !Designator.Entries.empty()
898 << !!VD << CCEK << VD;
899 if (VD)
900 Info.Note(VD->getLocation(), diag::note_declared_at);
901 else
902 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
903 diag::note_constexpr_temporary_here);
904 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000905 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000906 }
Richard Smith61e61622012-01-12 06:08:57 +0000907 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000908 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000909 }
Richard Smith9a17a682011-11-07 05:07:52 +0000910
Richard Smithb4e85ed2012-01-06 16:39:00 +0000911 bool IsReferenceType = E->isGLValue();
912
913 if (Designator.Invalid) {
Richard Smith61e61622012-01-12 06:08:57 +0000914 // This is not a core constant expression. An appropriate diagnostic will
915 // have already been produced.
Richard Smith9a17a682011-11-07 05:07:52 +0000916 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
917 APValue::NoLValuePath());
918 return true;
919 }
920
Richard Smithb4e85ed2012-01-06 16:39:00 +0000921 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
922 Designator.Entries, Designator.IsOnePastTheEnd);
923
924 // Allow address constant expressions to be past-the-end pointers. This is
925 // an extension: the standard requires them to point to an object.
926 if (!IsReferenceType)
927 return true;
928
929 // A reference constant expression must refer to an object.
930 if (!Base) {
931 // FIXME: diagnostic
932 Info.CCEDiag(E->getExprLoc());
Richard Smith61e61622012-01-12 06:08:57 +0000933 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000934 }
935
Richard Smithc1c5f272011-12-13 06:39:58 +0000936 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +0000937 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000938 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
939 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
940 << !Designator.Entries.empty() << !!VD << VD;
941 if (VD)
942 Info.Note(VD->getLocation(), diag::note_declared_at);
943 else
944 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
945 diag::note_constexpr_temporary_here);
Richard Smithc1c5f272011-12-13 06:39:58 +0000946 }
947
Richard Smith9a17a682011-11-07 05:07:52 +0000948 return true;
949}
950
Richard Smith51201882011-12-30 21:15:51 +0000951/// Check that this core constant expression is of literal type, and if not,
952/// produce an appropriate diagnostic.
953static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
954 if (!E->isRValue() || E->getType()->isLiteralType())
955 return true;
956
957 // Prvalue constant expressions must be of literal types.
958 if (Info.getLangOpts().CPlusPlus0x)
959 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
960 << E->getType();
961 else
962 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
963 return false;
964}
965
Richard Smith47a1eed2011-10-29 20:57:55 +0000966/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000967/// constant expression, and if it is, produce the corresponding constant value.
Richard Smith51201882011-12-30 21:15:51 +0000968/// If not, report an appropriate diagnostic. Does not check that the expression
969/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +0000970static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000971 const CCValue &CCValue, APValue &Value,
972 CheckConstantExpressionKind CCEK
973 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +0000974 if (!CCValue.isLValue()) {
975 Value = CCValue;
976 return true;
977 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000978 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +0000979}
980
Richard Smith9e36b532011-10-31 05:11:32 +0000981const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000982 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +0000983}
984
985static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000986 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +0000987}
988
Richard Smith65ac5982011-11-01 21:06:14 +0000989static bool IsWeakLValue(const LValue &Value) {
990 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +0000991 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +0000992}
993
Richard Smithe24f5fc2011-11-17 22:56:20 +0000994static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +0000995 // A null base expression indicates a null pointer. These are always
996 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000997 if (!Value.getLValueBase()) {
998 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +0000999 return true;
1000 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001001
Richard Smithe24f5fc2011-11-17 22:56:20 +00001002 // We have a non-null base. These are generally known to be true, but if it's
1003 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001004 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001005 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001006 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001007}
1008
Richard Smith47a1eed2011-10-29 20:57:55 +00001009static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001010 switch (Val.getKind()) {
1011 case APValue::Uninitialized:
1012 return false;
1013 case APValue::Int:
1014 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001015 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001016 case APValue::Float:
1017 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001018 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001019 case APValue::ComplexInt:
1020 Result = Val.getComplexIntReal().getBoolValue() ||
1021 Val.getComplexIntImag().getBoolValue();
1022 return true;
1023 case APValue::ComplexFloat:
1024 Result = !Val.getComplexFloatReal().isZero() ||
1025 !Val.getComplexFloatImag().isZero();
1026 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001027 case APValue::LValue:
1028 return EvalPointerValueAsBool(Val, Result);
1029 case APValue::MemberPointer:
1030 Result = Val.getMemberPointerDecl();
1031 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001032 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001033 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001034 case APValue::Struct:
1035 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001036 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001037 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001038 }
1039
Richard Smithc49bd112011-10-28 17:51:58 +00001040 llvm_unreachable("unknown APValue kind");
1041}
1042
1043static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1044 EvalInfo &Info) {
1045 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001046 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001047 if (!Evaluate(Val, Info, E))
1048 return false;
1049 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001050}
1051
Richard Smithc1c5f272011-12-13 06:39:58 +00001052template<typename T>
1053static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1054 const T &SrcValue, QualType DestType) {
1055 llvm::SmallVector<char, 32> Buffer;
1056 SrcValue.toString(Buffer);
1057 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
1058 << StringRef(Buffer.data(), Buffer.size()) << DestType;
1059 return false;
1060}
1061
1062static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1063 QualType SrcType, const APFloat &Value,
1064 QualType DestType, APSInt &Result) {
1065 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001066 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001067 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Richard Smithc1c5f272011-12-13 06:39:58 +00001069 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001070 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001071 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1072 & APFloat::opInvalidOp)
1073 return HandleOverflow(Info, E, Value, DestType);
1074 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001075}
1076
Richard Smithc1c5f272011-12-13 06:39:58 +00001077static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1078 QualType SrcType, QualType DestType,
1079 APFloat &Result) {
1080 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001081 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001082 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1083 APFloat::rmNearestTiesToEven, &ignored)
1084 & APFloat::opOverflow)
1085 return HandleOverflow(Info, E, Value, DestType);
1086 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001087}
1088
Richard Smithf72fccf2012-01-30 22:27:01 +00001089static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1090 QualType DestType, QualType SrcType,
1091 APSInt &Value) {
1092 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001093 APSInt Result = Value;
1094 // Figure out if this is a truncate, extend or noop cast.
1095 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001096 Result = Result.extOrTrunc(DestWidth);
Richard Smithf72fccf2012-01-30 22:27:01 +00001097
1098 // Check whether we overflowed. If so, fold the cast anyway.
1099 if (DestType->isSignedIntegerOrEnumerationType() &&
1100 ((Result.isNegative() && Value.isUnsigned()) ||
1101 Result.extOrTrunc(Value.getBitWidth()) != Value))
1102 (void)HandleOverflow(Info, E, Value, DestType);
1103
Douglas Gregor575a1c92011-05-20 16:38:50 +00001104 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001105 return Result;
1106}
1107
Richard Smithc1c5f272011-12-13 06:39:58 +00001108static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1109 QualType SrcType, const APSInt &Value,
1110 QualType DestType, APFloat &Result) {
1111 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1112 if (Result.convertFromAPInt(Value, Value.isSigned(),
1113 APFloat::rmNearestTiesToEven)
1114 & APFloat::opOverflow)
1115 return HandleOverflow(Info, E, Value, DestType);
1116 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001117}
1118
Eli Friedmane6a24e82011-12-22 03:51:45 +00001119static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1120 llvm::APInt &Res) {
1121 CCValue SVal;
1122 if (!Evaluate(SVal, Info, E))
1123 return false;
1124 if (SVal.isInt()) {
1125 Res = SVal.getInt();
1126 return true;
1127 }
1128 if (SVal.isFloat()) {
1129 Res = SVal.getFloat().bitcastToAPInt();
1130 return true;
1131 }
1132 if (SVal.isVector()) {
1133 QualType VecTy = E->getType();
1134 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1135 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1136 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1137 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1138 Res = llvm::APInt::getNullValue(VecSize);
1139 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1140 APValue &Elt = SVal.getVectorElt(i);
1141 llvm::APInt EltAsInt;
1142 if (Elt.isInt()) {
1143 EltAsInt = Elt.getInt();
1144 } else if (Elt.isFloat()) {
1145 EltAsInt = Elt.getFloat().bitcastToAPInt();
1146 } else {
1147 // Don't try to handle vectors of anything other than int or float
1148 // (not sure if it's possible to hit this case).
1149 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1150 return false;
1151 }
1152 unsigned BaseEltSize = EltAsInt.getBitWidth();
1153 if (BigEndian)
1154 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1155 else
1156 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1157 }
1158 return true;
1159 }
1160 // Give up if the input isn't an int, float, or vector. For example, we
1161 // reject "(v4i16)(intptr_t)&a".
1162 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1163 return false;
1164}
1165
Richard Smithb4e85ed2012-01-06 16:39:00 +00001166/// Cast an lvalue referring to a base subobject to a derived class, by
1167/// truncating the lvalue's path to the given length.
1168static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1169 const RecordDecl *TruncatedType,
1170 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001171 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001172
1173 // Check we actually point to a derived class object.
1174 if (TruncatedElements == D.Entries.size())
1175 return true;
1176 assert(TruncatedElements >= D.MostDerivedPathLength &&
1177 "not casting to a derived class");
1178 if (!Result.checkSubobject(Info, E, CSK_Derived))
1179 return false;
1180
1181 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001182 const RecordDecl *RD = TruncatedType;
1183 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001184 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1185 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001186 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001187 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001188 else
Richard Smith180f4792011-11-10 06:34:14 +00001189 Result.Offset -= Layout.getBaseClassOffset(Base);
1190 RD = Base;
1191 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001192 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001193 return true;
1194}
1195
Richard Smithb4e85ed2012-01-06 16:39:00 +00001196static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001197 const CXXRecordDecl *Derived,
1198 const CXXRecordDecl *Base,
1199 const ASTRecordLayout *RL = 0) {
1200 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1201 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001202 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001203}
1204
Richard Smithb4e85ed2012-01-06 16:39:00 +00001205static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001206 const CXXRecordDecl *DerivedDecl,
1207 const CXXBaseSpecifier *Base) {
1208 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1209
1210 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001211 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001212 return true;
1213 }
1214
Richard Smithb4e85ed2012-01-06 16:39:00 +00001215 SubobjectDesignator &D = Obj.Designator;
1216 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001217 return false;
1218
Richard Smithb4e85ed2012-01-06 16:39:00 +00001219 // Extract most-derived object and corresponding type.
1220 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1221 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1222 return false;
1223
1224 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001225 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1226 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001227 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001228 return true;
1229}
1230
1231/// Update LVal to refer to the given field, which must be a member of the type
1232/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001233static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001234 const FieldDecl *FD,
1235 const ASTRecordLayout *RL = 0) {
1236 if (!RL)
1237 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1238
1239 unsigned I = FD->getFieldIndex();
1240 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001241 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001242}
1243
Richard Smithd9b02e72012-01-25 22:15:11 +00001244/// Update LVal to refer to the given indirect field.
1245static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1246 LValue &LVal,
1247 const IndirectFieldDecl *IFD) {
1248 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1249 CE = IFD->chain_end(); C != CE; ++C)
1250 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1251}
1252
Richard Smith180f4792011-11-10 06:34:14 +00001253/// Get the size of the given type in char units.
1254static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1255 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1256 // extension.
1257 if (Type->isVoidType() || Type->isFunctionType()) {
1258 Size = CharUnits::One();
1259 return true;
1260 }
1261
1262 if (!Type->isConstantSizeType()) {
1263 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001264 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001265 return false;
1266 }
1267
1268 Size = Info.Ctx.getTypeSizeInChars(Type);
1269 return true;
1270}
1271
1272/// Update a pointer value to model pointer arithmetic.
1273/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001274/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001275/// \param LVal - The pointer value to be updated.
1276/// \param EltTy - The pointee type represented by LVal.
1277/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001278static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1279 LValue &LVal, QualType EltTy,
1280 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001281 CharUnits SizeOfPointee;
1282 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1283 return false;
1284
1285 // Compute the new offset in the appropriate width.
1286 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001287 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001288 return true;
1289}
1290
Richard Smith03f96112011-10-24 17:54:18 +00001291/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001292static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1293 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001294 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001295 // If this is a parameter to an active constexpr function call, perform
1296 // argument substitution.
1297 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001298 // Assume arguments of a potential constant expression are unknown
1299 // constant expressions.
1300 if (Info.CheckingPotentialConstantExpression)
1301 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001302 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001303 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001304 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001305 }
Richard Smith177dce72011-11-01 16:57:24 +00001306 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1307 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001308 }
Richard Smith03f96112011-10-24 17:54:18 +00001309
Richard Smith099e7f62011-12-19 06:19:21 +00001310 // Dig out the initializer, and use the declaration which it's attached to.
1311 const Expr *Init = VD->getAnyInitializer(VD);
1312 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001313 // If we're checking a potential constant expression, the variable could be
1314 // initialized later.
1315 if (!Info.CheckingPotentialConstantExpression)
1316 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001317 return false;
1318 }
1319
Richard Smith180f4792011-11-10 06:34:14 +00001320 // If we're currently evaluating the initializer of this declaration, use that
1321 // in-flight value.
1322 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001323 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1324 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001325 return !Result.isUninit();
1326 }
1327
Richard Smith65ac5982011-11-01 21:06:14 +00001328 // Never evaluate the initializer of a weak variable. We can't be sure that
1329 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001330 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001331 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001332 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001333 }
Richard Smith65ac5982011-11-01 21:06:14 +00001334
Richard Smith099e7f62011-12-19 06:19:21 +00001335 // Check that we can fold the initializer. In C++, we will have already done
1336 // this in the cases where it matters for conformance.
1337 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1338 if (!VD->evaluateValue(Notes)) {
1339 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1340 Notes.size() + 1) << VD;
1341 Info.Note(VD->getLocation(), diag::note_declared_at);
1342 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001343 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001344 } else if (!VD->checkInitIsICE()) {
1345 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1346 Notes.size() + 1) << VD;
1347 Info.Note(VD->getLocation(), diag::note_declared_at);
1348 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001349 }
Richard Smith03f96112011-10-24 17:54:18 +00001350
Richard Smithb4e85ed2012-01-06 16:39:00 +00001351 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001352 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001353}
1354
Richard Smithc49bd112011-10-28 17:51:58 +00001355static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001356 Qualifiers Quals = T.getQualifiers();
1357 return Quals.hasConst() && !Quals.hasVolatile();
1358}
1359
Richard Smith59efe262011-11-11 04:05:33 +00001360/// Get the base index of the given base class within an APValue representing
1361/// the given derived class.
1362static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1363 const CXXRecordDecl *Base) {
1364 Base = Base->getCanonicalDecl();
1365 unsigned Index = 0;
1366 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1367 E = Derived->bases_end(); I != E; ++I, ++Index) {
1368 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1369 return Index;
1370 }
1371
1372 llvm_unreachable("base class missing from derived class's bases list");
1373}
1374
Richard Smithcc5d4f62011-11-07 09:22:26 +00001375/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001376static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1377 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001378 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001379 if (Sub.Invalid)
1380 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001381 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001382 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001383 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001384 (unsigned)diag::note_constexpr_read_past_end :
1385 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001386 return false;
1387 }
Richard Smithf64699e2011-11-11 08:28:03 +00001388 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001389 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001390 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1391 // This object might be initialized later.
1392 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001393
1394 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1395 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001396 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001397 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001398 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001399 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001400 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001401 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001402 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001403 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001404 // Note, it should not be possible to form a pointer with a valid
1405 // designator which points more than one past the end of the array.
1406 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001407 (unsigned)diag::note_constexpr_read_past_end :
1408 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001409 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001410 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001411 if (O->getArrayInitializedElts() > Index)
1412 O = &O->getArrayInitializedElt(Index);
1413 else
1414 O = &O->getArrayFiller();
1415 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001416 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1417 // Next subobject is a class, struct or union field.
1418 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1419 if (RD->isUnion()) {
1420 const FieldDecl *UnionField = O->getUnionField();
1421 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001422 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001423 Info.Diag(E->getExprLoc(),
1424 diag::note_constexpr_read_inactive_union_member)
1425 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001426 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001427 }
Richard Smith180f4792011-11-10 06:34:14 +00001428 O = &O->getUnionValue();
1429 } else
1430 O = &O->getStructField(Field->getFieldIndex());
1431 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001432
1433 if (ObjType.isVolatileQualified()) {
1434 if (Info.getLangOpts().CPlusPlus) {
1435 // FIXME: Include a description of the path to the volatile subobject.
1436 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1437 << 2 << Field;
1438 Info.Note(Field->getLocation(), diag::note_declared_at);
1439 } else {
1440 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1441 }
1442 return false;
1443 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001444 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001445 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001446 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1447 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1448 O = &O->getStructBase(getBaseIndex(Derived, Base));
1449 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001450 }
Richard Smith180f4792011-11-10 06:34:14 +00001451
Richard Smithf48fdb02011-12-09 22:58:01 +00001452 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001453 if (!Info.CheckingPotentialConstantExpression)
1454 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001455 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001456 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001457 }
1458
Richard Smithb4e85ed2012-01-06 16:39:00 +00001459 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001460 return true;
1461}
1462
Richard Smith180f4792011-11-10 06:34:14 +00001463/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1464/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1465/// for looking up the glvalue referred to by an entity of reference type.
1466///
1467/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001468/// \param Conv - The expression for which we are performing the conversion.
1469/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001470/// \param Type - The type we expect this conversion to produce.
1471/// \param LVal - The glvalue on which we are attempting to perform this action.
1472/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001473static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1474 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001475 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001476 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1477 if (!Info.getLangOpts().CPlusPlus)
1478 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1479
Richard Smithb4e85ed2012-01-06 16:39:00 +00001480 if (LVal.Designator.Invalid)
1481 // A diagnostic will have already been produced.
1482 return false;
1483
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001484 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001485 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001486 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001487
Richard Smithf48fdb02011-12-09 22:58:01 +00001488 if (!LVal.Base) {
1489 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001490 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1491 return false;
1492 }
1493
1494 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1495 // is not a constant expression (even if the object is non-volatile). We also
1496 // apply this rule to C++98, in order to conform to the expected 'volatile'
1497 // semantics.
1498 if (Type.isVolatileQualified()) {
1499 if (Info.getLangOpts().CPlusPlus)
1500 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1501 else
1502 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001503 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001504 }
Richard Smithc49bd112011-10-28 17:51:58 +00001505
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001506 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001507 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1508 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001509 // expressions are constant expressions too. Inside constexpr functions,
1510 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001511 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001512 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001513 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001514 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001515 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001516 }
1517
Richard Smith7098cbd2011-12-21 05:04:46 +00001518 // DR1313: If the object is volatile-qualified but the glvalue was not,
1519 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001520 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001521 if (VT.isVolatileQualified()) {
1522 if (Info.getLangOpts().CPlusPlus) {
1523 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1524 Info.Note(VD->getLocation(), diag::note_declared_at);
1525 } else {
1526 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001527 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001528 return false;
1529 }
1530
1531 if (!isa<ParmVarDecl>(VD)) {
1532 if (VD->isConstexpr()) {
1533 // OK, we can read this variable.
1534 } else if (VT->isIntegralOrEnumerationType()) {
1535 if (!VT.isConstQualified()) {
1536 if (Info.getLangOpts().CPlusPlus) {
1537 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1538 Info.Note(VD->getLocation(), diag::note_declared_at);
1539 } else {
1540 Info.Diag(Loc);
1541 }
1542 return false;
1543 }
1544 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1545 // We support folding of const floating-point types, in order to make
1546 // static const data members of such types (supported as an extension)
1547 // more useful.
1548 if (Info.getLangOpts().CPlusPlus0x) {
1549 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1550 Info.Note(VD->getLocation(), diag::note_declared_at);
1551 } else {
1552 Info.CCEDiag(Loc);
1553 }
1554 } else {
1555 // FIXME: Allow folding of values of any literal type in all languages.
1556 if (Info.getLangOpts().CPlusPlus0x) {
1557 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1558 Info.Note(VD->getLocation(), diag::note_declared_at);
1559 } else {
1560 Info.Diag(Loc);
1561 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001562 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001563 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001564 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001565
Richard Smithf48fdb02011-12-09 22:58:01 +00001566 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001567 return false;
1568
Richard Smith47a1eed2011-10-29 20:57:55 +00001569 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001570 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001571
1572 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1573 // conversion. This happens when the declaration and the lvalue should be
1574 // considered synonymous, for instance when initializing an array of char
1575 // from a string literal. Continue as if the initializer lvalue was the
1576 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001577 assert(RVal.getLValueOffset().isZero() &&
1578 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001579 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001580 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001581 }
1582
Richard Smith7098cbd2011-12-21 05:04:46 +00001583 // Volatile temporary objects cannot be read in constant expressions.
1584 if (Base->getType().isVolatileQualified()) {
1585 if (Info.getLangOpts().CPlusPlus) {
1586 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1587 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1588 } else {
1589 Info.Diag(Loc);
1590 }
1591 return false;
1592 }
1593
Richard Smith0a3bdb62011-11-04 02:25:55 +00001594 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1595 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1596 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001597 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001598 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001599 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001600 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001601
1602 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001603 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001604 const ConstantArrayType *CAT =
1605 Info.Ctx.getAsConstantArrayType(S->getType());
1606 if (Index >= CAT->getSize().getZExtValue()) {
1607 // Note, it should not be possible to form a pointer which points more
1608 // than one past the end of the array without producing a prior const expr
1609 // diagnostic.
1610 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001611 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001612 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001613 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1614 Type->isUnsignedIntegerType());
1615 if (Index < S->getLength())
1616 Value = S->getCodeUnit(Index);
1617 RVal = CCValue(Value);
1618 return true;
1619 }
1620
Richard Smithcc5d4f62011-11-07 09:22:26 +00001621 if (Frame) {
1622 // If this is a temporary expression with a nontrivial initializer, grab the
1623 // value from the relevant stack frame.
1624 RVal = Frame->Temporaries[Base];
1625 } else if (const CompoundLiteralExpr *CLE
1626 = dyn_cast<CompoundLiteralExpr>(Base)) {
1627 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1628 // initializer until now for such expressions. Such an expression can't be
1629 // an ICE in C, so this only matters for fold.
1630 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1631 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1632 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001633 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001634 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001635 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001636 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001637
Richard Smithf48fdb02011-12-09 22:58:01 +00001638 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1639 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001640}
1641
Richard Smith59efe262011-11-11 04:05:33 +00001642/// Build an lvalue for the object argument of a member function call.
1643static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1644 LValue &This) {
1645 if (Object->getType()->isPointerType())
1646 return EvaluatePointer(Object, This, Info);
1647
1648 if (Object->isGLValue())
1649 return EvaluateLValue(Object, This, Info);
1650
Richard Smithe24f5fc2011-11-17 22:56:20 +00001651 if (Object->getType()->isLiteralType())
1652 return EvaluateTemporary(Object, This, Info);
1653
1654 return false;
1655}
1656
1657/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1658/// lvalue referring to the result.
1659///
1660/// \param Info - Information about the ongoing evaluation.
1661/// \param BO - The member pointer access operation.
1662/// \param LV - Filled in with a reference to the resulting object.
1663/// \param IncludeMember - Specifies whether the member itself is included in
1664/// the resulting LValue subobject designator. This is not possible when
1665/// creating a bound member function.
1666/// \return The field or method declaration to which the member pointer refers,
1667/// or 0 if evaluation fails.
1668static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1669 const BinaryOperator *BO,
1670 LValue &LV,
1671 bool IncludeMember = true) {
1672 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1673
Richard Smith745f5142012-01-27 01:14:48 +00001674 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1675 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001676 return 0;
1677
1678 MemberPtr MemPtr;
1679 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1680 return 0;
1681
1682 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1683 // member value, the behavior is undefined.
1684 if (!MemPtr.getDecl())
1685 return 0;
1686
Richard Smith745f5142012-01-27 01:14:48 +00001687 if (!EvalObjOK)
1688 return 0;
1689
Richard Smithe24f5fc2011-11-17 22:56:20 +00001690 if (MemPtr.isDerivedMember()) {
1691 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001692 // The end of the derived-to-base path for the base object must match the
1693 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001694 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001695 LV.Designator.Entries.size())
1696 return 0;
1697 unsigned PathLengthToMember =
1698 LV.Designator.Entries.size() - MemPtr.Path.size();
1699 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1700 const CXXRecordDecl *LVDecl = getAsBaseClass(
1701 LV.Designator.Entries[PathLengthToMember + I]);
1702 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1703 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1704 return 0;
1705 }
1706
1707 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001708 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1709 PathLengthToMember))
1710 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001711 } else if (!MemPtr.Path.empty()) {
1712 // Extend the LValue path with the member pointer's path.
1713 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1714 MemPtr.Path.size() + IncludeMember);
1715
1716 // Walk down to the appropriate base class.
1717 QualType LVType = BO->getLHS()->getType();
1718 if (const PointerType *PT = LVType->getAs<PointerType>())
1719 LVType = PT->getPointeeType();
1720 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1721 assert(RD && "member pointer access on non-class-type expression");
1722 // The first class in the path is that of the lvalue.
1723 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1724 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001725 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001726 RD = Base;
1727 }
1728 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001729 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001730 }
1731
1732 // Add the member. Note that we cannot build bound member functions here.
1733 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001734 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1735 HandleLValueMember(Info, BO, LV, FD);
1736 else if (const IndirectFieldDecl *IFD =
1737 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1738 HandleLValueIndirectMember(Info, BO, LV, IFD);
1739 else
1740 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001741 }
1742
1743 return MemPtr.getDecl();
1744}
1745
1746/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1747/// the provided lvalue, which currently refers to the base object.
1748static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1749 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001750 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001751 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001752 return false;
1753
Richard Smithb4e85ed2012-01-06 16:39:00 +00001754 QualType TargetQT = E->getType();
1755 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1756 TargetQT = PT->getPointeeType();
1757
1758 // Check this cast lands within the final derived-to-base subobject path.
1759 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1760 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1761 << D.MostDerivedType << TargetQT;
1762 return false;
1763 }
1764
Richard Smithe24f5fc2011-11-17 22:56:20 +00001765 // Check the type of the final cast. We don't need to check the path,
1766 // since a cast can only be formed if the path is unique.
1767 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001768 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1769 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001770 if (NewEntriesSize == D.MostDerivedPathLength)
1771 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1772 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001773 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001774 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1775 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1776 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001777 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001778 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001779
1780 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001781 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001782}
1783
Mike Stumpc4c90452009-10-27 22:09:17 +00001784namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001785enum EvalStmtResult {
1786 /// Evaluation failed.
1787 ESR_Failed,
1788 /// Hit a 'return' statement.
1789 ESR_Returned,
1790 /// Evaluation succeeded.
1791 ESR_Succeeded
1792};
1793}
1794
1795// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001796static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001797 const Stmt *S) {
1798 switch (S->getStmtClass()) {
1799 default:
1800 return ESR_Failed;
1801
1802 case Stmt::NullStmtClass:
1803 case Stmt::DeclStmtClass:
1804 return ESR_Succeeded;
1805
Richard Smithc1c5f272011-12-13 06:39:58 +00001806 case Stmt::ReturnStmtClass: {
1807 CCValue CCResult;
1808 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1809 if (!Evaluate(CCResult, Info, RetExpr) ||
1810 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1811 CCEK_ReturnValue))
1812 return ESR_Failed;
1813 return ESR_Returned;
1814 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001815
1816 case Stmt::CompoundStmtClass: {
1817 const CompoundStmt *CS = cast<CompoundStmt>(S);
1818 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1819 BE = CS->body_end(); BI != BE; ++BI) {
1820 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1821 if (ESR != ESR_Succeeded)
1822 return ESR;
1823 }
1824 return ESR_Succeeded;
1825 }
1826 }
1827}
1828
Richard Smith61802452011-12-22 02:22:31 +00001829/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1830/// default constructor. If so, we'll fold it whether or not it's marked as
1831/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1832/// so we need special handling.
1833static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001834 const CXXConstructorDecl *CD,
1835 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001836 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1837 return false;
1838
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001839 // Value-initialization does not call a trivial default constructor, so such a
1840 // call is a core constant expression whether or not the constructor is
1841 // constexpr.
1842 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001843 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001844 // FIXME: If DiagDecl is an implicitly-declared special member function,
1845 // we should be much more explicit about why it's not constexpr.
1846 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1847 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1848 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00001849 } else {
1850 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1851 }
1852 }
1853 return true;
1854}
1855
Richard Smithc1c5f272011-12-13 06:39:58 +00001856/// CheckConstexprFunction - Check that a function can be called in a constant
1857/// expression.
1858static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1859 const FunctionDecl *Declaration,
1860 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00001861 // Potential constant expressions can contain calls to declared, but not yet
1862 // defined, constexpr functions.
1863 if (Info.CheckingPotentialConstantExpression && !Definition &&
1864 Declaration->isConstexpr())
1865 return false;
1866
Richard Smithc1c5f272011-12-13 06:39:58 +00001867 // Can we evaluate this function call?
1868 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1869 return true;
1870
1871 if (Info.getLangOpts().CPlusPlus0x) {
1872 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001873 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1874 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001875 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1876 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1877 << DiagDecl;
1878 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1879 } else {
1880 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1881 }
1882 return false;
1883}
1884
Richard Smith180f4792011-11-10 06:34:14 +00001885namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001886typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001887}
1888
1889/// EvaluateArgs - Evaluate the arguments to a function call.
1890static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1891 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00001892 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001893 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00001894 I != E; ++I) {
1895 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
1896 // If we're checking for a potential constant expression, evaluate all
1897 // initializers even if some of them fail.
1898 if (!Info.keepEvaluatingAfterFailure())
1899 return false;
1900 Success = false;
1901 }
1902 }
1903 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00001904}
1905
Richard Smithd0dccea2011-10-28 22:34:42 +00001906/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00001907static bool HandleFunctionCall(SourceLocation CallLoc,
1908 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001909 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001910 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00001911 ArgVector ArgValues(Args.size());
1912 if (!EvaluateArgs(Args, ArgValues, Info))
1913 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001914
Richard Smith745f5142012-01-27 01:14:48 +00001915 if (!Info.CheckCallLimit(CallLoc))
1916 return false;
1917
1918 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001919 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1920}
1921
Richard Smith180f4792011-11-10 06:34:14 +00001922/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00001923static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001924 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001925 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00001926 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00001927 ArgVector ArgValues(Args.size());
1928 if (!EvaluateArgs(Args, ArgValues, Info))
1929 return false;
1930
Richard Smith745f5142012-01-27 01:14:48 +00001931 if (!Info.CheckCallLimit(CallLoc))
1932 return false;
1933
1934 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001935
1936 // If it's a delegating constructor, just delegate.
1937 if (Definition->isDelegatingConstructor()) {
1938 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1939 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1940 }
1941
Richard Smith610a60c2012-01-10 04:32:03 +00001942 // For a trivial copy or move constructor, perform an APValue copy. This is
1943 // essential for unions, where the operations performed by the constructor
1944 // cannot be represented by ctor-initializers.
Richard Smith180f4792011-11-10 06:34:14 +00001945 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith610a60c2012-01-10 04:32:03 +00001946 if (Definition->isDefaulted() &&
1947 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
1948 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
1949 LValue RHS;
1950 RHS.setFrom(ArgValues[0]);
1951 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00001952 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
1953 RHS, Value))
1954 return false;
1955 assert((Value.isStruct() || Value.isUnion()) &&
1956 "trivial copy/move from non-class type?");
1957 // Any CCValue of class type must already be a constant expression.
1958 Result = Value;
1959 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00001960 }
1961
1962 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00001963 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00001964 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1965 std::distance(RD->field_begin(), RD->field_end()));
1966
1967 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1968
Richard Smith745f5142012-01-27 01:14:48 +00001969 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001970 unsigned BasesSeen = 0;
1971#ifndef NDEBUG
1972 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1973#endif
1974 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1975 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00001976 LValue Subobject = This;
1977 APValue *Value = &Result;
1978
1979 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00001980 if ((*I)->isBaseInitializer()) {
1981 QualType BaseType((*I)->getBaseClass(), 0);
1982#ifndef NDEBUG
1983 // Non-virtual base classes are initialized in the order in the class
1984 // definition. We cannot have a virtual base class for a literal type.
1985 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1986 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1987 "base class initializers not in expected order");
1988 ++BaseIt;
1989#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00001990 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00001991 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00001992 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00001993 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001994 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00001995 if (RD->isUnion()) {
1996 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00001997 Value = &Result.getUnionValue();
1998 } else {
1999 Value = &Result.getStructField(FD->getFieldIndex());
2000 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002001 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002002 // Walk the indirect field decl's chain to find the object to initialize,
2003 // and make sure we've initialized every step along it.
2004 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2005 CE = IFD->chain_end();
2006 C != CE; ++C) {
2007 FieldDecl *FD = cast<FieldDecl>(*C);
2008 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2009 // Switch the union field if it differs. This happens if we had
2010 // preceding zero-initialization, and we're now initializing a union
2011 // subobject other than the first.
2012 // FIXME: In this case, the values of the other subobjects are
2013 // specified, since zero-initialization sets all padding bits to zero.
2014 if (Value->isUninit() ||
2015 (Value->isUnion() && Value->getUnionField() != FD)) {
2016 if (CD->isUnion())
2017 *Value = APValue(FD);
2018 else
2019 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2020 std::distance(CD->field_begin(), CD->field_end()));
2021 }
Richard Smith745f5142012-01-27 01:14:48 +00002022 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002023 if (CD->isUnion())
2024 Value = &Value->getUnionValue();
2025 else
2026 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002027 }
Richard Smith180f4792011-11-10 06:34:14 +00002028 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002029 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002030 }
Richard Smith745f5142012-01-27 01:14:48 +00002031
2032 if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
2033 (*I)->isBaseInitializer()
2034 ? CCEK_Constant : CCEK_MemberInit)) {
2035 // If we're checking for a potential constant expression, evaluate all
2036 // initializers even if some of them fail.
2037 if (!Info.keepEvaluatingAfterFailure())
2038 return false;
2039 Success = false;
2040 }
Richard Smith180f4792011-11-10 06:34:14 +00002041 }
2042
Richard Smith745f5142012-01-27 01:14:48 +00002043 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002044}
2045
Richard Smithd0dccea2011-10-28 22:34:42 +00002046namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002047class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002048 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002049 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002050public:
2051
Richard Smith1e12c592011-10-16 21:26:27 +00002052 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002053
2054 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002055 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002056 return true;
2057 }
2058
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002059 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2060 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002061 return Visit(E->getResultExpr());
2062 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002063 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002064 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002065 return true;
2066 return false;
2067 }
John McCallf85e1932011-06-15 23:02:42 +00002068 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002069 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002070 return true;
2071 return false;
2072 }
2073 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002074 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002075 return true;
2076 return false;
2077 }
2078
Mike Stumpc4c90452009-10-27 22:09:17 +00002079 // We don't want to evaluate BlockExprs multiple times, as they generate
2080 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002081 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2082 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2083 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002084 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002085 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2086 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2087 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2088 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2089 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2090 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002091 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002092 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002093 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002094 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002095 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002096 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2097 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2098 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2099 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002100 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002101 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2102 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2103 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2104 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2105 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002106 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002107 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002108 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002109 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002110 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002111
2112 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002113 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002114 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2115 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002116 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002117 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002118 return false;
2119 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002120
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002121 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002122};
2123
John McCall56ca35d2011-02-17 10:25:35 +00002124class OpaqueValueEvaluation {
2125 EvalInfo &info;
2126 OpaqueValueExpr *opaqueValue;
2127
2128public:
2129 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2130 Expr *value)
2131 : info(info), opaqueValue(opaqueValue) {
2132
2133 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002134 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002135 this->opaqueValue = 0;
2136 return;
2137 }
John McCall56ca35d2011-02-17 10:25:35 +00002138 }
2139
2140 bool hasError() const { return opaqueValue == 0; }
2141
2142 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002143 // FIXME: This will not work for recursive constexpr functions using opaque
2144 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002145 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2146 }
2147};
2148
Mike Stumpc4c90452009-10-27 22:09:17 +00002149} // end anonymous namespace
2150
Eli Friedman4efaa272008-11-12 09:44:48 +00002151//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002152// Generic Evaluation
2153//===----------------------------------------------------------------------===//
2154namespace {
2155
Richard Smithf48fdb02011-12-09 22:58:01 +00002156// FIXME: RetTy is always bool. Remove it.
2157template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002158class ExprEvaluatorBase
2159 : public ConstStmtVisitor<Derived, RetTy> {
2160private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002161 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002162 return static_cast<Derived*>(this)->Success(V, E);
2163 }
Richard Smith51201882011-12-30 21:15:51 +00002164 RetTy DerivedZeroInitialization(const Expr *E) {
2165 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002166 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002167
2168protected:
2169 EvalInfo &Info;
2170 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2171 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2172
Richard Smithdd1f29b2011-12-12 09:28:41 +00002173 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002174 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002175 }
2176
2177 /// Report an evaluation error. This should only be called when an error is
2178 /// first discovered. When propagating an error, just return false.
2179 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002180 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002181 return false;
2182 }
2183 bool Error(const Expr *E) {
2184 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2185 }
2186
Richard Smith51201882011-12-30 21:15:51 +00002187 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002188
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002189public:
2190 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2191
2192 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002193 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002194 }
2195 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002196 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002197 }
2198
2199 RetTy VisitParenExpr(const ParenExpr *E)
2200 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2201 RetTy VisitUnaryExtension(const UnaryOperator *E)
2202 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2203 RetTy VisitUnaryPlus(const UnaryOperator *E)
2204 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2205 RetTy VisitChooseExpr(const ChooseExpr *E)
2206 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2207 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2208 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002209 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2210 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002211 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2212 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002213 // We cannot create any objects for which cleanups are required, so there is
2214 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2215 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2216 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002217
Richard Smithc216a012011-12-12 12:46:16 +00002218 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2219 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2220 return static_cast<Derived*>(this)->VisitCastExpr(E);
2221 }
2222 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2223 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2224 return static_cast<Derived*>(this)->VisitCastExpr(E);
2225 }
2226
Richard Smithe24f5fc2011-11-17 22:56:20 +00002227 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2228 switch (E->getOpcode()) {
2229 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002230 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002231
2232 case BO_Comma:
2233 VisitIgnoredValue(E->getLHS());
2234 return StmtVisitorTy::Visit(E->getRHS());
2235
2236 case BO_PtrMemD:
2237 case BO_PtrMemI: {
2238 LValue Obj;
2239 if (!HandleMemberPointerAccess(Info, E, Obj))
2240 return false;
2241 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002242 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002243 return false;
2244 return DerivedSuccess(Result, E);
2245 }
2246 }
2247 }
2248
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002249 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2250 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2251 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002252 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002253
2254 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002255 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002256 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002257
2258 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2259 }
2260
2261 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2262 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002263 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002264 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002265
Richard Smithc49bd112011-10-28 17:51:58 +00002266 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002267 return StmtVisitorTy::Visit(EvalExpr);
2268 }
2269
2270 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002271 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002272 if (!Value) {
2273 const Expr *Source = E->getSourceExpr();
2274 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002275 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002276 if (Source == E) { // sanity checking.
2277 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002278 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002279 }
2280 return StmtVisitorTy::Visit(Source);
2281 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002282 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002283 }
Richard Smithf10d9172011-10-11 21:43:33 +00002284
Richard Smithd0dccea2011-10-28 22:34:42 +00002285 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002286 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002287 QualType CalleeType = Callee->getType();
2288
Richard Smithd0dccea2011-10-28 22:34:42 +00002289 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002290 LValue *This = 0, ThisVal;
2291 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002292
Richard Smith59efe262011-11-11 04:05:33 +00002293 // Extract function decl and 'this' pointer from the callee.
2294 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002295 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002296 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2297 // Explicit bound member calls, such as x.f() or p->g();
2298 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002299 return false;
2300 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002301 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002302 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2303 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002304 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2305 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002306 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002307 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002308 return Error(Callee);
2309
2310 FD = dyn_cast<FunctionDecl>(Member);
2311 if (!FD)
2312 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002313 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002314 LValue Call;
2315 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002316 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002317
Richard Smithb4e85ed2012-01-06 16:39:00 +00002318 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002319 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002320 FD = dyn_cast_or_null<FunctionDecl>(
2321 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002322 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002323 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002324
2325 // Overloaded operator calls to member functions are represented as normal
2326 // calls with '*this' as the first argument.
2327 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2328 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002329 // FIXME: When selecting an implicit conversion for an overloaded
2330 // operator delete, we sometimes try to evaluate calls to conversion
2331 // operators without a 'this' parameter!
2332 if (Args.empty())
2333 return Error(E);
2334
Richard Smith59efe262011-11-11 04:05:33 +00002335 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2336 return false;
2337 This = &ThisVal;
2338 Args = Args.slice(1);
2339 }
2340
2341 // Don't call function pointers which have been cast to some other type.
2342 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002343 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002344 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002345 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002346
Richard Smithc1c5f272011-12-13 06:39:58 +00002347 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002348 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002349 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002350
Richard Smithc1c5f272011-12-13 06:39:58 +00002351 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002352 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2353 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002354 return false;
2355
Richard Smithb4e85ed2012-01-06 16:39:00 +00002356 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002357 }
2358
Richard Smithc49bd112011-10-28 17:51:58 +00002359 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2360 return StmtVisitorTy::Visit(E->getInitializer());
2361 }
Richard Smithf10d9172011-10-11 21:43:33 +00002362 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002363 if (E->getNumInits() == 0)
2364 return DerivedZeroInitialization(E);
2365 if (E->getNumInits() == 1)
2366 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002367 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002368 }
2369 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002370 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002371 }
2372 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002373 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002374 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002375 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002376 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002377 }
Richard Smithf10d9172011-10-11 21:43:33 +00002378
Richard Smith180f4792011-11-10 06:34:14 +00002379 /// A member expression where the object is a prvalue is itself a prvalue.
2380 RetTy VisitMemberExpr(const MemberExpr *E) {
2381 assert(!E->isArrow() && "missing call to bound member function?");
2382
2383 CCValue Val;
2384 if (!Evaluate(Val, Info, E->getBase()))
2385 return false;
2386
2387 QualType BaseTy = E->getBase()->getType();
2388
2389 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002390 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002391 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2392 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2393 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2394
Richard Smithb4e85ed2012-01-06 16:39:00 +00002395 SubobjectDesignator Designator(BaseTy);
2396 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002397
Richard Smithf48fdb02011-12-09 22:58:01 +00002398 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002399 DerivedSuccess(Val, E);
2400 }
2401
Richard Smithc49bd112011-10-28 17:51:58 +00002402 RetTy VisitCastExpr(const CastExpr *E) {
2403 switch (E->getCastKind()) {
2404 default:
2405 break;
2406
David Chisnall7a7ee302012-01-16 17:27:18 +00002407 case CK_AtomicToNonAtomic:
2408 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002409 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002410 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002411 return StmtVisitorTy::Visit(E->getSubExpr());
2412
2413 case CK_LValueToRValue: {
2414 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002415 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2416 return false;
2417 CCValue RVal;
2418 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2419 return false;
2420 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002421 }
2422 }
2423
Richard Smithf48fdb02011-12-09 22:58:01 +00002424 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002425 }
2426
Richard Smith8327fad2011-10-24 18:44:57 +00002427 /// Visit a value which is evaluated, but whose value is ignored.
2428 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002429 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002430 if (!Evaluate(Scratch, Info, E))
2431 Info.EvalStatus.HasSideEffects = true;
2432 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002433};
2434
2435}
2436
2437//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002438// Common base class for lvalue and temporary evaluation.
2439//===----------------------------------------------------------------------===//
2440namespace {
2441template<class Derived>
2442class LValueExprEvaluatorBase
2443 : public ExprEvaluatorBase<Derived, bool> {
2444protected:
2445 LValue &Result;
2446 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2447 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2448
2449 bool Success(APValue::LValueBase B) {
2450 Result.set(B);
2451 return true;
2452 }
2453
2454public:
2455 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2456 ExprEvaluatorBaseTy(Info), Result(Result) {}
2457
2458 bool Success(const CCValue &V, const Expr *E) {
2459 Result.setFrom(V);
2460 return true;
2461 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002462
Richard Smithe24f5fc2011-11-17 22:56:20 +00002463 bool VisitMemberExpr(const MemberExpr *E) {
2464 // Handle non-static data members.
2465 QualType BaseTy;
2466 if (E->isArrow()) {
2467 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2468 return false;
2469 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002470 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002471 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002472 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2473 return false;
2474 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002475 } else {
2476 if (!this->Visit(E->getBase()))
2477 return false;
2478 BaseTy = E->getBase()->getType();
2479 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002480
Richard Smithd9b02e72012-01-25 22:15:11 +00002481 const ValueDecl *MD = E->getMemberDecl();
2482 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2483 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2484 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2485 (void)BaseTy;
2486 HandleLValueMember(this->Info, E, Result, FD);
2487 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2488 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2489 } else
2490 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002491
Richard Smithd9b02e72012-01-25 22:15:11 +00002492 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002493 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002494 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002495 RefValue))
2496 return false;
2497 return Success(RefValue, E);
2498 }
2499 return true;
2500 }
2501
2502 bool VisitBinaryOperator(const BinaryOperator *E) {
2503 switch (E->getOpcode()) {
2504 default:
2505 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2506
2507 case BO_PtrMemD:
2508 case BO_PtrMemI:
2509 return HandleMemberPointerAccess(this->Info, E, Result);
2510 }
2511 }
2512
2513 bool VisitCastExpr(const CastExpr *E) {
2514 switch (E->getCastKind()) {
2515 default:
2516 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2517
2518 case CK_DerivedToBase:
2519 case CK_UncheckedDerivedToBase: {
2520 if (!this->Visit(E->getSubExpr()))
2521 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002522
2523 // Now figure out the necessary offset to add to the base LV to get from
2524 // the derived class to the base class.
2525 QualType Type = E->getSubExpr()->getType();
2526
2527 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2528 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002529 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002530 *PathI))
2531 return false;
2532 Type = (*PathI)->getType();
2533 }
2534
2535 return true;
2536 }
2537 }
2538 }
2539};
2540}
2541
2542//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002543// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002544//
2545// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2546// function designators (in C), decl references to void objects (in C), and
2547// temporaries (if building with -Wno-address-of-temporary).
2548//
2549// LValue evaluation produces values comprising a base expression of one of the
2550// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002551// - Declarations
2552// * VarDecl
2553// * FunctionDecl
2554// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002555// * CompoundLiteralExpr in C
2556// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002557// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002558// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002559// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002560// * ObjCEncodeExpr
2561// * AddrLabelExpr
2562// * BlockExpr
2563// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002564// - Locals and temporaries
2565// * Any Expr, with a Frame indicating the function in which the temporary was
2566// evaluated.
2567// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002568//===----------------------------------------------------------------------===//
2569namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002570class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002571 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002572public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002573 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2574 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002575
Richard Smithc49bd112011-10-28 17:51:58 +00002576 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2577
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002578 bool VisitDeclRefExpr(const DeclRefExpr *E);
2579 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002580 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002581 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2582 bool VisitMemberExpr(const MemberExpr *E);
2583 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2584 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002585 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002586 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2587 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002588
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002589 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002590 switch (E->getCastKind()) {
2591 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002592 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002593
Eli Friedmandb924222011-10-11 00:13:24 +00002594 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002595 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002596 if (!Visit(E->getSubExpr()))
2597 return false;
2598 Result.Designator.setInvalid();
2599 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002600
Richard Smithe24f5fc2011-11-17 22:56:20 +00002601 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002602 if (!Visit(E->getSubExpr()))
2603 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002604 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002605 }
2606 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002607
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002608 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002609
Eli Friedman4efaa272008-11-12 09:44:48 +00002610};
2611} // end anonymous namespace
2612
Richard Smithc49bd112011-10-28 17:51:58 +00002613/// Evaluate an expression as an lvalue. This can be legitimately called on
2614/// expressions which are not glvalues, in a few cases:
2615/// * function designators in C,
2616/// * "extern void" objects,
2617/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002618static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002619 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2620 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2621 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002622 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002623}
2624
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002625bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002626 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2627 return Success(FD);
2628 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002629 return VisitVarDecl(E, VD);
2630 return Error(E);
2631}
Richard Smith436c8892011-10-24 23:14:33 +00002632
Richard Smithc49bd112011-10-28 17:51:58 +00002633bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002634 if (!VD->getType()->isReferenceType()) {
2635 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002636 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002637 return true;
2638 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002639 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002640 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002641
Richard Smith47a1eed2011-10-29 20:57:55 +00002642 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002643 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2644 return false;
2645 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002646}
2647
Richard Smithbd552ef2011-10-31 05:52:43 +00002648bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2649 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002650 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002651 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002652 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2653
2654 Result.set(E, Info.CurrentCall);
2655 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2656 Result, E->GetTemporaryExpr());
2657 }
2658
2659 // Materialization of an lvalue temporary occurs when we need to force a copy
2660 // (for instance, if it's a bitfield).
2661 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2662 if (!Visit(E->GetTemporaryExpr()))
2663 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002664 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002665 Info.CurrentCall->Temporaries[E]))
2666 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002667 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002668 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002669}
2670
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002671bool
2672LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002673 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2674 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2675 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002676 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002677}
2678
Richard Smith47d21452011-12-27 12:18:28 +00002679bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2680 if (E->isTypeOperand())
2681 return Success(E);
2682 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2683 if (RD && RD->isPolymorphic()) {
2684 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2685 << E->getExprOperand()->getType()
2686 << E->getExprOperand()->getSourceRange();
2687 return false;
2688 }
2689 return Success(E);
2690}
2691
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002692bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002693 // Handle static data members.
2694 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2695 VisitIgnoredValue(E->getBase());
2696 return VisitVarDecl(E, VD);
2697 }
2698
Richard Smithd0dccea2011-10-28 22:34:42 +00002699 // Handle static member functions.
2700 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2701 if (MD->isStatic()) {
2702 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002703 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002704 }
2705 }
2706
Richard Smith180f4792011-11-10 06:34:14 +00002707 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002708 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002709}
2710
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002711bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002712 // FIXME: Deal with vectors as array subscript bases.
2713 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002714 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002715
Anders Carlsson3068d112008-11-16 19:01:22 +00002716 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002717 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002718
Anders Carlsson3068d112008-11-16 19:01:22 +00002719 APSInt Index;
2720 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002721 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002722 int64_t IndexValue
2723 = Index.isSigned() ? Index.getSExtValue()
2724 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002725
Richard Smithb4e85ed2012-01-06 16:39:00 +00002726 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002727}
Eli Friedman4efaa272008-11-12 09:44:48 +00002728
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002729bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002730 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002731}
2732
Eli Friedman4efaa272008-11-12 09:44:48 +00002733//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002734// Pointer Evaluation
2735//===----------------------------------------------------------------------===//
2736
Anders Carlssonc754aa62008-07-08 05:13:58 +00002737namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002738class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002739 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002740 LValue &Result;
2741
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002742 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002743 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002744 return true;
2745 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002746public:
Mike Stump1eb44332009-09-09 15:08:12 +00002747
John McCallefdb83e2010-05-07 21:00:08 +00002748 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002749 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002750
Richard Smith47a1eed2011-10-29 20:57:55 +00002751 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002752 Result.setFrom(V);
2753 return true;
2754 }
Richard Smith51201882011-12-30 21:15:51 +00002755 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002756 return Success((Expr*)0);
2757 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002758
John McCallefdb83e2010-05-07 21:00:08 +00002759 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002760 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002761 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002762 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002763 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002764 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002765 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002766 bool VisitCallExpr(const CallExpr *E);
2767 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002768 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002769 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002770 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002771 }
Richard Smith180f4792011-11-10 06:34:14 +00002772 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2773 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002774 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002775 Result = *Info.CurrentCall->This;
2776 return true;
2777 }
John McCall56ca35d2011-02-17 10:25:35 +00002778
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002779 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002780};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002781} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002782
John McCallefdb83e2010-05-07 21:00:08 +00002783static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002784 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002785 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002786}
2787
John McCallefdb83e2010-05-07 21:00:08 +00002788bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002789 if (E->getOpcode() != BO_Add &&
2790 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002791 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002792
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002793 const Expr *PExp = E->getLHS();
2794 const Expr *IExp = E->getRHS();
2795 if (IExp->getType()->isPointerType())
2796 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002797
Richard Smith745f5142012-01-27 01:14:48 +00002798 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
2799 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00002800 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002801
John McCallefdb83e2010-05-07 21:00:08 +00002802 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00002803 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00002804 return false;
2805 int64_t AdditionalOffset
2806 = Offset.isSigned() ? Offset.getSExtValue()
2807 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002808 if (E->getOpcode() == BO_Sub)
2809 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002810
Richard Smith180f4792011-11-10 06:34:14 +00002811 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002812 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2813 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002814}
Eli Friedman4efaa272008-11-12 09:44:48 +00002815
John McCallefdb83e2010-05-07 21:00:08 +00002816bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2817 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002818}
Mike Stump1eb44332009-09-09 15:08:12 +00002819
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002820bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2821 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002822
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002823 switch (E->getCastKind()) {
2824 default:
2825 break;
2826
John McCall2de56d12010-08-25 11:45:40 +00002827 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002828 case CK_CPointerToObjCPointerCast:
2829 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002830 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002831 if (!Visit(SubExpr))
2832 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002833 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2834 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2835 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002836 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002837 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002838 if (SubExpr->getType()->isVoidPointerType())
2839 CCEDiag(E, diag::note_constexpr_invalid_cast)
2840 << 3 << SubExpr->getType();
2841 else
2842 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2843 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002844 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002845
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002846 case CK_DerivedToBase:
2847 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002848 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002849 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002850 if (!Result.Base && Result.Offset.isZero())
2851 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002852
Richard Smith180f4792011-11-10 06:34:14 +00002853 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002854 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002855 QualType Type =
2856 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002857
Richard Smith180f4792011-11-10 06:34:14 +00002858 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002859 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002860 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2861 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002862 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002863 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002864 }
2865
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002866 return true;
2867 }
2868
Richard Smithe24f5fc2011-11-17 22:56:20 +00002869 case CK_BaseToDerived:
2870 if (!Visit(E->getSubExpr()))
2871 return false;
2872 if (!Result.Base && Result.Offset.isZero())
2873 return true;
2874 return HandleBaseToDerivedCast(Info, E, Result);
2875
Richard Smith47a1eed2011-10-29 20:57:55 +00002876 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00002877 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002878
John McCall2de56d12010-08-25 11:45:40 +00002879 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002880 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2881
Richard Smith47a1eed2011-10-29 20:57:55 +00002882 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002883 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002884 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002885
John McCallefdb83e2010-05-07 21:00:08 +00002886 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002887 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2888 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002889 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002890 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002891 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002892 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002893 return true;
2894 } else {
2895 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002896 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002897 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002898 }
2899 }
John McCall2de56d12010-08-25 11:45:40 +00002900 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002901 if (SubExpr->isGLValue()) {
2902 if (!EvaluateLValue(SubExpr, Result, Info))
2903 return false;
2904 } else {
2905 Result.set(SubExpr, Info.CurrentCall);
2906 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2907 Info, Result, SubExpr))
2908 return false;
2909 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002910 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002911 if (const ConstantArrayType *CAT
2912 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2913 Result.addArray(Info, E, CAT);
2914 else
2915 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00002916 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002917
John McCall2de56d12010-08-25 11:45:40 +00002918 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002919 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002920 }
2921
Richard Smithc49bd112011-10-28 17:51:58 +00002922 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002923}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002924
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002925bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002926 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002927 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002928
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002929 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002930}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002931
2932//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002933// Member Pointer Evaluation
2934//===----------------------------------------------------------------------===//
2935
2936namespace {
2937class MemberPointerExprEvaluator
2938 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2939 MemberPtr &Result;
2940
2941 bool Success(const ValueDecl *D) {
2942 Result = MemberPtr(D);
2943 return true;
2944 }
2945public:
2946
2947 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2948 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2949
2950 bool Success(const CCValue &V, const Expr *E) {
2951 Result.setFrom(V);
2952 return true;
2953 }
Richard Smith51201882011-12-30 21:15:51 +00002954 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002955 return Success((const ValueDecl*)0);
2956 }
2957
2958 bool VisitCastExpr(const CastExpr *E);
2959 bool VisitUnaryAddrOf(const UnaryOperator *E);
2960};
2961} // end anonymous namespace
2962
2963static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2964 EvalInfo &Info) {
2965 assert(E->isRValue() && E->getType()->isMemberPointerType());
2966 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2967}
2968
2969bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2970 switch (E->getCastKind()) {
2971 default:
2972 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2973
2974 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00002975 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002976
2977 case CK_BaseToDerivedMemberPointer: {
2978 if (!Visit(E->getSubExpr()))
2979 return false;
2980 if (E->path_empty())
2981 return true;
2982 // Base-to-derived member pointer casts store the path in derived-to-base
2983 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2984 // the wrong end of the derived->base arc, so stagger the path by one class.
2985 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2986 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2987 PathI != PathE; ++PathI) {
2988 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2989 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2990 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00002991 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002992 }
2993 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2994 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002995 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002996 return true;
2997 }
2998
2999 case CK_DerivedToBaseMemberPointer:
3000 if (!Visit(E->getSubExpr()))
3001 return false;
3002 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3003 PathE = E->path_end(); PathI != PathE; ++PathI) {
3004 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3005 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3006 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003007 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003008 }
3009 return true;
3010 }
3011}
3012
3013bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3014 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3015 // member can be formed.
3016 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3017}
3018
3019//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003020// Record Evaluation
3021//===----------------------------------------------------------------------===//
3022
3023namespace {
3024 class RecordExprEvaluator
3025 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3026 const LValue &This;
3027 APValue &Result;
3028 public:
3029
3030 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3031 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3032
3033 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003034 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00003035 }
Richard Smith51201882011-12-30 21:15:51 +00003036 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003037
Richard Smith59efe262011-11-11 04:05:33 +00003038 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003039 bool VisitInitListExpr(const InitListExpr *E);
3040 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3041 };
3042}
3043
Richard Smith51201882011-12-30 21:15:51 +00003044/// Perform zero-initialization on an object of non-union class type.
3045/// C++11 [dcl.init]p5:
3046/// To zero-initialize an object or reference of type T means:
3047/// [...]
3048/// -- if T is a (possibly cv-qualified) non-union class type,
3049/// each non-static data member and each base-class subobject is
3050/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003051static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3052 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003053 const LValue &This, APValue &Result) {
3054 assert(!RD->isUnion() && "Expected non-union class type");
3055 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3056 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3057 std::distance(RD->field_begin(), RD->field_end()));
3058
3059 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3060
3061 if (CD) {
3062 unsigned Index = 0;
3063 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003064 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003065 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3066 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003067 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3068 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003069 Result.getStructBase(Index)))
3070 return false;
3071 }
3072 }
3073
Richard Smithb4e85ed2012-01-06 16:39:00 +00003074 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3075 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003076 // -- if T is a reference type, no initialization is performed.
3077 if ((*I)->getType()->isReferenceType())
3078 continue;
3079
3080 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003081 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003082
3083 ImplicitValueInitExpr VIE((*I)->getType());
3084 if (!EvaluateConstantExpression(
3085 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3086 return false;
3087 }
3088
3089 return true;
3090}
3091
3092bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3093 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3094 if (RD->isUnion()) {
3095 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3096 // object's first non-static named data member is zero-initialized
3097 RecordDecl::field_iterator I = RD->field_begin();
3098 if (I == RD->field_end()) {
3099 Result = APValue((const FieldDecl*)0);
3100 return true;
3101 }
3102
3103 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003104 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003105 Result = APValue(*I);
3106 ImplicitValueInitExpr VIE((*I)->getType());
3107 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3108 Subobject, &VIE);
3109 }
3110
Richard Smithb4e85ed2012-01-06 16:39:00 +00003111 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003112}
3113
Richard Smith59efe262011-11-11 04:05:33 +00003114bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3115 switch (E->getCastKind()) {
3116 default:
3117 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3118
3119 case CK_ConstructorConversion:
3120 return Visit(E->getSubExpr());
3121
3122 case CK_DerivedToBase:
3123 case CK_UncheckedDerivedToBase: {
3124 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003125 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003126 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003127 if (!DerivedObject.isStruct())
3128 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003129
3130 // Derived-to-base rvalue conversion: just slice off the derived part.
3131 APValue *Value = &DerivedObject;
3132 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3133 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3134 PathE = E->path_end(); PathI != PathE; ++PathI) {
3135 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3136 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3137 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3138 RD = Base;
3139 }
3140 Result = *Value;
3141 return true;
3142 }
3143 }
3144}
3145
Richard Smith180f4792011-11-10 06:34:14 +00003146bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3147 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3148 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3149
3150 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003151 const FieldDecl *Field = E->getInitializedFieldInUnion();
3152 Result = APValue(Field);
3153 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003154 return true;
Richard Smithec789162012-01-12 18:54:33 +00003155
3156 // If the initializer list for a union does not contain any elements, the
3157 // first element of the union is value-initialized.
3158 ImplicitValueInitExpr VIE(Field->getType());
3159 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3160
Richard Smith180f4792011-11-10 06:34:14 +00003161 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003162 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003163 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003164 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003165 }
3166
3167 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3168 "initializer list for class with base classes");
3169 Result = APValue(APValue::UninitStruct(), 0,
3170 std::distance(RD->field_begin(), RD->field_end()));
3171 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003172 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003173 for (RecordDecl::field_iterator Field = RD->field_begin(),
3174 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3175 // Anonymous bit-fields are not considered members of the class for
3176 // purposes of aggregate initialization.
3177 if (Field->isUnnamedBitfield())
3178 continue;
3179
3180 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003181
Richard Smith745f5142012-01-27 01:14:48 +00003182 bool HaveInit = ElementNo < E->getNumInits();
3183
3184 // FIXME: Diagnostics here should point to the end of the initializer
3185 // list, not the start.
3186 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3187 *Field, &Layout);
3188
3189 // Perform an implicit value-initialization for members beyond the end of
3190 // the initializer list.
3191 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3192
3193 if (!EvaluateConstantExpression(
3194 Result.getStructField((*Field)->getFieldIndex()),
3195 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3196 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003197 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003198 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003199 }
3200 }
3201
Richard Smith745f5142012-01-27 01:14:48 +00003202 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003203}
3204
3205bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3206 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003207 bool ZeroInit = E->requiresZeroInitialization();
3208 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003209 // If we've already performed zero-initialization, we're already done.
3210 if (!Result.isUninit())
3211 return true;
3212
Richard Smith51201882011-12-30 21:15:51 +00003213 if (ZeroInit)
3214 return ZeroInitialization(E);
3215
Richard Smith61802452011-12-22 02:22:31 +00003216 const CXXRecordDecl *RD = FD->getParent();
3217 if (RD->isUnion())
3218 Result = APValue((FieldDecl*)0);
3219 else
3220 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3221 std::distance(RD->field_begin(), RD->field_end()));
3222 return true;
3223 }
3224
Richard Smith180f4792011-11-10 06:34:14 +00003225 const FunctionDecl *Definition = 0;
3226 FD->getBody(Definition);
3227
Richard Smithc1c5f272011-12-13 06:39:58 +00003228 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3229 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003230
Richard Smith610a60c2012-01-10 04:32:03 +00003231 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003232 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003233 if (const MaterializeTemporaryExpr *ME
3234 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3235 return Visit(ME->GetTemporaryExpr());
3236
Richard Smith51201882011-12-30 21:15:51 +00003237 if (ZeroInit && !ZeroInitialization(E))
3238 return false;
3239
Richard Smith180f4792011-11-10 06:34:14 +00003240 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003241 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003242 cast<CXXConstructorDecl>(Definition), Info,
3243 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003244}
3245
3246static bool EvaluateRecord(const Expr *E, const LValue &This,
3247 APValue &Result, EvalInfo &Info) {
3248 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003249 "can't evaluate expression as a record rvalue");
3250 return RecordExprEvaluator(Info, This, Result).Visit(E);
3251}
3252
3253//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003254// Temporary Evaluation
3255//
3256// Temporaries are represented in the AST as rvalues, but generally behave like
3257// lvalues. The full-object of which the temporary is a subobject is implicitly
3258// materialized so that a reference can bind to it.
3259//===----------------------------------------------------------------------===//
3260namespace {
3261class TemporaryExprEvaluator
3262 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3263public:
3264 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3265 LValueExprEvaluatorBaseTy(Info, Result) {}
3266
3267 /// Visit an expression which constructs the value of this temporary.
3268 bool VisitConstructExpr(const Expr *E) {
3269 Result.set(E, Info.CurrentCall);
3270 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3271 Result, E);
3272 }
3273
3274 bool VisitCastExpr(const CastExpr *E) {
3275 switch (E->getCastKind()) {
3276 default:
3277 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3278
3279 case CK_ConstructorConversion:
3280 return VisitConstructExpr(E->getSubExpr());
3281 }
3282 }
3283 bool VisitInitListExpr(const InitListExpr *E) {
3284 return VisitConstructExpr(E);
3285 }
3286 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3287 return VisitConstructExpr(E);
3288 }
3289 bool VisitCallExpr(const CallExpr *E) {
3290 return VisitConstructExpr(E);
3291 }
3292};
3293} // end anonymous namespace
3294
3295/// Evaluate an expression of record type as a temporary.
3296static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003297 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003298 return TemporaryExprEvaluator(Info, Result).Visit(E);
3299}
3300
3301//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003302// Vector Evaluation
3303//===----------------------------------------------------------------------===//
3304
3305namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003306 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003307 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3308 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003309 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003310
Richard Smith07fc6572011-10-22 21:10:00 +00003311 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3312 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003313
Richard Smith07fc6572011-10-22 21:10:00 +00003314 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3315 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3316 // FIXME: remove this APValue copy.
3317 Result = APValue(V.data(), V.size());
3318 return true;
3319 }
Richard Smith69c2c502011-11-04 05:33:44 +00003320 bool Success(const CCValue &V, const Expr *E) {
3321 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003322 Result = V;
3323 return true;
3324 }
Richard Smith51201882011-12-30 21:15:51 +00003325 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003326
Richard Smith07fc6572011-10-22 21:10:00 +00003327 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003328 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003329 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003330 bool VisitInitListExpr(const InitListExpr *E);
3331 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003332 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003333 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003334 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003335 };
3336} // end anonymous namespace
3337
3338static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003339 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003340 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003341}
3342
Richard Smith07fc6572011-10-22 21:10:00 +00003343bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3344 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003345 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003346
Richard Smithd62ca372011-12-06 22:44:34 +00003347 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003348 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003349
Eli Friedman46a52322011-03-25 00:43:55 +00003350 switch (E->getCastKind()) {
3351 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003352 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003353 if (SETy->isIntegerType()) {
3354 APSInt IntResult;
3355 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003356 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003357 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003358 } else if (SETy->isRealFloatingType()) {
3359 APFloat F(0.0);
3360 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003361 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003362 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003363 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003364 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003365 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003366
3367 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003368 SmallVector<APValue, 4> Elts(NElts, Val);
3369 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003370 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003371 case CK_BitCast: {
3372 // Evaluate the operand into an APInt we can extract from.
3373 llvm::APInt SValInt;
3374 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3375 return false;
3376 // Extract the elements
3377 QualType EltTy = VTy->getElementType();
3378 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3379 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3380 SmallVector<APValue, 4> Elts;
3381 if (EltTy->isRealFloatingType()) {
3382 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3383 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3384 unsigned FloatEltSize = EltSize;
3385 if (&Sem == &APFloat::x87DoubleExtended)
3386 FloatEltSize = 80;
3387 for (unsigned i = 0; i < NElts; i++) {
3388 llvm::APInt Elt;
3389 if (BigEndian)
3390 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3391 else
3392 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3393 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3394 }
3395 } else if (EltTy->isIntegerType()) {
3396 for (unsigned i = 0; i < NElts; i++) {
3397 llvm::APInt Elt;
3398 if (BigEndian)
3399 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3400 else
3401 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3402 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3403 }
3404 } else {
3405 return Error(E);
3406 }
3407 return Success(Elts, E);
3408 }
Eli Friedman46a52322011-03-25 00:43:55 +00003409 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003410 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003411 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003412}
3413
Richard Smith07fc6572011-10-22 21:10:00 +00003414bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003415VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003416 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003417 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003418 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003419
Nate Begeman59b5da62009-01-18 03:20:47 +00003420 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003421 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003422
Eli Friedman3edd5a92012-01-03 23:24:20 +00003423 // The number of initializers can be less than the number of
3424 // vector elements. For OpenCL, this can be due to nested vector
3425 // initialization. For GCC compatibility, missing trailing elements
3426 // should be initialized with zeroes.
3427 unsigned CountInits = 0, CountElts = 0;
3428 while (CountElts < NumElements) {
3429 // Handle nested vector initialization.
3430 if (CountInits < NumInits
3431 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3432 APValue v;
3433 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3434 return Error(E);
3435 unsigned vlen = v.getVectorLength();
3436 for (unsigned j = 0; j < vlen; j++)
3437 Elements.push_back(v.getVectorElt(j));
3438 CountElts += vlen;
3439 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003440 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003441 if (CountInits < NumInits) {
3442 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3443 return Error(E);
3444 } else // trailing integer zero.
3445 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3446 Elements.push_back(APValue(sInt));
3447 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003448 } else {
3449 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003450 if (CountInits < NumInits) {
3451 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3452 return Error(E);
3453 } else // trailing float zero.
3454 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3455 Elements.push_back(APValue(f));
3456 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003457 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003458 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003459 }
Richard Smith07fc6572011-10-22 21:10:00 +00003460 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003461}
3462
Richard Smith07fc6572011-10-22 21:10:00 +00003463bool
Richard Smith51201882011-12-30 21:15:51 +00003464VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003465 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003466 QualType EltTy = VT->getElementType();
3467 APValue ZeroElement;
3468 if (EltTy->isIntegerType())
3469 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3470 else
3471 ZeroElement =
3472 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3473
Chris Lattner5f9e2722011-07-23 10:55:15 +00003474 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003475 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003476}
3477
Richard Smith07fc6572011-10-22 21:10:00 +00003478bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003479 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003480 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003481}
3482
Nate Begeman59b5da62009-01-18 03:20:47 +00003483//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003484// Array Evaluation
3485//===----------------------------------------------------------------------===//
3486
3487namespace {
3488 class ArrayExprEvaluator
3489 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003490 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003491 APValue &Result;
3492 public:
3493
Richard Smith180f4792011-11-10 06:34:14 +00003494 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3495 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003496
3497 bool Success(const APValue &V, const Expr *E) {
3498 assert(V.isArray() && "Expected array type");
3499 Result = V;
3500 return true;
3501 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003502
Richard Smith51201882011-12-30 21:15:51 +00003503 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003504 const ConstantArrayType *CAT =
3505 Info.Ctx.getAsConstantArrayType(E->getType());
3506 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003507 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003508
3509 Result = APValue(APValue::UninitArray(), 0,
3510 CAT->getSize().getZExtValue());
3511 if (!Result.hasArrayFiller()) return true;
3512
Richard Smith51201882011-12-30 21:15:51 +00003513 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003514 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003515 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003516 ImplicitValueInitExpr VIE(CAT->getElementType());
3517 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3518 Subobject, &VIE);
3519 }
3520
Richard Smithcc5d4f62011-11-07 09:22:26 +00003521 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003522 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003523 };
3524} // end anonymous namespace
3525
Richard Smith180f4792011-11-10 06:34:14 +00003526static bool EvaluateArray(const Expr *E, const LValue &This,
3527 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003528 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003529 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003530}
3531
3532bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3533 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3534 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003535 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003536
Richard Smith974c5f92011-12-22 01:07:19 +00003537 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3538 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003539 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003540 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3541 LValue LV;
3542 if (!EvaluateLValue(E->getInit(0), LV, Info))
3543 return false;
3544 uint64_t NumElements = CAT->getSize().getZExtValue();
3545 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3546
3547 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003548 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003549 for (uint64_t I = 0; I < NumElements; ++I) {
3550 CCValue Char;
3551 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
Richard Smith745f5142012-01-27 01:14:48 +00003552 CAT->getElementType(), LV, Char) ||
3553 !CheckConstantExpression(Info, E->getInit(0), Char,
3554 Result.getArrayInitializedElt(I)) ||
3555 !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
Richard Smithb4e85ed2012-01-06 16:39:00 +00003556 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003557 return false;
3558 }
3559 return true;
3560 }
3561
Richard Smith745f5142012-01-27 01:14:48 +00003562 bool Success = true;
3563
Richard Smithcc5d4f62011-11-07 09:22:26 +00003564 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3565 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003566 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003567 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003568 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003569 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003570 I != End; ++I, ++Index) {
3571 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
Richard Smith745f5142012-01-27 01:14:48 +00003572 Info, Subobject, cast<Expr>(*I)) ||
3573 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3574 CAT->getElementType(), 1)) {
3575 if (!Info.keepEvaluatingAfterFailure())
3576 return false;
3577 Success = false;
3578 }
Richard Smith180f4792011-11-10 06:34:14 +00003579 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003580
Richard Smith745f5142012-01-27 01:14:48 +00003581 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003582 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003583 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3584 // but sometimes does:
3585 // struct S { constexpr S() : p(&p) {} void *p; };
3586 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003587 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith745f5142012-01-27 01:14:48 +00003588 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003589}
3590
Richard Smithe24f5fc2011-11-17 22:56:20 +00003591bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3592 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3593 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003594 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003595
Richard Smithec789162012-01-12 18:54:33 +00003596 bool HadZeroInit = !Result.isUninit();
3597 if (!HadZeroInit)
3598 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003599 if (!Result.hasArrayFiller())
3600 return true;
3601
3602 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003603
Richard Smith51201882011-12-30 21:15:51 +00003604 bool ZeroInit = E->requiresZeroInitialization();
3605 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003606 if (HadZeroInit)
3607 return true;
3608
Richard Smith51201882011-12-30 21:15:51 +00003609 if (ZeroInit) {
3610 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003611 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003612 ImplicitValueInitExpr VIE(CAT->getElementType());
3613 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3614 Subobject, &VIE);
3615 }
3616
Richard Smith61802452011-12-22 02:22:31 +00003617 const CXXRecordDecl *RD = FD->getParent();
3618 if (RD->isUnion())
3619 Result.getArrayFiller() = APValue((FieldDecl*)0);
3620 else
3621 Result.getArrayFiller() =
3622 APValue(APValue::UninitStruct(), RD->getNumBases(),
3623 std::distance(RD->field_begin(), RD->field_end()));
3624 return true;
3625 }
3626
Richard Smithe24f5fc2011-11-17 22:56:20 +00003627 const FunctionDecl *Definition = 0;
3628 FD->getBody(Definition);
3629
Richard Smithc1c5f272011-12-13 06:39:58 +00003630 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3631 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003632
3633 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3634 // but sometimes does:
3635 // struct S { constexpr S() : p(&p) {} void *p; };
3636 // S s[10];
3637 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003638 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003639
Richard Smithec789162012-01-12 18:54:33 +00003640 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003641 ImplicitValueInitExpr VIE(CAT->getElementType());
3642 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3643 &VIE))
3644 return false;
3645 }
3646
Richard Smithe24f5fc2011-11-17 22:56:20 +00003647 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003648 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003649 cast<CXXConstructorDecl>(Definition),
3650 Info, Result.getArrayFiller());
3651}
3652
Richard Smithcc5d4f62011-11-07 09:22:26 +00003653//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003654// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003655//
3656// As a GNU extension, we support casting pointers to sufficiently-wide integer
3657// types and back in constant folding. Integer values are thus represented
3658// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003659//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003660
3661namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003662class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003663 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003664 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003665public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003666 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003667 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003668
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003669 bool Success(const llvm::APSInt &SI, const Expr *E) {
3670 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003671 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003672 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003673 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003674 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003675 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003676 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003677 return true;
3678 }
3679
Daniel Dunbar131eb432009-02-19 09:06:44 +00003680 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003681 assert(E->getType()->isIntegralOrEnumerationType() &&
3682 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003683 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003684 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003685 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003686 Result.getInt().setIsUnsigned(
3687 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003688 return true;
3689 }
3690
3691 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003692 assert(E->getType()->isIntegralOrEnumerationType() &&
3693 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003694 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003695 return true;
3696 }
3697
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003698 bool Success(CharUnits Size, const Expr *E) {
3699 return Success(Size.getQuantity(), E);
3700 }
3701
Richard Smith47a1eed2011-10-29 20:57:55 +00003702 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003703 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003704 Result = V;
3705 return true;
3706 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003707 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003708 }
Mike Stump1eb44332009-09-09 15:08:12 +00003709
Richard Smith51201882011-12-30 21:15:51 +00003710 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003711
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003712 //===--------------------------------------------------------------------===//
3713 // Visitor Methods
3714 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003715
Chris Lattner4c4867e2008-07-12 00:38:25 +00003716 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003717 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003718 }
3719 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003720 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003721 }
Eli Friedman04309752009-11-24 05:28:59 +00003722
3723 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3724 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003725 if (CheckReferencedDecl(E, E->getDecl()))
3726 return true;
3727
3728 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003729 }
3730 bool VisitMemberExpr(const MemberExpr *E) {
3731 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003732 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003733 return true;
3734 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003735
3736 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003737 }
3738
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003739 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003740 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003741 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003742 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003743
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003744 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003745 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003746
Anders Carlsson3068d112008-11-16 19:01:22 +00003747 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003748 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003749 }
Mike Stump1eb44332009-09-09 15:08:12 +00003750
Richard Smithf10d9172011-10-11 21:43:33 +00003751 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003752 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003753 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003754 }
3755
Sebastian Redl64b45f72009-01-05 20:52:13 +00003756 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003757 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003758 }
3759
Francois Pichet6ad6f282010-12-07 00:08:36 +00003760 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3761 return Success(E->getValue(), E);
3762 }
3763
John Wiegley21ff2e52011-04-28 00:16:57 +00003764 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3765 return Success(E->getValue(), E);
3766 }
3767
John Wiegley55262202011-04-25 06:54:41 +00003768 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3769 return Success(E->getValue(), E);
3770 }
3771
Eli Friedman722c7172009-02-28 03:59:05 +00003772 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003773 bool VisitUnaryImag(const UnaryOperator *E);
3774
Sebastian Redl295995c2010-09-10 20:55:47 +00003775 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003776 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003777
Chris Lattnerfcee0012008-07-11 21:24:13 +00003778private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003779 CharUnits GetAlignOfExpr(const Expr *E);
3780 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003781 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003782 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003783 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003784};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003785} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003786
Richard Smithc49bd112011-10-28 17:51:58 +00003787/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3788/// produce either the integer value or a pointer.
3789///
3790/// GCC has a heinous extension which folds casts between pointer types and
3791/// pointer-sized integral types. We support this by allowing the evaluation of
3792/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3793/// Some simple arithmetic on such values is supported (they are treated much
3794/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003795static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003796 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003797 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003798 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003799}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003800
Richard Smithf48fdb02011-12-09 22:58:01 +00003801static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003802 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003803 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003804 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003805 if (!Val.isInt()) {
3806 // FIXME: It would be better to produce the diagnostic for casting
3807 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003808 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003809 return false;
3810 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003811 Result = Val.getInt();
3812 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003813}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003814
Richard Smithf48fdb02011-12-09 22:58:01 +00003815/// Check whether the given declaration can be directly converted to an integral
3816/// rvalue. If not, no diagnostic is produced; there are other things we can
3817/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003818bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003819 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003820 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003821 // Check for signedness/width mismatches between E type and ECD value.
3822 bool SameSign = (ECD->getInitVal().isSigned()
3823 == E->getType()->isSignedIntegerOrEnumerationType());
3824 bool SameWidth = (ECD->getInitVal().getBitWidth()
3825 == Info.Ctx.getIntWidth(E->getType()));
3826 if (SameSign && SameWidth)
3827 return Success(ECD->getInitVal(), E);
3828 else {
3829 // Get rid of mismatch (otherwise Success assertions will fail)
3830 // by computing a new value matching the type of E.
3831 llvm::APSInt Val = ECD->getInitVal();
3832 if (!SameSign)
3833 Val.setIsSigned(!ECD->getInitVal().isSigned());
3834 if (!SameWidth)
3835 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3836 return Success(Val, E);
3837 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003838 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003839 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003840}
3841
Chris Lattnera4d55d82008-10-06 06:40:35 +00003842/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3843/// as GCC.
3844static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3845 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003846 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003847 enum gcc_type_class {
3848 no_type_class = -1,
3849 void_type_class, integer_type_class, char_type_class,
3850 enumeral_type_class, boolean_type_class,
3851 pointer_type_class, reference_type_class, offset_type_class,
3852 real_type_class, complex_type_class,
3853 function_type_class, method_type_class,
3854 record_type_class, union_type_class,
3855 array_type_class, string_type_class,
3856 lang_type_class
3857 };
Mike Stump1eb44332009-09-09 15:08:12 +00003858
3859 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003860 // ideal, however it is what gcc does.
3861 if (E->getNumArgs() == 0)
3862 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003863
Chris Lattnera4d55d82008-10-06 06:40:35 +00003864 QualType ArgTy = E->getArg(0)->getType();
3865 if (ArgTy->isVoidType())
3866 return void_type_class;
3867 else if (ArgTy->isEnumeralType())
3868 return enumeral_type_class;
3869 else if (ArgTy->isBooleanType())
3870 return boolean_type_class;
3871 else if (ArgTy->isCharType())
3872 return string_type_class; // gcc doesn't appear to use char_type_class
3873 else if (ArgTy->isIntegerType())
3874 return integer_type_class;
3875 else if (ArgTy->isPointerType())
3876 return pointer_type_class;
3877 else if (ArgTy->isReferenceType())
3878 return reference_type_class;
3879 else if (ArgTy->isRealType())
3880 return real_type_class;
3881 else if (ArgTy->isComplexType())
3882 return complex_type_class;
3883 else if (ArgTy->isFunctionType())
3884 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003885 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003886 return record_type_class;
3887 else if (ArgTy->isUnionType())
3888 return union_type_class;
3889 else if (ArgTy->isArrayType())
3890 return array_type_class;
3891 else if (ArgTy->isUnionType())
3892 return union_type_class;
3893 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003894 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003895}
3896
Richard Smith80d4b552011-12-28 19:48:30 +00003897/// EvaluateBuiltinConstantPForLValue - Determine the result of
3898/// __builtin_constant_p when applied to the given lvalue.
3899///
3900/// An lvalue is only "constant" if it is a pointer or reference to the first
3901/// character of a string literal.
3902template<typename LValue>
3903static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3904 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3905 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3906}
3907
3908/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3909/// GCC as we can manage.
3910static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3911 QualType ArgType = Arg->getType();
3912
3913 // __builtin_constant_p always has one operand. The rules which gcc follows
3914 // are not precisely documented, but are as follows:
3915 //
3916 // - If the operand is of integral, floating, complex or enumeration type,
3917 // and can be folded to a known value of that type, it returns 1.
3918 // - If the operand and can be folded to a pointer to the first character
3919 // of a string literal (or such a pointer cast to an integral type), it
3920 // returns 1.
3921 //
3922 // Otherwise, it returns 0.
3923 //
3924 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3925 // its support for this does not currently work.
3926 if (ArgType->isIntegralOrEnumerationType()) {
3927 Expr::EvalResult Result;
3928 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3929 return false;
3930
3931 APValue &V = Result.Val;
3932 if (V.getKind() == APValue::Int)
3933 return true;
3934
3935 return EvaluateBuiltinConstantPForLValue(V);
3936 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3937 return Arg->isEvaluatable(Ctx);
3938 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3939 LValue LV;
3940 Expr::EvalStatus Status;
3941 EvalInfo Info(Ctx, Status);
3942 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3943 : EvaluatePointer(Arg, LV, Info)) &&
3944 !Status.HasSideEffects)
3945 return EvaluateBuiltinConstantPForLValue(LV);
3946 }
3947
3948 // Anything else isn't considered to be sufficiently constant.
3949 return false;
3950}
3951
John McCall42c8f872010-05-10 23:27:23 +00003952/// Retrieves the "underlying object type" of the given expression,
3953/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003954QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3955 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3956 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003957 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003958 } else if (const Expr *E = B.get<const Expr*>()) {
3959 if (isa<CompoundLiteralExpr>(E))
3960 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003961 }
3962
3963 return QualType();
3964}
3965
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003966bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003967 // TODO: Perhaps we should let LLVM lower this?
3968 LValue Base;
3969 if (!EvaluatePointer(E->getArg(0), Base, Info))
3970 return false;
3971
3972 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003973 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003974
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003975 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003976 if (T.isNull() ||
3977 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003978 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003979 T->isVariablyModifiedType() ||
3980 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003981 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00003982
3983 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3984 CharUnits Offset = Base.getLValueOffset();
3985
3986 if (!Offset.isNegative() && Offset <= Size)
3987 Size -= Offset;
3988 else
3989 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003990 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00003991}
3992
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003993bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003994 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00003995 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003996 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003997
3998 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00003999 if (TryEvaluateBuiltinObjectSize(E))
4000 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004001
Eric Christopherb2aaf512010-01-19 22:58:35 +00004002 // If evaluating the argument has side-effects we can't determine
4003 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004004 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004005 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004006 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004007 return Success(0, E);
4008 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004009
Richard Smithf48fdb02011-12-09 22:58:01 +00004010 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004011 }
4012
Chris Lattner019f4e82008-10-06 05:28:25 +00004013 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004014 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004015
Richard Smith80d4b552011-12-28 19:48:30 +00004016 case Builtin::BI__builtin_constant_p:
4017 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004018
Chris Lattner21fb98e2009-09-23 06:06:36 +00004019 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004020 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004021 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004022 return Success(Operand, E);
4023 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004024
4025 case Builtin::BI__builtin_expect:
4026 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004027
Douglas Gregor5726d402010-09-10 06:27:15 +00004028 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004029 // A call to strlen is not a constant expression.
4030 if (Info.getLangOpts().CPlusPlus0x)
4031 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4032 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4033 else
4034 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4035 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004036 case Builtin::BI__builtin_strlen:
4037 // As an extension, we support strlen() and __builtin_strlen() as constant
4038 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004039 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004040 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4041 // The string literal may have embedded null characters. Find the first
4042 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004043 StringRef Str = S->getString();
4044 StringRef::size_type Pos = Str.find(0);
4045 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004046 Str = Str.substr(0, Pos);
4047
4048 return Success(Str.size(), E);
4049 }
4050
Richard Smithf48fdb02011-12-09 22:58:01 +00004051 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004052
4053 case Builtin::BI__atomic_is_lock_free: {
4054 APSInt SizeVal;
4055 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4056 return false;
4057
4058 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4059 // of two less than the maximum inline atomic width, we know it is
4060 // lock-free. If the size isn't a power of two, or greater than the
4061 // maximum alignment where we promote atomics, we know it is not lock-free
4062 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4063 // the answer can only be determined at runtime; for example, 16-byte
4064 // atomics have lock-free implementations on some, but not all,
4065 // x86-64 processors.
4066
4067 // Check power-of-two.
4068 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4069 if (!Size.isPowerOfTwo())
4070#if 0
4071 // FIXME: Suppress this folding until the ABI for the promotion width
4072 // settles.
4073 return Success(0, E);
4074#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004075 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004076#endif
4077
4078#if 0
4079 // Check against promotion width.
4080 // FIXME: Suppress this folding until the ABI for the promotion width
4081 // settles.
4082 unsigned PromoteWidthBits =
4083 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4084 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4085 return Success(0, E);
4086#endif
4087
4088 // Check against inlining width.
4089 unsigned InlineWidthBits =
4090 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4091 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4092 return Success(1, E);
4093
Richard Smithf48fdb02011-12-09 22:58:01 +00004094 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004095 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004096 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004097}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004098
Richard Smith625b8072011-10-31 01:37:14 +00004099static bool HasSameBase(const LValue &A, const LValue &B) {
4100 if (!A.getLValueBase())
4101 return !B.getLValueBase();
4102 if (!B.getLValueBase())
4103 return false;
4104
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004105 if (A.getLValueBase().getOpaqueValue() !=
4106 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004107 const Decl *ADecl = GetLValueBaseDecl(A);
4108 if (!ADecl)
4109 return false;
4110 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004111 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004112 return false;
4113 }
4114
4115 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00004116 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00004117}
4118
Chris Lattnerb542afe2008-07-11 19:10:17 +00004119bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004120 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004121 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004122
John McCall2de56d12010-08-25 11:45:40 +00004123 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004124 VisitIgnoredValue(E->getLHS());
4125 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004126 }
4127
4128 if (E->isLogicalOp()) {
4129 // These need to be handled specially because the operands aren't
4130 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004131 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004132
Richard Smithc49bd112011-10-28 17:51:58 +00004133 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004134 // We were able to evaluate the LHS, see if we can get away with not
4135 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004136 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004137 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004138
Richard Smithc49bd112011-10-28 17:51:58 +00004139 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004140 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004141 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004142 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004143 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004144 }
4145 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004146 // FIXME: If both evaluations fail, we should produce the diagnostic from
4147 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4148 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004149 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004150 // We can't evaluate the LHS; however, sometimes the result
4151 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004152 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004153 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004154 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004155 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004156
4157 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004158 }
4159 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004160 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004161
Eli Friedmana6afa762008-11-13 06:09:17 +00004162 return false;
4163 }
4164
Anders Carlsson286f85e2008-11-16 07:17:21 +00004165 QualType LHSTy = E->getLHS()->getType();
4166 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004167
4168 if (LHSTy->isAnyComplexType()) {
4169 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004170 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004171
Richard Smith745f5142012-01-27 01:14:48 +00004172 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4173 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004174 return false;
4175
Richard Smith745f5142012-01-27 01:14:48 +00004176 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004177 return false;
4178
4179 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004180 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004181 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004182 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004183 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4184
John McCall2de56d12010-08-25 11:45:40 +00004185 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004186 return Success((CR_r == APFloat::cmpEqual &&
4187 CR_i == APFloat::cmpEqual), E);
4188 else {
John McCall2de56d12010-08-25 11:45:40 +00004189 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004190 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004191 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004192 CR_r == APFloat::cmpLessThan ||
4193 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004194 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004195 CR_i == APFloat::cmpLessThan ||
4196 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004197 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004198 } else {
John McCall2de56d12010-08-25 11:45:40 +00004199 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004200 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4201 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4202 else {
John McCall2de56d12010-08-25 11:45:40 +00004203 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004204 "Invalid compex comparison.");
4205 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4206 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4207 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004208 }
4209 }
Mike Stump1eb44332009-09-09 15:08:12 +00004210
Anders Carlsson286f85e2008-11-16 07:17:21 +00004211 if (LHSTy->isRealFloatingType() &&
4212 RHSTy->isRealFloatingType()) {
4213 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004214
Richard Smith745f5142012-01-27 01:14:48 +00004215 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4216 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004217 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004218
Richard Smith745f5142012-01-27 01:14:48 +00004219 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004220 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004221
Anders Carlsson286f85e2008-11-16 07:17:21 +00004222 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004223
Anders Carlsson286f85e2008-11-16 07:17:21 +00004224 switch (E->getOpcode()) {
4225 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004226 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004227 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004228 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004229 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004230 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004231 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004232 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004233 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004234 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004235 E);
John McCall2de56d12010-08-25 11:45:40 +00004236 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004237 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004238 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004239 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004240 || CR == APFloat::cmpLessThan
4241 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004242 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004243 }
Mike Stump1eb44332009-09-09 15:08:12 +00004244
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004245 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004246 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004247 LValue LHSValue, RHSValue;
4248
4249 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4250 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004251 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004252
Richard Smith745f5142012-01-27 01:14:48 +00004253 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004254 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004255
Richard Smith625b8072011-10-31 01:37:14 +00004256 // Reject differing bases from the normal codepath; we special-case
4257 // comparisons to null.
4258 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004259 if (E->getOpcode() == BO_Sub) {
4260 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004261 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4262 return false;
4263 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4264 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4265 if (!LHSExpr || !RHSExpr)
4266 return false;
4267 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4268 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4269 if (!LHSAddrExpr || !RHSAddrExpr)
4270 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004271 // Make sure both labels come from the same function.
4272 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4273 RHSAddrExpr->getLabel()->getDeclContext())
4274 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004275 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4276 return true;
4277 }
Richard Smith9e36b532011-10-31 05:11:32 +00004278 // Inequalities and subtractions between unrelated pointers have
4279 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004280 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004281 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004282 // A constant address may compare equal to the address of a symbol.
4283 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004284 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004285 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4286 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004287 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004288 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00004289 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00004290 // distinct. However, we do know that the address of a literal will be
4291 // non-null.
4292 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4293 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004294 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004295 // We can't tell whether weak symbols will end up pointing to the same
4296 // object.
4297 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004298 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004299 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004300 // (Note that clang defaults to -fmerge-all-constants, which can
4301 // lead to inconsistent results for comparisons involving the address
4302 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004303 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004304 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004305
Richard Smithcc5d4f62011-11-07 09:22:26 +00004306 // FIXME: Implement the C++11 restrictions:
4307 // - Pointer subtractions must be on elements of the same array.
4308 // - Pointer comparisons must be between members with the same access.
4309
John McCall2de56d12010-08-25 11:45:40 +00004310 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00004311 QualType Type = E->getLHS()->getType();
4312 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004313
Richard Smith180f4792011-11-10 06:34:14 +00004314 CharUnits ElementSize;
4315 if (!HandleSizeof(Info, ElementType, ElementSize))
4316 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004317
Richard Smith180f4792011-11-10 06:34:14 +00004318 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00004319 RHSValue.getLValueOffset();
4320 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004321 }
Richard Smith625b8072011-10-31 01:37:14 +00004322
4323 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4324 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4325 switch (E->getOpcode()) {
4326 default: llvm_unreachable("missing comparison operator");
4327 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4328 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4329 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4330 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4331 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4332 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004333 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004334 }
4335 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004336 if (!LHSTy->isIntegralOrEnumerationType() ||
4337 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004338 // We can't continue from here for non-integral types.
4339 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004340 }
4341
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004342 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004343 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004344
4345 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4346 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004347 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004348
Richard Smith745f5142012-01-27 01:14:48 +00004349 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004350 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004351
Richard Smith47a1eed2011-10-29 20:57:55 +00004352 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004353
4354 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004355 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004356 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4357 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004358 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004359 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004360 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004361 LHSVal.getLValueOffset() -= AdditionalOffset;
4362 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004363 return true;
4364 }
4365
4366 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004367 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004368 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004369 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4370 LHSVal.getInt().getZExtValue());
4371 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004372 return true;
4373 }
4374
Eli Friedman65639282012-01-04 23:13:47 +00004375 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4376 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004377 if (!LHSVal.getLValueOffset().isZero() ||
4378 !RHSVal.getLValueOffset().isZero())
4379 return false;
4380 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4381 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4382 if (!LHSExpr || !RHSExpr)
4383 return false;
4384 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4385 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4386 if (!LHSAddrExpr || !RHSAddrExpr)
4387 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004388 // Make sure both labels come from the same function.
4389 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4390 RHSAddrExpr->getLabel()->getDeclContext())
4391 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004392 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4393 return true;
4394 }
4395
Eli Friedman42edd0d2009-03-24 01:14:50 +00004396 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004397 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004398 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004399
Richard Smithc49bd112011-10-28 17:51:58 +00004400 APSInt &LHS = LHSVal.getInt();
4401 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004402
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004403 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004404 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004405 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004406 case BO_Mul: return Success(LHS * RHS, E);
4407 case BO_Add: return Success(LHS + RHS, E);
4408 case BO_Sub: return Success(LHS - RHS, E);
4409 case BO_And: return Success(LHS & RHS, E);
4410 case BO_Xor: return Success(LHS ^ RHS, E);
4411 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004412 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00004413 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004414 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004415 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004416 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004417 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004418 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004419 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004420 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00004421 // During constant-folding, a negative shift is an opposite shift.
4422 if (RHS.isSigned() && RHS.isNegative()) {
4423 RHS = -RHS;
4424 goto shift_right;
4425 }
4426
4427 shift_left:
4428 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00004429 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4430 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004431 }
John McCall2de56d12010-08-25 11:45:40 +00004432 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00004433 // During constant-folding, a negative shift is an opposite shift.
4434 if (RHS.isSigned() && RHS.isNegative()) {
4435 RHS = -RHS;
4436 goto shift_left;
4437 }
4438
4439 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00004440 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00004441 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4442 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004443 }
Mike Stump1eb44332009-09-09 15:08:12 +00004444
Richard Smithc49bd112011-10-28 17:51:58 +00004445 case BO_LT: return Success(LHS < RHS, E);
4446 case BO_GT: return Success(LHS > RHS, E);
4447 case BO_LE: return Success(LHS <= RHS, E);
4448 case BO_GE: return Success(LHS >= RHS, E);
4449 case BO_EQ: return Success(LHS == RHS, E);
4450 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004451 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004452}
4453
Ken Dyck8b752f12010-01-27 17:10:57 +00004454CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004455 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4456 // the result is the size of the referenced type."
4457 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4458 // result shall be the alignment of the referenced type."
4459 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4460 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004461
4462 // __alignof is defined to return the preferred alignment.
4463 return Info.Ctx.toCharUnitsFromBits(
4464 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004465}
4466
Ken Dyck8b752f12010-01-27 17:10:57 +00004467CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004468 E = E->IgnoreParens();
4469
4470 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004471 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004472 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004473 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4474 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004475
Chris Lattneraf707ab2009-01-24 21:53:27 +00004476 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004477 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4478 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004479
Chris Lattnere9feb472009-01-24 21:09:06 +00004480 return GetAlignOfType(E->getType());
4481}
4482
4483
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004484/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4485/// a result as the expression's type.
4486bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4487 const UnaryExprOrTypeTraitExpr *E) {
4488 switch(E->getKind()) {
4489 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004490 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004491 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004492 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004493 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004494 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004495
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004496 case UETT_VecStep: {
4497 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004498
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004499 if (Ty->isVectorType()) {
4500 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004501
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004502 // The vec_step built-in functions that take a 3-component
4503 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4504 if (n == 3)
4505 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004506
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004507 return Success(n, E);
4508 } else
4509 return Success(1, E);
4510 }
4511
4512 case UETT_SizeOf: {
4513 QualType SrcTy = E->getTypeOfArgument();
4514 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4515 // the result is the size of the referenced type."
4516 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4517 // result shall be the alignment of the referenced type."
4518 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4519 SrcTy = Ref->getPointeeType();
4520
Richard Smith180f4792011-11-10 06:34:14 +00004521 CharUnits Sizeof;
4522 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004523 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004524 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004525 }
4526 }
4527
4528 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004529}
4530
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004531bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004532 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004533 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004534 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004535 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004536 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004537 for (unsigned i = 0; i != n; ++i) {
4538 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4539 switch (ON.getKind()) {
4540 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004541 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004542 APSInt IdxResult;
4543 if (!EvaluateInteger(Idx, IdxResult, Info))
4544 return false;
4545 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4546 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004547 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004548 CurrentType = AT->getElementType();
4549 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4550 Result += IdxResult.getSExtValue() * ElementSize;
4551 break;
4552 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004553
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004554 case OffsetOfExpr::OffsetOfNode::Field: {
4555 FieldDecl *MemberDecl = ON.getField();
4556 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004557 if (!RT)
4558 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004559 RecordDecl *RD = RT->getDecl();
4560 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004561 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004562 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004563 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004564 CurrentType = MemberDecl->getType().getNonReferenceType();
4565 break;
4566 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004567
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004568 case OffsetOfExpr::OffsetOfNode::Identifier:
4569 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004570
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004571 case OffsetOfExpr::OffsetOfNode::Base: {
4572 CXXBaseSpecifier *BaseSpec = ON.getBase();
4573 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004574 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004575
4576 // Find the layout of the class whose base we are looking into.
4577 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004578 if (!RT)
4579 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004580 RecordDecl *RD = RT->getDecl();
4581 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4582
4583 // Find the base class itself.
4584 CurrentType = BaseSpec->getType();
4585 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4586 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004587 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004588
4589 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004590 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004591 break;
4592 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004593 }
4594 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004595 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004596}
4597
Chris Lattnerb542afe2008-07-11 19:10:17 +00004598bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004599 switch (E->getOpcode()) {
4600 default:
4601 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4602 // See C99 6.6p3.
4603 return Error(E);
4604 case UO_Extension:
4605 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4606 // If so, we could clear the diagnostic ID.
4607 return Visit(E->getSubExpr());
4608 case UO_Plus:
4609 // The result is just the value.
4610 return Visit(E->getSubExpr());
4611 case UO_Minus: {
4612 if (!Visit(E->getSubExpr()))
4613 return false;
4614 if (!Result.isInt()) return Error(E);
4615 return Success(-Result.getInt(), E);
4616 }
4617 case UO_Not: {
4618 if (!Visit(E->getSubExpr()))
4619 return false;
4620 if (!Result.isInt()) return Error(E);
4621 return Success(~Result.getInt(), E);
4622 }
4623 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004624 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004625 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004626 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004627 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004628 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004629 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004630}
Mike Stump1eb44332009-09-09 15:08:12 +00004631
Chris Lattner732b2232008-07-12 01:15:53 +00004632/// HandleCast - This is used to evaluate implicit or explicit casts where the
4633/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004634bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4635 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004636 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004637 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004638
Eli Friedman46a52322011-03-25 00:43:55 +00004639 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004640 case CK_BaseToDerived:
4641 case CK_DerivedToBase:
4642 case CK_UncheckedDerivedToBase:
4643 case CK_Dynamic:
4644 case CK_ToUnion:
4645 case CK_ArrayToPointerDecay:
4646 case CK_FunctionToPointerDecay:
4647 case CK_NullToPointer:
4648 case CK_NullToMemberPointer:
4649 case CK_BaseToDerivedMemberPointer:
4650 case CK_DerivedToBaseMemberPointer:
4651 case CK_ConstructorConversion:
4652 case CK_IntegralToPointer:
4653 case CK_ToVoid:
4654 case CK_VectorSplat:
4655 case CK_IntegralToFloating:
4656 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004657 case CK_CPointerToObjCPointerCast:
4658 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004659 case CK_AnyPointerToBlockPointerCast:
4660 case CK_ObjCObjectLValueCast:
4661 case CK_FloatingRealToComplex:
4662 case CK_FloatingComplexToReal:
4663 case CK_FloatingComplexCast:
4664 case CK_FloatingComplexToIntegralComplex:
4665 case CK_IntegralRealToComplex:
4666 case CK_IntegralComplexCast:
4667 case CK_IntegralComplexToFloatingComplex:
4668 llvm_unreachable("invalid cast kind for integral value");
4669
Eli Friedmane50c2972011-03-25 19:07:11 +00004670 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004671 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004672 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00004673 case CK_ARCProduceObject:
4674 case CK_ARCConsumeObject:
4675 case CK_ARCReclaimReturnedObject:
4676 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004677 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004678
Richard Smith7d580a42012-01-17 21:17:26 +00004679 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00004680 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00004681 case CK_AtomicToNonAtomic:
4682 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00004683 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004684 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004685
4686 case CK_MemberPointerToBoolean:
4687 case CK_PointerToBoolean:
4688 case CK_IntegralToBoolean:
4689 case CK_FloatingToBoolean:
4690 case CK_FloatingComplexToBoolean:
4691 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004692 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004693 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004694 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004695 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004696 }
4697
Eli Friedman46a52322011-03-25 00:43:55 +00004698 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004699 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004700 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004701
Eli Friedmanbe265702009-02-20 01:15:07 +00004702 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00004703 // Allow casts of address-of-label differences if they are no-ops
4704 // or narrowing. (The narrowing case isn't actually guaranteed to
4705 // be constant-evaluatable except in some narrow cases which are hard
4706 // to detect here. We let it through on the assumption the user knows
4707 // what they are doing.)
4708 if (Result.isAddrLabelDiff())
4709 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00004710 // Only allow casts of lvalues if they are lossless.
4711 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4712 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004713
Richard Smithf72fccf2012-01-30 22:27:01 +00004714 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
4715 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004716 }
Mike Stump1eb44332009-09-09 15:08:12 +00004717
Eli Friedman46a52322011-03-25 00:43:55 +00004718 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004719 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4720
John McCallefdb83e2010-05-07 21:00:08 +00004721 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004722 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004723 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004724
Daniel Dunbardd211642009-02-19 22:24:01 +00004725 if (LV.getLValueBase()) {
4726 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00004727 // FIXME: Allow a larger integer size than the pointer size, and allow
4728 // narrowing back down to pointer width in subsequent integral casts.
4729 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00004730 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004731 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004732
Richard Smithb755a9d2011-11-16 07:18:12 +00004733 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004734 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004735 return true;
4736 }
4737
Ken Dycka7305832010-01-15 12:37:54 +00004738 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4739 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00004740 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004741 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004742
Eli Friedman46a52322011-03-25 00:43:55 +00004743 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004744 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004745 if (!EvaluateComplex(SubExpr, C, Info))
4746 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004747 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004748 }
Eli Friedman2217c872009-02-22 11:46:18 +00004749
Eli Friedman46a52322011-03-25 00:43:55 +00004750 case CK_FloatingToIntegral: {
4751 APFloat F(0.0);
4752 if (!EvaluateFloat(SubExpr, F, Info))
4753 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004754
Richard Smithc1c5f272011-12-13 06:39:58 +00004755 APSInt Value;
4756 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4757 return false;
4758 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004759 }
4760 }
Mike Stump1eb44332009-09-09 15:08:12 +00004761
Eli Friedman46a52322011-03-25 00:43:55 +00004762 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004763}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004764
Eli Friedman722c7172009-02-28 03:59:05 +00004765bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4766 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004767 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004768 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4769 return false;
4770 if (!LV.isComplexInt())
4771 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004772 return Success(LV.getComplexIntReal(), E);
4773 }
4774
4775 return Visit(E->getSubExpr());
4776}
4777
Eli Friedman664a1042009-02-27 04:45:43 +00004778bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004779 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004780 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004781 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4782 return false;
4783 if (!LV.isComplexInt())
4784 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004785 return Success(LV.getComplexIntImag(), E);
4786 }
4787
Richard Smith8327fad2011-10-24 18:44:57 +00004788 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004789 return Success(0, E);
4790}
4791
Douglas Gregoree8aff02011-01-04 17:33:58 +00004792bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4793 return Success(E->getPackLength(), E);
4794}
4795
Sebastian Redl295995c2010-09-10 20:55:47 +00004796bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4797 return Success(E->getValue(), E);
4798}
4799
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004800//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004801// Float Evaluation
4802//===----------------------------------------------------------------------===//
4803
4804namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004805class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004806 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004807 APFloat &Result;
4808public:
4809 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004810 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004811
Richard Smith47a1eed2011-10-29 20:57:55 +00004812 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004813 Result = V.getFloat();
4814 return true;
4815 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004816
Richard Smith51201882011-12-30 21:15:51 +00004817 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00004818 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4819 return true;
4820 }
4821
Chris Lattner019f4e82008-10-06 05:28:25 +00004822 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004823
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004824 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004825 bool VisitBinaryOperator(const BinaryOperator *E);
4826 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004827 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004828
John McCallabd3a852010-05-07 22:08:54 +00004829 bool VisitUnaryReal(const UnaryOperator *E);
4830 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004831
Richard Smith51201882011-12-30 21:15:51 +00004832 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004833};
4834} // end anonymous namespace
4835
4836static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004837 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004838 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004839}
4840
Jay Foad4ba2a172011-01-12 09:06:06 +00004841static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004842 QualType ResultTy,
4843 const Expr *Arg,
4844 bool SNaN,
4845 llvm::APFloat &Result) {
4846 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4847 if (!S) return false;
4848
4849 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4850
4851 llvm::APInt fill;
4852
4853 // Treat empty strings as if they were zero.
4854 if (S->getString().empty())
4855 fill = llvm::APInt(32, 0);
4856 else if (S->getString().getAsInteger(0, fill))
4857 return false;
4858
4859 if (SNaN)
4860 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4861 else
4862 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4863 return true;
4864}
4865
Chris Lattner019f4e82008-10-06 05:28:25 +00004866bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004867 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004868 default:
4869 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4870
Chris Lattner019f4e82008-10-06 05:28:25 +00004871 case Builtin::BI__builtin_huge_val:
4872 case Builtin::BI__builtin_huge_valf:
4873 case Builtin::BI__builtin_huge_vall:
4874 case Builtin::BI__builtin_inf:
4875 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004876 case Builtin::BI__builtin_infl: {
4877 const llvm::fltSemantics &Sem =
4878 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004879 Result = llvm::APFloat::getInf(Sem);
4880 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004881 }
Mike Stump1eb44332009-09-09 15:08:12 +00004882
John McCalldb7b72a2010-02-28 13:00:19 +00004883 case Builtin::BI__builtin_nans:
4884 case Builtin::BI__builtin_nansf:
4885 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004886 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4887 true, Result))
4888 return Error(E);
4889 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004890
Chris Lattner9e621712008-10-06 06:31:58 +00004891 case Builtin::BI__builtin_nan:
4892 case Builtin::BI__builtin_nanf:
4893 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004894 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004895 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004896 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4897 false, Result))
4898 return Error(E);
4899 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004900
4901 case Builtin::BI__builtin_fabs:
4902 case Builtin::BI__builtin_fabsf:
4903 case Builtin::BI__builtin_fabsl:
4904 if (!EvaluateFloat(E->getArg(0), Result, Info))
4905 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004906
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004907 if (Result.isNegative())
4908 Result.changeSign();
4909 return true;
4910
Mike Stump1eb44332009-09-09 15:08:12 +00004911 case Builtin::BI__builtin_copysign:
4912 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004913 case Builtin::BI__builtin_copysignl: {
4914 APFloat RHS(0.);
4915 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4916 !EvaluateFloat(E->getArg(1), RHS, Info))
4917 return false;
4918 Result.copySign(RHS);
4919 return true;
4920 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004921 }
4922}
4923
John McCallabd3a852010-05-07 22:08:54 +00004924bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004925 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4926 ComplexValue CV;
4927 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4928 return false;
4929 Result = CV.FloatReal;
4930 return true;
4931 }
4932
4933 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00004934}
4935
4936bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004937 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4938 ComplexValue CV;
4939 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4940 return false;
4941 Result = CV.FloatImag;
4942 return true;
4943 }
4944
Richard Smith8327fad2011-10-24 18:44:57 +00004945 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00004946 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4947 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00004948 return true;
4949}
4950
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004951bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004952 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004953 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004954 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004955 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00004956 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004957 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4958 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004959 Result.changeSign();
4960 return true;
4961 }
4962}
Chris Lattner019f4e82008-10-06 05:28:25 +00004963
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004964bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004965 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4966 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00004967
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004968 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00004969 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
4970 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004971 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004972 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004973 return false;
4974
4975 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004976 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004977 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004978 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4979 return true;
John McCall2de56d12010-08-25 11:45:40 +00004980 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004981 Result.add(RHS, APFloat::rmNearestTiesToEven);
4982 return true;
John McCall2de56d12010-08-25 11:45:40 +00004983 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004984 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4985 return true;
John McCall2de56d12010-08-25 11:45:40 +00004986 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004987 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4988 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004989 }
4990}
4991
4992bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4993 Result = E->getValue();
4994 return true;
4995}
4996
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004997bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4998 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00004999
Eli Friedman2a523ee2011-03-25 00:54:52 +00005000 switch (E->getCastKind()) {
5001 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005002 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005003
5004 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005005 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005006 return EvaluateInteger(SubExpr, IntResult, Info) &&
5007 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5008 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005009 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005010
5011 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005012 if (!Visit(SubExpr))
5013 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005014 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5015 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005016 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005017
Eli Friedman2a523ee2011-03-25 00:54:52 +00005018 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005019 ComplexValue V;
5020 if (!EvaluateComplex(SubExpr, V, Info))
5021 return false;
5022 Result = V.getComplexFloatReal();
5023 return true;
5024 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005025 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005026}
5027
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005028//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005029// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005030//===----------------------------------------------------------------------===//
5031
5032namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005033class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005034 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005035 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005036
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005037public:
John McCallf4cf1a12010-05-07 17:22:02 +00005038 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005039 : ExprEvaluatorBaseTy(info), Result(Result) {}
5040
Richard Smith47a1eed2011-10-29 20:57:55 +00005041 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005042 Result.setFrom(V);
5043 return true;
5044 }
Mike Stump1eb44332009-09-09 15:08:12 +00005045
Eli Friedman7ead5c72012-01-10 04:58:17 +00005046 bool ZeroInitialization(const Expr *E);
5047
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005048 //===--------------------------------------------------------------------===//
5049 // Visitor Methods
5050 //===--------------------------------------------------------------------===//
5051
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005052 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005053 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005054 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005055 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005056 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005057};
5058} // end anonymous namespace
5059
John McCallf4cf1a12010-05-07 17:22:02 +00005060static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5061 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005062 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005063 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005064}
5065
Eli Friedman7ead5c72012-01-10 04:58:17 +00005066bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005067 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005068 if (ElemTy->isRealFloatingType()) {
5069 Result.makeComplexFloat();
5070 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5071 Result.FloatReal = Zero;
5072 Result.FloatImag = Zero;
5073 } else {
5074 Result.makeComplexInt();
5075 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5076 Result.IntReal = Zero;
5077 Result.IntImag = Zero;
5078 }
5079 return true;
5080}
5081
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005082bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5083 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005084
5085 if (SubExpr->getType()->isRealFloatingType()) {
5086 Result.makeComplexFloat();
5087 APFloat &Imag = Result.FloatImag;
5088 if (!EvaluateFloat(SubExpr, Imag, Info))
5089 return false;
5090
5091 Result.FloatReal = APFloat(Imag.getSemantics());
5092 return true;
5093 } else {
5094 assert(SubExpr->getType()->isIntegerType() &&
5095 "Unexpected imaginary literal.");
5096
5097 Result.makeComplexInt();
5098 APSInt &Imag = Result.IntImag;
5099 if (!EvaluateInteger(SubExpr, Imag, Info))
5100 return false;
5101
5102 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5103 return true;
5104 }
5105}
5106
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005107bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005108
John McCall8786da72010-12-14 17:51:41 +00005109 switch (E->getCastKind()) {
5110 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005111 case CK_BaseToDerived:
5112 case CK_DerivedToBase:
5113 case CK_UncheckedDerivedToBase:
5114 case CK_Dynamic:
5115 case CK_ToUnion:
5116 case CK_ArrayToPointerDecay:
5117 case CK_FunctionToPointerDecay:
5118 case CK_NullToPointer:
5119 case CK_NullToMemberPointer:
5120 case CK_BaseToDerivedMemberPointer:
5121 case CK_DerivedToBaseMemberPointer:
5122 case CK_MemberPointerToBoolean:
5123 case CK_ConstructorConversion:
5124 case CK_IntegralToPointer:
5125 case CK_PointerToIntegral:
5126 case CK_PointerToBoolean:
5127 case CK_ToVoid:
5128 case CK_VectorSplat:
5129 case CK_IntegralCast:
5130 case CK_IntegralToBoolean:
5131 case CK_IntegralToFloating:
5132 case CK_FloatingToIntegral:
5133 case CK_FloatingToBoolean:
5134 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005135 case CK_CPointerToObjCPointerCast:
5136 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005137 case CK_AnyPointerToBlockPointerCast:
5138 case CK_ObjCObjectLValueCast:
5139 case CK_FloatingComplexToReal:
5140 case CK_FloatingComplexToBoolean:
5141 case CK_IntegralComplexToReal:
5142 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005143 case CK_ARCProduceObject:
5144 case CK_ARCConsumeObject:
5145 case CK_ARCReclaimReturnedObject:
5146 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005147 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005148
John McCall8786da72010-12-14 17:51:41 +00005149 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005150 case CK_AtomicToNonAtomic:
5151 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005152 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005153 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005154
5155 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005156 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005157 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005158 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005159
5160 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005161 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005162 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005163 return false;
5164
John McCall8786da72010-12-14 17:51:41 +00005165 Result.makeComplexFloat();
5166 Result.FloatImag = APFloat(Real.getSemantics());
5167 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005168 }
5169
John McCall8786da72010-12-14 17:51:41 +00005170 case CK_FloatingComplexCast: {
5171 if (!Visit(E->getSubExpr()))
5172 return false;
5173
5174 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5175 QualType From
5176 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5177
Richard Smithc1c5f272011-12-13 06:39:58 +00005178 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5179 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005180 }
5181
5182 case CK_FloatingComplexToIntegralComplex: {
5183 if (!Visit(E->getSubExpr()))
5184 return false;
5185
5186 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5187 QualType From
5188 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5189 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005190 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5191 To, Result.IntReal) &&
5192 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5193 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005194 }
5195
5196 case CK_IntegralRealToComplex: {
5197 APSInt &Real = Result.IntReal;
5198 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5199 return false;
5200
5201 Result.makeComplexInt();
5202 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5203 return true;
5204 }
5205
5206 case CK_IntegralComplexCast: {
5207 if (!Visit(E->getSubExpr()))
5208 return false;
5209
5210 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5211 QualType From
5212 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5213
Richard Smithf72fccf2012-01-30 22:27:01 +00005214 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5215 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005216 return true;
5217 }
5218
5219 case CK_IntegralComplexToFloatingComplex: {
5220 if (!Visit(E->getSubExpr()))
5221 return false;
5222
5223 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5224 QualType From
5225 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5226 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005227 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5228 To, Result.FloatReal) &&
5229 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5230 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005231 }
5232 }
5233
5234 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005235}
5236
John McCallf4cf1a12010-05-07 17:22:02 +00005237bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005238 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005239 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5240
Richard Smith745f5142012-01-27 01:14:48 +00005241 bool LHSOK = Visit(E->getLHS());
5242 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005243 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005244
John McCallf4cf1a12010-05-07 17:22:02 +00005245 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005246 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005247 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005248
Daniel Dunbar3f279872009-01-29 01:32:56 +00005249 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5250 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005251 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005252 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005253 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005254 if (Result.isComplexFloat()) {
5255 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5256 APFloat::rmNearestTiesToEven);
5257 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5258 APFloat::rmNearestTiesToEven);
5259 } else {
5260 Result.getComplexIntReal() += RHS.getComplexIntReal();
5261 Result.getComplexIntImag() += RHS.getComplexIntImag();
5262 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005263 break;
John McCall2de56d12010-08-25 11:45:40 +00005264 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005265 if (Result.isComplexFloat()) {
5266 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5267 APFloat::rmNearestTiesToEven);
5268 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5269 APFloat::rmNearestTiesToEven);
5270 } else {
5271 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5272 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5273 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005274 break;
John McCall2de56d12010-08-25 11:45:40 +00005275 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005276 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005277 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005278 APFloat &LHS_r = LHS.getComplexFloatReal();
5279 APFloat &LHS_i = LHS.getComplexFloatImag();
5280 APFloat &RHS_r = RHS.getComplexFloatReal();
5281 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005282
Daniel Dunbar3f279872009-01-29 01:32:56 +00005283 APFloat Tmp = LHS_r;
5284 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5285 Result.getComplexFloatReal() = Tmp;
5286 Tmp = LHS_i;
5287 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5288 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5289
5290 Tmp = LHS_r;
5291 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5292 Result.getComplexFloatImag() = Tmp;
5293 Tmp = LHS_i;
5294 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5295 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5296 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005297 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005298 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005299 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5300 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005301 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005302 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5303 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5304 }
5305 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005306 case BO_Div:
5307 if (Result.isComplexFloat()) {
5308 ComplexValue LHS = Result;
5309 APFloat &LHS_r = LHS.getComplexFloatReal();
5310 APFloat &LHS_i = LHS.getComplexFloatImag();
5311 APFloat &RHS_r = RHS.getComplexFloatReal();
5312 APFloat &RHS_i = RHS.getComplexFloatImag();
5313 APFloat &Res_r = Result.getComplexFloatReal();
5314 APFloat &Res_i = Result.getComplexFloatImag();
5315
5316 APFloat Den = RHS_r;
5317 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5318 APFloat Tmp = RHS_i;
5319 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5320 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5321
5322 Res_r = LHS_r;
5323 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5324 Tmp = LHS_i;
5325 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5326 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5327 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5328
5329 Res_i = LHS_i;
5330 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5331 Tmp = LHS_r;
5332 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5333 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5334 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5335 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005336 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5337 return Error(E, diag::note_expr_divide_by_zero);
5338
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005339 ComplexValue LHS = Result;
5340 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5341 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5342 Result.getComplexIntReal() =
5343 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5344 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5345 Result.getComplexIntImag() =
5346 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5347 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5348 }
5349 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005350 }
5351
John McCallf4cf1a12010-05-07 17:22:02 +00005352 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005353}
5354
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005355bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5356 // Get the operand value into 'Result'.
5357 if (!Visit(E->getSubExpr()))
5358 return false;
5359
5360 switch (E->getOpcode()) {
5361 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005362 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005363 case UO_Extension:
5364 return true;
5365 case UO_Plus:
5366 // The result is always just the subexpr.
5367 return true;
5368 case UO_Minus:
5369 if (Result.isComplexFloat()) {
5370 Result.getComplexFloatReal().changeSign();
5371 Result.getComplexFloatImag().changeSign();
5372 }
5373 else {
5374 Result.getComplexIntReal() = -Result.getComplexIntReal();
5375 Result.getComplexIntImag() = -Result.getComplexIntImag();
5376 }
5377 return true;
5378 case UO_Not:
5379 if (Result.isComplexFloat())
5380 Result.getComplexFloatImag().changeSign();
5381 else
5382 Result.getComplexIntImag() = -Result.getComplexIntImag();
5383 return true;
5384 }
5385}
5386
Eli Friedman7ead5c72012-01-10 04:58:17 +00005387bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5388 if (E->getNumInits() == 2) {
5389 if (E->getType()->isComplexType()) {
5390 Result.makeComplexFloat();
5391 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5392 return false;
5393 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5394 return false;
5395 } else {
5396 Result.makeComplexInt();
5397 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5398 return false;
5399 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5400 return false;
5401 }
5402 return true;
5403 }
5404 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5405}
5406
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005407//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005408// Void expression evaluation, primarily for a cast to void on the LHS of a
5409// comma operator
5410//===----------------------------------------------------------------------===//
5411
5412namespace {
5413class VoidExprEvaluator
5414 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5415public:
5416 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5417
5418 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005419
5420 bool VisitCastExpr(const CastExpr *E) {
5421 switch (E->getCastKind()) {
5422 default:
5423 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5424 case CK_ToVoid:
5425 VisitIgnoredValue(E->getSubExpr());
5426 return true;
5427 }
5428 }
5429};
5430} // end anonymous namespace
5431
5432static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5433 assert(E->isRValue() && E->getType()->isVoidType());
5434 return VoidExprEvaluator(Info).Visit(E);
5435}
5436
5437//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005438// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005439//===----------------------------------------------------------------------===//
5440
Richard Smith47a1eed2011-10-29 20:57:55 +00005441static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005442 // In C, function designators are not lvalues, but we evaluate them as if they
5443 // are.
5444 if (E->isGLValue() || E->getType()->isFunctionType()) {
5445 LValue LV;
5446 if (!EvaluateLValue(E, LV, Info))
5447 return false;
5448 LV.moveInto(Result);
5449 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005450 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005451 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005452 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005453 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005454 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005455 } else if (E->getType()->hasPointerRepresentation()) {
5456 LValue LV;
5457 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005458 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005459 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005460 } else if (E->getType()->isRealFloatingType()) {
5461 llvm::APFloat F(0.0);
5462 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005463 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005464 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005465 } else if (E->getType()->isAnyComplexType()) {
5466 ComplexValue C;
5467 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005468 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005469 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005470 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005471 MemberPtr P;
5472 if (!EvaluateMemberPointer(E, P, Info))
5473 return false;
5474 P.moveInto(Result);
5475 return true;
Richard Smith51201882011-12-30 21:15:51 +00005476 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005477 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005478 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005479 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005480 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005481 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005482 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005483 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005484 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005485 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5486 return false;
5487 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005488 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005489 if (Info.getLangOpts().CPlusPlus0x)
5490 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5491 << E->getType();
5492 else
5493 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005494 if (!EvaluateVoid(E, Info))
5495 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005496 } else if (Info.getLangOpts().CPlusPlus0x) {
5497 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5498 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005499 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005500 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005501 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005502 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005503
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005504 return true;
5505}
5506
Richard Smith69c2c502011-11-04 05:33:44 +00005507/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5508/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5509/// since later initializers for an object can indirectly refer to subobjects
5510/// which were initialized earlier.
5511static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005512 const LValue &This, const Expr *E,
5513 CheckConstantExpressionKind CCEK) {
Richard Smith51201882011-12-30 21:15:51 +00005514 if (!CheckLiteralType(Info, E))
5515 return false;
5516
5517 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005518 // Evaluate arrays and record types in-place, so that later initializers can
5519 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005520 if (E->getType()->isArrayType())
5521 return EvaluateArray(E, This, Result, Info);
5522 else if (E->getType()->isRecordType())
5523 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005524 }
5525
5526 // For any other type, in-place evaluation is unimportant.
5527 CCValue CoreConstResult;
5528 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005529 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005530}
5531
Richard Smithf48fdb02011-12-09 22:58:01 +00005532/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5533/// lvalue-to-rvalue cast if it is an lvalue.
5534static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005535 if (!CheckLiteralType(Info, E))
5536 return false;
5537
Richard Smithf48fdb02011-12-09 22:58:01 +00005538 CCValue Value;
5539 if (!::Evaluate(Value, Info, E))
5540 return false;
5541
5542 if (E->isGLValue()) {
5543 LValue LV;
5544 LV.setFrom(Value);
5545 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5546 return false;
5547 }
5548
5549 // Check this core constant expression is a constant expression, and if so,
5550 // convert it to one.
5551 return CheckConstantExpression(Info, E, Value, Result);
5552}
Richard Smithc49bd112011-10-28 17:51:58 +00005553
Richard Smith51f47082011-10-29 00:50:52 +00005554/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005555/// any crazy technique (that has nothing to do with language standards) that
5556/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005557/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5558/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005559bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005560 // Fast-path evaluations of integer literals, since we sometimes see files
5561 // containing vast quantities of these.
5562 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5563 Result.Val = APValue(APSInt(L->getValue(),
5564 L->getType()->isUnsignedIntegerType()));
5565 return true;
5566 }
5567
Richard Smith2d6a5672012-01-14 04:30:29 +00005568 // FIXME: Evaluating values of large array and record types can cause
5569 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005570 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5571 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005572 return false;
5573
Richard Smithf48fdb02011-12-09 22:58:01 +00005574 EvalInfo Info(Ctx, Result);
5575 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005576}
5577
Jay Foad4ba2a172011-01-12 09:06:06 +00005578bool Expr::EvaluateAsBooleanCondition(bool &Result,
5579 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005580 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005581 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005582 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5583 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005584 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005585}
5586
Richard Smith80d4b552011-12-28 19:48:30 +00005587bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5588 SideEffectsKind AllowSideEffects) const {
5589 if (!getType()->isIntegralOrEnumerationType())
5590 return false;
5591
Richard Smithc49bd112011-10-28 17:51:58 +00005592 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005593 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5594 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005595 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005596
Richard Smithc49bd112011-10-28 17:51:58 +00005597 Result = ExprResult.Val.getInt();
5598 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005599}
5600
Jay Foad4ba2a172011-01-12 09:06:06 +00005601bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005602 EvalInfo Info(Ctx, Result);
5603
John McCallefdb83e2010-05-07 21:00:08 +00005604 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005605 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005606 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5607 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005608}
5609
Richard Smith099e7f62011-12-19 06:19:21 +00005610bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5611 const VarDecl *VD,
5612 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005613 // FIXME: Evaluating initializers for large array and record types can cause
5614 // performance problems. Only do so in C++11 for now.
5615 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5616 !Ctx.getLangOptions().CPlusPlus0x)
5617 return false;
5618
Richard Smith099e7f62011-12-19 06:19:21 +00005619 Expr::EvalStatus EStatus;
5620 EStatus.Diag = &Notes;
5621
5622 EvalInfo InitInfo(Ctx, EStatus);
5623 InitInfo.setEvaluatingDecl(VD, Value);
5624
Richard Smith51201882011-12-30 21:15:51 +00005625 if (!CheckLiteralType(InitInfo, this))
5626 return false;
5627
Richard Smith099e7f62011-12-19 06:19:21 +00005628 LValue LVal;
5629 LVal.set(VD);
5630
Richard Smith51201882011-12-30 21:15:51 +00005631 // C++11 [basic.start.init]p2:
5632 // Variables with static storage duration or thread storage duration shall be
5633 // zero-initialized before any other initialization takes place.
5634 // This behavior is not present in C.
5635 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5636 !VD->getType()->isReferenceType()) {
5637 ImplicitValueInitExpr VIE(VD->getType());
5638 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5639 return false;
5640 }
5641
Richard Smith099e7f62011-12-19 06:19:21 +00005642 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5643 !EStatus.HasSideEffects;
5644}
5645
Richard Smith51f47082011-10-29 00:50:52 +00005646/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5647/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005648bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005649 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005650 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005651}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005652
Jay Foad4ba2a172011-01-12 09:06:06 +00005653bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005654 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005655}
5656
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005657APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005658 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005659 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005660 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005661 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005662 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005663
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005664 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005665}
John McCalld905f5a2010-05-07 05:32:02 +00005666
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005667 bool Expr::EvalResult::isGlobalLValue() const {
5668 assert(Val.isLValue());
5669 return IsGlobalLValue(Val.getLValueBase());
5670 }
5671
5672
John McCalld905f5a2010-05-07 05:32:02 +00005673/// isIntegerConstantExpr - this recursive routine will test if an expression is
5674/// an integer constant expression.
5675
5676/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5677/// comma, etc
5678///
5679/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5680/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5681/// cast+dereference.
5682
5683// CheckICE - This function does the fundamental ICE checking: the returned
5684// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5685// Note that to reduce code duplication, this helper does no evaluation
5686// itself; the caller checks whether the expression is evaluatable, and
5687// in the rare cases where CheckICE actually cares about the evaluated
5688// value, it calls into Evalute.
5689//
5690// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005691// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005692// 1: This expression is not an ICE, but if it isn't evaluated, it's
5693// a legal subexpression for an ICE. This return value is used to handle
5694// the comma operator in C99 mode.
5695// 2: This expression is not an ICE, and is not a legal subexpression for one.
5696
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005697namespace {
5698
John McCalld905f5a2010-05-07 05:32:02 +00005699struct ICEDiag {
5700 unsigned Val;
5701 SourceLocation Loc;
5702
5703 public:
5704 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5705 ICEDiag() : Val(0) {}
5706};
5707
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005708}
5709
5710static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00005711
5712static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5713 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005714 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005715 !EVResult.Val.isInt()) {
5716 return ICEDiag(2, E->getLocStart());
5717 }
5718 return NoDiag();
5719}
5720
5721static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5722 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005723 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00005724 return ICEDiag(2, E->getLocStart());
5725 }
5726
5727 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00005728#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00005729#define STMT(Node, Base) case Expr::Node##Class:
5730#define EXPR(Node, Base)
5731#include "clang/AST/StmtNodes.inc"
5732 case Expr::PredefinedExprClass:
5733 case Expr::FloatingLiteralClass:
5734 case Expr::ImaginaryLiteralClass:
5735 case Expr::StringLiteralClass:
5736 case Expr::ArraySubscriptExprClass:
5737 case Expr::MemberExprClass:
5738 case Expr::CompoundAssignOperatorClass:
5739 case Expr::CompoundLiteralExprClass:
5740 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005741 case Expr::DesignatedInitExprClass:
5742 case Expr::ImplicitValueInitExprClass:
5743 case Expr::ParenListExprClass:
5744 case Expr::VAArgExprClass:
5745 case Expr::AddrLabelExprClass:
5746 case Expr::StmtExprClass:
5747 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00005748 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005749 case Expr::CXXDynamicCastExprClass:
5750 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00005751 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005752 case Expr::CXXNullPtrLiteralExprClass:
5753 case Expr::CXXThisExprClass:
5754 case Expr::CXXThrowExprClass:
5755 case Expr::CXXNewExprClass:
5756 case Expr::CXXDeleteExprClass:
5757 case Expr::CXXPseudoDestructorExprClass:
5758 case Expr::UnresolvedLookupExprClass:
5759 case Expr::DependentScopeDeclRefExprClass:
5760 case Expr::CXXConstructExprClass:
5761 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005762 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005763 case Expr::CXXTemporaryObjectExprClass:
5764 case Expr::CXXUnresolvedConstructExprClass:
5765 case Expr::CXXDependentScopeMemberExprClass:
5766 case Expr::UnresolvedMemberExprClass:
5767 case Expr::ObjCStringLiteralClass:
5768 case Expr::ObjCEncodeExprClass:
5769 case Expr::ObjCMessageExprClass:
5770 case Expr::ObjCSelectorExprClass:
5771 case Expr::ObjCProtocolExprClass:
5772 case Expr::ObjCIvarRefExprClass:
5773 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005774 case Expr::ObjCIsaExprClass:
5775 case Expr::ShuffleVectorExprClass:
5776 case Expr::BlockExprClass:
5777 case Expr::BlockDeclRefExprClass:
5778 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005779 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005780 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005781 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005782 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005783 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005784 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005785 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005786 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005787 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005788 return ICEDiag(2, E->getLocStart());
5789
Douglas Gregoree8aff02011-01-04 17:33:58 +00005790 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005791 case Expr::GNUNullExprClass:
5792 // GCC considers the GNU __null value to be an integral constant expression.
5793 return NoDiag();
5794
John McCall91a57552011-07-15 05:09:51 +00005795 case Expr::SubstNonTypeTemplateParmExprClass:
5796 return
5797 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5798
John McCalld905f5a2010-05-07 05:32:02 +00005799 case Expr::ParenExprClass:
5800 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005801 case Expr::GenericSelectionExprClass:
5802 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005803 case Expr::IntegerLiteralClass:
5804 case Expr::CharacterLiteralClass:
5805 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005806 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005807 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005808 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005809 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005810 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005811 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005812 return NoDiag();
5813 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005814 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005815 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5816 // constant expressions, but they can never be ICEs because an ICE cannot
5817 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005818 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005819 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005820 return CheckEvalInICE(E, Ctx);
5821 return ICEDiag(2, E->getLocStart());
5822 }
5823 case Expr::DeclRefExprClass:
5824 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5825 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005826 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005827 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5828
5829 // Parameter variables are never constants. Without this check,
5830 // getAnyInitializer() can find a default argument, which leads
5831 // to chaos.
5832 if (isa<ParmVarDecl>(D))
5833 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5834
5835 // C++ 7.1.5.1p2
5836 // A variable of non-volatile const-qualified integral or enumeration
5837 // type initialized by an ICE can be used in ICEs.
5838 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005839 if (!Dcl->getType()->isIntegralOrEnumerationType())
5840 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5841
Richard Smith099e7f62011-12-19 06:19:21 +00005842 const VarDecl *VD;
5843 // Look for a declaration of this variable that has an initializer, and
5844 // check whether it is an ICE.
5845 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5846 return NoDiag();
5847 else
5848 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00005849 }
5850 }
5851 return ICEDiag(2, E->getLocStart());
5852 case Expr::UnaryOperatorClass: {
5853 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5854 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005855 case UO_PostInc:
5856 case UO_PostDec:
5857 case UO_PreInc:
5858 case UO_PreDec:
5859 case UO_AddrOf:
5860 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005861 // C99 6.6/3 allows increment and decrement within unevaluated
5862 // subexpressions of constant expressions, but they can never be ICEs
5863 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005864 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005865 case UO_Extension:
5866 case UO_LNot:
5867 case UO_Plus:
5868 case UO_Minus:
5869 case UO_Not:
5870 case UO_Real:
5871 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005872 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005873 }
5874
5875 // OffsetOf falls through here.
5876 }
5877 case Expr::OffsetOfExprClass: {
5878 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005879 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005880 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005881 // compliance: we should warn earlier for offsetof expressions with
5882 // array subscripts that aren't ICEs, and if the array subscripts
5883 // are ICEs, the value of the offsetof must be an integer constant.
5884 return CheckEvalInICE(E, Ctx);
5885 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005886 case Expr::UnaryExprOrTypeTraitExprClass: {
5887 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5888 if ((Exp->getKind() == UETT_SizeOf) &&
5889 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005890 return ICEDiag(2, E->getLocStart());
5891 return NoDiag();
5892 }
5893 case Expr::BinaryOperatorClass: {
5894 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5895 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005896 case BO_PtrMemD:
5897 case BO_PtrMemI:
5898 case BO_Assign:
5899 case BO_MulAssign:
5900 case BO_DivAssign:
5901 case BO_RemAssign:
5902 case BO_AddAssign:
5903 case BO_SubAssign:
5904 case BO_ShlAssign:
5905 case BO_ShrAssign:
5906 case BO_AndAssign:
5907 case BO_XorAssign:
5908 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00005909 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5910 // constant expressions, but they can never be ICEs because an ICE cannot
5911 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005912 return ICEDiag(2, E->getLocStart());
5913
John McCall2de56d12010-08-25 11:45:40 +00005914 case BO_Mul:
5915 case BO_Div:
5916 case BO_Rem:
5917 case BO_Add:
5918 case BO_Sub:
5919 case BO_Shl:
5920 case BO_Shr:
5921 case BO_LT:
5922 case BO_GT:
5923 case BO_LE:
5924 case BO_GE:
5925 case BO_EQ:
5926 case BO_NE:
5927 case BO_And:
5928 case BO_Xor:
5929 case BO_Or:
5930 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00005931 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5932 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00005933 if (Exp->getOpcode() == BO_Div ||
5934 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00005935 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00005936 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00005937 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005938 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005939 if (REval == 0)
5940 return ICEDiag(1, E->getLocStart());
5941 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005942 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005943 if (LEval.isMinSignedValue())
5944 return ICEDiag(1, E->getLocStart());
5945 }
5946 }
5947 }
John McCall2de56d12010-08-25 11:45:40 +00005948 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00005949 if (Ctx.getLangOptions().C99) {
5950 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5951 // if it isn't evaluated.
5952 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5953 return ICEDiag(1, E->getLocStart());
5954 } else {
5955 // In both C89 and C++, commas in ICEs are illegal.
5956 return ICEDiag(2, E->getLocStart());
5957 }
5958 }
5959 if (LHSResult.Val >= RHSResult.Val)
5960 return LHSResult;
5961 return RHSResult;
5962 }
John McCall2de56d12010-08-25 11:45:40 +00005963 case BO_LAnd:
5964 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00005965 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5966 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5967 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5968 // Rare case where the RHS has a comma "side-effect"; we need
5969 // to actually check the condition to see whether the side
5970 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00005971 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005972 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00005973 return RHSResult;
5974 return NoDiag();
5975 }
5976
5977 if (LHSResult.Val >= RHSResult.Val)
5978 return LHSResult;
5979 return RHSResult;
5980 }
5981 }
5982 }
5983 case Expr::ImplicitCastExprClass:
5984 case Expr::CStyleCastExprClass:
5985 case Expr::CXXFunctionalCastExprClass:
5986 case Expr::CXXStaticCastExprClass:
5987 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00005988 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005989 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00005990 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00005991 if (isa<ExplicitCastExpr>(E)) {
5992 if (const FloatingLiteral *FL
5993 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5994 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5995 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5996 APSInt IgnoredVal(DestWidth, !DestSigned);
5997 bool Ignored;
5998 // If the value does not fit in the destination type, the behavior is
5999 // undefined, so we are not required to treat it as a constant
6000 // expression.
6001 if (FL->getValue().convertToInteger(IgnoredVal,
6002 llvm::APFloat::rmTowardZero,
6003 &Ignored) & APFloat::opInvalidOp)
6004 return ICEDiag(2, E->getLocStart());
6005 return NoDiag();
6006 }
6007 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006008 switch (cast<CastExpr>(E)->getCastKind()) {
6009 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006010 case CK_AtomicToNonAtomic:
6011 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006012 case CK_NoOp:
6013 case CK_IntegralToBoolean:
6014 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006015 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006016 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006017 return ICEDiag(2, E->getLocStart());
6018 }
John McCalld905f5a2010-05-07 05:32:02 +00006019 }
John McCall56ca35d2011-02-17 10:25:35 +00006020 case Expr::BinaryConditionalOperatorClass: {
6021 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6022 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6023 if (CommonResult.Val == 2) return CommonResult;
6024 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6025 if (FalseResult.Val == 2) return FalseResult;
6026 if (CommonResult.Val == 1) return CommonResult;
6027 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006028 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006029 return FalseResult;
6030 }
John McCalld905f5a2010-05-07 05:32:02 +00006031 case Expr::ConditionalOperatorClass: {
6032 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6033 // If the condition (ignoring parens) is a __builtin_constant_p call,
6034 // then only the true side is actually considered in an integer constant
6035 // expression, and it is fully evaluated. This is an important GNU
6036 // extension. See GCC PR38377 for discussion.
6037 if (const CallExpr *CallCE
6038 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006039 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6040 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006041 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006042 if (CondResult.Val == 2)
6043 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006044
Richard Smithf48fdb02011-12-09 22:58:01 +00006045 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6046 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006047
John McCalld905f5a2010-05-07 05:32:02 +00006048 if (TrueResult.Val == 2)
6049 return TrueResult;
6050 if (FalseResult.Val == 2)
6051 return FalseResult;
6052 if (CondResult.Val == 1)
6053 return CondResult;
6054 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6055 return NoDiag();
6056 // Rare case where the diagnostics depend on which side is evaluated
6057 // Note that if we get here, CondResult is 0, and at least one of
6058 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006059 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006060 return FalseResult;
6061 }
6062 return TrueResult;
6063 }
6064 case Expr::CXXDefaultArgExprClass:
6065 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6066 case Expr::ChooseExprClass: {
6067 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6068 }
6069 }
6070
David Blaikie30263482012-01-20 21:50:17 +00006071 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006072}
6073
Richard Smithf48fdb02011-12-09 22:58:01 +00006074/// Evaluate an expression as a C++11 integral constant expression.
6075static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6076 const Expr *E,
6077 llvm::APSInt *Value,
6078 SourceLocation *Loc) {
6079 if (!E->getType()->isIntegralOrEnumerationType()) {
6080 if (Loc) *Loc = E->getExprLoc();
6081 return false;
6082 }
6083
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006084 APValue Result;
6085 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006086 return false;
6087
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006088 assert(Result.isInt() && "pointer cast to int is not an ICE");
6089 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006090 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006091}
6092
Richard Smithdd1f29b2011-12-12 09:28:41 +00006093bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006094 if (Ctx.getLangOptions().CPlusPlus0x)
6095 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6096
John McCalld905f5a2010-05-07 05:32:02 +00006097 ICEDiag d = CheckICE(this, Ctx);
6098 if (d.Val != 0) {
6099 if (Loc) *Loc = d.Loc;
6100 return false;
6101 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006102 return true;
6103}
6104
6105bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6106 SourceLocation *Loc, bool isEvaluated) const {
6107 if (Ctx.getLangOptions().CPlusPlus0x)
6108 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6109
6110 if (!isIntegerConstantExpr(Ctx, Loc))
6111 return false;
6112 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006113 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006114 return true;
6115}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006116
6117bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6118 SourceLocation *Loc) const {
6119 // We support this checking in C++98 mode in order to diagnose compatibility
6120 // issues.
6121 assert(Ctx.getLangOptions().CPlusPlus);
6122
6123 Expr::EvalStatus Status;
6124 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6125 Status.Diag = &Diags;
6126 EvalInfo Info(Ctx, Status);
6127
6128 APValue Scratch;
6129 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6130
6131 if (!Diags.empty()) {
6132 IsConstExpr = false;
6133 if (Loc) *Loc = Diags[0].first;
6134 } else if (!IsConstExpr) {
6135 // FIXME: This shouldn't happen.
6136 if (Loc) *Loc = getExprLoc();
6137 }
6138
6139 return IsConstExpr;
6140}
Richard Smith745f5142012-01-27 01:14:48 +00006141
6142bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6143 llvm::SmallVectorImpl<
6144 PartialDiagnosticAt> &Diags) {
6145 // FIXME: It would be useful to check constexpr function templates, but at the
6146 // moment the constant expression evaluator cannot cope with the non-rigorous
6147 // ASTs which we build for dependent expressions.
6148 if (FD->isDependentContext())
6149 return true;
6150
6151 Expr::EvalStatus Status;
6152 Status.Diag = &Diags;
6153
6154 EvalInfo Info(FD->getASTContext(), Status);
6155 Info.CheckingPotentialConstantExpression = true;
6156
6157 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6158 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6159
6160 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6161 // is a temporary being used as the 'this' pointer.
6162 LValue This;
6163 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6164 This.set(&VIE, Info.CurrentCall);
6165
6166 APValue Scratch;
6167 ArrayRef<const Expr*> Args;
6168
6169 SourceLocation Loc = FD->getLocation();
6170
6171 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
6172 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6173 } else
6174 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6175 Args, FD->getBody(), Info, Scratch);
6176
6177 return Diags.empty();
6178}