blob: a45aea974c798d410944209fa38ab5311d3612f2 [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>
Richard Smith7b48a292012-02-01 05:53:12 +000048#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000049
Anders Carlssonc44eec62008-07-03 04:20:39 +000050using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000051using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000052using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000053
Chris Lattner87eae5e2008-07-11 22:52:41 +000054/// EvalInfo - This is a private struct used by the evaluator to capture
55/// information about a subexpression as it is folded. It retains information
56/// about the AST context, but also maintains information about the folded
57/// expression.
58///
59/// If an expression could be evaluated, it is still possible it is not a C
60/// "integer constant expression" or constant expression. If not, this struct
61/// captures information about how and why not.
62///
63/// One bit of information passed *into* the request for constant folding
64/// indicates whether the subexpression is "evaluated" or not according to C
65/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
66/// evaluate the expression regardless of what the RHS is, but C only allows
67/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000068namespace {
Richard Smith180f4792011-11-10 06:34:14 +000069 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000070 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000071 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000072
Richard Smith1bf9a9e2011-11-12 22:28:03 +000073 QualType getType(APValue::LValueBase B) {
74 if (!B) return QualType();
75 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
76 return D->getType();
77 return B.get<const Expr*>()->getType();
78 }
79
Richard Smith180f4792011-11-10 06:34:14 +000080 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000081 /// field or base class.
82 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000083 APValue::BaseOrMemberType Value;
84 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000085 return Value;
86 }
87
88 /// Get an LValue path entry, which is known to not be an array index, as a
89 /// field declaration.
90 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
91 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000092 }
93 /// Get an LValue path entry, which is known to not be an array index, as a
94 /// base class declaration.
95 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000096 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000097 }
98 /// Determine whether this LValue path entry for a base class names a virtual
99 /// base class.
100 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +0000101 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +0000102 }
103
Richard Smithb4e85ed2012-01-06 16:39:00 +0000104 /// Find the path length and type of the most-derived subobject in the given
105 /// path, and find the size of the containing array, if any.
106 static
107 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
108 ArrayRef<APValue::LValuePathEntry> Path,
109 uint64_t &ArraySize, QualType &Type) {
110 unsigned MostDerivedLength = 0;
111 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000112 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000113 if (Type->isArrayType()) {
114 const ConstantArrayType *CAT =
115 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
116 Type = CAT->getElementType();
117 ArraySize = CAT->getSize().getZExtValue();
118 MostDerivedLength = I + 1;
119 } else if (const FieldDecl *FD = getAsField(Path[I])) {
120 Type = FD->getType();
121 ArraySize = 0;
122 MostDerivedLength = I + 1;
123 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000124 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000125 ArraySize = 0;
126 }
Richard Smith9a17a682011-11-07 05:07:52 +0000127 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000128 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000129 }
130
Richard Smithb4e85ed2012-01-06 16:39:00 +0000131 // The order of this enum is important for diagnostics.
132 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000133 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
134 CSK_This
Richard Smithb4e85ed2012-01-06 16:39:00 +0000135 };
136
Richard Smith0a3bdb62011-11-04 02:25:55 +0000137 /// A path from a glvalue to a subobject of that glvalue.
138 struct SubobjectDesignator {
139 /// True if the subobject was named in a manner not supported by C++11. Such
140 /// lvalues can still be folded, but they are not core constant expressions
141 /// and we cannot perform lvalue-to-rvalue conversions on them.
142 bool Invalid : 1;
143
Richard Smithb4e85ed2012-01-06 16:39:00 +0000144 /// Is this a pointer one past the end of an object?
145 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000146
Richard Smithb4e85ed2012-01-06 16:39:00 +0000147 /// The length of the path to the most-derived object of which this is a
148 /// subobject.
149 unsigned MostDerivedPathLength : 30;
150
151 /// The size of the array of which the most-derived object is an element, or
152 /// 0 if the most-derived object is not an array element.
153 uint64_t MostDerivedArraySize;
154
155 /// The type of the most derived object referred to by this address.
156 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000157
Richard Smith9a17a682011-11-07 05:07:52 +0000158 typedef APValue::LValuePathEntry PathEntry;
159
Richard Smith0a3bdb62011-11-04 02:25:55 +0000160 /// The entries on the path from the glvalue to the designated subobject.
161 SmallVector<PathEntry, 8> Entries;
162
Richard Smithb4e85ed2012-01-06 16:39:00 +0000163 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000164
Richard Smithb4e85ed2012-01-06 16:39:00 +0000165 explicit SubobjectDesignator(QualType T)
166 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
167 MostDerivedArraySize(0), MostDerivedType(T) {}
168
169 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
170 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
171 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000172 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000173 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000174 ArrayRef<PathEntry> VEntries = V.getLValuePath();
175 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
176 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000177 MostDerivedPathLength =
178 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
179 V.getLValuePath(), MostDerivedArraySize,
180 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000181 }
182 }
183
Richard Smith0a3bdb62011-11-04 02:25:55 +0000184 void setInvalid() {
185 Invalid = true;
186 Entries.clear();
187 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000188
189 /// Determine whether this is a one-past-the-end pointer.
190 bool isOnePastTheEnd() const {
191 if (IsOnePastTheEnd)
192 return true;
193 if (MostDerivedArraySize &&
194 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
195 return true;
196 return false;
197 }
198
199 /// Check that this refers to a valid subobject.
200 bool isValidSubobject() const {
201 if (Invalid)
202 return false;
203 return !isOnePastTheEnd();
204 }
205 /// Check that this refers to a valid subobject, and if not, produce a
206 /// relevant diagnostic and set the designator as invalid.
207 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
208
209 /// Update this designator to refer to the first element within this array.
210 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000211 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000212 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000213 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000214
215 // This is a most-derived object.
216 MostDerivedType = CAT->getElementType();
217 MostDerivedArraySize = CAT->getSize().getZExtValue();
218 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000219 }
220 /// Update this designator to refer to the given base or member of this
221 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000222 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000223 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000224 APValue::BaseOrMemberType Value(D, Virtual);
225 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000226 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000227
228 // If this isn't a base class, it's a new most-derived object.
229 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
230 MostDerivedType = FD->getType();
231 MostDerivedArraySize = 0;
232 MostDerivedPathLength = Entries.size();
233 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000234 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000235 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000236 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000237 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000238 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000239 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000240 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000241 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
242 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
243 setInvalid();
244 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000245 return;
246 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000247 // [expr.add]p4: For the purposes of these operators, a pointer to a
248 // nonarray object behaves the same as a pointer to the first element of
249 // an array of length one with the type of the object as its element type.
250 if (IsOnePastTheEnd && N == (uint64_t)-1)
251 IsOnePastTheEnd = false;
252 else if (!IsOnePastTheEnd && N == 1)
253 IsOnePastTheEnd = true;
254 else if (N != 0) {
255 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000256 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000257 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000258 }
259 };
260
Richard Smith47a1eed2011-10-29 20:57:55 +0000261 /// A core constant value. This can be the value of any constant expression,
262 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000263 ///
264 /// For an LValue, the base and offset are stored in the APValue subobject,
265 /// but the other information is stored in the SubobjectDesignator. For all
266 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000267 class CCValue : public APValue {
268 typedef llvm::APSInt APSInt;
269 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000270 /// If the value is a reference or pointer into a parameter or temporary,
271 /// this is the corresponding call stack frame.
272 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000273 /// If the value is a reference or pointer, this is a description of how the
274 /// subobject was specified.
275 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000276 public:
Richard Smith177dce72011-11-01 16:57:24 +0000277 struct GlobalValue {};
278
Richard Smith47a1eed2011-10-29 20:57:55 +0000279 CCValue() {}
280 explicit CCValue(const APSInt &I) : APValue(I) {}
281 explicit CCValue(const APFloat &F) : APValue(F) {}
282 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
283 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
284 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000285 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000286 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000287 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000288 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000289 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
290 APValue(V), CallFrame(0), Designator(Ctx, V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000291 CCValue(const ValueDecl *D, bool IsDerivedMember,
292 ArrayRef<const CXXRecordDecl*> Path) :
293 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000294 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
295 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000296
Richard Smith177dce72011-11-01 16:57:24 +0000297 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000298 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000299 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000300 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000301 SubobjectDesignator &getLValueDesignator() {
302 assert(getKind() == LValue);
303 return Designator;
304 }
305 const SubobjectDesignator &getLValueDesignator() const {
306 return const_cast<CCValue*>(this)->getLValueDesignator();
307 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000308 };
309
Richard Smithd0dccea2011-10-28 22:34:42 +0000310 /// A stack frame in the constexpr call stack.
311 struct CallStackFrame {
312 EvalInfo &Info;
313
314 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000315 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000316
Richard Smith08d6e032011-12-16 19:06:07 +0000317 /// CallLoc - The location of the call expression for this call.
318 SourceLocation CallLoc;
319
320 /// Callee - The function which was called.
321 const FunctionDecl *Callee;
322
Richard Smith180f4792011-11-10 06:34:14 +0000323 /// This - The binding for the this pointer in this call, if any.
324 const LValue *This;
325
Richard Smithd0dccea2011-10-28 22:34:42 +0000326 /// ParmBindings - Parameter bindings for this function call, indexed by
327 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000328 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000329
Richard Smithbd552ef2011-10-31 05:52:43 +0000330 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
331 typedef MapTy::const_iterator temp_iterator;
332 /// Temporaries - Temporary lvalues materialized within this stack frame.
333 MapTy Temporaries;
334
Richard Smith08d6e032011-12-16 19:06:07 +0000335 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
336 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000337 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000338 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000339 };
340
Richard Smithdd1f29b2011-12-12 09:28:41 +0000341 /// A partial diagnostic which we might know in advance that we are not going
342 /// to emit.
343 class OptionalDiagnostic {
344 PartialDiagnostic *Diag;
345
346 public:
347 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
348
349 template<typename T>
350 OptionalDiagnostic &operator<<(const T &v) {
351 if (Diag)
352 *Diag << v;
353 return *this;
354 }
Richard Smith789f9b62012-01-31 04:08:20 +0000355
356 OptionalDiagnostic &operator<<(const APSInt &I) {
357 if (Diag) {
358 llvm::SmallVector<char, 32> Buffer;
359 I.toString(Buffer);
360 *Diag << StringRef(Buffer.data(), Buffer.size());
361 }
362 return *this;
363 }
364
365 OptionalDiagnostic &operator<<(const APFloat &F) {
366 if (Diag) {
367 llvm::SmallVector<char, 32> Buffer;
368 F.toString(Buffer);
369 *Diag << StringRef(Buffer.data(), Buffer.size());
370 }
371 return *this;
372 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000373 };
374
Richard Smithbd552ef2011-10-31 05:52:43 +0000375 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000376 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000377
378 /// EvalStatus - Contains information about the evaluation.
379 Expr::EvalStatus &EvalStatus;
380
381 /// CurrentCall - The top of the constexpr call stack.
382 CallStackFrame *CurrentCall;
383
Richard Smithbd552ef2011-10-31 05:52:43 +0000384 /// CallStackDepth - The number of calls in the call stack right now.
385 unsigned CallStackDepth;
386
387 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
388 /// OpaqueValues - Values used as the common expression in a
389 /// BinaryConditionalOperator.
390 MapTy OpaqueValues;
391
392 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000393 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000394 CallStackFrame BottomFrame;
395
Richard Smith180f4792011-11-10 06:34:14 +0000396 /// EvaluatingDecl - This is the declaration whose initializer is being
397 /// evaluated, if any.
398 const VarDecl *EvaluatingDecl;
399
400 /// EvaluatingDeclValue - This is the value being constructed for the
401 /// declaration whose initializer is being evaluated, if any.
402 APValue *EvaluatingDeclValue;
403
Richard Smithc1c5f272011-12-13 06:39:58 +0000404 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
405 /// notes attached to it will also be stored, otherwise they will not be.
406 bool HasActiveDiagnostic;
407
Richard Smith745f5142012-01-27 01:14:48 +0000408 /// CheckingPotentialConstantExpression - Are we checking whether the
409 /// expression is a potential constant expression? If so, some diagnostics
410 /// are suppressed.
411 bool CheckingPotentialConstantExpression;
412
Richard Smithbd552ef2011-10-31 05:52:43 +0000413
414 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000415 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000416 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000417 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
418 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000419
Richard Smithbd552ef2011-10-31 05:52:43 +0000420 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
421 MapTy::const_iterator i = OpaqueValues.find(e);
422 if (i == OpaqueValues.end()) return 0;
423 return &i->second;
424 }
425
Richard Smith180f4792011-11-10 06:34:14 +0000426 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
427 EvaluatingDecl = VD;
428 EvaluatingDeclValue = &Value;
429 }
430
Richard Smithc18c4232011-11-21 19:36:32 +0000431 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
432
Richard Smithc1c5f272011-12-13 06:39:58 +0000433 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000434 // Don't perform any constexpr calls (other than the call we're checking)
435 // when checking a potential constant expression.
436 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
437 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +0000438 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
439 return true;
440 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
441 << getLangOpts().ConstexprCallDepth;
442 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000443 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000444
Richard Smithc1c5f272011-12-13 06:39:58 +0000445 private:
446 /// Add a diagnostic to the diagnostics list.
447 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
448 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
449 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
450 return EvalStatus.Diag->back().second;
451 }
452
Richard Smith08d6e032011-12-16 19:06:07 +0000453 /// Add notes containing a call stack to the current point of evaluation.
454 void addCallStack(unsigned Limit);
455
Richard Smithc1c5f272011-12-13 06:39:58 +0000456 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000457 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000458 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
459 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000460 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000461 // If we have a prior diagnostic, it will be noting that the expression
462 // isn't a constant expression. This diagnostic is more important.
463 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000464 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000465 unsigned CallStackNotes = CallStackDepth - 1;
466 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
467 if (Limit)
468 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000469 if (CheckingPotentialConstantExpression)
470 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000471
Richard Smithc1c5f272011-12-13 06:39:58 +0000472 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000473 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000474 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
475 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000476 if (!CheckingPotentialConstantExpression)
477 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000478 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000479 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000480 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000481 return OptionalDiagnostic();
482 }
483
484 /// Diagnose that the evaluation does not produce a C++11 core constant
485 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000486 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
487 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000488 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000489 // Don't override a previous diagnostic.
490 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
491 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000492 return Diag(Loc, DiagId, ExtraNotes);
493 }
494
495 /// Add a note to a prior diagnostic.
496 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
497 if (!HasActiveDiagnostic)
498 return OptionalDiagnostic();
499 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000500 }
Richard Smith099e7f62011-12-19 06:19:21 +0000501
502 /// Add a stack of notes to a prior diagnostic.
503 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
504 if (HasActiveDiagnostic) {
505 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
506 Diags.begin(), Diags.end());
507 }
508 }
Richard Smith745f5142012-01-27 01:14:48 +0000509
510 /// Should we continue evaluation as much as possible after encountering a
511 /// construct which can't be folded?
512 bool keepEvaluatingAfterFailure() {
513 return CheckingPotentialConstantExpression && EvalStatus.Diag->empty();
514 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000515 };
Richard Smithf15fda02012-02-02 01:16:57 +0000516
517 /// Object used to treat all foldable expressions as constant expressions.
518 struct FoldConstant {
519 bool Enabled;
520
521 explicit FoldConstant(EvalInfo &Info)
522 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
523 !Info.EvalStatus.HasSideEffects) {
524 }
525 // Treat the value we've computed since this object was created as constant.
526 void Fold(EvalInfo &Info) {
527 if (Enabled && !Info.EvalStatus.Diag->empty() &&
528 !Info.EvalStatus.HasSideEffects)
529 Info.EvalStatus.Diag->clear();
530 }
531 };
Richard Smith08d6e032011-12-16 19:06:07 +0000532}
Richard Smithbd552ef2011-10-31 05:52:43 +0000533
Richard Smithb4e85ed2012-01-06 16:39:00 +0000534bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
535 CheckSubobjectKind CSK) {
536 if (Invalid)
537 return false;
538 if (isOnePastTheEnd()) {
539 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
540 << CSK;
541 setInvalid();
542 return false;
543 }
544 return true;
545}
546
547void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
548 const Expr *E, uint64_t N) {
549 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
550 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
551 << static_cast<int>(N) << /*array*/ 0
552 << static_cast<unsigned>(MostDerivedArraySize);
553 else
554 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
555 << static_cast<int>(N) << /*non-array*/ 1;
556 setInvalid();
557}
558
Richard Smith08d6e032011-12-16 19:06:07 +0000559CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
560 const FunctionDecl *Callee, const LValue *This,
561 const CCValue *Arguments)
562 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
563 This(This), Arguments(Arguments) {
564 Info.CurrentCall = this;
565 ++Info.CallStackDepth;
566}
567
568CallStackFrame::~CallStackFrame() {
569 assert(Info.CurrentCall == this && "calls retired out of order");
570 --Info.CallStackDepth;
571 Info.CurrentCall = Caller;
572}
573
574/// Produce a string describing the given constexpr call.
575static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
576 unsigned ArgIndex = 0;
577 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
578 !isa<CXXConstructorDecl>(Frame->Callee);
579
580 if (!IsMemberCall)
581 Out << *Frame->Callee << '(';
582
583 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
584 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000585 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000586 Out << ", ";
587
588 const ParmVarDecl *Param = *I;
589 const CCValue &Arg = Frame->Arguments[ArgIndex];
590 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
591 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
592 else {
593 // Deliberately slice off the frame to form an APValue we can print.
594 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
595 Arg.getLValueDesignator().Entries,
Richard Smithb4e85ed2012-01-06 16:39:00 +0000596 Arg.getLValueDesignator().IsOnePastTheEnd);
Richard Smith08d6e032011-12-16 19:06:07 +0000597 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
598 }
599
600 if (ArgIndex == 0 && IsMemberCall)
601 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000602 }
603
Richard Smith08d6e032011-12-16 19:06:07 +0000604 Out << ')';
605}
606
607void EvalInfo::addCallStack(unsigned Limit) {
608 // Determine which calls to skip, if any.
609 unsigned ActiveCalls = CallStackDepth - 1;
610 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
611 if (Limit && Limit < ActiveCalls) {
612 SkipStart = Limit / 2 + Limit % 2;
613 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000614 }
615
Richard Smith08d6e032011-12-16 19:06:07 +0000616 // Walk the call stack and add the diagnostics.
617 unsigned CallIdx = 0;
618 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
619 Frame = Frame->Caller, ++CallIdx) {
620 // Skip this call?
621 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
622 if (CallIdx == SkipStart) {
623 // Note that we're skipping calls.
624 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
625 << unsigned(ActiveCalls - Limit);
626 }
627 continue;
628 }
629
630 llvm::SmallVector<char, 128> Buffer;
631 llvm::raw_svector_ostream Out(Buffer);
632 describeCall(Frame, Out);
633 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
634 }
635}
636
637namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000638 struct ComplexValue {
639 private:
640 bool IsInt;
641
642 public:
643 APSInt IntReal, IntImag;
644 APFloat FloatReal, FloatImag;
645
646 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
647
648 void makeComplexFloat() { IsInt = false; }
649 bool isComplexFloat() const { return !IsInt; }
650 APFloat &getComplexFloatReal() { return FloatReal; }
651 APFloat &getComplexFloatImag() { return FloatImag; }
652
653 void makeComplexInt() { IsInt = true; }
654 bool isComplexInt() const { return IsInt; }
655 APSInt &getComplexIntReal() { return IntReal; }
656 APSInt &getComplexIntImag() { return IntImag; }
657
Richard Smith47a1eed2011-10-29 20:57:55 +0000658 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000659 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000660 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000661 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000662 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000663 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000664 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000665 assert(v.isComplexFloat() || v.isComplexInt());
666 if (v.isComplexFloat()) {
667 makeComplexFloat();
668 FloatReal = v.getComplexFloatReal();
669 FloatImag = v.getComplexFloatImag();
670 } else {
671 makeComplexInt();
672 IntReal = v.getComplexIntReal();
673 IntImag = v.getComplexIntImag();
674 }
675 }
John McCallf4cf1a12010-05-07 17:22:02 +0000676 };
John McCallefdb83e2010-05-07 21:00:08 +0000677
678 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000679 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000680 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000681 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000682 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000683
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000684 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000685 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000686 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000687 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000688 SubobjectDesignator &getLValueDesignator() { return Designator; }
689 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000690
Richard Smith47a1eed2011-10-29 20:57:55 +0000691 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000692 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000693 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000694 void setFrom(const CCValue &V) {
695 assert(V.isLValue());
696 Base = V.getLValueBase();
697 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000698 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000699 Designator = V.getLValueDesignator();
700 }
701
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000702 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
703 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000704 Offset = CharUnits::Zero();
705 Frame = F;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000706 Designator = SubobjectDesignator(getType(B));
707 }
708
709 // Check that this LValue is not based on a null pointer. If it is, produce
710 // a diagnostic and mark the designator as invalid.
711 bool checkNullPointer(EvalInfo &Info, const Expr *E,
712 CheckSubobjectKind CSK) {
713 if (Designator.Invalid)
714 return false;
715 if (!Base) {
716 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
717 << CSK;
718 Designator.setInvalid();
719 return false;
720 }
721 return true;
722 }
723
724 // Check this LValue refers to an object. If not, set the designator to be
725 // invalid and emit a diagnostic.
726 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
727 return checkNullPointer(Info, E, CSK) &&
728 Designator.checkSubobject(Info, E, CSK);
729 }
730
731 void addDecl(EvalInfo &Info, const Expr *E,
732 const Decl *D, bool Virtual = false) {
733 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
734 Designator.addDeclUnchecked(D, Virtual);
735 }
736 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
737 checkSubobject(Info, E, CSK_ArrayToPointer);
738 Designator.addArrayUnchecked(CAT);
739 }
740 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
741 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
742 return;
743 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000744 }
John McCallefdb83e2010-05-07 21:00:08 +0000745 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000746
747 struct MemberPtr {
748 MemberPtr() {}
749 explicit MemberPtr(const ValueDecl *Decl) :
750 DeclAndIsDerivedMember(Decl, false), Path() {}
751
752 /// The member or (direct or indirect) field referred to by this member
753 /// pointer, or 0 if this is a null member pointer.
754 const ValueDecl *getDecl() const {
755 return DeclAndIsDerivedMember.getPointer();
756 }
757 /// Is this actually a member of some type derived from the relevant class?
758 bool isDerivedMember() const {
759 return DeclAndIsDerivedMember.getInt();
760 }
761 /// Get the class which the declaration actually lives in.
762 const CXXRecordDecl *getContainingRecord() const {
763 return cast<CXXRecordDecl>(
764 DeclAndIsDerivedMember.getPointer()->getDeclContext());
765 }
766
767 void moveInto(CCValue &V) const {
768 V = CCValue(getDecl(), isDerivedMember(), Path);
769 }
770 void setFrom(const CCValue &V) {
771 assert(V.isMemberPointer());
772 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
773 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
774 Path.clear();
775 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
776 Path.insert(Path.end(), P.begin(), P.end());
777 }
778
779 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
780 /// whether the member is a member of some class derived from the class type
781 /// of the member pointer.
782 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
783 /// Path - The path of base/derived classes from the member declaration's
784 /// class (exclusive) to the class type of the member pointer (inclusive).
785 SmallVector<const CXXRecordDecl*, 4> Path;
786
787 /// Perform a cast towards the class of the Decl (either up or down the
788 /// hierarchy).
789 bool castBack(const CXXRecordDecl *Class) {
790 assert(!Path.empty());
791 const CXXRecordDecl *Expected;
792 if (Path.size() >= 2)
793 Expected = Path[Path.size() - 2];
794 else
795 Expected = getContainingRecord();
796 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
797 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
798 // if B does not contain the original member and is not a base or
799 // derived class of the class containing the original member, the result
800 // of the cast is undefined.
801 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
802 // (D::*). We consider that to be a language defect.
803 return false;
804 }
805 Path.pop_back();
806 return true;
807 }
808 /// Perform a base-to-derived member pointer cast.
809 bool castToDerived(const CXXRecordDecl *Derived) {
810 if (!getDecl())
811 return true;
812 if (!isDerivedMember()) {
813 Path.push_back(Derived);
814 return true;
815 }
816 if (!castBack(Derived))
817 return false;
818 if (Path.empty())
819 DeclAndIsDerivedMember.setInt(false);
820 return true;
821 }
822 /// Perform a derived-to-base member pointer cast.
823 bool castToBase(const CXXRecordDecl *Base) {
824 if (!getDecl())
825 return true;
826 if (Path.empty())
827 DeclAndIsDerivedMember.setInt(true);
828 if (isDerivedMember()) {
829 Path.push_back(Base);
830 return true;
831 }
832 return castBack(Base);
833 }
834 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000835
Richard Smithb02e4622012-02-01 01:42:44 +0000836 /// Compare two member pointers, which are assumed to be of the same type.
837 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
838 if (!LHS.getDecl() || !RHS.getDecl())
839 return !LHS.getDecl() && !RHS.getDecl();
840 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
841 return false;
842 return LHS.Path == RHS.Path;
843 }
844
Richard Smithc1c5f272011-12-13 06:39:58 +0000845 /// Kinds of constant expression checking, for diagnostics.
846 enum CheckConstantExpressionKind {
847 CCEK_Constant, ///< A normal constant.
848 CCEK_ReturnValue, ///< A constexpr function return value.
849 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
850 };
John McCallf4cf1a12010-05-07 17:22:02 +0000851}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000852
Richard Smith47a1eed2011-10-29 20:57:55 +0000853static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000854static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000855 const LValue &This, const Expr *E,
856 CheckConstantExpressionKind CCEK
857 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000858static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
859static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000860static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
861 EvalInfo &Info);
862static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000863static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000864static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000865 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000866static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000867static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000868
869//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000870// Misc utilities
871//===----------------------------------------------------------------------===//
872
Richard Smith180f4792011-11-10 06:34:14 +0000873/// Should this call expression be treated as a string literal?
874static bool IsStringLiteralCall(const CallExpr *E) {
875 unsigned Builtin = E->isBuiltinCall();
876 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
877 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
878}
879
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000880static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000881 // C++11 [expr.const]p3 An address constant expression is a prvalue core
882 // constant expression of pointer type that evaluates to...
883
884 // ... a null pointer value, or a prvalue core constant expression of type
885 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000886 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000887
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000888 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
889 // ... the address of an object with static storage duration,
890 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
891 return VD->hasGlobalStorage();
892 // ... the address of a function,
893 return isa<FunctionDecl>(D);
894 }
895
896 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000897 switch (E->getStmtClass()) {
898 default:
899 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000900 case Expr::CompoundLiteralExprClass:
901 return cast<CompoundLiteralExpr>(E)->isFileScope();
902 // A string literal has static storage duration.
903 case Expr::StringLiteralClass:
904 case Expr::PredefinedExprClass:
905 case Expr::ObjCStringLiteralClass:
906 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000907 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000908 return true;
909 case Expr::CallExprClass:
910 return IsStringLiteralCall(cast<CallExpr>(E));
911 // For GCC compatibility, &&label has static storage duration.
912 case Expr::AddrLabelExprClass:
913 return true;
914 // A Block literal expression may be used as the initialization value for
915 // Block variables at global or local static scope.
916 case Expr::BlockExprClass:
917 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000918 case Expr::ImplicitValueInitExprClass:
919 // FIXME:
920 // We can never form an lvalue with an implicit value initialization as its
921 // base through expression evaluation, so these only appear in one case: the
922 // implicit variable declaration we invent when checking whether a constexpr
923 // constructor can produce a constant expression. We must assume that such
924 // an expression might be a global lvalue.
925 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000926 }
John McCall42c8f872010-05-10 23:27:23 +0000927}
928
Richard Smith9a17a682011-11-07 05:07:52 +0000929/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000930/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000931/// either LValue or CCValue. Return true if we can fold this expression,
932/// whether or not it's a constant expression.
Richard Smith9a17a682011-11-07 05:07:52 +0000933template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000934static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000935 const T &LVal, APValue &Value,
936 CheckConstantExpressionKind CCEK) {
937 APValue::LValueBase Base = LVal.getLValueBase();
938 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
939
940 if (!IsGlobalLValue(Base)) {
941 if (Info.getLangOpts().CPlusPlus0x) {
942 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
943 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
944 << E->isGLValue() << !Designator.Entries.empty()
945 << !!VD << CCEK << VD;
946 if (VD)
947 Info.Note(VD->getLocation(), diag::note_declared_at);
948 else
949 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
950 diag::note_constexpr_temporary_here);
951 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000952 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000953 }
Richard Smith61e61622012-01-12 06:08:57 +0000954 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000955 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000956 }
Richard Smith9a17a682011-11-07 05:07:52 +0000957
Richard Smithb4e85ed2012-01-06 16:39:00 +0000958 bool IsReferenceType = E->isGLValue();
959
960 if (Designator.Invalid) {
Richard Smith61e61622012-01-12 06:08:57 +0000961 // This is not a core constant expression. An appropriate diagnostic will
962 // have already been produced.
Richard Smith9a17a682011-11-07 05:07:52 +0000963 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
964 APValue::NoLValuePath());
965 return true;
966 }
967
Richard Smithb4e85ed2012-01-06 16:39:00 +0000968 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
969 Designator.Entries, Designator.IsOnePastTheEnd);
970
971 // Allow address constant expressions to be past-the-end pointers. This is
972 // an extension: the standard requires them to point to an object.
973 if (!IsReferenceType)
974 return true;
975
976 // A reference constant expression must refer to an object.
977 if (!Base) {
978 // FIXME: diagnostic
979 Info.CCEDiag(E->getExprLoc());
Richard Smith61e61622012-01-12 06:08:57 +0000980 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000981 }
982
Richard Smithc1c5f272011-12-13 06:39:58 +0000983 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +0000984 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000985 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
986 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
987 << !Designator.Entries.empty() << !!VD << VD;
988 if (VD)
989 Info.Note(VD->getLocation(), diag::note_declared_at);
990 else
991 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
992 diag::note_constexpr_temporary_here);
Richard Smithc1c5f272011-12-13 06:39:58 +0000993 }
994
Richard Smith9a17a682011-11-07 05:07:52 +0000995 return true;
996}
997
Richard Smith51201882011-12-30 21:15:51 +0000998/// Check that this core constant expression is of literal type, and if not,
999/// produce an appropriate diagnostic.
1000static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1001 if (!E->isRValue() || E->getType()->isLiteralType())
1002 return true;
1003
1004 // Prvalue constant expressions must be of literal types.
1005 if (Info.getLangOpts().CPlusPlus0x)
1006 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
1007 << E->getType();
1008 else
1009 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1010 return false;
1011}
1012
Richard Smith47a1eed2011-10-29 20:57:55 +00001013/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +00001014/// constant expression, and if it is, produce the corresponding constant value.
Richard Smith51201882011-12-30 21:15:51 +00001015/// If not, report an appropriate diagnostic. Does not check that the expression
1016/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +00001017static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +00001018 const CCValue &CCValue, APValue &Value,
1019 CheckConstantExpressionKind CCEK
1020 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +00001021 if (!CCValue.isLValue()) {
1022 Value = CCValue;
1023 return true;
1024 }
Richard Smithc1c5f272011-12-13 06:39:58 +00001025 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +00001026}
1027
Richard Smith9e36b532011-10-31 05:11:32 +00001028const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001029 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001030}
1031
1032static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001033 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +00001034}
1035
Richard Smith65ac5982011-11-01 21:06:14 +00001036static bool IsWeakLValue(const LValue &Value) {
1037 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001038 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001039}
1040
Richard Smithe24f5fc2011-11-17 22:56:20 +00001041static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001042 // A null base expression indicates a null pointer. These are always
1043 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001044 if (!Value.getLValueBase()) {
1045 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001046 return true;
1047 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001048
Richard Smithe24f5fc2011-11-17 22:56:20 +00001049 // We have a non-null base. These are generally known to be true, but if it's
1050 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001051 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001052 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001053 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001054}
1055
Richard Smith47a1eed2011-10-29 20:57:55 +00001056static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001057 switch (Val.getKind()) {
1058 case APValue::Uninitialized:
1059 return false;
1060 case APValue::Int:
1061 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001062 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001063 case APValue::Float:
1064 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001065 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001066 case APValue::ComplexInt:
1067 Result = Val.getComplexIntReal().getBoolValue() ||
1068 Val.getComplexIntImag().getBoolValue();
1069 return true;
1070 case APValue::ComplexFloat:
1071 Result = !Val.getComplexFloatReal().isZero() ||
1072 !Val.getComplexFloatImag().isZero();
1073 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001074 case APValue::LValue:
1075 return EvalPointerValueAsBool(Val, Result);
1076 case APValue::MemberPointer:
1077 Result = Val.getMemberPointerDecl();
1078 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001079 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001080 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001081 case APValue::Struct:
1082 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001083 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001084 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001085 }
1086
Richard Smithc49bd112011-10-28 17:51:58 +00001087 llvm_unreachable("unknown APValue kind");
1088}
1089
1090static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1091 EvalInfo &Info) {
1092 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001093 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001094 if (!Evaluate(Val, Info, E))
1095 return false;
1096 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001097}
1098
Richard Smithc1c5f272011-12-13 06:39:58 +00001099template<typename T>
1100static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1101 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001102 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001103 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001104 return false;
1105}
1106
1107static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1108 QualType SrcType, const APFloat &Value,
1109 QualType DestType, APSInt &Result) {
1110 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001111 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001112 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Richard Smithc1c5f272011-12-13 06:39:58 +00001114 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001115 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001116 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1117 & APFloat::opInvalidOp)
1118 return HandleOverflow(Info, E, Value, DestType);
1119 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001120}
1121
Richard Smithc1c5f272011-12-13 06:39:58 +00001122static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1123 QualType SrcType, QualType DestType,
1124 APFloat &Result) {
1125 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001126 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001127 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1128 APFloat::rmNearestTiesToEven, &ignored)
1129 & APFloat::opOverflow)
1130 return HandleOverflow(Info, E, Value, DestType);
1131 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001132}
1133
Richard Smithf72fccf2012-01-30 22:27:01 +00001134static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1135 QualType DestType, QualType SrcType,
1136 APSInt &Value) {
1137 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001138 APSInt Result = Value;
1139 // Figure out if this is a truncate, extend or noop cast.
1140 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001141 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001142 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001143 return Result;
1144}
1145
Richard Smithc1c5f272011-12-13 06:39:58 +00001146static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1147 QualType SrcType, const APSInt &Value,
1148 QualType DestType, APFloat &Result) {
1149 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1150 if (Result.convertFromAPInt(Value, Value.isSigned(),
1151 APFloat::rmNearestTiesToEven)
1152 & APFloat::opOverflow)
1153 return HandleOverflow(Info, E, Value, DestType);
1154 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001155}
1156
Eli Friedmane6a24e82011-12-22 03:51:45 +00001157static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1158 llvm::APInt &Res) {
1159 CCValue SVal;
1160 if (!Evaluate(SVal, Info, E))
1161 return false;
1162 if (SVal.isInt()) {
1163 Res = SVal.getInt();
1164 return true;
1165 }
1166 if (SVal.isFloat()) {
1167 Res = SVal.getFloat().bitcastToAPInt();
1168 return true;
1169 }
1170 if (SVal.isVector()) {
1171 QualType VecTy = E->getType();
1172 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1173 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1174 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1175 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1176 Res = llvm::APInt::getNullValue(VecSize);
1177 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1178 APValue &Elt = SVal.getVectorElt(i);
1179 llvm::APInt EltAsInt;
1180 if (Elt.isInt()) {
1181 EltAsInt = Elt.getInt();
1182 } else if (Elt.isFloat()) {
1183 EltAsInt = Elt.getFloat().bitcastToAPInt();
1184 } else {
1185 // Don't try to handle vectors of anything other than int or float
1186 // (not sure if it's possible to hit this case).
1187 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1188 return false;
1189 }
1190 unsigned BaseEltSize = EltAsInt.getBitWidth();
1191 if (BigEndian)
1192 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1193 else
1194 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1195 }
1196 return true;
1197 }
1198 // Give up if the input isn't an int, float, or vector. For example, we
1199 // reject "(v4i16)(intptr_t)&a".
1200 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1201 return false;
1202}
1203
Richard Smithb4e85ed2012-01-06 16:39:00 +00001204/// Cast an lvalue referring to a base subobject to a derived class, by
1205/// truncating the lvalue's path to the given length.
1206static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1207 const RecordDecl *TruncatedType,
1208 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001209 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001210
1211 // Check we actually point to a derived class object.
1212 if (TruncatedElements == D.Entries.size())
1213 return true;
1214 assert(TruncatedElements >= D.MostDerivedPathLength &&
1215 "not casting to a derived class");
1216 if (!Result.checkSubobject(Info, E, CSK_Derived))
1217 return false;
1218
1219 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001220 const RecordDecl *RD = TruncatedType;
1221 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001222 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1223 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001224 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001225 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001226 else
Richard Smith180f4792011-11-10 06:34:14 +00001227 Result.Offset -= Layout.getBaseClassOffset(Base);
1228 RD = Base;
1229 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001230 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001231 return true;
1232}
1233
Richard Smithb4e85ed2012-01-06 16:39:00 +00001234static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001235 const CXXRecordDecl *Derived,
1236 const CXXRecordDecl *Base,
1237 const ASTRecordLayout *RL = 0) {
1238 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1239 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001240 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001241}
1242
Richard Smithb4e85ed2012-01-06 16:39:00 +00001243static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001244 const CXXRecordDecl *DerivedDecl,
1245 const CXXBaseSpecifier *Base) {
1246 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1247
1248 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001249 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001250 return true;
1251 }
1252
Richard Smithb4e85ed2012-01-06 16:39:00 +00001253 SubobjectDesignator &D = Obj.Designator;
1254 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001255 return false;
1256
Richard Smithb4e85ed2012-01-06 16:39:00 +00001257 // Extract most-derived object and corresponding type.
1258 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1259 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1260 return false;
1261
1262 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001263 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1264 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001265 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001266 return true;
1267}
1268
1269/// Update LVal to refer to the given field, which must be a member of the type
1270/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001271static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001272 const FieldDecl *FD,
1273 const ASTRecordLayout *RL = 0) {
1274 if (!RL)
1275 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1276
1277 unsigned I = FD->getFieldIndex();
1278 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001279 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001280}
1281
Richard Smithd9b02e72012-01-25 22:15:11 +00001282/// Update LVal to refer to the given indirect field.
1283static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1284 LValue &LVal,
1285 const IndirectFieldDecl *IFD) {
1286 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1287 CE = IFD->chain_end(); C != CE; ++C)
1288 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1289}
1290
Richard Smith180f4792011-11-10 06:34:14 +00001291/// Get the size of the given type in char units.
1292static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1293 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1294 // extension.
1295 if (Type->isVoidType() || Type->isFunctionType()) {
1296 Size = CharUnits::One();
1297 return true;
1298 }
1299
1300 if (!Type->isConstantSizeType()) {
1301 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001302 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001303 return false;
1304 }
1305
1306 Size = Info.Ctx.getTypeSizeInChars(Type);
1307 return true;
1308}
1309
1310/// Update a pointer value to model pointer arithmetic.
1311/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001312/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001313/// \param LVal - The pointer value to be updated.
1314/// \param EltTy - The pointee type represented by LVal.
1315/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001316static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1317 LValue &LVal, QualType EltTy,
1318 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001319 CharUnits SizeOfPointee;
1320 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1321 return false;
1322
1323 // Compute the new offset in the appropriate width.
1324 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001325 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001326 return true;
1327}
1328
Richard Smith03f96112011-10-24 17:54:18 +00001329/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001330static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1331 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001332 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001333 // If this is a parameter to an active constexpr function call, perform
1334 // argument substitution.
1335 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001336 // Assume arguments of a potential constant expression are unknown
1337 // constant expressions.
1338 if (Info.CheckingPotentialConstantExpression)
1339 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001340 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001341 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001342 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001343 }
Richard Smith177dce72011-11-01 16:57:24 +00001344 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1345 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001346 }
Richard Smith03f96112011-10-24 17:54:18 +00001347
Richard Smith099e7f62011-12-19 06:19:21 +00001348 // Dig out the initializer, and use the declaration which it's attached to.
1349 const Expr *Init = VD->getAnyInitializer(VD);
1350 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001351 // If we're checking a potential constant expression, the variable could be
1352 // initialized later.
1353 if (!Info.CheckingPotentialConstantExpression)
1354 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001355 return false;
1356 }
1357
Richard Smith180f4792011-11-10 06:34:14 +00001358 // If we're currently evaluating the initializer of this declaration, use that
1359 // in-flight value.
1360 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001361 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1362 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001363 return !Result.isUninit();
1364 }
1365
Richard Smith65ac5982011-11-01 21:06:14 +00001366 // Never evaluate the initializer of a weak variable. We can't be sure that
1367 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001368 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001369 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001370 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001371 }
Richard Smith65ac5982011-11-01 21:06:14 +00001372
Richard Smith099e7f62011-12-19 06:19:21 +00001373 // Check that we can fold the initializer. In C++, we will have already done
1374 // this in the cases where it matters for conformance.
1375 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1376 if (!VD->evaluateValue(Notes)) {
1377 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1378 Notes.size() + 1) << VD;
1379 Info.Note(VD->getLocation(), diag::note_declared_at);
1380 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001381 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001382 } else if (!VD->checkInitIsICE()) {
1383 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1384 Notes.size() + 1) << VD;
1385 Info.Note(VD->getLocation(), diag::note_declared_at);
1386 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001387 }
Richard Smith03f96112011-10-24 17:54:18 +00001388
Richard Smithb4e85ed2012-01-06 16:39:00 +00001389 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001390 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001391}
1392
Richard Smithc49bd112011-10-28 17:51:58 +00001393static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001394 Qualifiers Quals = T.getQualifiers();
1395 return Quals.hasConst() && !Quals.hasVolatile();
1396}
1397
Richard Smith59efe262011-11-11 04:05:33 +00001398/// Get the base index of the given base class within an APValue representing
1399/// the given derived class.
1400static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1401 const CXXRecordDecl *Base) {
1402 Base = Base->getCanonicalDecl();
1403 unsigned Index = 0;
1404 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1405 E = Derived->bases_end(); I != E; ++I, ++Index) {
1406 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1407 return Index;
1408 }
1409
1410 llvm_unreachable("base class missing from derived class's bases list");
1411}
1412
Richard Smithcc5d4f62011-11-07 09:22:26 +00001413/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001414static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1415 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001416 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001417 if (Sub.Invalid)
1418 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001419 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001420 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001421 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001422 (unsigned)diag::note_constexpr_read_past_end :
1423 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001424 return false;
1425 }
Richard Smithf64699e2011-11-11 08:28:03 +00001426 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001427 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001428 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1429 // This object might be initialized later.
1430 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001431
1432 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1433 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001434 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001435 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001436 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001437 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001438 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001439 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001440 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001441 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001442 // Note, it should not be possible to form a pointer with a valid
1443 // designator which points more than one past the end of the array.
1444 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001445 (unsigned)diag::note_constexpr_read_past_end :
1446 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001447 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001448 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001449 if (O->getArrayInitializedElts() > Index)
1450 O = &O->getArrayInitializedElt(Index);
1451 else
1452 O = &O->getArrayFiller();
1453 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001454 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1455 // Next subobject is a class, struct or union field.
1456 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1457 if (RD->isUnion()) {
1458 const FieldDecl *UnionField = O->getUnionField();
1459 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001460 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001461 Info.Diag(E->getExprLoc(),
1462 diag::note_constexpr_read_inactive_union_member)
1463 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001464 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001465 }
Richard Smith180f4792011-11-10 06:34:14 +00001466 O = &O->getUnionValue();
1467 } else
1468 O = &O->getStructField(Field->getFieldIndex());
1469 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001470
1471 if (ObjType.isVolatileQualified()) {
1472 if (Info.getLangOpts().CPlusPlus) {
1473 // FIXME: Include a description of the path to the volatile subobject.
1474 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1475 << 2 << Field;
1476 Info.Note(Field->getLocation(), diag::note_declared_at);
1477 } else {
1478 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1479 }
1480 return false;
1481 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001482 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001483 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001484 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1485 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1486 O = &O->getStructBase(getBaseIndex(Derived, Base));
1487 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001488 }
Richard Smith180f4792011-11-10 06:34:14 +00001489
Richard Smithf48fdb02011-12-09 22:58:01 +00001490 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001491 if (!Info.CheckingPotentialConstantExpression)
1492 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001493 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001494 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001495 }
1496
Richard Smithb4e85ed2012-01-06 16:39:00 +00001497 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001498 return true;
1499}
1500
Richard Smithf15fda02012-02-02 01:16:57 +00001501/// Find the position where two subobject designators diverge, or equivalently
1502/// the length of the common initial subsequence.
1503static unsigned FindDesignatorMismatch(QualType ObjType,
1504 const SubobjectDesignator &A,
1505 const SubobjectDesignator &B,
1506 bool &WasArrayIndex) {
1507 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1508 for (/**/; I != N; ++I) {
1509 if (!ObjType.isNull() && ObjType->isArrayType()) {
1510 // Next subobject is an array element.
1511 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1512 WasArrayIndex = true;
1513 return I;
1514 }
1515 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
1516 } else {
1517 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1518 WasArrayIndex = false;
1519 return I;
1520 }
1521 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1522 // Next subobject is a field.
1523 ObjType = FD->getType();
1524 else
1525 // Next subobject is a base class.
1526 ObjType = QualType();
1527 }
1528 }
1529 WasArrayIndex = false;
1530 return I;
1531}
1532
1533/// Determine whether the given subobject designators refer to elements of the
1534/// same array object.
1535static bool AreElementsOfSameArray(QualType ObjType,
1536 const SubobjectDesignator &A,
1537 const SubobjectDesignator &B) {
1538 if (A.Entries.size() != B.Entries.size())
1539 return false;
1540
1541 bool IsArray = A.MostDerivedArraySize != 0;
1542 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1543 // A is a subobject of the array element.
1544 return false;
1545
1546 // If A (and B) designates an array element, the last entry will be the array
1547 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1548 // of length 1' case, and the entire path must match.
1549 bool WasArrayIndex;
1550 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1551 return CommonLength >= A.Entries.size() - IsArray;
1552}
1553
Richard Smith180f4792011-11-10 06:34:14 +00001554/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1555/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1556/// for looking up the glvalue referred to by an entity of reference type.
1557///
1558/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001559/// \param Conv - The expression for which we are performing the conversion.
1560/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001561/// \param Type - The type we expect this conversion to produce.
1562/// \param LVal - The glvalue on which we are attempting to perform this action.
1563/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001564static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1565 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001566 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001567 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1568 if (!Info.getLangOpts().CPlusPlus)
1569 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1570
Richard Smithb4e85ed2012-01-06 16:39:00 +00001571 if (LVal.Designator.Invalid)
1572 // A diagnostic will have already been produced.
1573 return false;
1574
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001575 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001576 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001577 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001578
Richard Smithf48fdb02011-12-09 22:58:01 +00001579 if (!LVal.Base) {
1580 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001581 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1582 return false;
1583 }
1584
1585 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1586 // is not a constant expression (even if the object is non-volatile). We also
1587 // apply this rule to C++98, in order to conform to the expected 'volatile'
1588 // semantics.
1589 if (Type.isVolatileQualified()) {
1590 if (Info.getLangOpts().CPlusPlus)
1591 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1592 else
1593 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001594 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001595 }
Richard Smithc49bd112011-10-28 17:51:58 +00001596
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001597 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001598 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1599 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001600 // expressions are constant expressions too. Inside constexpr functions,
1601 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001602 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001603 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf15fda02012-02-02 01:16:57 +00001604 if (const VarDecl *VDef = VD->getDefinition())
1605 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001606 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001607 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001608 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001609 }
1610
Richard Smith7098cbd2011-12-21 05:04:46 +00001611 // DR1313: If the object is volatile-qualified but the glvalue was not,
1612 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001613 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001614 if (VT.isVolatileQualified()) {
1615 if (Info.getLangOpts().CPlusPlus) {
1616 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1617 Info.Note(VD->getLocation(), diag::note_declared_at);
1618 } else {
1619 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001620 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001621 return false;
1622 }
1623
1624 if (!isa<ParmVarDecl>(VD)) {
1625 if (VD->isConstexpr()) {
1626 // OK, we can read this variable.
1627 } else if (VT->isIntegralOrEnumerationType()) {
1628 if (!VT.isConstQualified()) {
1629 if (Info.getLangOpts().CPlusPlus) {
1630 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1631 Info.Note(VD->getLocation(), diag::note_declared_at);
1632 } else {
1633 Info.Diag(Loc);
1634 }
1635 return false;
1636 }
1637 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1638 // We support folding of const floating-point types, in order to make
1639 // static const data members of such types (supported as an extension)
1640 // more useful.
1641 if (Info.getLangOpts().CPlusPlus0x) {
1642 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1643 Info.Note(VD->getLocation(), diag::note_declared_at);
1644 } else {
1645 Info.CCEDiag(Loc);
1646 }
1647 } else {
1648 // FIXME: Allow folding of values of any literal type in all languages.
1649 if (Info.getLangOpts().CPlusPlus0x) {
1650 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1651 Info.Note(VD->getLocation(), diag::note_declared_at);
1652 } else {
1653 Info.Diag(Loc);
1654 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001655 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001656 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001657 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001658
Richard Smithf48fdb02011-12-09 22:58:01 +00001659 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001660 return false;
1661
Richard Smith47a1eed2011-10-29 20:57:55 +00001662 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001663 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001664
1665 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1666 // conversion. This happens when the declaration and the lvalue should be
1667 // considered synonymous, for instance when initializing an array of char
1668 // from a string literal. Continue as if the initializer lvalue was the
1669 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001670 assert(RVal.getLValueOffset().isZero() &&
1671 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001672 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001673 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001674 }
1675
Richard Smith7098cbd2011-12-21 05:04:46 +00001676 // Volatile temporary objects cannot be read in constant expressions.
1677 if (Base->getType().isVolatileQualified()) {
1678 if (Info.getLangOpts().CPlusPlus) {
1679 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1680 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1681 } else {
1682 Info.Diag(Loc);
1683 }
1684 return false;
1685 }
1686
Richard Smith0a3bdb62011-11-04 02:25:55 +00001687 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1688 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1689 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001690 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001691 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001692 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001693 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001694
1695 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001696 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001697 const ConstantArrayType *CAT =
1698 Info.Ctx.getAsConstantArrayType(S->getType());
1699 if (Index >= CAT->getSize().getZExtValue()) {
1700 // Note, it should not be possible to form a pointer which points more
1701 // than one past the end of the array without producing a prior const expr
1702 // diagnostic.
1703 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001704 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001705 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001706 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1707 Type->isUnsignedIntegerType());
1708 if (Index < S->getLength())
1709 Value = S->getCodeUnit(Index);
1710 RVal = CCValue(Value);
1711 return true;
1712 }
1713
Richard Smithcc5d4f62011-11-07 09:22:26 +00001714 if (Frame) {
1715 // If this is a temporary expression with a nontrivial initializer, grab the
1716 // value from the relevant stack frame.
1717 RVal = Frame->Temporaries[Base];
1718 } else if (const CompoundLiteralExpr *CLE
1719 = dyn_cast<CompoundLiteralExpr>(Base)) {
1720 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1721 // initializer until now for such expressions. Such an expression can't be
1722 // an ICE in C, so this only matters for fold.
1723 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1724 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1725 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001726 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001727 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001728 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001729 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001730
Richard Smithf48fdb02011-12-09 22:58:01 +00001731 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1732 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001733}
1734
Richard Smith59efe262011-11-11 04:05:33 +00001735/// Build an lvalue for the object argument of a member function call.
1736static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1737 LValue &This) {
1738 if (Object->getType()->isPointerType())
1739 return EvaluatePointer(Object, This, Info);
1740
1741 if (Object->isGLValue())
1742 return EvaluateLValue(Object, This, Info);
1743
Richard Smithe24f5fc2011-11-17 22:56:20 +00001744 if (Object->getType()->isLiteralType())
1745 return EvaluateTemporary(Object, This, Info);
1746
1747 return false;
1748}
1749
1750/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1751/// lvalue referring to the result.
1752///
1753/// \param Info - Information about the ongoing evaluation.
1754/// \param BO - The member pointer access operation.
1755/// \param LV - Filled in with a reference to the resulting object.
1756/// \param IncludeMember - Specifies whether the member itself is included in
1757/// the resulting LValue subobject designator. This is not possible when
1758/// creating a bound member function.
1759/// \return The field or method declaration to which the member pointer refers,
1760/// or 0 if evaluation fails.
1761static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1762 const BinaryOperator *BO,
1763 LValue &LV,
1764 bool IncludeMember = true) {
1765 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1766
Richard Smith745f5142012-01-27 01:14:48 +00001767 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1768 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001769 return 0;
1770
1771 MemberPtr MemPtr;
1772 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1773 return 0;
1774
1775 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1776 // member value, the behavior is undefined.
1777 if (!MemPtr.getDecl())
1778 return 0;
1779
Richard Smith745f5142012-01-27 01:14:48 +00001780 if (!EvalObjOK)
1781 return 0;
1782
Richard Smithe24f5fc2011-11-17 22:56:20 +00001783 if (MemPtr.isDerivedMember()) {
1784 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001785 // The end of the derived-to-base path for the base object must match the
1786 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001787 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001788 LV.Designator.Entries.size())
1789 return 0;
1790 unsigned PathLengthToMember =
1791 LV.Designator.Entries.size() - MemPtr.Path.size();
1792 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1793 const CXXRecordDecl *LVDecl = getAsBaseClass(
1794 LV.Designator.Entries[PathLengthToMember + I]);
1795 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1796 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1797 return 0;
1798 }
1799
1800 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001801 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1802 PathLengthToMember))
1803 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001804 } else if (!MemPtr.Path.empty()) {
1805 // Extend the LValue path with the member pointer's path.
1806 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1807 MemPtr.Path.size() + IncludeMember);
1808
1809 // Walk down to the appropriate base class.
1810 QualType LVType = BO->getLHS()->getType();
1811 if (const PointerType *PT = LVType->getAs<PointerType>())
1812 LVType = PT->getPointeeType();
1813 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1814 assert(RD && "member pointer access on non-class-type expression");
1815 // The first class in the path is that of the lvalue.
1816 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1817 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001818 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001819 RD = Base;
1820 }
1821 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001822 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001823 }
1824
1825 // Add the member. Note that we cannot build bound member functions here.
1826 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001827 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1828 HandleLValueMember(Info, BO, LV, FD);
1829 else if (const IndirectFieldDecl *IFD =
1830 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1831 HandleLValueIndirectMember(Info, BO, LV, IFD);
1832 else
1833 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001834 }
1835
1836 return MemPtr.getDecl();
1837}
1838
1839/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1840/// the provided lvalue, which currently refers to the base object.
1841static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1842 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001843 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001844 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001845 return false;
1846
Richard Smithb4e85ed2012-01-06 16:39:00 +00001847 QualType TargetQT = E->getType();
1848 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1849 TargetQT = PT->getPointeeType();
1850
1851 // Check this cast lands within the final derived-to-base subobject path.
1852 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1853 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1854 << D.MostDerivedType << TargetQT;
1855 return false;
1856 }
1857
Richard Smithe24f5fc2011-11-17 22:56:20 +00001858 // Check the type of the final cast. We don't need to check the path,
1859 // since a cast can only be formed if the path is unique.
1860 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001861 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1862 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001863 if (NewEntriesSize == D.MostDerivedPathLength)
1864 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1865 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001866 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001867 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1868 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1869 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001870 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001871 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001872
1873 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001874 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001875}
1876
Mike Stumpc4c90452009-10-27 22:09:17 +00001877namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001878enum EvalStmtResult {
1879 /// Evaluation failed.
1880 ESR_Failed,
1881 /// Hit a 'return' statement.
1882 ESR_Returned,
1883 /// Evaluation succeeded.
1884 ESR_Succeeded
1885};
1886}
1887
1888// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001889static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001890 const Stmt *S) {
1891 switch (S->getStmtClass()) {
1892 default:
1893 return ESR_Failed;
1894
1895 case Stmt::NullStmtClass:
1896 case Stmt::DeclStmtClass:
1897 return ESR_Succeeded;
1898
Richard Smithc1c5f272011-12-13 06:39:58 +00001899 case Stmt::ReturnStmtClass: {
1900 CCValue CCResult;
1901 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1902 if (!Evaluate(CCResult, Info, RetExpr) ||
1903 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1904 CCEK_ReturnValue))
1905 return ESR_Failed;
1906 return ESR_Returned;
1907 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001908
1909 case Stmt::CompoundStmtClass: {
1910 const CompoundStmt *CS = cast<CompoundStmt>(S);
1911 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1912 BE = CS->body_end(); BI != BE; ++BI) {
1913 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1914 if (ESR != ESR_Succeeded)
1915 return ESR;
1916 }
1917 return ESR_Succeeded;
1918 }
1919 }
1920}
1921
Richard Smith61802452011-12-22 02:22:31 +00001922/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1923/// default constructor. If so, we'll fold it whether or not it's marked as
1924/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1925/// so we need special handling.
1926static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001927 const CXXConstructorDecl *CD,
1928 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001929 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1930 return false;
1931
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001932 // Value-initialization does not call a trivial default constructor, so such a
1933 // call is a core constant expression whether or not the constructor is
1934 // constexpr.
1935 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001936 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001937 // FIXME: If DiagDecl is an implicitly-declared special member function,
1938 // we should be much more explicit about why it's not constexpr.
1939 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1940 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1941 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00001942 } else {
1943 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1944 }
1945 }
1946 return true;
1947}
1948
Richard Smithc1c5f272011-12-13 06:39:58 +00001949/// CheckConstexprFunction - Check that a function can be called in a constant
1950/// expression.
1951static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1952 const FunctionDecl *Declaration,
1953 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00001954 // Potential constant expressions can contain calls to declared, but not yet
1955 // defined, constexpr functions.
1956 if (Info.CheckingPotentialConstantExpression && !Definition &&
1957 Declaration->isConstexpr())
1958 return false;
1959
Richard Smithc1c5f272011-12-13 06:39:58 +00001960 // Can we evaluate this function call?
1961 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1962 return true;
1963
1964 if (Info.getLangOpts().CPlusPlus0x) {
1965 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001966 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1967 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001968 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1969 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1970 << DiagDecl;
1971 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1972 } else {
1973 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1974 }
1975 return false;
1976}
1977
Richard Smith180f4792011-11-10 06:34:14 +00001978namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001979typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001980}
1981
1982/// EvaluateArgs - Evaluate the arguments to a function call.
1983static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1984 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00001985 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001986 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00001987 I != E; ++I) {
1988 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
1989 // If we're checking for a potential constant expression, evaluate all
1990 // initializers even if some of them fail.
1991 if (!Info.keepEvaluatingAfterFailure())
1992 return false;
1993 Success = false;
1994 }
1995 }
1996 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00001997}
1998
Richard Smithd0dccea2011-10-28 22:34:42 +00001999/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002000static bool HandleFunctionCall(SourceLocation CallLoc,
2001 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002002 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00002003 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002004 ArgVector ArgValues(Args.size());
2005 if (!EvaluateArgs(Args, ArgValues, Info))
2006 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002007
Richard Smith745f5142012-01-27 01:14:48 +00002008 if (!Info.CheckCallLimit(CallLoc))
2009 return false;
2010
2011 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002012 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2013}
2014
Richard Smith180f4792011-11-10 06:34:14 +00002015/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002016static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002017 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002018 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002019 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002020 ArgVector ArgValues(Args.size());
2021 if (!EvaluateArgs(Args, ArgValues, Info))
2022 return false;
2023
Richard Smith745f5142012-01-27 01:14:48 +00002024 if (!Info.CheckCallLimit(CallLoc))
2025 return false;
2026
2027 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002028
2029 // If it's a delegating constructor, just delegate.
2030 if (Definition->isDelegatingConstructor()) {
2031 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
2032 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
2033 }
2034
Richard Smith610a60c2012-01-10 04:32:03 +00002035 // For a trivial copy or move constructor, perform an APValue copy. This is
2036 // essential for unions, where the operations performed by the constructor
2037 // cannot be represented by ctor-initializers.
Richard Smith180f4792011-11-10 06:34:14 +00002038 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith610a60c2012-01-10 04:32:03 +00002039 if (Definition->isDefaulted() &&
2040 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
2041 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
2042 LValue RHS;
2043 RHS.setFrom(ArgValues[0]);
2044 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00002045 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2046 RHS, Value))
2047 return false;
2048 assert((Value.isStruct() || Value.isUnion()) &&
2049 "trivial copy/move from non-class type?");
2050 // Any CCValue of class type must already be a constant expression.
2051 Result = Value;
2052 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00002053 }
2054
2055 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002056 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002057 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2058 std::distance(RD->field_begin(), RD->field_end()));
2059
2060 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2061
Richard Smith745f5142012-01-27 01:14:48 +00002062 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002063 unsigned BasesSeen = 0;
2064#ifndef NDEBUG
2065 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2066#endif
2067 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2068 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002069 LValue Subobject = This;
2070 APValue *Value = &Result;
2071
2072 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002073 if ((*I)->isBaseInitializer()) {
2074 QualType BaseType((*I)->getBaseClass(), 0);
2075#ifndef NDEBUG
2076 // Non-virtual base classes are initialized in the order in the class
2077 // definition. We cannot have a virtual base class for a literal type.
2078 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2079 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2080 "base class initializers not in expected order");
2081 ++BaseIt;
2082#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002083 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002084 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002085 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002086 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002087 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002088 if (RD->isUnion()) {
2089 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002090 Value = &Result.getUnionValue();
2091 } else {
2092 Value = &Result.getStructField(FD->getFieldIndex());
2093 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002094 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002095 // Walk the indirect field decl's chain to find the object to initialize,
2096 // and make sure we've initialized every step along it.
2097 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2098 CE = IFD->chain_end();
2099 C != CE; ++C) {
2100 FieldDecl *FD = cast<FieldDecl>(*C);
2101 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2102 // Switch the union field if it differs. This happens if we had
2103 // preceding zero-initialization, and we're now initializing a union
2104 // subobject other than the first.
2105 // FIXME: In this case, the values of the other subobjects are
2106 // specified, since zero-initialization sets all padding bits to zero.
2107 if (Value->isUninit() ||
2108 (Value->isUnion() && Value->getUnionField() != FD)) {
2109 if (CD->isUnion())
2110 *Value = APValue(FD);
2111 else
2112 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2113 std::distance(CD->field_begin(), CD->field_end()));
2114 }
Richard Smith745f5142012-01-27 01:14:48 +00002115 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002116 if (CD->isUnion())
2117 Value = &Value->getUnionValue();
2118 else
2119 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002120 }
Richard Smith180f4792011-11-10 06:34:14 +00002121 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002122 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002123 }
Richard Smith745f5142012-01-27 01:14:48 +00002124
2125 if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
2126 (*I)->isBaseInitializer()
2127 ? CCEK_Constant : CCEK_MemberInit)) {
2128 // If we're checking for a potential constant expression, evaluate all
2129 // initializers even if some of them fail.
2130 if (!Info.keepEvaluatingAfterFailure())
2131 return false;
2132 Success = false;
2133 }
Richard Smith180f4792011-11-10 06:34:14 +00002134 }
2135
Richard Smith745f5142012-01-27 01:14:48 +00002136 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002137}
2138
Richard Smithd0dccea2011-10-28 22:34:42 +00002139namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002140class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002141 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002142 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002143public:
2144
Richard Smith1e12c592011-10-16 21:26:27 +00002145 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002146
2147 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002148 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002149 return true;
2150 }
2151
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002152 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2153 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002154 return Visit(E->getResultExpr());
2155 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002156 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002157 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002158 return true;
2159 return false;
2160 }
John McCallf85e1932011-06-15 23:02:42 +00002161 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002162 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002163 return true;
2164 return false;
2165 }
2166 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002167 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002168 return true;
2169 return false;
2170 }
2171
Mike Stumpc4c90452009-10-27 22:09:17 +00002172 // We don't want to evaluate BlockExprs multiple times, as they generate
2173 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002174 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2175 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2176 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002177 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002178 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2179 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2180 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2181 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2182 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2183 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002184 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002185 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002186 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002187 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002188 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002189 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2190 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2191 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2192 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002193 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002194 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2195 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2196 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2197 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2198 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002199 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002200 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002201 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002202 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002203 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002204
2205 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002206 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002207 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2208 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002209 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002210 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002211 return false;
2212 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002213
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002214 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002215};
2216
John McCall56ca35d2011-02-17 10:25:35 +00002217class OpaqueValueEvaluation {
2218 EvalInfo &info;
2219 OpaqueValueExpr *opaqueValue;
2220
2221public:
2222 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2223 Expr *value)
2224 : info(info), opaqueValue(opaqueValue) {
2225
2226 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002227 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002228 this->opaqueValue = 0;
2229 return;
2230 }
John McCall56ca35d2011-02-17 10:25:35 +00002231 }
2232
2233 bool hasError() const { return opaqueValue == 0; }
2234
2235 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002236 // FIXME: This will not work for recursive constexpr functions using opaque
2237 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002238 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2239 }
2240};
2241
Mike Stumpc4c90452009-10-27 22:09:17 +00002242} // end anonymous namespace
2243
Eli Friedman4efaa272008-11-12 09:44:48 +00002244//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002245// Generic Evaluation
2246//===----------------------------------------------------------------------===//
2247namespace {
2248
Richard Smithf48fdb02011-12-09 22:58:01 +00002249// FIXME: RetTy is always bool. Remove it.
2250template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002251class ExprEvaluatorBase
2252 : public ConstStmtVisitor<Derived, RetTy> {
2253private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002254 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002255 return static_cast<Derived*>(this)->Success(V, E);
2256 }
Richard Smith51201882011-12-30 21:15:51 +00002257 RetTy DerivedZeroInitialization(const Expr *E) {
2258 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002259 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002260
2261protected:
2262 EvalInfo &Info;
2263 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2264 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2265
Richard Smithdd1f29b2011-12-12 09:28:41 +00002266 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002267 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002268 }
2269
2270 /// Report an evaluation error. This should only be called when an error is
2271 /// first discovered. When propagating an error, just return false.
2272 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002273 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002274 return false;
2275 }
2276 bool Error(const Expr *E) {
2277 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2278 }
2279
Richard Smith51201882011-12-30 21:15:51 +00002280 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002281
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002282public:
2283 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2284
2285 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002286 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002287 }
2288 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002289 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002290 }
2291
2292 RetTy VisitParenExpr(const ParenExpr *E)
2293 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2294 RetTy VisitUnaryExtension(const UnaryOperator *E)
2295 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2296 RetTy VisitUnaryPlus(const UnaryOperator *E)
2297 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2298 RetTy VisitChooseExpr(const ChooseExpr *E)
2299 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2300 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2301 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002302 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2303 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002304 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2305 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002306 // We cannot create any objects for which cleanups are required, so there is
2307 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2308 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2309 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002310
Richard Smithc216a012011-12-12 12:46:16 +00002311 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2312 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2313 return static_cast<Derived*>(this)->VisitCastExpr(E);
2314 }
2315 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2316 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2317 return static_cast<Derived*>(this)->VisitCastExpr(E);
2318 }
2319
Richard Smithe24f5fc2011-11-17 22:56:20 +00002320 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2321 switch (E->getOpcode()) {
2322 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002323 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002324
2325 case BO_Comma:
2326 VisitIgnoredValue(E->getLHS());
2327 return StmtVisitorTy::Visit(E->getRHS());
2328
2329 case BO_PtrMemD:
2330 case BO_PtrMemI: {
2331 LValue Obj;
2332 if (!HandleMemberPointerAccess(Info, E, Obj))
2333 return false;
2334 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002335 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002336 return false;
2337 return DerivedSuccess(Result, E);
2338 }
2339 }
2340 }
2341
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002342 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2343 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2344 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002345 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002346
2347 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002348 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002349 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002350
2351 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2352 }
2353
2354 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002355 bool IsBcpCall = false;
2356 // If the condition (ignoring parens) is a __builtin_constant_p call,
2357 // the result is a constant expression if it can be folded without
2358 // side-effects. This is an important GNU extension. See GCC PR38377
2359 // for discussion.
2360 if (const CallExpr *CallCE =
2361 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2362 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2363 IsBcpCall = true;
2364
2365 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2366 // constant expression; we can't check whether it's potentially foldable.
2367 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2368 return false;
2369
2370 FoldConstant Fold(Info);
2371
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002372 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002373 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002374 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002375
Richard Smithc49bd112011-10-28 17:51:58 +00002376 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Richard Smithf15fda02012-02-02 01:16:57 +00002377 if (!StmtVisitorTy::Visit(EvalExpr))
2378 return false;
2379
2380 if (IsBcpCall)
2381 Fold.Fold(Info);
2382
2383 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002384 }
2385
2386 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002387 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002388 if (!Value) {
2389 const Expr *Source = E->getSourceExpr();
2390 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002391 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002392 if (Source == E) { // sanity checking.
2393 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002394 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002395 }
2396 return StmtVisitorTy::Visit(Source);
2397 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002398 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002399 }
Richard Smithf10d9172011-10-11 21:43:33 +00002400
Richard Smithd0dccea2011-10-28 22:34:42 +00002401 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002402 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002403 QualType CalleeType = Callee->getType();
2404
Richard Smithd0dccea2011-10-28 22:34:42 +00002405 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002406 LValue *This = 0, ThisVal;
2407 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002408
Richard Smith59efe262011-11-11 04:05:33 +00002409 // Extract function decl and 'this' pointer from the callee.
2410 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002411 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002412 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2413 // Explicit bound member calls, such as x.f() or p->g();
2414 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002415 return false;
2416 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002417 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002418 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2419 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002420 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2421 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002422 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002423 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002424 return Error(Callee);
2425
2426 FD = dyn_cast<FunctionDecl>(Member);
2427 if (!FD)
2428 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002429 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002430 LValue Call;
2431 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002432 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002433
Richard Smithb4e85ed2012-01-06 16:39:00 +00002434 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002435 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002436 FD = dyn_cast_or_null<FunctionDecl>(
2437 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002438 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002439 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002440
2441 // Overloaded operator calls to member functions are represented as normal
2442 // calls with '*this' as the first argument.
2443 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2444 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002445 // FIXME: When selecting an implicit conversion for an overloaded
2446 // operator delete, we sometimes try to evaluate calls to conversion
2447 // operators without a 'this' parameter!
2448 if (Args.empty())
2449 return Error(E);
2450
Richard Smith59efe262011-11-11 04:05:33 +00002451 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2452 return false;
2453 This = &ThisVal;
2454 Args = Args.slice(1);
2455 }
2456
2457 // Don't call function pointers which have been cast to some other type.
2458 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002459 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002460 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002461 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002462
Richard Smithb04035a2012-02-01 02:39:43 +00002463 if (This && !This->checkSubobject(Info, E, CSK_This))
2464 return false;
2465
Richard Smithc1c5f272011-12-13 06:39:58 +00002466 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002467 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002468 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002469
Richard Smithc1c5f272011-12-13 06:39:58 +00002470 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002471 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2472 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002473 return false;
2474
Richard Smithb4e85ed2012-01-06 16:39:00 +00002475 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002476 }
2477
Richard Smithc49bd112011-10-28 17:51:58 +00002478 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2479 return StmtVisitorTy::Visit(E->getInitializer());
2480 }
Richard Smithf10d9172011-10-11 21:43:33 +00002481 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002482 if (E->getNumInits() == 0)
2483 return DerivedZeroInitialization(E);
2484 if (E->getNumInits() == 1)
2485 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002486 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002487 }
2488 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002489 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002490 }
2491 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002492 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002493 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002494 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002495 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002496 }
Richard Smithf10d9172011-10-11 21:43:33 +00002497
Richard Smith180f4792011-11-10 06:34:14 +00002498 /// A member expression where the object is a prvalue is itself a prvalue.
2499 RetTy VisitMemberExpr(const MemberExpr *E) {
2500 assert(!E->isArrow() && "missing call to bound member function?");
2501
2502 CCValue Val;
2503 if (!Evaluate(Val, Info, E->getBase()))
2504 return false;
2505
2506 QualType BaseTy = E->getBase()->getType();
2507
2508 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002509 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002510 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2511 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2512 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2513
Richard Smithb4e85ed2012-01-06 16:39:00 +00002514 SubobjectDesignator Designator(BaseTy);
2515 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002516
Richard Smithf48fdb02011-12-09 22:58:01 +00002517 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002518 DerivedSuccess(Val, E);
2519 }
2520
Richard Smithc49bd112011-10-28 17:51:58 +00002521 RetTy VisitCastExpr(const CastExpr *E) {
2522 switch (E->getCastKind()) {
2523 default:
2524 break;
2525
David Chisnall7a7ee302012-01-16 17:27:18 +00002526 case CK_AtomicToNonAtomic:
2527 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002528 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002529 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002530 return StmtVisitorTy::Visit(E->getSubExpr());
2531
2532 case CK_LValueToRValue: {
2533 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002534 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2535 return false;
2536 CCValue RVal;
2537 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2538 return false;
2539 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002540 }
2541 }
2542
Richard Smithf48fdb02011-12-09 22:58:01 +00002543 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002544 }
2545
Richard Smith8327fad2011-10-24 18:44:57 +00002546 /// Visit a value which is evaluated, but whose value is ignored.
2547 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002548 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002549 if (!Evaluate(Scratch, Info, E))
2550 Info.EvalStatus.HasSideEffects = true;
2551 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002552};
2553
2554}
2555
2556//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002557// Common base class for lvalue and temporary evaluation.
2558//===----------------------------------------------------------------------===//
2559namespace {
2560template<class Derived>
2561class LValueExprEvaluatorBase
2562 : public ExprEvaluatorBase<Derived, bool> {
2563protected:
2564 LValue &Result;
2565 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2566 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2567
2568 bool Success(APValue::LValueBase B) {
2569 Result.set(B);
2570 return true;
2571 }
2572
2573public:
2574 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2575 ExprEvaluatorBaseTy(Info), Result(Result) {}
2576
2577 bool Success(const CCValue &V, const Expr *E) {
2578 Result.setFrom(V);
2579 return true;
2580 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002581
Richard Smithe24f5fc2011-11-17 22:56:20 +00002582 bool VisitMemberExpr(const MemberExpr *E) {
2583 // Handle non-static data members.
2584 QualType BaseTy;
2585 if (E->isArrow()) {
2586 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2587 return false;
2588 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002589 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002590 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002591 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2592 return false;
2593 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002594 } else {
2595 if (!this->Visit(E->getBase()))
2596 return false;
2597 BaseTy = E->getBase()->getType();
2598 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002599
Richard Smithd9b02e72012-01-25 22:15:11 +00002600 const ValueDecl *MD = E->getMemberDecl();
2601 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2602 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2603 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2604 (void)BaseTy;
2605 HandleLValueMember(this->Info, E, Result, FD);
2606 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2607 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2608 } else
2609 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002610
Richard Smithd9b02e72012-01-25 22:15:11 +00002611 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002612 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002613 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002614 RefValue))
2615 return false;
2616 return Success(RefValue, E);
2617 }
2618 return true;
2619 }
2620
2621 bool VisitBinaryOperator(const BinaryOperator *E) {
2622 switch (E->getOpcode()) {
2623 default:
2624 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2625
2626 case BO_PtrMemD:
2627 case BO_PtrMemI:
2628 return HandleMemberPointerAccess(this->Info, E, Result);
2629 }
2630 }
2631
2632 bool VisitCastExpr(const CastExpr *E) {
2633 switch (E->getCastKind()) {
2634 default:
2635 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2636
2637 case CK_DerivedToBase:
2638 case CK_UncheckedDerivedToBase: {
2639 if (!this->Visit(E->getSubExpr()))
2640 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002641
2642 // Now figure out the necessary offset to add to the base LV to get from
2643 // the derived class to the base class.
2644 QualType Type = E->getSubExpr()->getType();
2645
2646 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2647 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002648 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002649 *PathI))
2650 return false;
2651 Type = (*PathI)->getType();
2652 }
2653
2654 return true;
2655 }
2656 }
2657 }
2658};
2659}
2660
2661//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002662// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002663//
2664// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2665// function designators (in C), decl references to void objects (in C), and
2666// temporaries (if building with -Wno-address-of-temporary).
2667//
2668// LValue evaluation produces values comprising a base expression of one of the
2669// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002670// - Declarations
2671// * VarDecl
2672// * FunctionDecl
2673// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002674// * CompoundLiteralExpr in C
2675// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002676// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002677// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002678// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002679// * ObjCEncodeExpr
2680// * AddrLabelExpr
2681// * BlockExpr
2682// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002683// - Locals and temporaries
2684// * Any Expr, with a Frame indicating the function in which the temporary was
2685// evaluated.
2686// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002687//===----------------------------------------------------------------------===//
2688namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002689class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002690 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002691public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002692 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2693 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002694
Richard Smithc49bd112011-10-28 17:51:58 +00002695 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2696
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002697 bool VisitDeclRefExpr(const DeclRefExpr *E);
2698 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002699 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002700 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2701 bool VisitMemberExpr(const MemberExpr *E);
2702 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2703 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002704 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002705 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2706 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002707
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002708 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002709 switch (E->getCastKind()) {
2710 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002711 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002712
Eli Friedmandb924222011-10-11 00:13:24 +00002713 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002714 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002715 if (!Visit(E->getSubExpr()))
2716 return false;
2717 Result.Designator.setInvalid();
2718 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002719
Richard Smithe24f5fc2011-11-17 22:56:20 +00002720 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002721 if (!Visit(E->getSubExpr()))
2722 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002723 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002724 }
2725 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002726
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002727 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002728
Eli Friedman4efaa272008-11-12 09:44:48 +00002729};
2730} // end anonymous namespace
2731
Richard Smithc49bd112011-10-28 17:51:58 +00002732/// Evaluate an expression as an lvalue. This can be legitimately called on
2733/// expressions which are not glvalues, in a few cases:
2734/// * function designators in C,
2735/// * "extern void" objects,
2736/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002737static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002738 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2739 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2740 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002741 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002742}
2743
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002744bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002745 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2746 return Success(FD);
2747 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002748 return VisitVarDecl(E, VD);
2749 return Error(E);
2750}
Richard Smith436c8892011-10-24 23:14:33 +00002751
Richard Smithc49bd112011-10-28 17:51:58 +00002752bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002753 if (!VD->getType()->isReferenceType()) {
2754 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002755 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002756 return true;
2757 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002758 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002759 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002760
Richard Smith47a1eed2011-10-29 20:57:55 +00002761 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002762 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2763 return false;
2764 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002765}
2766
Richard Smithbd552ef2011-10-31 05:52:43 +00002767bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2768 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002769 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002770 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002771 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2772
2773 Result.set(E, Info.CurrentCall);
2774 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2775 Result, E->GetTemporaryExpr());
2776 }
2777
2778 // Materialization of an lvalue temporary occurs when we need to force a copy
2779 // (for instance, if it's a bitfield).
2780 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2781 if (!Visit(E->GetTemporaryExpr()))
2782 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002783 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002784 Info.CurrentCall->Temporaries[E]))
2785 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002786 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002787 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002788}
2789
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002790bool
2791LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002792 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2793 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2794 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002795 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002796}
2797
Richard Smith47d21452011-12-27 12:18:28 +00002798bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2799 if (E->isTypeOperand())
2800 return Success(E);
2801 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2802 if (RD && RD->isPolymorphic()) {
2803 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2804 << E->getExprOperand()->getType()
2805 << E->getExprOperand()->getSourceRange();
2806 return false;
2807 }
2808 return Success(E);
2809}
2810
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002811bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002812 // Handle static data members.
2813 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2814 VisitIgnoredValue(E->getBase());
2815 return VisitVarDecl(E, VD);
2816 }
2817
Richard Smithd0dccea2011-10-28 22:34:42 +00002818 // Handle static member functions.
2819 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2820 if (MD->isStatic()) {
2821 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002822 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002823 }
2824 }
2825
Richard Smith180f4792011-11-10 06:34:14 +00002826 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002827 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002828}
2829
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002830bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002831 // FIXME: Deal with vectors as array subscript bases.
2832 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002833 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002834
Anders Carlsson3068d112008-11-16 19:01:22 +00002835 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002836 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002837
Anders Carlsson3068d112008-11-16 19:01:22 +00002838 APSInt Index;
2839 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002840 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002841 int64_t IndexValue
2842 = Index.isSigned() ? Index.getSExtValue()
2843 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002844
Richard Smithb4e85ed2012-01-06 16:39:00 +00002845 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002846}
Eli Friedman4efaa272008-11-12 09:44:48 +00002847
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002848bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002849 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002850}
2851
Eli Friedman4efaa272008-11-12 09:44:48 +00002852//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002853// Pointer Evaluation
2854//===----------------------------------------------------------------------===//
2855
Anders Carlssonc754aa62008-07-08 05:13:58 +00002856namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002857class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002858 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002859 LValue &Result;
2860
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002861 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002862 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002863 return true;
2864 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002865public:
Mike Stump1eb44332009-09-09 15:08:12 +00002866
John McCallefdb83e2010-05-07 21:00:08 +00002867 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002868 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002869
Richard Smith47a1eed2011-10-29 20:57:55 +00002870 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002871 Result.setFrom(V);
2872 return true;
2873 }
Richard Smith51201882011-12-30 21:15:51 +00002874 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002875 return Success((Expr*)0);
2876 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002877
John McCallefdb83e2010-05-07 21:00:08 +00002878 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002879 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002880 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002881 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002882 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002883 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002884 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002885 bool VisitCallExpr(const CallExpr *E);
2886 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002887 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002888 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002889 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002890 }
Richard Smith180f4792011-11-10 06:34:14 +00002891 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2892 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002893 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002894 Result = *Info.CurrentCall->This;
2895 return true;
2896 }
John McCall56ca35d2011-02-17 10:25:35 +00002897
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002898 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002899};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002900} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002901
John McCallefdb83e2010-05-07 21:00:08 +00002902static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002903 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002904 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002905}
2906
John McCallefdb83e2010-05-07 21:00:08 +00002907bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002908 if (E->getOpcode() != BO_Add &&
2909 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002910 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002911
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002912 const Expr *PExp = E->getLHS();
2913 const Expr *IExp = E->getRHS();
2914 if (IExp->getType()->isPointerType())
2915 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002916
Richard Smith745f5142012-01-27 01:14:48 +00002917 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
2918 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00002919 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002920
John McCallefdb83e2010-05-07 21:00:08 +00002921 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00002922 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00002923 return false;
2924 int64_t AdditionalOffset
2925 = Offset.isSigned() ? Offset.getSExtValue()
2926 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002927 if (E->getOpcode() == BO_Sub)
2928 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002929
Richard Smith180f4792011-11-10 06:34:14 +00002930 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002931 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2932 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002933}
Eli Friedman4efaa272008-11-12 09:44:48 +00002934
John McCallefdb83e2010-05-07 21:00:08 +00002935bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2936 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002937}
Mike Stump1eb44332009-09-09 15:08:12 +00002938
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002939bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2940 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002941
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002942 switch (E->getCastKind()) {
2943 default:
2944 break;
2945
John McCall2de56d12010-08-25 11:45:40 +00002946 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002947 case CK_CPointerToObjCPointerCast:
2948 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002949 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002950 if (!Visit(SubExpr))
2951 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002952 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2953 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2954 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002955 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002956 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002957 if (SubExpr->getType()->isVoidPointerType())
2958 CCEDiag(E, diag::note_constexpr_invalid_cast)
2959 << 3 << SubExpr->getType();
2960 else
2961 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2962 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002963 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002964
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002965 case CK_DerivedToBase:
2966 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002967 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002968 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002969 if (!Result.Base && Result.Offset.isZero())
2970 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002971
Richard Smith180f4792011-11-10 06:34:14 +00002972 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002973 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002974 QualType Type =
2975 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002976
Richard Smith180f4792011-11-10 06:34:14 +00002977 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002978 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002979 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2980 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002981 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002982 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002983 }
2984
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002985 return true;
2986 }
2987
Richard Smithe24f5fc2011-11-17 22:56:20 +00002988 case CK_BaseToDerived:
2989 if (!Visit(E->getSubExpr()))
2990 return false;
2991 if (!Result.Base && Result.Offset.isZero())
2992 return true;
2993 return HandleBaseToDerivedCast(Info, E, Result);
2994
Richard Smith47a1eed2011-10-29 20:57:55 +00002995 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00002996 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002997
John McCall2de56d12010-08-25 11:45:40 +00002998 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002999 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3000
Richard Smith47a1eed2011-10-29 20:57:55 +00003001 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003002 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003003 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003004
John McCallefdb83e2010-05-07 21:00:08 +00003005 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003006 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3007 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003008 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003009 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00003010 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003011 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003012 return true;
3013 } else {
3014 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003015 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00003016 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003017 }
3018 }
John McCall2de56d12010-08-25 11:45:40 +00003019 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003020 if (SubExpr->isGLValue()) {
3021 if (!EvaluateLValue(SubExpr, Result, Info))
3022 return false;
3023 } else {
3024 Result.set(SubExpr, Info.CurrentCall);
3025 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
3026 Info, Result, SubExpr))
3027 return false;
3028 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003029 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003030 if (const ConstantArrayType *CAT
3031 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3032 Result.addArray(Info, E, CAT);
3033 else
3034 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003035 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003036
John McCall2de56d12010-08-25 11:45:40 +00003037 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003038 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003039 }
3040
Richard Smithc49bd112011-10-28 17:51:58 +00003041 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003042}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003043
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003044bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003045 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003046 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003047
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003048 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003049}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003050
3051//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003052// Member Pointer Evaluation
3053//===----------------------------------------------------------------------===//
3054
3055namespace {
3056class MemberPointerExprEvaluator
3057 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3058 MemberPtr &Result;
3059
3060 bool Success(const ValueDecl *D) {
3061 Result = MemberPtr(D);
3062 return true;
3063 }
3064public:
3065
3066 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3067 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3068
3069 bool Success(const CCValue &V, const Expr *E) {
3070 Result.setFrom(V);
3071 return true;
3072 }
Richard Smith51201882011-12-30 21:15:51 +00003073 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003074 return Success((const ValueDecl*)0);
3075 }
3076
3077 bool VisitCastExpr(const CastExpr *E);
3078 bool VisitUnaryAddrOf(const UnaryOperator *E);
3079};
3080} // end anonymous namespace
3081
3082static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3083 EvalInfo &Info) {
3084 assert(E->isRValue() && E->getType()->isMemberPointerType());
3085 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3086}
3087
3088bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3089 switch (E->getCastKind()) {
3090 default:
3091 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3092
3093 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003094 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003095
3096 case CK_BaseToDerivedMemberPointer: {
3097 if (!Visit(E->getSubExpr()))
3098 return false;
3099 if (E->path_empty())
3100 return true;
3101 // Base-to-derived member pointer casts store the path in derived-to-base
3102 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3103 // the wrong end of the derived->base arc, so stagger the path by one class.
3104 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3105 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3106 PathI != PathE; ++PathI) {
3107 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3108 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3109 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003110 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003111 }
3112 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3113 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003114 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003115 return true;
3116 }
3117
3118 case CK_DerivedToBaseMemberPointer:
3119 if (!Visit(E->getSubExpr()))
3120 return false;
3121 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3122 PathE = E->path_end(); PathI != PathE; ++PathI) {
3123 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3124 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3125 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003126 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003127 }
3128 return true;
3129 }
3130}
3131
3132bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3133 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3134 // member can be formed.
3135 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3136}
3137
3138//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003139// Record Evaluation
3140//===----------------------------------------------------------------------===//
3141
3142namespace {
3143 class RecordExprEvaluator
3144 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3145 const LValue &This;
3146 APValue &Result;
3147 public:
3148
3149 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3150 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3151
3152 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003153 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00003154 }
Richard Smith51201882011-12-30 21:15:51 +00003155 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003156
Richard Smith59efe262011-11-11 04:05:33 +00003157 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003158 bool VisitInitListExpr(const InitListExpr *E);
3159 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3160 };
3161}
3162
Richard Smith51201882011-12-30 21:15:51 +00003163/// Perform zero-initialization on an object of non-union class type.
3164/// C++11 [dcl.init]p5:
3165/// To zero-initialize an object or reference of type T means:
3166/// [...]
3167/// -- if T is a (possibly cv-qualified) non-union class type,
3168/// each non-static data member and each base-class subobject is
3169/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003170static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3171 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003172 const LValue &This, APValue &Result) {
3173 assert(!RD->isUnion() && "Expected non-union class type");
3174 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3175 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3176 std::distance(RD->field_begin(), RD->field_end()));
3177
3178 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3179
3180 if (CD) {
3181 unsigned Index = 0;
3182 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003183 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003184 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3185 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003186 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3187 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003188 Result.getStructBase(Index)))
3189 return false;
3190 }
3191 }
3192
Richard Smithb4e85ed2012-01-06 16:39:00 +00003193 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3194 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003195 // -- if T is a reference type, no initialization is performed.
3196 if ((*I)->getType()->isReferenceType())
3197 continue;
3198
3199 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003200 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003201
3202 ImplicitValueInitExpr VIE((*I)->getType());
3203 if (!EvaluateConstantExpression(
3204 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3205 return false;
3206 }
3207
3208 return true;
3209}
3210
3211bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3212 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3213 if (RD->isUnion()) {
3214 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3215 // object's first non-static named data member is zero-initialized
3216 RecordDecl::field_iterator I = RD->field_begin();
3217 if (I == RD->field_end()) {
3218 Result = APValue((const FieldDecl*)0);
3219 return true;
3220 }
3221
3222 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003223 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003224 Result = APValue(*I);
3225 ImplicitValueInitExpr VIE((*I)->getType());
3226 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3227 Subobject, &VIE);
3228 }
3229
Richard Smithb4e85ed2012-01-06 16:39:00 +00003230 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003231}
3232
Richard Smith59efe262011-11-11 04:05:33 +00003233bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3234 switch (E->getCastKind()) {
3235 default:
3236 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3237
3238 case CK_ConstructorConversion:
3239 return Visit(E->getSubExpr());
3240
3241 case CK_DerivedToBase:
3242 case CK_UncheckedDerivedToBase: {
3243 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003244 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003245 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003246 if (!DerivedObject.isStruct())
3247 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003248
3249 // Derived-to-base rvalue conversion: just slice off the derived part.
3250 APValue *Value = &DerivedObject;
3251 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3252 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3253 PathE = E->path_end(); PathI != PathE; ++PathI) {
3254 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3255 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3256 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3257 RD = Base;
3258 }
3259 Result = *Value;
3260 return true;
3261 }
3262 }
3263}
3264
Richard Smith180f4792011-11-10 06:34:14 +00003265bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3266 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3267 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3268
3269 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003270 const FieldDecl *Field = E->getInitializedFieldInUnion();
3271 Result = APValue(Field);
3272 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003273 return true;
Richard Smithec789162012-01-12 18:54:33 +00003274
3275 // If the initializer list for a union does not contain any elements, the
3276 // first element of the union is value-initialized.
3277 ImplicitValueInitExpr VIE(Field->getType());
3278 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3279
Richard Smith180f4792011-11-10 06:34:14 +00003280 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003281 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003282 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003283 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003284 }
3285
3286 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3287 "initializer list for class with base classes");
3288 Result = APValue(APValue::UninitStruct(), 0,
3289 std::distance(RD->field_begin(), RD->field_end()));
3290 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003291 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003292 for (RecordDecl::field_iterator Field = RD->field_begin(),
3293 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3294 // Anonymous bit-fields are not considered members of the class for
3295 // purposes of aggregate initialization.
3296 if (Field->isUnnamedBitfield())
3297 continue;
3298
3299 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003300
Richard Smith745f5142012-01-27 01:14:48 +00003301 bool HaveInit = ElementNo < E->getNumInits();
3302
3303 // FIXME: Diagnostics here should point to the end of the initializer
3304 // list, not the start.
3305 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3306 *Field, &Layout);
3307
3308 // Perform an implicit value-initialization for members beyond the end of
3309 // the initializer list.
3310 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3311
3312 if (!EvaluateConstantExpression(
3313 Result.getStructField((*Field)->getFieldIndex()),
3314 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3315 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003316 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003317 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003318 }
3319 }
3320
Richard Smith745f5142012-01-27 01:14:48 +00003321 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003322}
3323
3324bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3325 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003326 bool ZeroInit = E->requiresZeroInitialization();
3327 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003328 // If we've already performed zero-initialization, we're already done.
3329 if (!Result.isUninit())
3330 return true;
3331
Richard Smith51201882011-12-30 21:15:51 +00003332 if (ZeroInit)
3333 return ZeroInitialization(E);
3334
Richard Smith61802452011-12-22 02:22:31 +00003335 const CXXRecordDecl *RD = FD->getParent();
3336 if (RD->isUnion())
3337 Result = APValue((FieldDecl*)0);
3338 else
3339 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3340 std::distance(RD->field_begin(), RD->field_end()));
3341 return true;
3342 }
3343
Richard Smith180f4792011-11-10 06:34:14 +00003344 const FunctionDecl *Definition = 0;
3345 FD->getBody(Definition);
3346
Richard Smithc1c5f272011-12-13 06:39:58 +00003347 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3348 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003349
Richard Smith610a60c2012-01-10 04:32:03 +00003350 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003351 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003352 if (const MaterializeTemporaryExpr *ME
3353 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3354 return Visit(ME->GetTemporaryExpr());
3355
Richard Smith51201882011-12-30 21:15:51 +00003356 if (ZeroInit && !ZeroInitialization(E))
3357 return false;
3358
Richard Smith180f4792011-11-10 06:34:14 +00003359 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003360 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003361 cast<CXXConstructorDecl>(Definition), Info,
3362 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003363}
3364
3365static bool EvaluateRecord(const Expr *E, const LValue &This,
3366 APValue &Result, EvalInfo &Info) {
3367 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003368 "can't evaluate expression as a record rvalue");
3369 return RecordExprEvaluator(Info, This, Result).Visit(E);
3370}
3371
3372//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003373// Temporary Evaluation
3374//
3375// Temporaries are represented in the AST as rvalues, but generally behave like
3376// lvalues. The full-object of which the temporary is a subobject is implicitly
3377// materialized so that a reference can bind to it.
3378//===----------------------------------------------------------------------===//
3379namespace {
3380class TemporaryExprEvaluator
3381 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3382public:
3383 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3384 LValueExprEvaluatorBaseTy(Info, Result) {}
3385
3386 /// Visit an expression which constructs the value of this temporary.
3387 bool VisitConstructExpr(const Expr *E) {
3388 Result.set(E, Info.CurrentCall);
3389 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3390 Result, E);
3391 }
3392
3393 bool VisitCastExpr(const CastExpr *E) {
3394 switch (E->getCastKind()) {
3395 default:
3396 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3397
3398 case CK_ConstructorConversion:
3399 return VisitConstructExpr(E->getSubExpr());
3400 }
3401 }
3402 bool VisitInitListExpr(const InitListExpr *E) {
3403 return VisitConstructExpr(E);
3404 }
3405 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3406 return VisitConstructExpr(E);
3407 }
3408 bool VisitCallExpr(const CallExpr *E) {
3409 return VisitConstructExpr(E);
3410 }
3411};
3412} // end anonymous namespace
3413
3414/// Evaluate an expression of record type as a temporary.
3415static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003416 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003417 return TemporaryExprEvaluator(Info, Result).Visit(E);
3418}
3419
3420//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003421// Vector Evaluation
3422//===----------------------------------------------------------------------===//
3423
3424namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003425 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003426 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3427 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003428 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Richard Smith07fc6572011-10-22 21:10:00 +00003430 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3431 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003432
Richard Smith07fc6572011-10-22 21:10:00 +00003433 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3434 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3435 // FIXME: remove this APValue copy.
3436 Result = APValue(V.data(), V.size());
3437 return true;
3438 }
Richard Smith69c2c502011-11-04 05:33:44 +00003439 bool Success(const CCValue &V, const Expr *E) {
3440 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003441 Result = V;
3442 return true;
3443 }
Richard Smith51201882011-12-30 21:15:51 +00003444 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003445
Richard Smith07fc6572011-10-22 21:10:00 +00003446 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003447 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003448 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003449 bool VisitInitListExpr(const InitListExpr *E);
3450 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003451 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003452 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003453 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003454 };
3455} // end anonymous namespace
3456
3457static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003458 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003459 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003460}
3461
Richard Smith07fc6572011-10-22 21:10:00 +00003462bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3463 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003464 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003465
Richard Smithd62ca372011-12-06 22:44:34 +00003466 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003467 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003468
Eli Friedman46a52322011-03-25 00:43:55 +00003469 switch (E->getCastKind()) {
3470 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003471 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003472 if (SETy->isIntegerType()) {
3473 APSInt IntResult;
3474 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003475 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003476 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003477 } else if (SETy->isRealFloatingType()) {
3478 APFloat F(0.0);
3479 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003480 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003481 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003482 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003483 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003484 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003485
3486 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003487 SmallVector<APValue, 4> Elts(NElts, Val);
3488 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003489 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003490 case CK_BitCast: {
3491 // Evaluate the operand into an APInt we can extract from.
3492 llvm::APInt SValInt;
3493 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3494 return false;
3495 // Extract the elements
3496 QualType EltTy = VTy->getElementType();
3497 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3498 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3499 SmallVector<APValue, 4> Elts;
3500 if (EltTy->isRealFloatingType()) {
3501 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3502 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3503 unsigned FloatEltSize = EltSize;
3504 if (&Sem == &APFloat::x87DoubleExtended)
3505 FloatEltSize = 80;
3506 for (unsigned i = 0; i < NElts; i++) {
3507 llvm::APInt Elt;
3508 if (BigEndian)
3509 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3510 else
3511 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3512 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3513 }
3514 } else if (EltTy->isIntegerType()) {
3515 for (unsigned i = 0; i < NElts; i++) {
3516 llvm::APInt Elt;
3517 if (BigEndian)
3518 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3519 else
3520 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3521 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3522 }
3523 } else {
3524 return Error(E);
3525 }
3526 return Success(Elts, E);
3527 }
Eli Friedman46a52322011-03-25 00:43:55 +00003528 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003529 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003530 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003531}
3532
Richard Smith07fc6572011-10-22 21:10:00 +00003533bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003534VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003535 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003536 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003537 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003538
Nate Begeman59b5da62009-01-18 03:20:47 +00003539 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003540 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003541
Eli Friedman3edd5a92012-01-03 23:24:20 +00003542 // The number of initializers can be less than the number of
3543 // vector elements. For OpenCL, this can be due to nested vector
3544 // initialization. For GCC compatibility, missing trailing elements
3545 // should be initialized with zeroes.
3546 unsigned CountInits = 0, CountElts = 0;
3547 while (CountElts < NumElements) {
3548 // Handle nested vector initialization.
3549 if (CountInits < NumInits
3550 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3551 APValue v;
3552 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3553 return Error(E);
3554 unsigned vlen = v.getVectorLength();
3555 for (unsigned j = 0; j < vlen; j++)
3556 Elements.push_back(v.getVectorElt(j));
3557 CountElts += vlen;
3558 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003559 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003560 if (CountInits < NumInits) {
3561 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3562 return Error(E);
3563 } else // trailing integer zero.
3564 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3565 Elements.push_back(APValue(sInt));
3566 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003567 } else {
3568 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003569 if (CountInits < NumInits) {
3570 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3571 return Error(E);
3572 } else // trailing float zero.
3573 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3574 Elements.push_back(APValue(f));
3575 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003576 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003577 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003578 }
Richard Smith07fc6572011-10-22 21:10:00 +00003579 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003580}
3581
Richard Smith07fc6572011-10-22 21:10:00 +00003582bool
Richard Smith51201882011-12-30 21:15:51 +00003583VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003584 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003585 QualType EltTy = VT->getElementType();
3586 APValue ZeroElement;
3587 if (EltTy->isIntegerType())
3588 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3589 else
3590 ZeroElement =
3591 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3592
Chris Lattner5f9e2722011-07-23 10:55:15 +00003593 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003594 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003595}
3596
Richard Smith07fc6572011-10-22 21:10:00 +00003597bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003598 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003599 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003600}
3601
Nate Begeman59b5da62009-01-18 03:20:47 +00003602//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003603// Array Evaluation
3604//===----------------------------------------------------------------------===//
3605
3606namespace {
3607 class ArrayExprEvaluator
3608 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003609 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003610 APValue &Result;
3611 public:
3612
Richard Smith180f4792011-11-10 06:34:14 +00003613 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3614 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003615
3616 bool Success(const APValue &V, const Expr *E) {
3617 assert(V.isArray() && "Expected array type");
3618 Result = V;
3619 return true;
3620 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003621
Richard Smith51201882011-12-30 21:15:51 +00003622 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003623 const ConstantArrayType *CAT =
3624 Info.Ctx.getAsConstantArrayType(E->getType());
3625 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003626 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003627
3628 Result = APValue(APValue::UninitArray(), 0,
3629 CAT->getSize().getZExtValue());
3630 if (!Result.hasArrayFiller()) return true;
3631
Richard Smith51201882011-12-30 21:15:51 +00003632 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003633 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003634 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003635 ImplicitValueInitExpr VIE(CAT->getElementType());
3636 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3637 Subobject, &VIE);
3638 }
3639
Richard Smithcc5d4f62011-11-07 09:22:26 +00003640 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003641 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003642 };
3643} // end anonymous namespace
3644
Richard Smith180f4792011-11-10 06:34:14 +00003645static bool EvaluateArray(const Expr *E, const LValue &This,
3646 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003647 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003648 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003649}
3650
3651bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3652 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3653 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003654 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003655
Richard Smith974c5f92011-12-22 01:07:19 +00003656 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3657 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003658 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003659 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3660 LValue LV;
3661 if (!EvaluateLValue(E->getInit(0), LV, Info))
3662 return false;
3663 uint64_t NumElements = CAT->getSize().getZExtValue();
3664 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3665
3666 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003667 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003668 for (uint64_t I = 0; I < NumElements; ++I) {
3669 CCValue Char;
3670 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
Richard Smith745f5142012-01-27 01:14:48 +00003671 CAT->getElementType(), LV, Char) ||
3672 !CheckConstantExpression(Info, E->getInit(0), Char,
3673 Result.getArrayInitializedElt(I)) ||
3674 !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
Richard Smithb4e85ed2012-01-06 16:39:00 +00003675 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003676 return false;
3677 }
3678 return true;
3679 }
3680
Richard Smith745f5142012-01-27 01:14:48 +00003681 bool Success = true;
3682
Richard Smithcc5d4f62011-11-07 09:22:26 +00003683 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3684 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003685 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003686 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003687 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003688 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003689 I != End; ++I, ++Index) {
3690 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
Richard Smith745f5142012-01-27 01:14:48 +00003691 Info, Subobject, cast<Expr>(*I)) ||
3692 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3693 CAT->getElementType(), 1)) {
3694 if (!Info.keepEvaluatingAfterFailure())
3695 return false;
3696 Success = false;
3697 }
Richard Smith180f4792011-11-10 06:34:14 +00003698 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003699
Richard Smith745f5142012-01-27 01:14:48 +00003700 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003701 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003702 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3703 // but sometimes does:
3704 // struct S { constexpr S() : p(&p) {} void *p; };
3705 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003706 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith745f5142012-01-27 01:14:48 +00003707 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003708}
3709
Richard Smithe24f5fc2011-11-17 22:56:20 +00003710bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3711 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3712 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003713 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003714
Richard Smithec789162012-01-12 18:54:33 +00003715 bool HadZeroInit = !Result.isUninit();
3716 if (!HadZeroInit)
3717 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003718 if (!Result.hasArrayFiller())
3719 return true;
3720
3721 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003722
Richard Smith51201882011-12-30 21:15:51 +00003723 bool ZeroInit = E->requiresZeroInitialization();
3724 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003725 if (HadZeroInit)
3726 return true;
3727
Richard Smith51201882011-12-30 21:15:51 +00003728 if (ZeroInit) {
3729 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003730 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003731 ImplicitValueInitExpr VIE(CAT->getElementType());
3732 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3733 Subobject, &VIE);
3734 }
3735
Richard Smith61802452011-12-22 02:22:31 +00003736 const CXXRecordDecl *RD = FD->getParent();
3737 if (RD->isUnion())
3738 Result.getArrayFiller() = APValue((FieldDecl*)0);
3739 else
3740 Result.getArrayFiller() =
3741 APValue(APValue::UninitStruct(), RD->getNumBases(),
3742 std::distance(RD->field_begin(), RD->field_end()));
3743 return true;
3744 }
3745
Richard Smithe24f5fc2011-11-17 22:56:20 +00003746 const FunctionDecl *Definition = 0;
3747 FD->getBody(Definition);
3748
Richard Smithc1c5f272011-12-13 06:39:58 +00003749 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3750 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003751
3752 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3753 // but sometimes does:
3754 // struct S { constexpr S() : p(&p) {} void *p; };
3755 // S s[10];
3756 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003757 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003758
Richard Smithec789162012-01-12 18:54:33 +00003759 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003760 ImplicitValueInitExpr VIE(CAT->getElementType());
3761 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3762 &VIE))
3763 return false;
3764 }
3765
Richard Smithe24f5fc2011-11-17 22:56:20 +00003766 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003767 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003768 cast<CXXConstructorDecl>(Definition),
3769 Info, Result.getArrayFiller());
3770}
3771
Richard Smithcc5d4f62011-11-07 09:22:26 +00003772//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003773// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003774//
3775// As a GNU extension, we support casting pointers to sufficiently-wide integer
3776// types and back in constant folding. Integer values are thus represented
3777// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003778//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003779
3780namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003781class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003782 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003783 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003784public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003785 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003786 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003787
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003788 bool Success(const llvm::APSInt &SI, const Expr *E) {
3789 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003790 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003791 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003792 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003793 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003794 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003795 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003796 return true;
3797 }
3798
Daniel Dunbar131eb432009-02-19 09:06:44 +00003799 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003800 assert(E->getType()->isIntegralOrEnumerationType() &&
3801 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003802 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003803 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003804 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003805 Result.getInt().setIsUnsigned(
3806 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003807 return true;
3808 }
3809
3810 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003811 assert(E->getType()->isIntegralOrEnumerationType() &&
3812 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003813 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003814 return true;
3815 }
3816
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003817 bool Success(CharUnits Size, const Expr *E) {
3818 return Success(Size.getQuantity(), E);
3819 }
3820
Richard Smith47a1eed2011-10-29 20:57:55 +00003821 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003822 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003823 Result = V;
3824 return true;
3825 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003826 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003827 }
Mike Stump1eb44332009-09-09 15:08:12 +00003828
Richard Smith51201882011-12-30 21:15:51 +00003829 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003830
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003831 //===--------------------------------------------------------------------===//
3832 // Visitor Methods
3833 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003834
Chris Lattner4c4867e2008-07-12 00:38:25 +00003835 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003836 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003837 }
3838 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003839 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003840 }
Eli Friedman04309752009-11-24 05:28:59 +00003841
3842 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3843 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003844 if (CheckReferencedDecl(E, E->getDecl()))
3845 return true;
3846
3847 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003848 }
3849 bool VisitMemberExpr(const MemberExpr *E) {
3850 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003851 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003852 return true;
3853 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003854
3855 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003856 }
3857
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003858 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003859 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003860 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003861 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003862
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003863 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003864 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003865
Anders Carlsson3068d112008-11-16 19:01:22 +00003866 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003867 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003868 }
Mike Stump1eb44332009-09-09 15:08:12 +00003869
Richard Smithf10d9172011-10-11 21:43:33 +00003870 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003871 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003872 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003873 }
3874
Sebastian Redl64b45f72009-01-05 20:52:13 +00003875 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003876 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003877 }
3878
Francois Pichet6ad6f282010-12-07 00:08:36 +00003879 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3880 return Success(E->getValue(), E);
3881 }
3882
John Wiegley21ff2e52011-04-28 00:16:57 +00003883 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3884 return Success(E->getValue(), E);
3885 }
3886
John Wiegley55262202011-04-25 06:54:41 +00003887 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3888 return Success(E->getValue(), E);
3889 }
3890
Eli Friedman722c7172009-02-28 03:59:05 +00003891 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003892 bool VisitUnaryImag(const UnaryOperator *E);
3893
Sebastian Redl295995c2010-09-10 20:55:47 +00003894 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003895 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003896
Chris Lattnerfcee0012008-07-11 21:24:13 +00003897private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003898 CharUnits GetAlignOfExpr(const Expr *E);
3899 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003900 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003901 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003902 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003903};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003904} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003905
Richard Smithc49bd112011-10-28 17:51:58 +00003906/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3907/// produce either the integer value or a pointer.
3908///
3909/// GCC has a heinous extension which folds casts between pointer types and
3910/// pointer-sized integral types. We support this by allowing the evaluation of
3911/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3912/// Some simple arithmetic on such values is supported (they are treated much
3913/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003914static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003915 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003916 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003917 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003918}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003919
Richard Smithf48fdb02011-12-09 22:58:01 +00003920static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003921 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003922 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003923 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003924 if (!Val.isInt()) {
3925 // FIXME: It would be better to produce the diagnostic for casting
3926 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003927 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003928 return false;
3929 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003930 Result = Val.getInt();
3931 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003932}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003933
Richard Smithf48fdb02011-12-09 22:58:01 +00003934/// Check whether the given declaration can be directly converted to an integral
3935/// rvalue. If not, no diagnostic is produced; there are other things we can
3936/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003937bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003938 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003939 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003940 // Check for signedness/width mismatches between E type and ECD value.
3941 bool SameSign = (ECD->getInitVal().isSigned()
3942 == E->getType()->isSignedIntegerOrEnumerationType());
3943 bool SameWidth = (ECD->getInitVal().getBitWidth()
3944 == Info.Ctx.getIntWidth(E->getType()));
3945 if (SameSign && SameWidth)
3946 return Success(ECD->getInitVal(), E);
3947 else {
3948 // Get rid of mismatch (otherwise Success assertions will fail)
3949 // by computing a new value matching the type of E.
3950 llvm::APSInt Val = ECD->getInitVal();
3951 if (!SameSign)
3952 Val.setIsSigned(!ECD->getInitVal().isSigned());
3953 if (!SameWidth)
3954 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3955 return Success(Val, E);
3956 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003957 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003958 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003959}
3960
Chris Lattnera4d55d82008-10-06 06:40:35 +00003961/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3962/// as GCC.
3963static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3964 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003965 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003966 enum gcc_type_class {
3967 no_type_class = -1,
3968 void_type_class, integer_type_class, char_type_class,
3969 enumeral_type_class, boolean_type_class,
3970 pointer_type_class, reference_type_class, offset_type_class,
3971 real_type_class, complex_type_class,
3972 function_type_class, method_type_class,
3973 record_type_class, union_type_class,
3974 array_type_class, string_type_class,
3975 lang_type_class
3976 };
Mike Stump1eb44332009-09-09 15:08:12 +00003977
3978 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003979 // ideal, however it is what gcc does.
3980 if (E->getNumArgs() == 0)
3981 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003982
Chris Lattnera4d55d82008-10-06 06:40:35 +00003983 QualType ArgTy = E->getArg(0)->getType();
3984 if (ArgTy->isVoidType())
3985 return void_type_class;
3986 else if (ArgTy->isEnumeralType())
3987 return enumeral_type_class;
3988 else if (ArgTy->isBooleanType())
3989 return boolean_type_class;
3990 else if (ArgTy->isCharType())
3991 return string_type_class; // gcc doesn't appear to use char_type_class
3992 else if (ArgTy->isIntegerType())
3993 return integer_type_class;
3994 else if (ArgTy->isPointerType())
3995 return pointer_type_class;
3996 else if (ArgTy->isReferenceType())
3997 return reference_type_class;
3998 else if (ArgTy->isRealType())
3999 return real_type_class;
4000 else if (ArgTy->isComplexType())
4001 return complex_type_class;
4002 else if (ArgTy->isFunctionType())
4003 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004004 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004005 return record_type_class;
4006 else if (ArgTy->isUnionType())
4007 return union_type_class;
4008 else if (ArgTy->isArrayType())
4009 return array_type_class;
4010 else if (ArgTy->isUnionType())
4011 return union_type_class;
4012 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004013 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004014}
4015
Richard Smith80d4b552011-12-28 19:48:30 +00004016/// EvaluateBuiltinConstantPForLValue - Determine the result of
4017/// __builtin_constant_p when applied to the given lvalue.
4018///
4019/// An lvalue is only "constant" if it is a pointer or reference to the first
4020/// character of a string literal.
4021template<typename LValue>
4022static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4023 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4024 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4025}
4026
4027/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4028/// GCC as we can manage.
4029static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4030 QualType ArgType = Arg->getType();
4031
4032 // __builtin_constant_p always has one operand. The rules which gcc follows
4033 // are not precisely documented, but are as follows:
4034 //
4035 // - If the operand is of integral, floating, complex or enumeration type,
4036 // and can be folded to a known value of that type, it returns 1.
4037 // - If the operand and can be folded to a pointer to the first character
4038 // of a string literal (or such a pointer cast to an integral type), it
4039 // returns 1.
4040 //
4041 // Otherwise, it returns 0.
4042 //
4043 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4044 // its support for this does not currently work.
4045 if (ArgType->isIntegralOrEnumerationType()) {
4046 Expr::EvalResult Result;
4047 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4048 return false;
4049
4050 APValue &V = Result.Val;
4051 if (V.getKind() == APValue::Int)
4052 return true;
4053
4054 return EvaluateBuiltinConstantPForLValue(V);
4055 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4056 return Arg->isEvaluatable(Ctx);
4057 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4058 LValue LV;
4059 Expr::EvalStatus Status;
4060 EvalInfo Info(Ctx, Status);
4061 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4062 : EvaluatePointer(Arg, LV, Info)) &&
4063 !Status.HasSideEffects)
4064 return EvaluateBuiltinConstantPForLValue(LV);
4065 }
4066
4067 // Anything else isn't considered to be sufficiently constant.
4068 return false;
4069}
4070
John McCall42c8f872010-05-10 23:27:23 +00004071/// Retrieves the "underlying object type" of the given expression,
4072/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004073QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4074 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4075 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004076 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004077 } else if (const Expr *E = B.get<const Expr*>()) {
4078 if (isa<CompoundLiteralExpr>(E))
4079 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004080 }
4081
4082 return QualType();
4083}
4084
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004085bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004086 // TODO: Perhaps we should let LLVM lower this?
4087 LValue Base;
4088 if (!EvaluatePointer(E->getArg(0), Base, Info))
4089 return false;
4090
4091 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004092 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004093
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004094 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004095 if (T.isNull() ||
4096 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004097 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004098 T->isVariablyModifiedType() ||
4099 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004100 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004101
4102 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4103 CharUnits Offset = Base.getLValueOffset();
4104
4105 if (!Offset.isNegative() && Offset <= Size)
4106 Size -= Offset;
4107 else
4108 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004109 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004110}
4111
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004112bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004113 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004114 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004115 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004116
4117 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004118 if (TryEvaluateBuiltinObjectSize(E))
4119 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004120
Eric Christopherb2aaf512010-01-19 22:58:35 +00004121 // If evaluating the argument has side-effects we can't determine
4122 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004123 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004124 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004125 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004126 return Success(0, E);
4127 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004128
Richard Smithf48fdb02011-12-09 22:58:01 +00004129 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004130 }
4131
Chris Lattner019f4e82008-10-06 05:28:25 +00004132 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004133 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004134
Richard Smith80d4b552011-12-28 19:48:30 +00004135 case Builtin::BI__builtin_constant_p:
4136 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004137
Chris Lattner21fb98e2009-09-23 06:06:36 +00004138 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004139 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004140 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004141 return Success(Operand, E);
4142 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004143
4144 case Builtin::BI__builtin_expect:
4145 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004146
Douglas Gregor5726d402010-09-10 06:27:15 +00004147 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004148 // A call to strlen is not a constant expression.
4149 if (Info.getLangOpts().CPlusPlus0x)
4150 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4151 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4152 else
4153 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4154 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004155 case Builtin::BI__builtin_strlen:
4156 // As an extension, we support strlen() and __builtin_strlen() as constant
4157 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004158 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004159 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4160 // The string literal may have embedded null characters. Find the first
4161 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004162 StringRef Str = S->getString();
4163 StringRef::size_type Pos = Str.find(0);
4164 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004165 Str = Str.substr(0, Pos);
4166
4167 return Success(Str.size(), E);
4168 }
4169
Richard Smithf48fdb02011-12-09 22:58:01 +00004170 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004171
4172 case Builtin::BI__atomic_is_lock_free: {
4173 APSInt SizeVal;
4174 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4175 return false;
4176
4177 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4178 // of two less than the maximum inline atomic width, we know it is
4179 // lock-free. If the size isn't a power of two, or greater than the
4180 // maximum alignment where we promote atomics, we know it is not lock-free
4181 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4182 // the answer can only be determined at runtime; for example, 16-byte
4183 // atomics have lock-free implementations on some, but not all,
4184 // x86-64 processors.
4185
4186 // Check power-of-two.
4187 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4188 if (!Size.isPowerOfTwo())
4189#if 0
4190 // FIXME: Suppress this folding until the ABI for the promotion width
4191 // settles.
4192 return Success(0, E);
4193#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004194 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004195#endif
4196
4197#if 0
4198 // Check against promotion width.
4199 // FIXME: Suppress this folding until the ABI for the promotion width
4200 // settles.
4201 unsigned PromoteWidthBits =
4202 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4203 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4204 return Success(0, E);
4205#endif
4206
4207 // Check against inlining width.
4208 unsigned InlineWidthBits =
4209 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4210 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4211 return Success(1, E);
4212
Richard Smithf48fdb02011-12-09 22:58:01 +00004213 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004214 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004215 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004216}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004217
Richard Smith625b8072011-10-31 01:37:14 +00004218static bool HasSameBase(const LValue &A, const LValue &B) {
4219 if (!A.getLValueBase())
4220 return !B.getLValueBase();
4221 if (!B.getLValueBase())
4222 return false;
4223
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004224 if (A.getLValueBase().getOpaqueValue() !=
4225 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004226 const Decl *ADecl = GetLValueBaseDecl(A);
4227 if (!ADecl)
4228 return false;
4229 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004230 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004231 return false;
4232 }
4233
4234 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00004235 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00004236}
4237
Richard Smith7b48a292012-02-01 05:53:12 +00004238/// Perform the given integer operation, which is known to need at most BitWidth
4239/// bits, and check for overflow in the original type (if that type was not an
4240/// unsigned type).
4241template<typename Operation>
4242static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4243 const APSInt &LHS, const APSInt &RHS,
4244 unsigned BitWidth, Operation Op) {
4245 if (LHS.isUnsigned())
4246 return Op(LHS, RHS);
4247
4248 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4249 APSInt Result = Value.trunc(LHS.getBitWidth());
4250 if (Result.extend(BitWidth) != Value)
4251 HandleOverflow(Info, E, Value, E->getType());
4252 return Result;
4253}
4254
Chris Lattnerb542afe2008-07-11 19:10:17 +00004255bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004256 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004257 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004258
John McCall2de56d12010-08-25 11:45:40 +00004259 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004260 VisitIgnoredValue(E->getLHS());
4261 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004262 }
4263
4264 if (E->isLogicalOp()) {
4265 // These need to be handled specially because the operands aren't
4266 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004267 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004268
Richard Smithc49bd112011-10-28 17:51:58 +00004269 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004270 // We were able to evaluate the LHS, see if we can get away with not
4271 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004272 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004273 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004274
Richard Smithc49bd112011-10-28 17:51:58 +00004275 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004276 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004277 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004278 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004279 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004280 }
4281 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004282 // FIXME: If both evaluations fail, we should produce the diagnostic from
4283 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4284 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004285 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004286 // We can't evaluate the LHS; however, sometimes the result
4287 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004288 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004289 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004290 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004291 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004292
4293 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004294 }
4295 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004296 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004297
Eli Friedmana6afa762008-11-13 06:09:17 +00004298 return false;
4299 }
4300
Anders Carlsson286f85e2008-11-16 07:17:21 +00004301 QualType LHSTy = E->getLHS()->getType();
4302 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004303
4304 if (LHSTy->isAnyComplexType()) {
4305 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004306 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004307
Richard Smith745f5142012-01-27 01:14:48 +00004308 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4309 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004310 return false;
4311
Richard Smith745f5142012-01-27 01:14:48 +00004312 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004313 return false;
4314
4315 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004316 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004317 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004318 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004319 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4320
John McCall2de56d12010-08-25 11:45:40 +00004321 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004322 return Success((CR_r == APFloat::cmpEqual &&
4323 CR_i == APFloat::cmpEqual), E);
4324 else {
John McCall2de56d12010-08-25 11:45:40 +00004325 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004326 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004327 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004328 CR_r == APFloat::cmpLessThan ||
4329 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004330 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004331 CR_i == APFloat::cmpLessThan ||
4332 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004333 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004334 } else {
John McCall2de56d12010-08-25 11:45:40 +00004335 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004336 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4337 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4338 else {
John McCall2de56d12010-08-25 11:45:40 +00004339 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004340 "Invalid compex comparison.");
4341 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4342 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4343 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004344 }
4345 }
Mike Stump1eb44332009-09-09 15:08:12 +00004346
Anders Carlsson286f85e2008-11-16 07:17:21 +00004347 if (LHSTy->isRealFloatingType() &&
4348 RHSTy->isRealFloatingType()) {
4349 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004350
Richard Smith745f5142012-01-27 01:14:48 +00004351 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4352 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004353 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004354
Richard Smith745f5142012-01-27 01:14:48 +00004355 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004356 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004357
Anders Carlsson286f85e2008-11-16 07:17:21 +00004358 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004359
Anders Carlsson286f85e2008-11-16 07:17:21 +00004360 switch (E->getOpcode()) {
4361 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004362 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004363 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004364 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004365 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004366 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004367 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004368 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004369 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004370 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004371 E);
John McCall2de56d12010-08-25 11:45:40 +00004372 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004373 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004374 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004375 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004376 || CR == APFloat::cmpLessThan
4377 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004378 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004379 }
Mike Stump1eb44332009-09-09 15:08:12 +00004380
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004381 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004382 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004383 LValue LHSValue, RHSValue;
4384
4385 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4386 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004387 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004388
Richard Smith745f5142012-01-27 01:14:48 +00004389 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004390 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004391
Richard Smith625b8072011-10-31 01:37:14 +00004392 // Reject differing bases from the normal codepath; we special-case
4393 // comparisons to null.
4394 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004395 if (E->getOpcode() == BO_Sub) {
4396 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004397 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4398 return false;
4399 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4400 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4401 if (!LHSExpr || !RHSExpr)
4402 return false;
4403 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4404 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4405 if (!LHSAddrExpr || !RHSAddrExpr)
4406 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004407 // Make sure both labels come from the same function.
4408 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4409 RHSAddrExpr->getLabel()->getDeclContext())
4410 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004411 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4412 return true;
4413 }
Richard Smith9e36b532011-10-31 05:11:32 +00004414 // Inequalities and subtractions between unrelated pointers have
4415 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004416 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004417 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004418 // A constant address may compare equal to the address of a symbol.
4419 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004420 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004421 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4422 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004423 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004424 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004425 // distinct addresses. In clang, the result of such a comparison is
4426 // unspecified, so it is not a constant expression. However, we do know
4427 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004428 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4429 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004430 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004431 // We can't tell whether weak symbols will end up pointing to the same
4432 // object.
4433 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004434 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004435 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004436 // (Note that clang defaults to -fmerge-all-constants, which can
4437 // lead to inconsistent results for comparisons involving the address
4438 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004439 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004440 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004441
Richard Smith15efc4d2012-02-01 08:10:20 +00004442 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4443 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4444
Richard Smithf15fda02012-02-02 01:16:57 +00004445 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4446 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4447
John McCall2de56d12010-08-25 11:45:40 +00004448 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004449 // C++11 [expr.add]p6:
4450 // Unless both pointers point to elements of the same array object, or
4451 // one past the last element of the array object, the behavior is
4452 // undefined.
4453 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4454 !AreElementsOfSameArray(getType(LHSValue.Base),
4455 LHSDesignator, RHSDesignator))
4456 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4457
Chris Lattner4992bdd2010-04-20 17:13:14 +00004458 QualType Type = E->getLHS()->getType();
4459 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004460
Richard Smith180f4792011-11-10 06:34:14 +00004461 CharUnits ElementSize;
4462 if (!HandleSizeof(Info, ElementType, ElementSize))
4463 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004464
Richard Smith15efc4d2012-02-01 08:10:20 +00004465 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4466 // and produce incorrect results when it overflows. Such behavior
4467 // appears to be non-conforming, but is common, so perhaps we should
4468 // assume the standard intended for such cases to be undefined behavior
4469 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004470
Richard Smith15efc4d2012-02-01 08:10:20 +00004471 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4472 // overflow in the final conversion to ptrdiff_t.
4473 APSInt LHS(
4474 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4475 APSInt RHS(
4476 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4477 APSInt ElemSize(
4478 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4479 APSInt TrueResult = (LHS - RHS) / ElemSize;
4480 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4481
4482 if (Result.extend(65) != TrueResult)
4483 HandleOverflow(Info, E, TrueResult, E->getType());
4484 return Success(Result, E);
4485 }
Richard Smith82f28582012-01-31 06:41:30 +00004486
4487 // C++11 [expr.rel]p3:
4488 // Pointers to void (after pointer conversions) can be compared, with a
4489 // result defined as follows: If both pointers represent the same
4490 // address or are both the null pointer value, the result is true if the
4491 // operator is <= or >= and false otherwise; otherwise the result is
4492 // unspecified.
4493 // We interpret this as applying to pointers to *cv* void.
4494 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004495 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004496 CCEDiag(E, diag::note_constexpr_void_comparison);
4497
Richard Smithf15fda02012-02-02 01:16:57 +00004498 // C++11 [expr.rel]p2:
4499 // - If two pointers point to non-static data members of the same object,
4500 // or to subobjects or array elements fo such members, recursively, the
4501 // pointer to the later declared member compares greater provided the
4502 // two members have the same access control and provided their class is
4503 // not a union.
4504 // [...]
4505 // - Otherwise pointer comparisons are unspecified.
4506 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4507 E->isRelationalOp()) {
4508 bool WasArrayIndex;
4509 unsigned Mismatch =
4510 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4511 RHSDesignator, WasArrayIndex);
4512 // At the point where the designators diverge, the comparison has a
4513 // specified value if:
4514 // - we are comparing array indices
4515 // - we are comparing fields of a union, or fields with the same access
4516 // Otherwise, the result is unspecified and thus the comparison is not a
4517 // constant expression.
4518 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4519 Mismatch < RHSDesignator.Entries.size()) {
4520 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4521 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4522 if (!LF && !RF)
4523 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4524 else if (!LF)
4525 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4526 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4527 << RF->getParent() << RF;
4528 else if (!RF)
4529 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4530 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4531 << LF->getParent() << LF;
4532 else if (!LF->getParent()->isUnion() &&
4533 LF->getAccess() != RF->getAccess())
4534 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4535 << LF << LF->getAccess() << RF << RF->getAccess()
4536 << LF->getParent();
4537 }
4538 }
4539
Richard Smith625b8072011-10-31 01:37:14 +00004540 switch (E->getOpcode()) {
4541 default: llvm_unreachable("missing comparison operator");
4542 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4543 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4544 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4545 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4546 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4547 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004548 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004549 }
4550 }
Richard Smithb02e4622012-02-01 01:42:44 +00004551
4552 if (LHSTy->isMemberPointerType()) {
4553 assert(E->isEqualityOp() && "unexpected member pointer operation");
4554 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4555
4556 MemberPtr LHSValue, RHSValue;
4557
4558 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4559 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4560 return false;
4561
4562 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4563 return false;
4564
4565 // C++11 [expr.eq]p2:
4566 // If both operands are null, they compare equal. Otherwise if only one is
4567 // null, they compare unequal.
4568 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4569 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4570 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4571 }
4572
4573 // Otherwise if either is a pointer to a virtual member function, the
4574 // result is unspecified.
4575 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4576 if (MD->isVirtual())
4577 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4578 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4579 if (MD->isVirtual())
4580 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4581
4582 // Otherwise they compare equal if and only if they would refer to the
4583 // same member of the same most derived object or the same subobject if
4584 // they were dereferenced with a hypothetical object of the associated
4585 // class type.
4586 bool Equal = LHSValue == RHSValue;
4587 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4588 }
4589
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004590 if (!LHSTy->isIntegralOrEnumerationType() ||
4591 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004592 // We can't continue from here for non-integral types.
4593 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004594 }
4595
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004596 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004597 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004598
4599 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4600 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004601 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004602
Richard Smith745f5142012-01-27 01:14:48 +00004603 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004604 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004605
Richard Smith47a1eed2011-10-29 20:57:55 +00004606 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004607
4608 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004609 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004610 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4611 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004612 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004613 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004614 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004615 LHSVal.getLValueOffset() -= AdditionalOffset;
4616 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004617 return true;
4618 }
4619
4620 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004621 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004622 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004623 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4624 LHSVal.getInt().getZExtValue());
4625 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004626 return true;
4627 }
4628
Eli Friedman65639282012-01-04 23:13:47 +00004629 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4630 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004631 if (!LHSVal.getLValueOffset().isZero() ||
4632 !RHSVal.getLValueOffset().isZero())
4633 return false;
4634 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4635 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4636 if (!LHSExpr || !RHSExpr)
4637 return false;
4638 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4639 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4640 if (!LHSAddrExpr || !RHSAddrExpr)
4641 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004642 // Make sure both labels come from the same function.
4643 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4644 RHSAddrExpr->getLabel()->getDeclContext())
4645 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004646 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4647 return true;
4648 }
4649
Eli Friedman42edd0d2009-03-24 01:14:50 +00004650 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004651 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004652 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004653
Richard Smithc49bd112011-10-28 17:51:58 +00004654 APSInt &LHS = LHSVal.getInt();
4655 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004656
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004657 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004658 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004659 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004660 case BO_Mul:
4661 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4662 LHS.getBitWidth() * 2,
4663 std::multiplies<APSInt>()), E);
4664 case BO_Add:
4665 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4666 LHS.getBitWidth() + 1,
4667 std::plus<APSInt>()), E);
4668 case BO_Sub:
4669 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4670 LHS.getBitWidth() + 1,
4671 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004672 case BO_And: return Success(LHS & RHS, E);
4673 case BO_Xor: return Success(LHS ^ RHS, E);
4674 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004675 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004676 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004677 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004678 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004679 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4680 // actually undefined behavior in C++11 due to a language defect.
4681 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4682 LHS.isSigned() && LHS.isMinSignedValue())
4683 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4684 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004685 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004686 // During constant-folding, a negative shift is an opposite shift. Such a
4687 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004688 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004689 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004690 RHS = -RHS;
4691 goto shift_right;
4692 }
4693
4694 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004695 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4696 // shifted type.
4697 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4698 if (SA != RHS) {
4699 CCEDiag(E, diag::note_constexpr_large_shift)
4700 << RHS << E->getType() << LHS.getBitWidth();
4701 } else if (LHS.isSigned()) {
4702 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4703 // operand, and must not overflow.
4704 if (LHS.isNegative())
4705 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4706 else if (LHS.countLeadingZeros() <= SA)
4707 HandleOverflow(Info, E, LHS.extend(LHS.getBitWidth() + SA) << SA,
4708 E->getType());
4709 }
4710
Richard Smithc49bd112011-10-28 17:51:58 +00004711 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004712 }
John McCall2de56d12010-08-25 11:45:40 +00004713 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004714 // During constant-folding, a negative shift is an opposite shift. Such a
4715 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004716 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004717 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004718 RHS = -RHS;
4719 goto shift_left;
4720 }
4721
4722 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004723 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4724 // shifted type.
4725 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4726 if (SA != RHS)
4727 CCEDiag(E, diag::note_constexpr_large_shift)
4728 << RHS << E->getType() << LHS.getBitWidth();
4729
Richard Smithc49bd112011-10-28 17:51:58 +00004730 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004731 }
Mike Stump1eb44332009-09-09 15:08:12 +00004732
Richard Smithc49bd112011-10-28 17:51:58 +00004733 case BO_LT: return Success(LHS < RHS, E);
4734 case BO_GT: return Success(LHS > RHS, E);
4735 case BO_LE: return Success(LHS <= RHS, E);
4736 case BO_GE: return Success(LHS >= RHS, E);
4737 case BO_EQ: return Success(LHS == RHS, E);
4738 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004739 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004740}
4741
Ken Dyck8b752f12010-01-27 17:10:57 +00004742CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004743 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4744 // the result is the size of the referenced type."
4745 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4746 // result shall be the alignment of the referenced type."
4747 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4748 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004749
4750 // __alignof is defined to return the preferred alignment.
4751 return Info.Ctx.toCharUnitsFromBits(
4752 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004753}
4754
Ken Dyck8b752f12010-01-27 17:10:57 +00004755CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004756 E = E->IgnoreParens();
4757
4758 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004759 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004760 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004761 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4762 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004763
Chris Lattneraf707ab2009-01-24 21:53:27 +00004764 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004765 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4766 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004767
Chris Lattnere9feb472009-01-24 21:09:06 +00004768 return GetAlignOfType(E->getType());
4769}
4770
4771
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004772/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4773/// a result as the expression's type.
4774bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4775 const UnaryExprOrTypeTraitExpr *E) {
4776 switch(E->getKind()) {
4777 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004778 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004779 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004780 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004781 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004782 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004783
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004784 case UETT_VecStep: {
4785 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004786
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004787 if (Ty->isVectorType()) {
4788 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004789
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004790 // The vec_step built-in functions that take a 3-component
4791 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4792 if (n == 3)
4793 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004794
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004795 return Success(n, E);
4796 } else
4797 return Success(1, E);
4798 }
4799
4800 case UETT_SizeOf: {
4801 QualType SrcTy = E->getTypeOfArgument();
4802 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4803 // the result is the size of the referenced type."
4804 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4805 // result shall be the alignment of the referenced type."
4806 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4807 SrcTy = Ref->getPointeeType();
4808
Richard Smith180f4792011-11-10 06:34:14 +00004809 CharUnits Sizeof;
4810 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004811 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004812 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004813 }
4814 }
4815
4816 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004817}
4818
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004819bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004820 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004821 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004822 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004823 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004824 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004825 for (unsigned i = 0; i != n; ++i) {
4826 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4827 switch (ON.getKind()) {
4828 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004829 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004830 APSInt IdxResult;
4831 if (!EvaluateInteger(Idx, IdxResult, Info))
4832 return false;
4833 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4834 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004835 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004836 CurrentType = AT->getElementType();
4837 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4838 Result += IdxResult.getSExtValue() * ElementSize;
4839 break;
4840 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004841
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004842 case OffsetOfExpr::OffsetOfNode::Field: {
4843 FieldDecl *MemberDecl = ON.getField();
4844 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004845 if (!RT)
4846 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004847 RecordDecl *RD = RT->getDecl();
4848 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004849 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004850 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004851 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004852 CurrentType = MemberDecl->getType().getNonReferenceType();
4853 break;
4854 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004855
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004856 case OffsetOfExpr::OffsetOfNode::Identifier:
4857 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004858
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004859 case OffsetOfExpr::OffsetOfNode::Base: {
4860 CXXBaseSpecifier *BaseSpec = ON.getBase();
4861 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004862 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004863
4864 // Find the layout of the class whose base we are looking into.
4865 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004866 if (!RT)
4867 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004868 RecordDecl *RD = RT->getDecl();
4869 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4870
4871 // Find the base class itself.
4872 CurrentType = BaseSpec->getType();
4873 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4874 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004875 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004876
4877 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004878 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004879 break;
4880 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004881 }
4882 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004883 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004884}
4885
Chris Lattnerb542afe2008-07-11 19:10:17 +00004886bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004887 switch (E->getOpcode()) {
4888 default:
4889 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4890 // See C99 6.6p3.
4891 return Error(E);
4892 case UO_Extension:
4893 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4894 // If so, we could clear the diagnostic ID.
4895 return Visit(E->getSubExpr());
4896 case UO_Plus:
4897 // The result is just the value.
4898 return Visit(E->getSubExpr());
4899 case UO_Minus: {
4900 if (!Visit(E->getSubExpr()))
4901 return false;
4902 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00004903 const APSInt &Value = Result.getInt();
4904 if (Value.isSigned() && Value.isMinSignedValue())
4905 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
4906 E->getType());
4907 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00004908 }
4909 case UO_Not: {
4910 if (!Visit(E->getSubExpr()))
4911 return false;
4912 if (!Result.isInt()) return Error(E);
4913 return Success(~Result.getInt(), E);
4914 }
4915 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004916 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004917 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004918 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004919 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004920 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004921 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004922}
Mike Stump1eb44332009-09-09 15:08:12 +00004923
Chris Lattner732b2232008-07-12 01:15:53 +00004924/// HandleCast - This is used to evaluate implicit or explicit casts where the
4925/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004926bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4927 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004928 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004929 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004930
Eli Friedman46a52322011-03-25 00:43:55 +00004931 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004932 case CK_BaseToDerived:
4933 case CK_DerivedToBase:
4934 case CK_UncheckedDerivedToBase:
4935 case CK_Dynamic:
4936 case CK_ToUnion:
4937 case CK_ArrayToPointerDecay:
4938 case CK_FunctionToPointerDecay:
4939 case CK_NullToPointer:
4940 case CK_NullToMemberPointer:
4941 case CK_BaseToDerivedMemberPointer:
4942 case CK_DerivedToBaseMemberPointer:
4943 case CK_ConstructorConversion:
4944 case CK_IntegralToPointer:
4945 case CK_ToVoid:
4946 case CK_VectorSplat:
4947 case CK_IntegralToFloating:
4948 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004949 case CK_CPointerToObjCPointerCast:
4950 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004951 case CK_AnyPointerToBlockPointerCast:
4952 case CK_ObjCObjectLValueCast:
4953 case CK_FloatingRealToComplex:
4954 case CK_FloatingComplexToReal:
4955 case CK_FloatingComplexCast:
4956 case CK_FloatingComplexToIntegralComplex:
4957 case CK_IntegralRealToComplex:
4958 case CK_IntegralComplexCast:
4959 case CK_IntegralComplexToFloatingComplex:
4960 llvm_unreachable("invalid cast kind for integral value");
4961
Eli Friedmane50c2972011-03-25 19:07:11 +00004962 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004963 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004964 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00004965 case CK_ARCProduceObject:
4966 case CK_ARCConsumeObject:
4967 case CK_ARCReclaimReturnedObject:
4968 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004969 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004970
Richard Smith7d580a42012-01-17 21:17:26 +00004971 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00004972 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00004973 case CK_AtomicToNonAtomic:
4974 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00004975 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004976 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004977
4978 case CK_MemberPointerToBoolean:
4979 case CK_PointerToBoolean:
4980 case CK_IntegralToBoolean:
4981 case CK_FloatingToBoolean:
4982 case CK_FloatingComplexToBoolean:
4983 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004984 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004985 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004986 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004987 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004988 }
4989
Eli Friedman46a52322011-03-25 00:43:55 +00004990 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004991 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004992 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004993
Eli Friedmanbe265702009-02-20 01:15:07 +00004994 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00004995 // Allow casts of address-of-label differences if they are no-ops
4996 // or narrowing. (The narrowing case isn't actually guaranteed to
4997 // be constant-evaluatable except in some narrow cases which are hard
4998 // to detect here. We let it through on the assumption the user knows
4999 // what they are doing.)
5000 if (Result.isAddrLabelDiff())
5001 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005002 // Only allow casts of lvalues if they are lossless.
5003 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5004 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005005
Richard Smithf72fccf2012-01-30 22:27:01 +00005006 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5007 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005008 }
Mike Stump1eb44332009-09-09 15:08:12 +00005009
Eli Friedman46a52322011-03-25 00:43:55 +00005010 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005011 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5012
John McCallefdb83e2010-05-07 21:00:08 +00005013 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005014 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005015 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005016
Daniel Dunbardd211642009-02-19 22:24:01 +00005017 if (LV.getLValueBase()) {
5018 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005019 // FIXME: Allow a larger integer size than the pointer size, and allow
5020 // narrowing back down to pointer width in subsequent integral casts.
5021 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005022 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005023 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005024
Richard Smithb755a9d2011-11-16 07:18:12 +00005025 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005026 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005027 return true;
5028 }
5029
Ken Dycka7305832010-01-15 12:37:54 +00005030 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5031 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005032 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005033 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005034
Eli Friedman46a52322011-03-25 00:43:55 +00005035 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005036 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005037 if (!EvaluateComplex(SubExpr, C, Info))
5038 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005039 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005040 }
Eli Friedman2217c872009-02-22 11:46:18 +00005041
Eli Friedman46a52322011-03-25 00:43:55 +00005042 case CK_FloatingToIntegral: {
5043 APFloat F(0.0);
5044 if (!EvaluateFloat(SubExpr, F, Info))
5045 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005046
Richard Smithc1c5f272011-12-13 06:39:58 +00005047 APSInt Value;
5048 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5049 return false;
5050 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005051 }
5052 }
Mike Stump1eb44332009-09-09 15:08:12 +00005053
Eli Friedman46a52322011-03-25 00:43:55 +00005054 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005055}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005056
Eli Friedman722c7172009-02-28 03:59:05 +00005057bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5058 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005059 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005060 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5061 return false;
5062 if (!LV.isComplexInt())
5063 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005064 return Success(LV.getComplexIntReal(), E);
5065 }
5066
5067 return Visit(E->getSubExpr());
5068}
5069
Eli Friedman664a1042009-02-27 04:45:43 +00005070bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005071 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005072 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005073 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5074 return false;
5075 if (!LV.isComplexInt())
5076 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005077 return Success(LV.getComplexIntImag(), E);
5078 }
5079
Richard Smith8327fad2011-10-24 18:44:57 +00005080 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005081 return Success(0, E);
5082}
5083
Douglas Gregoree8aff02011-01-04 17:33:58 +00005084bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5085 return Success(E->getPackLength(), E);
5086}
5087
Sebastian Redl295995c2010-09-10 20:55:47 +00005088bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5089 return Success(E->getValue(), E);
5090}
5091
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005092//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005093// Float Evaluation
5094//===----------------------------------------------------------------------===//
5095
5096namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005097class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005098 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005099 APFloat &Result;
5100public:
5101 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005102 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005103
Richard Smith47a1eed2011-10-29 20:57:55 +00005104 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005105 Result = V.getFloat();
5106 return true;
5107 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005108
Richard Smith51201882011-12-30 21:15:51 +00005109 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005110 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5111 return true;
5112 }
5113
Chris Lattner019f4e82008-10-06 05:28:25 +00005114 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005115
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005116 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005117 bool VisitBinaryOperator(const BinaryOperator *E);
5118 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005119 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005120
John McCallabd3a852010-05-07 22:08:54 +00005121 bool VisitUnaryReal(const UnaryOperator *E);
5122 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005123
Richard Smith51201882011-12-30 21:15:51 +00005124 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005125};
5126} // end anonymous namespace
5127
5128static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005129 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005130 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005131}
5132
Jay Foad4ba2a172011-01-12 09:06:06 +00005133static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005134 QualType ResultTy,
5135 const Expr *Arg,
5136 bool SNaN,
5137 llvm::APFloat &Result) {
5138 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5139 if (!S) return false;
5140
5141 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5142
5143 llvm::APInt fill;
5144
5145 // Treat empty strings as if they were zero.
5146 if (S->getString().empty())
5147 fill = llvm::APInt(32, 0);
5148 else if (S->getString().getAsInteger(0, fill))
5149 return false;
5150
5151 if (SNaN)
5152 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5153 else
5154 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5155 return true;
5156}
5157
Chris Lattner019f4e82008-10-06 05:28:25 +00005158bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005159 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005160 default:
5161 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5162
Chris Lattner019f4e82008-10-06 05:28:25 +00005163 case Builtin::BI__builtin_huge_val:
5164 case Builtin::BI__builtin_huge_valf:
5165 case Builtin::BI__builtin_huge_vall:
5166 case Builtin::BI__builtin_inf:
5167 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005168 case Builtin::BI__builtin_infl: {
5169 const llvm::fltSemantics &Sem =
5170 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005171 Result = llvm::APFloat::getInf(Sem);
5172 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005173 }
Mike Stump1eb44332009-09-09 15:08:12 +00005174
John McCalldb7b72a2010-02-28 13:00:19 +00005175 case Builtin::BI__builtin_nans:
5176 case Builtin::BI__builtin_nansf:
5177 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005178 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5179 true, Result))
5180 return Error(E);
5181 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005182
Chris Lattner9e621712008-10-06 06:31:58 +00005183 case Builtin::BI__builtin_nan:
5184 case Builtin::BI__builtin_nanf:
5185 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005186 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005187 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005188 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5189 false, Result))
5190 return Error(E);
5191 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005192
5193 case Builtin::BI__builtin_fabs:
5194 case Builtin::BI__builtin_fabsf:
5195 case Builtin::BI__builtin_fabsl:
5196 if (!EvaluateFloat(E->getArg(0), Result, Info))
5197 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005198
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005199 if (Result.isNegative())
5200 Result.changeSign();
5201 return true;
5202
Mike Stump1eb44332009-09-09 15:08:12 +00005203 case Builtin::BI__builtin_copysign:
5204 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005205 case Builtin::BI__builtin_copysignl: {
5206 APFloat RHS(0.);
5207 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5208 !EvaluateFloat(E->getArg(1), RHS, Info))
5209 return false;
5210 Result.copySign(RHS);
5211 return true;
5212 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005213 }
5214}
5215
John McCallabd3a852010-05-07 22:08:54 +00005216bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005217 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5218 ComplexValue CV;
5219 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5220 return false;
5221 Result = CV.FloatReal;
5222 return true;
5223 }
5224
5225 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005226}
5227
5228bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005229 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5230 ComplexValue CV;
5231 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5232 return false;
5233 Result = CV.FloatImag;
5234 return true;
5235 }
5236
Richard Smith8327fad2011-10-24 18:44:57 +00005237 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005238 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5239 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005240 return true;
5241}
5242
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005243bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005244 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005245 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005246 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005247 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005248 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005249 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5250 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005251 Result.changeSign();
5252 return true;
5253 }
5254}
Chris Lattner019f4e82008-10-06 05:28:25 +00005255
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005256bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005257 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5258 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005259
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005260 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005261 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5262 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005263 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005264 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005265 return false;
5266
5267 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005268 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005269 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005270 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005271 break;
John McCall2de56d12010-08-25 11:45:40 +00005272 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005273 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005274 break;
John McCall2de56d12010-08-25 11:45:40 +00005275 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005276 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005277 break;
John McCall2de56d12010-08-25 11:45:40 +00005278 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005279 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005280 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005281 }
Richard Smith7b48a292012-02-01 05:53:12 +00005282
5283 if (Result.isInfinity() || Result.isNaN())
5284 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5285 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005286}
5287
5288bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5289 Result = E->getValue();
5290 return true;
5291}
5292
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005293bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5294 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005295
Eli Friedman2a523ee2011-03-25 00:54:52 +00005296 switch (E->getCastKind()) {
5297 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005298 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005299
5300 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005301 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005302 return EvaluateInteger(SubExpr, IntResult, Info) &&
5303 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5304 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005305 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005306
5307 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005308 if (!Visit(SubExpr))
5309 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005310 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5311 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005312 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005313
Eli Friedman2a523ee2011-03-25 00:54:52 +00005314 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005315 ComplexValue V;
5316 if (!EvaluateComplex(SubExpr, V, Info))
5317 return false;
5318 Result = V.getComplexFloatReal();
5319 return true;
5320 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005321 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005322}
5323
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005324//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005325// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005326//===----------------------------------------------------------------------===//
5327
5328namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005329class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005330 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005331 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005332
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005333public:
John McCallf4cf1a12010-05-07 17:22:02 +00005334 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005335 : ExprEvaluatorBaseTy(info), Result(Result) {}
5336
Richard Smith47a1eed2011-10-29 20:57:55 +00005337 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005338 Result.setFrom(V);
5339 return true;
5340 }
Mike Stump1eb44332009-09-09 15:08:12 +00005341
Eli Friedman7ead5c72012-01-10 04:58:17 +00005342 bool ZeroInitialization(const Expr *E);
5343
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005344 //===--------------------------------------------------------------------===//
5345 // Visitor Methods
5346 //===--------------------------------------------------------------------===//
5347
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005348 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005349 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005350 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005351 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005352 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005353};
5354} // end anonymous namespace
5355
John McCallf4cf1a12010-05-07 17:22:02 +00005356static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5357 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005358 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005359 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005360}
5361
Eli Friedman7ead5c72012-01-10 04:58:17 +00005362bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005363 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005364 if (ElemTy->isRealFloatingType()) {
5365 Result.makeComplexFloat();
5366 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5367 Result.FloatReal = Zero;
5368 Result.FloatImag = Zero;
5369 } else {
5370 Result.makeComplexInt();
5371 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5372 Result.IntReal = Zero;
5373 Result.IntImag = Zero;
5374 }
5375 return true;
5376}
5377
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005378bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5379 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005380
5381 if (SubExpr->getType()->isRealFloatingType()) {
5382 Result.makeComplexFloat();
5383 APFloat &Imag = Result.FloatImag;
5384 if (!EvaluateFloat(SubExpr, Imag, Info))
5385 return false;
5386
5387 Result.FloatReal = APFloat(Imag.getSemantics());
5388 return true;
5389 } else {
5390 assert(SubExpr->getType()->isIntegerType() &&
5391 "Unexpected imaginary literal.");
5392
5393 Result.makeComplexInt();
5394 APSInt &Imag = Result.IntImag;
5395 if (!EvaluateInteger(SubExpr, Imag, Info))
5396 return false;
5397
5398 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5399 return true;
5400 }
5401}
5402
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005403bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005404
John McCall8786da72010-12-14 17:51:41 +00005405 switch (E->getCastKind()) {
5406 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005407 case CK_BaseToDerived:
5408 case CK_DerivedToBase:
5409 case CK_UncheckedDerivedToBase:
5410 case CK_Dynamic:
5411 case CK_ToUnion:
5412 case CK_ArrayToPointerDecay:
5413 case CK_FunctionToPointerDecay:
5414 case CK_NullToPointer:
5415 case CK_NullToMemberPointer:
5416 case CK_BaseToDerivedMemberPointer:
5417 case CK_DerivedToBaseMemberPointer:
5418 case CK_MemberPointerToBoolean:
5419 case CK_ConstructorConversion:
5420 case CK_IntegralToPointer:
5421 case CK_PointerToIntegral:
5422 case CK_PointerToBoolean:
5423 case CK_ToVoid:
5424 case CK_VectorSplat:
5425 case CK_IntegralCast:
5426 case CK_IntegralToBoolean:
5427 case CK_IntegralToFloating:
5428 case CK_FloatingToIntegral:
5429 case CK_FloatingToBoolean:
5430 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005431 case CK_CPointerToObjCPointerCast:
5432 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005433 case CK_AnyPointerToBlockPointerCast:
5434 case CK_ObjCObjectLValueCast:
5435 case CK_FloatingComplexToReal:
5436 case CK_FloatingComplexToBoolean:
5437 case CK_IntegralComplexToReal:
5438 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005439 case CK_ARCProduceObject:
5440 case CK_ARCConsumeObject:
5441 case CK_ARCReclaimReturnedObject:
5442 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005443 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005444
John McCall8786da72010-12-14 17:51:41 +00005445 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005446 case CK_AtomicToNonAtomic:
5447 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005448 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005449 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005450
5451 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005452 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005453 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005454 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005455
5456 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005457 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005458 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005459 return false;
5460
John McCall8786da72010-12-14 17:51:41 +00005461 Result.makeComplexFloat();
5462 Result.FloatImag = APFloat(Real.getSemantics());
5463 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005464 }
5465
John McCall8786da72010-12-14 17:51:41 +00005466 case CK_FloatingComplexCast: {
5467 if (!Visit(E->getSubExpr()))
5468 return false;
5469
5470 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5471 QualType From
5472 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5473
Richard Smithc1c5f272011-12-13 06:39:58 +00005474 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5475 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005476 }
5477
5478 case CK_FloatingComplexToIntegralComplex: {
5479 if (!Visit(E->getSubExpr()))
5480 return false;
5481
5482 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5483 QualType From
5484 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5485 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005486 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5487 To, Result.IntReal) &&
5488 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5489 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005490 }
5491
5492 case CK_IntegralRealToComplex: {
5493 APSInt &Real = Result.IntReal;
5494 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5495 return false;
5496
5497 Result.makeComplexInt();
5498 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5499 return true;
5500 }
5501
5502 case CK_IntegralComplexCast: {
5503 if (!Visit(E->getSubExpr()))
5504 return false;
5505
5506 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5507 QualType From
5508 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5509
Richard Smithf72fccf2012-01-30 22:27:01 +00005510 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5511 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005512 return true;
5513 }
5514
5515 case CK_IntegralComplexToFloatingComplex: {
5516 if (!Visit(E->getSubExpr()))
5517 return false;
5518
5519 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5520 QualType From
5521 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5522 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005523 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5524 To, Result.FloatReal) &&
5525 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5526 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005527 }
5528 }
5529
5530 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005531}
5532
John McCallf4cf1a12010-05-07 17:22:02 +00005533bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005534 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005535 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5536
Richard Smith745f5142012-01-27 01:14:48 +00005537 bool LHSOK = Visit(E->getLHS());
5538 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005539 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005540
John McCallf4cf1a12010-05-07 17:22:02 +00005541 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005542 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005543 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005544
Daniel Dunbar3f279872009-01-29 01:32:56 +00005545 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5546 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005547 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005548 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005549 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005550 if (Result.isComplexFloat()) {
5551 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5552 APFloat::rmNearestTiesToEven);
5553 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5554 APFloat::rmNearestTiesToEven);
5555 } else {
5556 Result.getComplexIntReal() += RHS.getComplexIntReal();
5557 Result.getComplexIntImag() += RHS.getComplexIntImag();
5558 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005559 break;
John McCall2de56d12010-08-25 11:45:40 +00005560 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005561 if (Result.isComplexFloat()) {
5562 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5563 APFloat::rmNearestTiesToEven);
5564 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5565 APFloat::rmNearestTiesToEven);
5566 } else {
5567 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5568 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5569 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005570 break;
John McCall2de56d12010-08-25 11:45:40 +00005571 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005572 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005573 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005574 APFloat &LHS_r = LHS.getComplexFloatReal();
5575 APFloat &LHS_i = LHS.getComplexFloatImag();
5576 APFloat &RHS_r = RHS.getComplexFloatReal();
5577 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005578
Daniel Dunbar3f279872009-01-29 01:32:56 +00005579 APFloat Tmp = LHS_r;
5580 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5581 Result.getComplexFloatReal() = Tmp;
5582 Tmp = LHS_i;
5583 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5584 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5585
5586 Tmp = LHS_r;
5587 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5588 Result.getComplexFloatImag() = Tmp;
5589 Tmp = LHS_i;
5590 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5591 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5592 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005593 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005594 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005595 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5596 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005597 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005598 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5599 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5600 }
5601 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005602 case BO_Div:
5603 if (Result.isComplexFloat()) {
5604 ComplexValue LHS = Result;
5605 APFloat &LHS_r = LHS.getComplexFloatReal();
5606 APFloat &LHS_i = LHS.getComplexFloatImag();
5607 APFloat &RHS_r = RHS.getComplexFloatReal();
5608 APFloat &RHS_i = RHS.getComplexFloatImag();
5609 APFloat &Res_r = Result.getComplexFloatReal();
5610 APFloat &Res_i = Result.getComplexFloatImag();
5611
5612 APFloat Den = RHS_r;
5613 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5614 APFloat Tmp = RHS_i;
5615 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5616 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5617
5618 Res_r = LHS_r;
5619 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5620 Tmp = LHS_i;
5621 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5622 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5623 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5624
5625 Res_i = LHS_i;
5626 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5627 Tmp = LHS_r;
5628 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5629 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5630 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5631 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005632 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5633 return Error(E, diag::note_expr_divide_by_zero);
5634
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005635 ComplexValue LHS = Result;
5636 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5637 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5638 Result.getComplexIntReal() =
5639 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5640 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5641 Result.getComplexIntImag() =
5642 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5643 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5644 }
5645 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005646 }
5647
John McCallf4cf1a12010-05-07 17:22:02 +00005648 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005649}
5650
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005651bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5652 // Get the operand value into 'Result'.
5653 if (!Visit(E->getSubExpr()))
5654 return false;
5655
5656 switch (E->getOpcode()) {
5657 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005658 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005659 case UO_Extension:
5660 return true;
5661 case UO_Plus:
5662 // The result is always just the subexpr.
5663 return true;
5664 case UO_Minus:
5665 if (Result.isComplexFloat()) {
5666 Result.getComplexFloatReal().changeSign();
5667 Result.getComplexFloatImag().changeSign();
5668 }
5669 else {
5670 Result.getComplexIntReal() = -Result.getComplexIntReal();
5671 Result.getComplexIntImag() = -Result.getComplexIntImag();
5672 }
5673 return true;
5674 case UO_Not:
5675 if (Result.isComplexFloat())
5676 Result.getComplexFloatImag().changeSign();
5677 else
5678 Result.getComplexIntImag() = -Result.getComplexIntImag();
5679 return true;
5680 }
5681}
5682
Eli Friedman7ead5c72012-01-10 04:58:17 +00005683bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5684 if (E->getNumInits() == 2) {
5685 if (E->getType()->isComplexType()) {
5686 Result.makeComplexFloat();
5687 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5688 return false;
5689 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5690 return false;
5691 } else {
5692 Result.makeComplexInt();
5693 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5694 return false;
5695 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5696 return false;
5697 }
5698 return true;
5699 }
5700 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5701}
5702
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005703//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005704// Void expression evaluation, primarily for a cast to void on the LHS of a
5705// comma operator
5706//===----------------------------------------------------------------------===//
5707
5708namespace {
5709class VoidExprEvaluator
5710 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5711public:
5712 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5713
5714 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005715
5716 bool VisitCastExpr(const CastExpr *E) {
5717 switch (E->getCastKind()) {
5718 default:
5719 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5720 case CK_ToVoid:
5721 VisitIgnoredValue(E->getSubExpr());
5722 return true;
5723 }
5724 }
5725};
5726} // end anonymous namespace
5727
5728static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5729 assert(E->isRValue() && E->getType()->isVoidType());
5730 return VoidExprEvaluator(Info).Visit(E);
5731}
5732
5733//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005734// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005735//===----------------------------------------------------------------------===//
5736
Richard Smith47a1eed2011-10-29 20:57:55 +00005737static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005738 // In C, function designators are not lvalues, but we evaluate them as if they
5739 // are.
5740 if (E->isGLValue() || E->getType()->isFunctionType()) {
5741 LValue LV;
5742 if (!EvaluateLValue(E, LV, Info))
5743 return false;
5744 LV.moveInto(Result);
5745 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005746 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005747 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005748 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005749 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005750 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005751 } else if (E->getType()->hasPointerRepresentation()) {
5752 LValue LV;
5753 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005754 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005755 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005756 } else if (E->getType()->isRealFloatingType()) {
5757 llvm::APFloat F(0.0);
5758 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005759 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005760 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005761 } else if (E->getType()->isAnyComplexType()) {
5762 ComplexValue C;
5763 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005764 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005765 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005766 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005767 MemberPtr P;
5768 if (!EvaluateMemberPointer(E, P, Info))
5769 return false;
5770 P.moveInto(Result);
5771 return true;
Richard Smith51201882011-12-30 21:15:51 +00005772 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005773 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005774 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005775 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005776 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005777 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005778 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005779 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005780 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005781 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5782 return false;
5783 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005784 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005785 if (Info.getLangOpts().CPlusPlus0x)
5786 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5787 << E->getType();
5788 else
5789 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005790 if (!EvaluateVoid(E, Info))
5791 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005792 } else if (Info.getLangOpts().CPlusPlus0x) {
5793 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5794 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005795 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005796 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005797 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005798 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005799
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005800 return true;
5801}
5802
Richard Smith69c2c502011-11-04 05:33:44 +00005803/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5804/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5805/// since later initializers for an object can indirectly refer to subobjects
5806/// which were initialized earlier.
5807static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005808 const LValue &This, const Expr *E,
5809 CheckConstantExpressionKind CCEK) {
Richard Smith51201882011-12-30 21:15:51 +00005810 if (!CheckLiteralType(Info, E))
5811 return false;
5812
5813 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005814 // Evaluate arrays and record types in-place, so that later initializers can
5815 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005816 if (E->getType()->isArrayType())
5817 return EvaluateArray(E, This, Result, Info);
5818 else if (E->getType()->isRecordType())
5819 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005820 }
5821
5822 // For any other type, in-place evaluation is unimportant.
5823 CCValue CoreConstResult;
5824 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005825 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005826}
5827
Richard Smithf48fdb02011-12-09 22:58:01 +00005828/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5829/// lvalue-to-rvalue cast if it is an lvalue.
5830static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005831 if (!CheckLiteralType(Info, E))
5832 return false;
5833
Richard Smithf48fdb02011-12-09 22:58:01 +00005834 CCValue Value;
5835 if (!::Evaluate(Value, Info, E))
5836 return false;
5837
5838 if (E->isGLValue()) {
5839 LValue LV;
5840 LV.setFrom(Value);
5841 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5842 return false;
5843 }
5844
5845 // Check this core constant expression is a constant expression, and if so,
5846 // convert it to one.
5847 return CheckConstantExpression(Info, E, Value, Result);
5848}
Richard Smithc49bd112011-10-28 17:51:58 +00005849
Richard Smith51f47082011-10-29 00:50:52 +00005850/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005851/// any crazy technique (that has nothing to do with language standards) that
5852/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005853/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5854/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005855bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005856 // Fast-path evaluations of integer literals, since we sometimes see files
5857 // containing vast quantities of these.
5858 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5859 Result.Val = APValue(APSInt(L->getValue(),
5860 L->getType()->isUnsignedIntegerType()));
5861 return true;
5862 }
5863
Richard Smith2d6a5672012-01-14 04:30:29 +00005864 // FIXME: Evaluating values of large array and record types can cause
5865 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005866 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5867 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005868 return false;
5869
Richard Smithf48fdb02011-12-09 22:58:01 +00005870 EvalInfo Info(Ctx, Result);
5871 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005872}
5873
Jay Foad4ba2a172011-01-12 09:06:06 +00005874bool Expr::EvaluateAsBooleanCondition(bool &Result,
5875 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005876 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005877 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005878 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5879 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005880 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005881}
5882
Richard Smith80d4b552011-12-28 19:48:30 +00005883bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5884 SideEffectsKind AllowSideEffects) const {
5885 if (!getType()->isIntegralOrEnumerationType())
5886 return false;
5887
Richard Smithc49bd112011-10-28 17:51:58 +00005888 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005889 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5890 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005891 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005892
Richard Smithc49bd112011-10-28 17:51:58 +00005893 Result = ExprResult.Val.getInt();
5894 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005895}
5896
Jay Foad4ba2a172011-01-12 09:06:06 +00005897bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005898 EvalInfo Info(Ctx, Result);
5899
John McCallefdb83e2010-05-07 21:00:08 +00005900 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005901 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005902 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5903 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005904}
5905
Richard Smith099e7f62011-12-19 06:19:21 +00005906bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5907 const VarDecl *VD,
5908 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005909 // FIXME: Evaluating initializers for large array and record types can cause
5910 // performance problems. Only do so in C++11 for now.
5911 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5912 !Ctx.getLangOptions().CPlusPlus0x)
5913 return false;
5914
Richard Smith099e7f62011-12-19 06:19:21 +00005915 Expr::EvalStatus EStatus;
5916 EStatus.Diag = &Notes;
5917
5918 EvalInfo InitInfo(Ctx, EStatus);
5919 InitInfo.setEvaluatingDecl(VD, Value);
5920
Richard Smith51201882011-12-30 21:15:51 +00005921 if (!CheckLiteralType(InitInfo, this))
5922 return false;
5923
Richard Smith099e7f62011-12-19 06:19:21 +00005924 LValue LVal;
5925 LVal.set(VD);
5926
Richard Smith51201882011-12-30 21:15:51 +00005927 // C++11 [basic.start.init]p2:
5928 // Variables with static storage duration or thread storage duration shall be
5929 // zero-initialized before any other initialization takes place.
5930 // This behavior is not present in C.
5931 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5932 !VD->getType()->isReferenceType()) {
5933 ImplicitValueInitExpr VIE(VD->getType());
5934 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5935 return false;
5936 }
5937
Richard Smith099e7f62011-12-19 06:19:21 +00005938 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5939 !EStatus.HasSideEffects;
5940}
5941
Richard Smith51f47082011-10-29 00:50:52 +00005942/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5943/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005944bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005945 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005946 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005947}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005948
Jay Foad4ba2a172011-01-12 09:06:06 +00005949bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005950 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005951}
5952
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005953APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005954 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005955 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005956 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005957 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005958 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005959
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005960 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005961}
John McCalld905f5a2010-05-07 05:32:02 +00005962
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005963 bool Expr::EvalResult::isGlobalLValue() const {
5964 assert(Val.isLValue());
5965 return IsGlobalLValue(Val.getLValueBase());
5966 }
5967
5968
John McCalld905f5a2010-05-07 05:32:02 +00005969/// isIntegerConstantExpr - this recursive routine will test if an expression is
5970/// an integer constant expression.
5971
5972/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5973/// comma, etc
5974///
5975/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5976/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5977/// cast+dereference.
5978
5979// CheckICE - This function does the fundamental ICE checking: the returned
5980// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5981// Note that to reduce code duplication, this helper does no evaluation
5982// itself; the caller checks whether the expression is evaluatable, and
5983// in the rare cases where CheckICE actually cares about the evaluated
5984// value, it calls into Evalute.
5985//
5986// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005987// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005988// 1: This expression is not an ICE, but if it isn't evaluated, it's
5989// a legal subexpression for an ICE. This return value is used to handle
5990// the comma operator in C99 mode.
5991// 2: This expression is not an ICE, and is not a legal subexpression for one.
5992
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005993namespace {
5994
John McCalld905f5a2010-05-07 05:32:02 +00005995struct ICEDiag {
5996 unsigned Val;
5997 SourceLocation Loc;
5998
5999 public:
6000 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6001 ICEDiag() : Val(0) {}
6002};
6003
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006004}
6005
6006static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006007
6008static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6009 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006010 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006011 !EVResult.Val.isInt()) {
6012 return ICEDiag(2, E->getLocStart());
6013 }
6014 return NoDiag();
6015}
6016
6017static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6018 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006019 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006020 return ICEDiag(2, E->getLocStart());
6021 }
6022
6023 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006024#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006025#define STMT(Node, Base) case Expr::Node##Class:
6026#define EXPR(Node, Base)
6027#include "clang/AST/StmtNodes.inc"
6028 case Expr::PredefinedExprClass:
6029 case Expr::FloatingLiteralClass:
6030 case Expr::ImaginaryLiteralClass:
6031 case Expr::StringLiteralClass:
6032 case Expr::ArraySubscriptExprClass:
6033 case Expr::MemberExprClass:
6034 case Expr::CompoundAssignOperatorClass:
6035 case Expr::CompoundLiteralExprClass:
6036 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006037 case Expr::DesignatedInitExprClass:
6038 case Expr::ImplicitValueInitExprClass:
6039 case Expr::ParenListExprClass:
6040 case Expr::VAArgExprClass:
6041 case Expr::AddrLabelExprClass:
6042 case Expr::StmtExprClass:
6043 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006044 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006045 case Expr::CXXDynamicCastExprClass:
6046 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006047 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006048 case Expr::CXXNullPtrLiteralExprClass:
6049 case Expr::CXXThisExprClass:
6050 case Expr::CXXThrowExprClass:
6051 case Expr::CXXNewExprClass:
6052 case Expr::CXXDeleteExprClass:
6053 case Expr::CXXPseudoDestructorExprClass:
6054 case Expr::UnresolvedLookupExprClass:
6055 case Expr::DependentScopeDeclRefExprClass:
6056 case Expr::CXXConstructExprClass:
6057 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006058 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006059 case Expr::CXXTemporaryObjectExprClass:
6060 case Expr::CXXUnresolvedConstructExprClass:
6061 case Expr::CXXDependentScopeMemberExprClass:
6062 case Expr::UnresolvedMemberExprClass:
6063 case Expr::ObjCStringLiteralClass:
6064 case Expr::ObjCEncodeExprClass:
6065 case Expr::ObjCMessageExprClass:
6066 case Expr::ObjCSelectorExprClass:
6067 case Expr::ObjCProtocolExprClass:
6068 case Expr::ObjCIvarRefExprClass:
6069 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006070 case Expr::ObjCIsaExprClass:
6071 case Expr::ShuffleVectorExprClass:
6072 case Expr::BlockExprClass:
6073 case Expr::BlockDeclRefExprClass:
6074 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006075 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006076 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006077 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006078 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006079 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006080 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006081 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006082 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006083 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006084 return ICEDiag(2, E->getLocStart());
6085
Douglas Gregoree8aff02011-01-04 17:33:58 +00006086 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006087 case Expr::GNUNullExprClass:
6088 // GCC considers the GNU __null value to be an integral constant expression.
6089 return NoDiag();
6090
John McCall91a57552011-07-15 05:09:51 +00006091 case Expr::SubstNonTypeTemplateParmExprClass:
6092 return
6093 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6094
John McCalld905f5a2010-05-07 05:32:02 +00006095 case Expr::ParenExprClass:
6096 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006097 case Expr::GenericSelectionExprClass:
6098 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006099 case Expr::IntegerLiteralClass:
6100 case Expr::CharacterLiteralClass:
6101 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006102 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006103 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006104 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006105 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006106 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006107 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006108 return NoDiag();
6109 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006110 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006111 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6112 // constant expressions, but they can never be ICEs because an ICE cannot
6113 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006114 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006115 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006116 return CheckEvalInICE(E, Ctx);
6117 return ICEDiag(2, E->getLocStart());
6118 }
6119 case Expr::DeclRefExprClass:
6120 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6121 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00006122 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006123 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
6124
6125 // Parameter variables are never constants. Without this check,
6126 // getAnyInitializer() can find a default argument, which leads
6127 // to chaos.
6128 if (isa<ParmVarDecl>(D))
6129 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6130
6131 // C++ 7.1.5.1p2
6132 // A variable of non-volatile const-qualified integral or enumeration
6133 // type initialized by an ICE can be used in ICEs.
6134 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006135 if (!Dcl->getType()->isIntegralOrEnumerationType())
6136 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6137
Richard Smith099e7f62011-12-19 06:19:21 +00006138 const VarDecl *VD;
6139 // Look for a declaration of this variable that has an initializer, and
6140 // check whether it is an ICE.
6141 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6142 return NoDiag();
6143 else
6144 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006145 }
6146 }
6147 return ICEDiag(2, E->getLocStart());
6148 case Expr::UnaryOperatorClass: {
6149 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6150 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006151 case UO_PostInc:
6152 case UO_PostDec:
6153 case UO_PreInc:
6154 case UO_PreDec:
6155 case UO_AddrOf:
6156 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006157 // C99 6.6/3 allows increment and decrement within unevaluated
6158 // subexpressions of constant expressions, but they can never be ICEs
6159 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006160 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006161 case UO_Extension:
6162 case UO_LNot:
6163 case UO_Plus:
6164 case UO_Minus:
6165 case UO_Not:
6166 case UO_Real:
6167 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006168 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006169 }
6170
6171 // OffsetOf falls through here.
6172 }
6173 case Expr::OffsetOfExprClass: {
6174 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006175 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006176 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006177 // compliance: we should warn earlier for offsetof expressions with
6178 // array subscripts that aren't ICEs, and if the array subscripts
6179 // are ICEs, the value of the offsetof must be an integer constant.
6180 return CheckEvalInICE(E, Ctx);
6181 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006182 case Expr::UnaryExprOrTypeTraitExprClass: {
6183 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6184 if ((Exp->getKind() == UETT_SizeOf) &&
6185 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006186 return ICEDiag(2, E->getLocStart());
6187 return NoDiag();
6188 }
6189 case Expr::BinaryOperatorClass: {
6190 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6191 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006192 case BO_PtrMemD:
6193 case BO_PtrMemI:
6194 case BO_Assign:
6195 case BO_MulAssign:
6196 case BO_DivAssign:
6197 case BO_RemAssign:
6198 case BO_AddAssign:
6199 case BO_SubAssign:
6200 case BO_ShlAssign:
6201 case BO_ShrAssign:
6202 case BO_AndAssign:
6203 case BO_XorAssign:
6204 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006205 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6206 // constant expressions, but they can never be ICEs because an ICE cannot
6207 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006208 return ICEDiag(2, E->getLocStart());
6209
John McCall2de56d12010-08-25 11:45:40 +00006210 case BO_Mul:
6211 case BO_Div:
6212 case BO_Rem:
6213 case BO_Add:
6214 case BO_Sub:
6215 case BO_Shl:
6216 case BO_Shr:
6217 case BO_LT:
6218 case BO_GT:
6219 case BO_LE:
6220 case BO_GE:
6221 case BO_EQ:
6222 case BO_NE:
6223 case BO_And:
6224 case BO_Xor:
6225 case BO_Or:
6226 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006227 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6228 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006229 if (Exp->getOpcode() == BO_Div ||
6230 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006231 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006232 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006233 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006234 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006235 if (REval == 0)
6236 return ICEDiag(1, E->getLocStart());
6237 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006238 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006239 if (LEval.isMinSignedValue())
6240 return ICEDiag(1, E->getLocStart());
6241 }
6242 }
6243 }
John McCall2de56d12010-08-25 11:45:40 +00006244 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006245 if (Ctx.getLangOptions().C99) {
6246 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6247 // if it isn't evaluated.
6248 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6249 return ICEDiag(1, E->getLocStart());
6250 } else {
6251 // In both C89 and C++, commas in ICEs are illegal.
6252 return ICEDiag(2, E->getLocStart());
6253 }
6254 }
6255 if (LHSResult.Val >= RHSResult.Val)
6256 return LHSResult;
6257 return RHSResult;
6258 }
John McCall2de56d12010-08-25 11:45:40 +00006259 case BO_LAnd:
6260 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006261 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6262 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6263 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6264 // Rare case where the RHS has a comma "side-effect"; we need
6265 // to actually check the condition to see whether the side
6266 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006267 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006268 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006269 return RHSResult;
6270 return NoDiag();
6271 }
6272
6273 if (LHSResult.Val >= RHSResult.Val)
6274 return LHSResult;
6275 return RHSResult;
6276 }
6277 }
6278 }
6279 case Expr::ImplicitCastExprClass:
6280 case Expr::CStyleCastExprClass:
6281 case Expr::CXXFunctionalCastExprClass:
6282 case Expr::CXXStaticCastExprClass:
6283 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006284 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006285 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006286 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006287 if (isa<ExplicitCastExpr>(E)) {
6288 if (const FloatingLiteral *FL
6289 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6290 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6291 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6292 APSInt IgnoredVal(DestWidth, !DestSigned);
6293 bool Ignored;
6294 // If the value does not fit in the destination type, the behavior is
6295 // undefined, so we are not required to treat it as a constant
6296 // expression.
6297 if (FL->getValue().convertToInteger(IgnoredVal,
6298 llvm::APFloat::rmTowardZero,
6299 &Ignored) & APFloat::opInvalidOp)
6300 return ICEDiag(2, E->getLocStart());
6301 return NoDiag();
6302 }
6303 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006304 switch (cast<CastExpr>(E)->getCastKind()) {
6305 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006306 case CK_AtomicToNonAtomic:
6307 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006308 case CK_NoOp:
6309 case CK_IntegralToBoolean:
6310 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006311 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006312 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006313 return ICEDiag(2, E->getLocStart());
6314 }
John McCalld905f5a2010-05-07 05:32:02 +00006315 }
John McCall56ca35d2011-02-17 10:25:35 +00006316 case Expr::BinaryConditionalOperatorClass: {
6317 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6318 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6319 if (CommonResult.Val == 2) return CommonResult;
6320 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6321 if (FalseResult.Val == 2) return FalseResult;
6322 if (CommonResult.Val == 1) return CommonResult;
6323 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006324 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006325 return FalseResult;
6326 }
John McCalld905f5a2010-05-07 05:32:02 +00006327 case Expr::ConditionalOperatorClass: {
6328 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6329 // If the condition (ignoring parens) is a __builtin_constant_p call,
6330 // then only the true side is actually considered in an integer constant
6331 // expression, and it is fully evaluated. This is an important GNU
6332 // extension. See GCC PR38377 for discussion.
6333 if (const CallExpr *CallCE
6334 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006335 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6336 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006337 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006338 if (CondResult.Val == 2)
6339 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006340
Richard Smithf48fdb02011-12-09 22:58:01 +00006341 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6342 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006343
John McCalld905f5a2010-05-07 05:32:02 +00006344 if (TrueResult.Val == 2)
6345 return TrueResult;
6346 if (FalseResult.Val == 2)
6347 return FalseResult;
6348 if (CondResult.Val == 1)
6349 return CondResult;
6350 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6351 return NoDiag();
6352 // Rare case where the diagnostics depend on which side is evaluated
6353 // Note that if we get here, CondResult is 0, and at least one of
6354 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006355 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006356 return FalseResult;
6357 }
6358 return TrueResult;
6359 }
6360 case Expr::CXXDefaultArgExprClass:
6361 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6362 case Expr::ChooseExprClass: {
6363 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6364 }
6365 }
6366
David Blaikie30263482012-01-20 21:50:17 +00006367 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006368}
6369
Richard Smithf48fdb02011-12-09 22:58:01 +00006370/// Evaluate an expression as a C++11 integral constant expression.
6371static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6372 const Expr *E,
6373 llvm::APSInt *Value,
6374 SourceLocation *Loc) {
6375 if (!E->getType()->isIntegralOrEnumerationType()) {
6376 if (Loc) *Loc = E->getExprLoc();
6377 return false;
6378 }
6379
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006380 APValue Result;
6381 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006382 return false;
6383
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006384 assert(Result.isInt() && "pointer cast to int is not an ICE");
6385 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006386 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006387}
6388
Richard Smithdd1f29b2011-12-12 09:28:41 +00006389bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006390 if (Ctx.getLangOptions().CPlusPlus0x)
6391 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6392
John McCalld905f5a2010-05-07 05:32:02 +00006393 ICEDiag d = CheckICE(this, Ctx);
6394 if (d.Val != 0) {
6395 if (Loc) *Loc = d.Loc;
6396 return false;
6397 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006398 return true;
6399}
6400
6401bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6402 SourceLocation *Loc, bool isEvaluated) const {
6403 if (Ctx.getLangOptions().CPlusPlus0x)
6404 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6405
6406 if (!isIntegerConstantExpr(Ctx, Loc))
6407 return false;
6408 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006409 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006410 return true;
6411}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006412
6413bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6414 SourceLocation *Loc) const {
6415 // We support this checking in C++98 mode in order to diagnose compatibility
6416 // issues.
6417 assert(Ctx.getLangOptions().CPlusPlus);
6418
6419 Expr::EvalStatus Status;
6420 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6421 Status.Diag = &Diags;
6422 EvalInfo Info(Ctx, Status);
6423
6424 APValue Scratch;
6425 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6426
6427 if (!Diags.empty()) {
6428 IsConstExpr = false;
6429 if (Loc) *Loc = Diags[0].first;
6430 } else if (!IsConstExpr) {
6431 // FIXME: This shouldn't happen.
6432 if (Loc) *Loc = getExprLoc();
6433 }
6434
6435 return IsConstExpr;
6436}
Richard Smith745f5142012-01-27 01:14:48 +00006437
6438bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6439 llvm::SmallVectorImpl<
6440 PartialDiagnosticAt> &Diags) {
6441 // FIXME: It would be useful to check constexpr function templates, but at the
6442 // moment the constant expression evaluator cannot cope with the non-rigorous
6443 // ASTs which we build for dependent expressions.
6444 if (FD->isDependentContext())
6445 return true;
6446
6447 Expr::EvalStatus Status;
6448 Status.Diag = &Diags;
6449
6450 EvalInfo Info(FD->getASTContext(), Status);
6451 Info.CheckingPotentialConstantExpression = true;
6452
6453 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6454 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6455
6456 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6457 // is a temporary being used as the 'this' pointer.
6458 LValue This;
6459 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6460 This.set(&VIE, Info.CurrentCall);
6461
6462 APValue Scratch;
6463 ArrayRef<const Expr*> Args;
6464
6465 SourceLocation Loc = FD->getLocation();
6466
6467 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
6468 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6469 } else
6470 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6471 Args, FD->getBody(), Info, Scratch);
6472
6473 return Diags.empty();
6474}