blob: f84c6347cb0a0fb980d26e2e091bd04bf23aeda4 [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"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000045#include "clang/Basic/PartialDiagnostic.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000046#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000047#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000048#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000049#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000050
Anders Carlssonc44eec62008-07-03 04:20:39 +000051using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000054
Chris Lattner87eae5e2008-07-11 22:52:41 +000055/// EvalInfo - This is a private struct used by the evaluator to capture
56/// information about a subexpression as it is folded. It retains information
57/// about the AST context, but also maintains information about the folded
58/// expression.
59///
60/// If an expression could be evaluated, it is still possible it is not a C
61/// "integer constant expression" or constant expression. If not, this struct
62/// captures information about how and why not.
63///
64/// One bit of information passed *into* the request for constant folding
65/// indicates whether the subexpression is "evaluated" or not according to C
66/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
67/// evaluate the expression regardless of what the RHS is, but C only allows
68/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000069namespace {
Richard Smith180f4792011-11-10 06:34:14 +000070 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000071 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000072 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000073
Richard Smith1bf9a9e2011-11-12 22:28:03 +000074 QualType getType(APValue::LValueBase B) {
75 if (!B) return QualType();
76 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
77 return D->getType();
78 return B.get<const Expr*>()->getType();
79 }
80
Richard Smith180f4792011-11-10 06:34:14 +000081 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000082 /// field or base class.
83 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000084 APValue::BaseOrMemberType Value;
85 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000086 return Value;
87 }
88
89 /// Get an LValue path entry, which is known to not be an array index, as a
90 /// field declaration.
91 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
92 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000093 }
94 /// Get an LValue path entry, which is known to not be an array index, as a
95 /// base class declaration.
96 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000097 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000098 }
99 /// Determine whether this LValue path entry for a base class names a virtual
100 /// base class.
101 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +0000102 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +0000103 }
104
Richard Smithb4e85ed2012-01-06 16:39:00 +0000105 /// Find the path length and type of the most-derived subobject in the given
106 /// path, and find the size of the containing array, if any.
107 static
108 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
109 ArrayRef<APValue::LValuePathEntry> Path,
110 uint64_t &ArraySize, QualType &Type) {
111 unsigned MostDerivedLength = 0;
112 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000113 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000114 if (Type->isArrayType()) {
115 const ConstantArrayType *CAT =
116 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
117 Type = CAT->getElementType();
118 ArraySize = CAT->getSize().getZExtValue();
119 MostDerivedLength = I + 1;
120 } else if (const FieldDecl *FD = getAsField(Path[I])) {
121 Type = FD->getType();
122 ArraySize = 0;
123 MostDerivedLength = I + 1;
124 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000125 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000126 ArraySize = 0;
127 }
Richard Smith9a17a682011-11-07 05:07:52 +0000128 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000129 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000130 }
131
Richard Smithb4e85ed2012-01-06 16:39:00 +0000132 // The order of this enum is important for diagnostics.
133 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000134 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
135 CSK_This
Richard Smithb4e85ed2012-01-06 16:39:00 +0000136 };
137
Richard Smith0a3bdb62011-11-04 02:25:55 +0000138 /// A path from a glvalue to a subobject of that glvalue.
139 struct SubobjectDesignator {
140 /// True if the subobject was named in a manner not supported by C++11. Such
141 /// lvalues can still be folded, but they are not core constant expressions
142 /// and we cannot perform lvalue-to-rvalue conversions on them.
143 bool Invalid : 1;
144
Richard Smithb4e85ed2012-01-06 16:39:00 +0000145 /// Is this a pointer one past the end of an object?
146 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000147
Richard Smithb4e85ed2012-01-06 16:39:00 +0000148 /// The length of the path to the most-derived object of which this is a
149 /// subobject.
150 unsigned MostDerivedPathLength : 30;
151
152 /// The size of the array of which the most-derived object is an element, or
153 /// 0 if the most-derived object is not an array element.
154 uint64_t MostDerivedArraySize;
155
156 /// The type of the most derived object referred to by this address.
157 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000158
Richard Smith9a17a682011-11-07 05:07:52 +0000159 typedef APValue::LValuePathEntry PathEntry;
160
Richard Smith0a3bdb62011-11-04 02:25:55 +0000161 /// The entries on the path from the glvalue to the designated subobject.
162 SmallVector<PathEntry, 8> Entries;
163
Richard Smithb4e85ed2012-01-06 16:39:00 +0000164 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000165
Richard Smithb4e85ed2012-01-06 16:39:00 +0000166 explicit SubobjectDesignator(QualType T)
167 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
168 MostDerivedArraySize(0), MostDerivedType(T) {}
169
170 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
171 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
172 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000173 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000174 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000175 ArrayRef<PathEntry> VEntries = V.getLValuePath();
176 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
177 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000178 MostDerivedPathLength =
179 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
180 V.getLValuePath(), MostDerivedArraySize,
181 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000182 }
183 }
184
Richard Smith0a3bdb62011-11-04 02:25:55 +0000185 void setInvalid() {
186 Invalid = true;
187 Entries.clear();
188 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000189
190 /// Determine whether this is a one-past-the-end pointer.
191 bool isOnePastTheEnd() const {
192 if (IsOnePastTheEnd)
193 return true;
194 if (MostDerivedArraySize &&
195 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
196 return true;
197 return false;
198 }
199
200 /// Check that this refers to a valid subobject.
201 bool isValidSubobject() const {
202 if (Invalid)
203 return false;
204 return !isOnePastTheEnd();
205 }
206 /// Check that this refers to a valid subobject, and if not, produce a
207 /// relevant diagnostic and set the designator as invalid.
208 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
209
210 /// Update this designator to refer to the first element within this array.
211 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000212 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000213 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000214 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000215
216 // This is a most-derived object.
217 MostDerivedType = CAT->getElementType();
218 MostDerivedArraySize = CAT->getSize().getZExtValue();
219 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000220 }
221 /// Update this designator to refer to the given base or member of this
222 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000223 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000224 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000225 APValue::BaseOrMemberType Value(D, Virtual);
226 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000227 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000228
229 // If this isn't a base class, it's a new most-derived object.
230 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
231 MostDerivedType = FD->getType();
232 MostDerivedArraySize = 0;
233 MostDerivedPathLength = Entries.size();
234 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000235 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000236 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000237 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000238 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000239 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000240 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000241 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000242 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
243 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
244 setInvalid();
245 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000246 return;
247 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000248 // [expr.add]p4: For the purposes of these operators, a pointer to a
249 // nonarray object behaves the same as a pointer to the first element of
250 // an array of length one with the type of the object as its element type.
251 if (IsOnePastTheEnd && N == (uint64_t)-1)
252 IsOnePastTheEnd = false;
253 else if (!IsOnePastTheEnd && N == 1)
254 IsOnePastTheEnd = true;
255 else if (N != 0) {
256 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000257 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000258 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000259 }
260 };
261
Richard Smith47a1eed2011-10-29 20:57:55 +0000262 /// A core constant value. This can be the value of any constant expression,
263 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000264 ///
265 /// For an LValue, the base and offset are stored in the APValue subobject,
266 /// but the other information is stored in the SubobjectDesignator. For all
267 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000268 class CCValue : public APValue {
269 typedef llvm::APSInt APSInt;
270 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000271 /// If the value is a reference or pointer into a parameter or temporary,
272 /// this is the corresponding call stack frame.
273 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000274 /// If the value is a reference or pointer, this is a description of how the
275 /// subobject was specified.
276 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000277 public:
Richard Smith177dce72011-11-01 16:57:24 +0000278 struct GlobalValue {};
279
Richard Smith47a1eed2011-10-29 20:57:55 +0000280 CCValue() {}
281 explicit CCValue(const APSInt &I) : APValue(I) {}
282 explicit CCValue(const APFloat &F) : APValue(F) {}
283 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
284 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
285 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000286 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000287 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000288 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000289 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000290 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
291 APValue(V), CallFrame(0), Designator(Ctx, V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000292 CCValue(const ValueDecl *D, bool IsDerivedMember,
293 ArrayRef<const CXXRecordDecl*> Path) :
294 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000295 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
296 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000297
Richard Smith177dce72011-11-01 16:57:24 +0000298 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000299 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000300 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000301 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000302 SubobjectDesignator &getLValueDesignator() {
303 assert(getKind() == LValue);
304 return Designator;
305 }
306 const SubobjectDesignator &getLValueDesignator() const {
307 return const_cast<CCValue*>(this)->getLValueDesignator();
308 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000309 };
310
Richard Smithd0dccea2011-10-28 22:34:42 +0000311 /// A stack frame in the constexpr call stack.
312 struct CallStackFrame {
313 EvalInfo &Info;
314
315 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000316 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000317
Richard Smith08d6e032011-12-16 19:06:07 +0000318 /// CallLoc - The location of the call expression for this call.
319 SourceLocation CallLoc;
320
321 /// Callee - The function which was called.
322 const FunctionDecl *Callee;
323
Richard Smith180f4792011-11-10 06:34:14 +0000324 /// This - The binding for the this pointer in this call, if any.
325 const LValue *This;
326
Richard Smithd0dccea2011-10-28 22:34:42 +0000327 /// ParmBindings - Parameter bindings for this function call, indexed by
328 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000329 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000330
Richard Smithbd552ef2011-10-31 05:52:43 +0000331 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
332 typedef MapTy::const_iterator temp_iterator;
333 /// Temporaries - Temporary lvalues materialized within this stack frame.
334 MapTy Temporaries;
335
Richard Smith08d6e032011-12-16 19:06:07 +0000336 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
337 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000338 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000339 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000340 };
341
Richard Smithdd1f29b2011-12-12 09:28:41 +0000342 /// A partial diagnostic which we might know in advance that we are not going
343 /// to emit.
344 class OptionalDiagnostic {
345 PartialDiagnostic *Diag;
346
347 public:
348 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
349
350 template<typename T>
351 OptionalDiagnostic &operator<<(const T &v) {
352 if (Diag)
353 *Diag << v;
354 return *this;
355 }
Richard Smith789f9b62012-01-31 04:08:20 +0000356
357 OptionalDiagnostic &operator<<(const APSInt &I) {
358 if (Diag) {
359 llvm::SmallVector<char, 32> Buffer;
360 I.toString(Buffer);
361 *Diag << StringRef(Buffer.data(), Buffer.size());
362 }
363 return *this;
364 }
365
366 OptionalDiagnostic &operator<<(const APFloat &F) {
367 if (Diag) {
368 llvm::SmallVector<char, 32> Buffer;
369 F.toString(Buffer);
370 *Diag << StringRef(Buffer.data(), Buffer.size());
371 }
372 return *this;
373 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000374 };
375
Richard Smithbd552ef2011-10-31 05:52:43 +0000376 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000377 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000378
379 /// EvalStatus - Contains information about the evaluation.
380 Expr::EvalStatus &EvalStatus;
381
382 /// CurrentCall - The top of the constexpr call stack.
383 CallStackFrame *CurrentCall;
384
Richard Smithbd552ef2011-10-31 05:52:43 +0000385 /// CallStackDepth - The number of calls in the call stack right now.
386 unsigned CallStackDepth;
387
388 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
389 /// OpaqueValues - Values used as the common expression in a
390 /// BinaryConditionalOperator.
391 MapTy OpaqueValues;
392
393 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000394 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000395 CallStackFrame BottomFrame;
396
Richard Smith180f4792011-11-10 06:34:14 +0000397 /// EvaluatingDecl - This is the declaration whose initializer is being
398 /// evaluated, if any.
399 const VarDecl *EvaluatingDecl;
400
401 /// EvaluatingDeclValue - This is the value being constructed for the
402 /// declaration whose initializer is being evaluated, if any.
403 APValue *EvaluatingDeclValue;
404
Richard Smithc1c5f272011-12-13 06:39:58 +0000405 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
406 /// notes attached to it will also be stored, otherwise they will not be.
407 bool HasActiveDiagnostic;
408
Richard Smith745f5142012-01-27 01:14:48 +0000409 /// CheckingPotentialConstantExpression - Are we checking whether the
410 /// expression is a potential constant expression? If so, some diagnostics
411 /// are suppressed.
412 bool CheckingPotentialConstantExpression;
413
Richard Smithbd552ef2011-10-31 05:52:43 +0000414
415 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000416 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000417 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000418 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
419 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000420
Richard Smithbd552ef2011-10-31 05:52:43 +0000421 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
422 MapTy::const_iterator i = OpaqueValues.find(e);
423 if (i == OpaqueValues.end()) return 0;
424 return &i->second;
425 }
426
Richard Smith180f4792011-11-10 06:34:14 +0000427 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
428 EvaluatingDecl = VD;
429 EvaluatingDeclValue = &Value;
430 }
431
Richard Smithc18c4232011-11-21 19:36:32 +0000432 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
433
Richard Smithc1c5f272011-12-13 06:39:58 +0000434 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000435 // Don't perform any constexpr calls (other than the call we're checking)
436 // when checking a potential constant expression.
437 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
438 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +0000439 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
440 return true;
441 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
442 << getLangOpts().ConstexprCallDepth;
443 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000444 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000445
Richard Smithc1c5f272011-12-13 06:39:58 +0000446 private:
447 /// Add a diagnostic to the diagnostics list.
448 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
449 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
450 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
451 return EvalStatus.Diag->back().second;
452 }
453
Richard Smith08d6e032011-12-16 19:06:07 +0000454 /// Add notes containing a call stack to the current point of evaluation.
455 void addCallStack(unsigned Limit);
456
Richard Smithc1c5f272011-12-13 06:39:58 +0000457 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000458 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000459 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
460 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000461 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000462 // If we have a prior diagnostic, it will be noting that the expression
463 // isn't a constant expression. This diagnostic is more important.
464 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000465 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000466 unsigned CallStackNotes = CallStackDepth - 1;
467 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
468 if (Limit)
469 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000470 if (CheckingPotentialConstantExpression)
471 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000472
Richard Smithc1c5f272011-12-13 06:39:58 +0000473 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000474 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000475 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
476 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000477 if (!CheckingPotentialConstantExpression)
478 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000479 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000480 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000481 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000482 return OptionalDiagnostic();
483 }
484
485 /// Diagnose that the evaluation does not produce a C++11 core constant
486 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000487 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
488 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000489 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000490 // Don't override a previous diagnostic.
491 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
492 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000493 return Diag(Loc, DiagId, ExtraNotes);
494 }
495
496 /// Add a note to a prior diagnostic.
497 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
498 if (!HasActiveDiagnostic)
499 return OptionalDiagnostic();
500 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000501 }
Richard Smith099e7f62011-12-19 06:19:21 +0000502
503 /// Add a stack of notes to a prior diagnostic.
504 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
505 if (HasActiveDiagnostic) {
506 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
507 Diags.begin(), Diags.end());
508 }
509 }
Richard Smith745f5142012-01-27 01:14:48 +0000510
511 /// Should we continue evaluation as much as possible after encountering a
512 /// construct which can't be folded?
513 bool keepEvaluatingAfterFailure() {
514 return CheckingPotentialConstantExpression && EvalStatus.Diag->empty();
515 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000516 };
Richard Smithf15fda02012-02-02 01:16:57 +0000517
518 /// Object used to treat all foldable expressions as constant expressions.
519 struct FoldConstant {
520 bool Enabled;
521
522 explicit FoldConstant(EvalInfo &Info)
523 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
524 !Info.EvalStatus.HasSideEffects) {
525 }
526 // Treat the value we've computed since this object was created as constant.
527 void Fold(EvalInfo &Info) {
528 if (Enabled && !Info.EvalStatus.Diag->empty() &&
529 !Info.EvalStatus.HasSideEffects)
530 Info.EvalStatus.Diag->clear();
531 }
532 };
Richard Smith08d6e032011-12-16 19:06:07 +0000533}
Richard Smithbd552ef2011-10-31 05:52:43 +0000534
Richard Smithb4e85ed2012-01-06 16:39:00 +0000535bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
536 CheckSubobjectKind CSK) {
537 if (Invalid)
538 return false;
539 if (isOnePastTheEnd()) {
540 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
541 << CSK;
542 setInvalid();
543 return false;
544 }
545 return true;
546}
547
548void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
549 const Expr *E, uint64_t N) {
550 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
551 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
552 << static_cast<int>(N) << /*array*/ 0
553 << static_cast<unsigned>(MostDerivedArraySize);
554 else
555 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
556 << static_cast<int>(N) << /*non-array*/ 1;
557 setInvalid();
558}
559
Richard Smith08d6e032011-12-16 19:06:07 +0000560CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
561 const FunctionDecl *Callee, const LValue *This,
562 const CCValue *Arguments)
563 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
564 This(This), Arguments(Arguments) {
565 Info.CurrentCall = this;
566 ++Info.CallStackDepth;
567}
568
569CallStackFrame::~CallStackFrame() {
570 assert(Info.CurrentCall == this && "calls retired out of order");
571 --Info.CallStackDepth;
572 Info.CurrentCall = Caller;
573}
574
575/// Produce a string describing the given constexpr call.
576static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
577 unsigned ArgIndex = 0;
578 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000579 !isa<CXXConstructorDecl>(Frame->Callee) &&
580 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000581
582 if (!IsMemberCall)
583 Out << *Frame->Callee << '(';
584
585 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
586 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000587 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000588 Out << ", ";
589
590 const ParmVarDecl *Param = *I;
591 const CCValue &Arg = Frame->Arguments[ArgIndex];
592 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
593 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
594 else {
595 // Deliberately slice off the frame to form an APValue we can print.
596 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
597 Arg.getLValueDesignator().Entries,
Richard Smithb4e85ed2012-01-06 16:39:00 +0000598 Arg.getLValueDesignator().IsOnePastTheEnd);
Richard Smith08d6e032011-12-16 19:06:07 +0000599 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
600 }
601
602 if (ArgIndex == 0 && IsMemberCall)
603 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000604 }
605
Richard Smith08d6e032011-12-16 19:06:07 +0000606 Out << ')';
607}
608
609void EvalInfo::addCallStack(unsigned Limit) {
610 // Determine which calls to skip, if any.
611 unsigned ActiveCalls = CallStackDepth - 1;
612 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
613 if (Limit && Limit < ActiveCalls) {
614 SkipStart = Limit / 2 + Limit % 2;
615 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000616 }
617
Richard Smith08d6e032011-12-16 19:06:07 +0000618 // Walk the call stack and add the diagnostics.
619 unsigned CallIdx = 0;
620 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
621 Frame = Frame->Caller, ++CallIdx) {
622 // Skip this call?
623 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
624 if (CallIdx == SkipStart) {
625 // Note that we're skipping calls.
626 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
627 << unsigned(ActiveCalls - Limit);
628 }
629 continue;
630 }
631
632 llvm::SmallVector<char, 128> Buffer;
633 llvm::raw_svector_ostream Out(Buffer);
634 describeCall(Frame, Out);
635 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
636 }
637}
638
639namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000640 struct ComplexValue {
641 private:
642 bool IsInt;
643
644 public:
645 APSInt IntReal, IntImag;
646 APFloat FloatReal, FloatImag;
647
648 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
649
650 void makeComplexFloat() { IsInt = false; }
651 bool isComplexFloat() const { return !IsInt; }
652 APFloat &getComplexFloatReal() { return FloatReal; }
653 APFloat &getComplexFloatImag() { return FloatImag; }
654
655 void makeComplexInt() { IsInt = true; }
656 bool isComplexInt() const { return IsInt; }
657 APSInt &getComplexIntReal() { return IntReal; }
658 APSInt &getComplexIntImag() { return IntImag; }
659
Richard Smith47a1eed2011-10-29 20:57:55 +0000660 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000661 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000662 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000663 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000664 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000665 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000666 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000667 assert(v.isComplexFloat() || v.isComplexInt());
668 if (v.isComplexFloat()) {
669 makeComplexFloat();
670 FloatReal = v.getComplexFloatReal();
671 FloatImag = v.getComplexFloatImag();
672 } else {
673 makeComplexInt();
674 IntReal = v.getComplexIntReal();
675 IntImag = v.getComplexIntImag();
676 }
677 }
John McCallf4cf1a12010-05-07 17:22:02 +0000678 };
John McCallefdb83e2010-05-07 21:00:08 +0000679
680 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000681 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000682 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000683 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000684 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000685
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000686 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000687 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000688 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000689 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000690 SubobjectDesignator &getLValueDesignator() { return Designator; }
691 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000692
Richard Smith47a1eed2011-10-29 20:57:55 +0000693 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000694 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000695 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000696 void setFrom(const CCValue &V) {
697 assert(V.isLValue());
698 Base = V.getLValueBase();
699 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000700 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000701 Designator = V.getLValueDesignator();
702 }
703
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000704 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
705 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000706 Offset = CharUnits::Zero();
707 Frame = F;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000708 Designator = SubobjectDesignator(getType(B));
709 }
710
711 // Check that this LValue is not based on a null pointer. If it is, produce
712 // a diagnostic and mark the designator as invalid.
713 bool checkNullPointer(EvalInfo &Info, const Expr *E,
714 CheckSubobjectKind CSK) {
715 if (Designator.Invalid)
716 return false;
717 if (!Base) {
718 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
719 << CSK;
720 Designator.setInvalid();
721 return false;
722 }
723 return true;
724 }
725
726 // Check this LValue refers to an object. If not, set the designator to be
727 // invalid and emit a diagnostic.
728 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
729 return checkNullPointer(Info, E, CSK) &&
730 Designator.checkSubobject(Info, E, CSK);
731 }
732
733 void addDecl(EvalInfo &Info, const Expr *E,
734 const Decl *D, bool Virtual = false) {
735 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
736 Designator.addDeclUnchecked(D, Virtual);
737 }
738 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
739 checkSubobject(Info, E, CSK_ArrayToPointer);
740 Designator.addArrayUnchecked(CAT);
741 }
742 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
743 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
744 return;
745 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000746 }
John McCallefdb83e2010-05-07 21:00:08 +0000747 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000748
749 struct MemberPtr {
750 MemberPtr() {}
751 explicit MemberPtr(const ValueDecl *Decl) :
752 DeclAndIsDerivedMember(Decl, false), Path() {}
753
754 /// The member or (direct or indirect) field referred to by this member
755 /// pointer, or 0 if this is a null member pointer.
756 const ValueDecl *getDecl() const {
757 return DeclAndIsDerivedMember.getPointer();
758 }
759 /// Is this actually a member of some type derived from the relevant class?
760 bool isDerivedMember() const {
761 return DeclAndIsDerivedMember.getInt();
762 }
763 /// Get the class which the declaration actually lives in.
764 const CXXRecordDecl *getContainingRecord() const {
765 return cast<CXXRecordDecl>(
766 DeclAndIsDerivedMember.getPointer()->getDeclContext());
767 }
768
769 void moveInto(CCValue &V) const {
770 V = CCValue(getDecl(), isDerivedMember(), Path);
771 }
772 void setFrom(const CCValue &V) {
773 assert(V.isMemberPointer());
774 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
775 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
776 Path.clear();
777 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
778 Path.insert(Path.end(), P.begin(), P.end());
779 }
780
781 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
782 /// whether the member is a member of some class derived from the class type
783 /// of the member pointer.
784 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
785 /// Path - The path of base/derived classes from the member declaration's
786 /// class (exclusive) to the class type of the member pointer (inclusive).
787 SmallVector<const CXXRecordDecl*, 4> Path;
788
789 /// Perform a cast towards the class of the Decl (either up or down the
790 /// hierarchy).
791 bool castBack(const CXXRecordDecl *Class) {
792 assert(!Path.empty());
793 const CXXRecordDecl *Expected;
794 if (Path.size() >= 2)
795 Expected = Path[Path.size() - 2];
796 else
797 Expected = getContainingRecord();
798 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
799 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
800 // if B does not contain the original member and is not a base or
801 // derived class of the class containing the original member, the result
802 // of the cast is undefined.
803 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
804 // (D::*). We consider that to be a language defect.
805 return false;
806 }
807 Path.pop_back();
808 return true;
809 }
810 /// Perform a base-to-derived member pointer cast.
811 bool castToDerived(const CXXRecordDecl *Derived) {
812 if (!getDecl())
813 return true;
814 if (!isDerivedMember()) {
815 Path.push_back(Derived);
816 return true;
817 }
818 if (!castBack(Derived))
819 return false;
820 if (Path.empty())
821 DeclAndIsDerivedMember.setInt(false);
822 return true;
823 }
824 /// Perform a derived-to-base member pointer cast.
825 bool castToBase(const CXXRecordDecl *Base) {
826 if (!getDecl())
827 return true;
828 if (Path.empty())
829 DeclAndIsDerivedMember.setInt(true);
830 if (isDerivedMember()) {
831 Path.push_back(Base);
832 return true;
833 }
834 return castBack(Base);
835 }
836 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000837
Richard Smithb02e4622012-02-01 01:42:44 +0000838 /// Compare two member pointers, which are assumed to be of the same type.
839 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
840 if (!LHS.getDecl() || !RHS.getDecl())
841 return !LHS.getDecl() && !RHS.getDecl();
842 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
843 return false;
844 return LHS.Path == RHS.Path;
845 }
846
Richard Smithc1c5f272011-12-13 06:39:58 +0000847 /// Kinds of constant expression checking, for diagnostics.
848 enum CheckConstantExpressionKind {
849 CCEK_Constant, ///< A normal constant.
850 CCEK_ReturnValue, ///< A constexpr function return value.
851 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
852 };
John McCallf4cf1a12010-05-07 17:22:02 +0000853}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000854
Richard Smith47a1eed2011-10-29 20:57:55 +0000855static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000856static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000857 const LValue &This, const Expr *E,
858 CheckConstantExpressionKind CCEK
859 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000860static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
861static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000862static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
863 EvalInfo &Info);
864static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000865static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000866static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000867 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000868static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000869static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000870
871//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000872// Misc utilities
873//===----------------------------------------------------------------------===//
874
Richard Smith180f4792011-11-10 06:34:14 +0000875/// Should this call expression be treated as a string literal?
876static bool IsStringLiteralCall(const CallExpr *E) {
877 unsigned Builtin = E->isBuiltinCall();
878 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
879 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
880}
881
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000882static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000883 // C++11 [expr.const]p3 An address constant expression is a prvalue core
884 // constant expression of pointer type that evaluates to...
885
886 // ... a null pointer value, or a prvalue core constant expression of type
887 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000888 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000889
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000890 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
891 // ... the address of an object with static storage duration,
892 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
893 return VD->hasGlobalStorage();
894 // ... the address of a function,
895 return isa<FunctionDecl>(D);
896 }
897
898 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000899 switch (E->getStmtClass()) {
900 default:
901 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000902 case Expr::CompoundLiteralExprClass:
903 return cast<CompoundLiteralExpr>(E)->isFileScope();
904 // A string literal has static storage duration.
905 case Expr::StringLiteralClass:
906 case Expr::PredefinedExprClass:
907 case Expr::ObjCStringLiteralClass:
908 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000909 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000910 return true;
911 case Expr::CallExprClass:
912 return IsStringLiteralCall(cast<CallExpr>(E));
913 // For GCC compatibility, &&label has static storage duration.
914 case Expr::AddrLabelExprClass:
915 return true;
916 // A Block literal expression may be used as the initialization value for
917 // Block variables at global or local static scope.
918 case Expr::BlockExprClass:
919 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000920 case Expr::ImplicitValueInitExprClass:
921 // FIXME:
922 // We can never form an lvalue with an implicit value initialization as its
923 // base through expression evaluation, so these only appear in one case: the
924 // implicit variable declaration we invent when checking whether a constexpr
925 // constructor can produce a constant expression. We must assume that such
926 // an expression might be a global lvalue.
927 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000928 }
John McCall42c8f872010-05-10 23:27:23 +0000929}
930
Richard Smith9a17a682011-11-07 05:07:52 +0000931/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000932/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000933/// either LValue or CCValue. Return true if we can fold this expression,
934/// whether or not it's a constant expression.
Richard Smith9a17a682011-11-07 05:07:52 +0000935template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000936static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000937 const T &LVal, APValue &Value,
938 CheckConstantExpressionKind CCEK) {
939 APValue::LValueBase Base = LVal.getLValueBase();
940 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
941
942 if (!IsGlobalLValue(Base)) {
943 if (Info.getLangOpts().CPlusPlus0x) {
944 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
945 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
946 << E->isGLValue() << !Designator.Entries.empty()
947 << !!VD << CCEK << VD;
948 if (VD)
949 Info.Note(VD->getLocation(), diag::note_declared_at);
950 else
951 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
952 diag::note_constexpr_temporary_here);
953 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000954 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000955 }
Richard Smith61e61622012-01-12 06:08:57 +0000956 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000957 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000958 }
Richard Smith9a17a682011-11-07 05:07:52 +0000959
Richard Smithb4e85ed2012-01-06 16:39:00 +0000960 bool IsReferenceType = E->isGLValue();
961
962 if (Designator.Invalid) {
Richard Smith61e61622012-01-12 06:08:57 +0000963 // This is not a core constant expression. An appropriate diagnostic will
964 // have already been produced.
Richard Smith9a17a682011-11-07 05:07:52 +0000965 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
966 APValue::NoLValuePath());
967 return true;
968 }
969
Richard Smithb4e85ed2012-01-06 16:39:00 +0000970 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
971 Designator.Entries, Designator.IsOnePastTheEnd);
972
973 // Allow address constant expressions to be past-the-end pointers. This is
974 // an extension: the standard requires them to point to an object.
975 if (!IsReferenceType)
976 return true;
977
978 // A reference constant expression must refer to an object.
979 if (!Base) {
980 // FIXME: diagnostic
981 Info.CCEDiag(E->getExprLoc());
Richard Smith61e61622012-01-12 06:08:57 +0000982 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000983 }
984
Richard Smithc1c5f272011-12-13 06:39:58 +0000985 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +0000986 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000987 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
988 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
989 << !Designator.Entries.empty() << !!VD << VD;
990 if (VD)
991 Info.Note(VD->getLocation(), diag::note_declared_at);
992 else
993 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
994 diag::note_constexpr_temporary_here);
Richard Smithc1c5f272011-12-13 06:39:58 +0000995 }
996
Richard Smith9a17a682011-11-07 05:07:52 +0000997 return true;
998}
999
Richard Smith51201882011-12-30 21:15:51 +00001000/// Check that this core constant expression is of literal type, and if not,
1001/// produce an appropriate diagnostic.
1002static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1003 if (!E->isRValue() || E->getType()->isLiteralType())
1004 return true;
1005
1006 // Prvalue constant expressions must be of literal types.
1007 if (Info.getLangOpts().CPlusPlus0x)
1008 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
1009 << E->getType();
1010 else
1011 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1012 return false;
1013}
1014
Richard Smith47a1eed2011-10-29 20:57:55 +00001015/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +00001016/// constant expression, and if it is, produce the corresponding constant value.
Richard Smith51201882011-12-30 21:15:51 +00001017/// If not, report an appropriate diagnostic. Does not check that the expression
1018/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +00001019static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +00001020 const CCValue &CCValue, APValue &Value,
1021 CheckConstantExpressionKind CCEK
1022 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +00001023 if (!CCValue.isLValue()) {
1024 Value = CCValue;
1025 return true;
1026 }
Richard Smithc1c5f272011-12-13 06:39:58 +00001027 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +00001028}
1029
Richard Smith9e36b532011-10-31 05:11:32 +00001030const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001031 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001032}
1033
1034static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001035 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +00001036}
1037
Richard Smith65ac5982011-11-01 21:06:14 +00001038static bool IsWeakLValue(const LValue &Value) {
1039 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001040 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001041}
1042
Richard Smithe24f5fc2011-11-17 22:56:20 +00001043static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001044 // A null base expression indicates a null pointer. These are always
1045 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001046 if (!Value.getLValueBase()) {
1047 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001048 return true;
1049 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001050
Richard Smithe24f5fc2011-11-17 22:56:20 +00001051 // We have a non-null base. These are generally known to be true, but if it's
1052 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001053 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001054 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001055 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001056}
1057
Richard Smith47a1eed2011-10-29 20:57:55 +00001058static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001059 switch (Val.getKind()) {
1060 case APValue::Uninitialized:
1061 return false;
1062 case APValue::Int:
1063 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001064 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001065 case APValue::Float:
1066 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001067 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001068 case APValue::ComplexInt:
1069 Result = Val.getComplexIntReal().getBoolValue() ||
1070 Val.getComplexIntImag().getBoolValue();
1071 return true;
1072 case APValue::ComplexFloat:
1073 Result = !Val.getComplexFloatReal().isZero() ||
1074 !Val.getComplexFloatImag().isZero();
1075 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001076 case APValue::LValue:
1077 return EvalPointerValueAsBool(Val, Result);
1078 case APValue::MemberPointer:
1079 Result = Val.getMemberPointerDecl();
1080 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001081 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001082 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001083 case APValue::Struct:
1084 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001085 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001086 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001087 }
1088
Richard Smithc49bd112011-10-28 17:51:58 +00001089 llvm_unreachable("unknown APValue kind");
1090}
1091
1092static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1093 EvalInfo &Info) {
1094 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001095 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001096 if (!Evaluate(Val, Info, E))
1097 return false;
1098 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001099}
1100
Richard Smithc1c5f272011-12-13 06:39:58 +00001101template<typename T>
1102static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1103 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001104 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001105 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001106 return false;
1107}
1108
1109static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1110 QualType SrcType, const APFloat &Value,
1111 QualType DestType, APSInt &Result) {
1112 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001113 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001114 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Richard Smithc1c5f272011-12-13 06:39:58 +00001116 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001117 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001118 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1119 & APFloat::opInvalidOp)
1120 return HandleOverflow(Info, E, Value, DestType);
1121 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001122}
1123
Richard Smithc1c5f272011-12-13 06:39:58 +00001124static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1125 QualType SrcType, QualType DestType,
1126 APFloat &Result) {
1127 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001128 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001129 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1130 APFloat::rmNearestTiesToEven, &ignored)
1131 & APFloat::opOverflow)
1132 return HandleOverflow(Info, E, Value, DestType);
1133 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001134}
1135
Richard Smithf72fccf2012-01-30 22:27:01 +00001136static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1137 QualType DestType, QualType SrcType,
1138 APSInt &Value) {
1139 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001140 APSInt Result = Value;
1141 // Figure out if this is a truncate, extend or noop cast.
1142 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001143 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001144 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001145 return Result;
1146}
1147
Richard Smithc1c5f272011-12-13 06:39:58 +00001148static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1149 QualType SrcType, const APSInt &Value,
1150 QualType DestType, APFloat &Result) {
1151 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1152 if (Result.convertFromAPInt(Value, Value.isSigned(),
1153 APFloat::rmNearestTiesToEven)
1154 & APFloat::opOverflow)
1155 return HandleOverflow(Info, E, Value, DestType);
1156 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001157}
1158
Eli Friedmane6a24e82011-12-22 03:51:45 +00001159static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1160 llvm::APInt &Res) {
1161 CCValue SVal;
1162 if (!Evaluate(SVal, Info, E))
1163 return false;
1164 if (SVal.isInt()) {
1165 Res = SVal.getInt();
1166 return true;
1167 }
1168 if (SVal.isFloat()) {
1169 Res = SVal.getFloat().bitcastToAPInt();
1170 return true;
1171 }
1172 if (SVal.isVector()) {
1173 QualType VecTy = E->getType();
1174 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1175 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1176 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1177 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1178 Res = llvm::APInt::getNullValue(VecSize);
1179 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1180 APValue &Elt = SVal.getVectorElt(i);
1181 llvm::APInt EltAsInt;
1182 if (Elt.isInt()) {
1183 EltAsInt = Elt.getInt();
1184 } else if (Elt.isFloat()) {
1185 EltAsInt = Elt.getFloat().bitcastToAPInt();
1186 } else {
1187 // Don't try to handle vectors of anything other than int or float
1188 // (not sure if it's possible to hit this case).
1189 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1190 return false;
1191 }
1192 unsigned BaseEltSize = EltAsInt.getBitWidth();
1193 if (BigEndian)
1194 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1195 else
1196 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1197 }
1198 return true;
1199 }
1200 // Give up if the input isn't an int, float, or vector. For example, we
1201 // reject "(v4i16)(intptr_t)&a".
1202 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1203 return false;
1204}
1205
Richard Smithb4e85ed2012-01-06 16:39:00 +00001206/// Cast an lvalue referring to a base subobject to a derived class, by
1207/// truncating the lvalue's path to the given length.
1208static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1209 const RecordDecl *TruncatedType,
1210 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001211 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001212
1213 // Check we actually point to a derived class object.
1214 if (TruncatedElements == D.Entries.size())
1215 return true;
1216 assert(TruncatedElements >= D.MostDerivedPathLength &&
1217 "not casting to a derived class");
1218 if (!Result.checkSubobject(Info, E, CSK_Derived))
1219 return false;
1220
1221 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001222 const RecordDecl *RD = TruncatedType;
1223 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001224 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1225 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001226 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001227 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001228 else
Richard Smith180f4792011-11-10 06:34:14 +00001229 Result.Offset -= Layout.getBaseClassOffset(Base);
1230 RD = Base;
1231 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001232 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001233 return true;
1234}
1235
Richard Smithb4e85ed2012-01-06 16:39:00 +00001236static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001237 const CXXRecordDecl *Derived,
1238 const CXXRecordDecl *Base,
1239 const ASTRecordLayout *RL = 0) {
1240 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1241 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001242 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001243}
1244
Richard Smithb4e85ed2012-01-06 16:39:00 +00001245static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001246 const CXXRecordDecl *DerivedDecl,
1247 const CXXBaseSpecifier *Base) {
1248 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1249
1250 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001251 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001252 return true;
1253 }
1254
Richard Smithb4e85ed2012-01-06 16:39:00 +00001255 SubobjectDesignator &D = Obj.Designator;
1256 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001257 return false;
1258
Richard Smithb4e85ed2012-01-06 16:39:00 +00001259 // Extract most-derived object and corresponding type.
1260 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1261 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1262 return false;
1263
1264 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001265 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1266 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001267 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001268 return true;
1269}
1270
1271/// Update LVal to refer to the given field, which must be a member of the type
1272/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001273static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001274 const FieldDecl *FD,
1275 const ASTRecordLayout *RL = 0) {
1276 if (!RL)
1277 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1278
1279 unsigned I = FD->getFieldIndex();
1280 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001281 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001282}
1283
Richard Smithd9b02e72012-01-25 22:15:11 +00001284/// Update LVal to refer to the given indirect field.
1285static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1286 LValue &LVal,
1287 const IndirectFieldDecl *IFD) {
1288 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1289 CE = IFD->chain_end(); C != CE; ++C)
1290 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1291}
1292
Richard Smith180f4792011-11-10 06:34:14 +00001293/// Get the size of the given type in char units.
1294static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1295 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1296 // extension.
1297 if (Type->isVoidType() || Type->isFunctionType()) {
1298 Size = CharUnits::One();
1299 return true;
1300 }
1301
1302 if (!Type->isConstantSizeType()) {
1303 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001304 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001305 return false;
1306 }
1307
1308 Size = Info.Ctx.getTypeSizeInChars(Type);
1309 return true;
1310}
1311
1312/// Update a pointer value to model pointer arithmetic.
1313/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001314/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001315/// \param LVal - The pointer value to be updated.
1316/// \param EltTy - The pointee type represented by LVal.
1317/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001318static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1319 LValue &LVal, QualType EltTy,
1320 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001321 CharUnits SizeOfPointee;
1322 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1323 return false;
1324
1325 // Compute the new offset in the appropriate width.
1326 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001327 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001328 return true;
1329}
1330
Richard Smith03f96112011-10-24 17:54:18 +00001331/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001332static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1333 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001334 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001335 // If this is a parameter to an active constexpr function call, perform
1336 // argument substitution.
1337 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001338 // Assume arguments of a potential constant expression are unknown
1339 // constant expressions.
1340 if (Info.CheckingPotentialConstantExpression)
1341 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001342 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001343 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001344 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001345 }
Richard Smith177dce72011-11-01 16:57:24 +00001346 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1347 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001348 }
Richard Smith03f96112011-10-24 17:54:18 +00001349
Richard Smith099e7f62011-12-19 06:19:21 +00001350 // Dig out the initializer, and use the declaration which it's attached to.
1351 const Expr *Init = VD->getAnyInitializer(VD);
1352 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001353 // If we're checking a potential constant expression, the variable could be
1354 // initialized later.
1355 if (!Info.CheckingPotentialConstantExpression)
1356 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001357 return false;
1358 }
1359
Richard Smith180f4792011-11-10 06:34:14 +00001360 // If we're currently evaluating the initializer of this declaration, use that
1361 // in-flight value.
1362 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001363 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1364 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001365 return !Result.isUninit();
1366 }
1367
Richard Smith65ac5982011-11-01 21:06:14 +00001368 // Never evaluate the initializer of a weak variable. We can't be sure that
1369 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001370 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001371 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001372 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001373 }
Richard Smith65ac5982011-11-01 21:06:14 +00001374
Richard Smith099e7f62011-12-19 06:19:21 +00001375 // Check that we can fold the initializer. In C++, we will have already done
1376 // this in the cases where it matters for conformance.
1377 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1378 if (!VD->evaluateValue(Notes)) {
1379 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1380 Notes.size() + 1) << VD;
1381 Info.Note(VD->getLocation(), diag::note_declared_at);
1382 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001383 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001384 } else if (!VD->checkInitIsICE()) {
1385 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1386 Notes.size() + 1) << VD;
1387 Info.Note(VD->getLocation(), diag::note_declared_at);
1388 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001389 }
Richard Smith03f96112011-10-24 17:54:18 +00001390
Richard Smithb4e85ed2012-01-06 16:39:00 +00001391 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001392 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001393}
1394
Richard Smithc49bd112011-10-28 17:51:58 +00001395static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001396 Qualifiers Quals = T.getQualifiers();
1397 return Quals.hasConst() && !Quals.hasVolatile();
1398}
1399
Richard Smith59efe262011-11-11 04:05:33 +00001400/// Get the base index of the given base class within an APValue representing
1401/// the given derived class.
1402static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1403 const CXXRecordDecl *Base) {
1404 Base = Base->getCanonicalDecl();
1405 unsigned Index = 0;
1406 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1407 E = Derived->bases_end(); I != E; ++I, ++Index) {
1408 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1409 return Index;
1410 }
1411
1412 llvm_unreachable("base class missing from derived class's bases list");
1413}
1414
Richard Smithcc5d4f62011-11-07 09:22:26 +00001415/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001416static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1417 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001418 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001419 if (Sub.Invalid)
1420 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001421 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001422 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001423 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001424 (unsigned)diag::note_constexpr_read_past_end :
1425 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001426 return false;
1427 }
Richard Smithf64699e2011-11-11 08:28:03 +00001428 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001429 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001430 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1431 // This object might be initialized later.
1432 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001433
1434 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1435 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001436 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001437 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001438 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001439 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001440 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001441 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001442 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001443 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001444 // Note, it should not be possible to form a pointer with a valid
1445 // designator which points more than one past the end of the array.
1446 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001447 (unsigned)diag::note_constexpr_read_past_end :
1448 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001449 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001450 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001451 if (O->getArrayInitializedElts() > Index)
1452 O = &O->getArrayInitializedElt(Index);
1453 else
1454 O = &O->getArrayFiller();
1455 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001456 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1457 // Next subobject is a class, struct or union field.
1458 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1459 if (RD->isUnion()) {
1460 const FieldDecl *UnionField = O->getUnionField();
1461 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001462 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001463 Info.Diag(E->getExprLoc(),
1464 diag::note_constexpr_read_inactive_union_member)
1465 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001466 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001467 }
Richard Smith180f4792011-11-10 06:34:14 +00001468 O = &O->getUnionValue();
1469 } else
1470 O = &O->getStructField(Field->getFieldIndex());
1471 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001472
1473 if (ObjType.isVolatileQualified()) {
1474 if (Info.getLangOpts().CPlusPlus) {
1475 // FIXME: Include a description of the path to the volatile subobject.
1476 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1477 << 2 << Field;
1478 Info.Note(Field->getLocation(), diag::note_declared_at);
1479 } else {
1480 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1481 }
1482 return false;
1483 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001484 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001485 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001486 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1487 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1488 O = &O->getStructBase(getBaseIndex(Derived, Base));
1489 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001490 }
Richard Smith180f4792011-11-10 06:34:14 +00001491
Richard Smithf48fdb02011-12-09 22:58:01 +00001492 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001493 if (!Info.CheckingPotentialConstantExpression)
1494 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001495 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001496 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001497 }
1498
Richard Smithb4e85ed2012-01-06 16:39:00 +00001499 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001500 return true;
1501}
1502
Richard Smithf15fda02012-02-02 01:16:57 +00001503/// Find the position where two subobject designators diverge, or equivalently
1504/// the length of the common initial subsequence.
1505static unsigned FindDesignatorMismatch(QualType ObjType,
1506 const SubobjectDesignator &A,
1507 const SubobjectDesignator &B,
1508 bool &WasArrayIndex) {
1509 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1510 for (/**/; I != N; ++I) {
1511 if (!ObjType.isNull() && ObjType->isArrayType()) {
1512 // Next subobject is an array element.
1513 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1514 WasArrayIndex = true;
1515 return I;
1516 }
1517 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
1518 } else {
1519 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1520 WasArrayIndex = false;
1521 return I;
1522 }
1523 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1524 // Next subobject is a field.
1525 ObjType = FD->getType();
1526 else
1527 // Next subobject is a base class.
1528 ObjType = QualType();
1529 }
1530 }
1531 WasArrayIndex = false;
1532 return I;
1533}
1534
1535/// Determine whether the given subobject designators refer to elements of the
1536/// same array object.
1537static bool AreElementsOfSameArray(QualType ObjType,
1538 const SubobjectDesignator &A,
1539 const SubobjectDesignator &B) {
1540 if (A.Entries.size() != B.Entries.size())
1541 return false;
1542
1543 bool IsArray = A.MostDerivedArraySize != 0;
1544 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1545 // A is a subobject of the array element.
1546 return false;
1547
1548 // If A (and B) designates an array element, the last entry will be the array
1549 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1550 // of length 1' case, and the entire path must match.
1551 bool WasArrayIndex;
1552 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1553 return CommonLength >= A.Entries.size() - IsArray;
1554}
1555
Richard Smith180f4792011-11-10 06:34:14 +00001556/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1557/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1558/// for looking up the glvalue referred to by an entity of reference type.
1559///
1560/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001561/// \param Conv - The expression for which we are performing the conversion.
1562/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001563/// \param Type - The type we expect this conversion to produce.
1564/// \param LVal - The glvalue on which we are attempting to perform this action.
1565/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001566static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1567 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001568 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001569 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1570 if (!Info.getLangOpts().CPlusPlus)
1571 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1572
Richard Smithb4e85ed2012-01-06 16:39:00 +00001573 if (LVal.Designator.Invalid)
1574 // A diagnostic will have already been produced.
1575 return false;
1576
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001577 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001578 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001579 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001580
Richard Smithf48fdb02011-12-09 22:58:01 +00001581 if (!LVal.Base) {
1582 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001583 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1584 return false;
1585 }
1586
1587 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1588 // is not a constant expression (even if the object is non-volatile). We also
1589 // apply this rule to C++98, in order to conform to the expected 'volatile'
1590 // semantics.
1591 if (Type.isVolatileQualified()) {
1592 if (Info.getLangOpts().CPlusPlus)
1593 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1594 else
1595 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001596 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001597 }
Richard Smithc49bd112011-10-28 17:51:58 +00001598
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001599 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001600 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1601 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001602 // expressions are constant expressions too. Inside constexpr functions,
1603 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001604 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001605 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf15fda02012-02-02 01:16:57 +00001606 if (const VarDecl *VDef = VD->getDefinition())
1607 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001608 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001609 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001610 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001611 }
1612
Richard Smith7098cbd2011-12-21 05:04:46 +00001613 // DR1313: If the object is volatile-qualified but the glvalue was not,
1614 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001615 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001616 if (VT.isVolatileQualified()) {
1617 if (Info.getLangOpts().CPlusPlus) {
1618 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1619 Info.Note(VD->getLocation(), diag::note_declared_at);
1620 } else {
1621 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001622 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001623 return false;
1624 }
1625
1626 if (!isa<ParmVarDecl>(VD)) {
1627 if (VD->isConstexpr()) {
1628 // OK, we can read this variable.
1629 } else if (VT->isIntegralOrEnumerationType()) {
1630 if (!VT.isConstQualified()) {
1631 if (Info.getLangOpts().CPlusPlus) {
1632 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1633 Info.Note(VD->getLocation(), diag::note_declared_at);
1634 } else {
1635 Info.Diag(Loc);
1636 }
1637 return false;
1638 }
1639 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1640 // We support folding of const floating-point types, in order to make
1641 // static const data members of such types (supported as an extension)
1642 // more useful.
1643 if (Info.getLangOpts().CPlusPlus0x) {
1644 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1645 Info.Note(VD->getLocation(), diag::note_declared_at);
1646 } else {
1647 Info.CCEDiag(Loc);
1648 }
1649 } else {
1650 // FIXME: Allow folding of values of any literal type in all languages.
1651 if (Info.getLangOpts().CPlusPlus0x) {
1652 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1653 Info.Note(VD->getLocation(), diag::note_declared_at);
1654 } else {
1655 Info.Diag(Loc);
1656 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001657 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001658 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001659 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001660
Richard Smithf48fdb02011-12-09 22:58:01 +00001661 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001662 return false;
1663
Richard Smith47a1eed2011-10-29 20:57:55 +00001664 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001665 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001666
1667 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1668 // conversion. This happens when the declaration and the lvalue should be
1669 // considered synonymous, for instance when initializing an array of char
1670 // from a string literal. Continue as if the initializer lvalue was the
1671 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001672 assert(RVal.getLValueOffset().isZero() &&
1673 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001674 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001675 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001676 }
1677
Richard Smith7098cbd2011-12-21 05:04:46 +00001678 // Volatile temporary objects cannot be read in constant expressions.
1679 if (Base->getType().isVolatileQualified()) {
1680 if (Info.getLangOpts().CPlusPlus) {
1681 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1682 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1683 } else {
1684 Info.Diag(Loc);
1685 }
1686 return false;
1687 }
1688
Richard Smith0a3bdb62011-11-04 02:25:55 +00001689 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1690 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1691 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001692 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001693 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001694 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001695 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001696
1697 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001698 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001699 const ConstantArrayType *CAT =
1700 Info.Ctx.getAsConstantArrayType(S->getType());
1701 if (Index >= CAT->getSize().getZExtValue()) {
1702 // Note, it should not be possible to form a pointer which points more
1703 // than one past the end of the array without producing a prior const expr
1704 // diagnostic.
1705 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001706 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001707 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001708 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1709 Type->isUnsignedIntegerType());
1710 if (Index < S->getLength())
1711 Value = S->getCodeUnit(Index);
1712 RVal = CCValue(Value);
1713 return true;
1714 }
1715
Richard Smithcc5d4f62011-11-07 09:22:26 +00001716 if (Frame) {
1717 // If this is a temporary expression with a nontrivial initializer, grab the
1718 // value from the relevant stack frame.
1719 RVal = Frame->Temporaries[Base];
1720 } else if (const CompoundLiteralExpr *CLE
1721 = dyn_cast<CompoundLiteralExpr>(Base)) {
1722 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1723 // initializer until now for such expressions. Such an expression can't be
1724 // an ICE in C, so this only matters for fold.
1725 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1726 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1727 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001728 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001729 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001730 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001731 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001732
Richard Smithf48fdb02011-12-09 22:58:01 +00001733 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1734 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001735}
1736
Richard Smith59efe262011-11-11 04:05:33 +00001737/// Build an lvalue for the object argument of a member function call.
1738static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1739 LValue &This) {
1740 if (Object->getType()->isPointerType())
1741 return EvaluatePointer(Object, This, Info);
1742
1743 if (Object->isGLValue())
1744 return EvaluateLValue(Object, This, Info);
1745
Richard Smithe24f5fc2011-11-17 22:56:20 +00001746 if (Object->getType()->isLiteralType())
1747 return EvaluateTemporary(Object, This, Info);
1748
1749 return false;
1750}
1751
1752/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1753/// lvalue referring to the result.
1754///
1755/// \param Info - Information about the ongoing evaluation.
1756/// \param BO - The member pointer access operation.
1757/// \param LV - Filled in with a reference to the resulting object.
1758/// \param IncludeMember - Specifies whether the member itself is included in
1759/// the resulting LValue subobject designator. This is not possible when
1760/// creating a bound member function.
1761/// \return The field or method declaration to which the member pointer refers,
1762/// or 0 if evaluation fails.
1763static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1764 const BinaryOperator *BO,
1765 LValue &LV,
1766 bool IncludeMember = true) {
1767 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1768
Richard Smith745f5142012-01-27 01:14:48 +00001769 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1770 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001771 return 0;
1772
1773 MemberPtr MemPtr;
1774 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1775 return 0;
1776
1777 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1778 // member value, the behavior is undefined.
1779 if (!MemPtr.getDecl())
1780 return 0;
1781
Richard Smith745f5142012-01-27 01:14:48 +00001782 if (!EvalObjOK)
1783 return 0;
1784
Richard Smithe24f5fc2011-11-17 22:56:20 +00001785 if (MemPtr.isDerivedMember()) {
1786 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001787 // The end of the derived-to-base path for the base object must match the
1788 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001789 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001790 LV.Designator.Entries.size())
1791 return 0;
1792 unsigned PathLengthToMember =
1793 LV.Designator.Entries.size() - MemPtr.Path.size();
1794 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1795 const CXXRecordDecl *LVDecl = getAsBaseClass(
1796 LV.Designator.Entries[PathLengthToMember + I]);
1797 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1798 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1799 return 0;
1800 }
1801
1802 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001803 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1804 PathLengthToMember))
1805 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001806 } else if (!MemPtr.Path.empty()) {
1807 // Extend the LValue path with the member pointer's path.
1808 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1809 MemPtr.Path.size() + IncludeMember);
1810
1811 // Walk down to the appropriate base class.
1812 QualType LVType = BO->getLHS()->getType();
1813 if (const PointerType *PT = LVType->getAs<PointerType>())
1814 LVType = PT->getPointeeType();
1815 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1816 assert(RD && "member pointer access on non-class-type expression");
1817 // The first class in the path is that of the lvalue.
1818 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1819 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001820 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001821 RD = Base;
1822 }
1823 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001824 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001825 }
1826
1827 // Add the member. Note that we cannot build bound member functions here.
1828 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001829 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1830 HandleLValueMember(Info, BO, LV, FD);
1831 else if (const IndirectFieldDecl *IFD =
1832 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1833 HandleLValueIndirectMember(Info, BO, LV, IFD);
1834 else
1835 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001836 }
1837
1838 return MemPtr.getDecl();
1839}
1840
1841/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1842/// the provided lvalue, which currently refers to the base object.
1843static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1844 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001845 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001846 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001847 return false;
1848
Richard Smithb4e85ed2012-01-06 16:39:00 +00001849 QualType TargetQT = E->getType();
1850 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1851 TargetQT = PT->getPointeeType();
1852
1853 // Check this cast lands within the final derived-to-base subobject path.
1854 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1855 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1856 << D.MostDerivedType << TargetQT;
1857 return false;
1858 }
1859
Richard Smithe24f5fc2011-11-17 22:56:20 +00001860 // Check the type of the final cast. We don't need to check the path,
1861 // since a cast can only be formed if the path is unique.
1862 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001863 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1864 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001865 if (NewEntriesSize == D.MostDerivedPathLength)
1866 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1867 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001868 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001869 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1870 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1871 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001872 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001873 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001874
1875 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001876 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001877}
1878
Mike Stumpc4c90452009-10-27 22:09:17 +00001879namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001880enum EvalStmtResult {
1881 /// Evaluation failed.
1882 ESR_Failed,
1883 /// Hit a 'return' statement.
1884 ESR_Returned,
1885 /// Evaluation succeeded.
1886 ESR_Succeeded
1887};
1888}
1889
1890// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001891static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001892 const Stmt *S) {
1893 switch (S->getStmtClass()) {
1894 default:
1895 return ESR_Failed;
1896
1897 case Stmt::NullStmtClass:
1898 case Stmt::DeclStmtClass:
1899 return ESR_Succeeded;
1900
Richard Smithc1c5f272011-12-13 06:39:58 +00001901 case Stmt::ReturnStmtClass: {
1902 CCValue CCResult;
1903 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1904 if (!Evaluate(CCResult, Info, RetExpr) ||
1905 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1906 CCEK_ReturnValue))
1907 return ESR_Failed;
1908 return ESR_Returned;
1909 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001910
1911 case Stmt::CompoundStmtClass: {
1912 const CompoundStmt *CS = cast<CompoundStmt>(S);
1913 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1914 BE = CS->body_end(); BI != BE; ++BI) {
1915 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1916 if (ESR != ESR_Succeeded)
1917 return ESR;
1918 }
1919 return ESR_Succeeded;
1920 }
1921 }
1922}
1923
Richard Smith61802452011-12-22 02:22:31 +00001924/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1925/// default constructor. If so, we'll fold it whether or not it's marked as
1926/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1927/// so we need special handling.
1928static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001929 const CXXConstructorDecl *CD,
1930 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001931 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1932 return false;
1933
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001934 // Value-initialization does not call a trivial default constructor, so such a
1935 // call is a core constant expression whether or not the constructor is
1936 // constexpr.
1937 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001938 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001939 // FIXME: If DiagDecl is an implicitly-declared special member function,
1940 // we should be much more explicit about why it's not constexpr.
1941 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1942 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1943 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00001944 } else {
1945 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1946 }
1947 }
1948 return true;
1949}
1950
Richard Smithc1c5f272011-12-13 06:39:58 +00001951/// CheckConstexprFunction - Check that a function can be called in a constant
1952/// expression.
1953static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1954 const FunctionDecl *Declaration,
1955 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00001956 // Potential constant expressions can contain calls to declared, but not yet
1957 // defined, constexpr functions.
1958 if (Info.CheckingPotentialConstantExpression && !Definition &&
1959 Declaration->isConstexpr())
1960 return false;
1961
Richard Smithc1c5f272011-12-13 06:39:58 +00001962 // Can we evaluate this function call?
1963 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1964 return true;
1965
1966 if (Info.getLangOpts().CPlusPlus0x) {
1967 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001968 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1969 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001970 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1971 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1972 << DiagDecl;
1973 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1974 } else {
1975 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1976 }
1977 return false;
1978}
1979
Richard Smith180f4792011-11-10 06:34:14 +00001980namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001981typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001982}
1983
1984/// EvaluateArgs - Evaluate the arguments to a function call.
1985static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1986 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00001987 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001988 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00001989 I != E; ++I) {
1990 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
1991 // If we're checking for a potential constant expression, evaluate all
1992 // initializers even if some of them fail.
1993 if (!Info.keepEvaluatingAfterFailure())
1994 return false;
1995 Success = false;
1996 }
1997 }
1998 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00001999}
2000
Richard Smithd0dccea2011-10-28 22:34:42 +00002001/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002002static bool HandleFunctionCall(SourceLocation CallLoc,
2003 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002004 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00002005 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002006 ArgVector ArgValues(Args.size());
2007 if (!EvaluateArgs(Args, ArgValues, Info))
2008 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002009
Richard Smith745f5142012-01-27 01:14:48 +00002010 if (!Info.CheckCallLimit(CallLoc))
2011 return false;
2012
2013 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002014 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2015}
2016
Richard Smith180f4792011-11-10 06:34:14 +00002017/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002018static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002019 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002020 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002021 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002022 ArgVector ArgValues(Args.size());
2023 if (!EvaluateArgs(Args, ArgValues, Info))
2024 return false;
2025
Richard Smith745f5142012-01-27 01:14:48 +00002026 if (!Info.CheckCallLimit(CallLoc))
2027 return false;
2028
2029 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002030
2031 // If it's a delegating constructor, just delegate.
2032 if (Definition->isDelegatingConstructor()) {
2033 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
2034 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
2035 }
2036
Richard Smith610a60c2012-01-10 04:32:03 +00002037 // For a trivial copy or move constructor, perform an APValue copy. This is
2038 // essential for unions, where the operations performed by the constructor
2039 // cannot be represented by ctor-initializers.
Richard Smith180f4792011-11-10 06:34:14 +00002040 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith610a60c2012-01-10 04:32:03 +00002041 if (Definition->isDefaulted() &&
2042 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
2043 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
2044 LValue RHS;
2045 RHS.setFrom(ArgValues[0]);
2046 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00002047 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2048 RHS, Value))
2049 return false;
2050 assert((Value.isStruct() || Value.isUnion()) &&
2051 "trivial copy/move from non-class type?");
2052 // Any CCValue of class type must already be a constant expression.
2053 Result = Value;
2054 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00002055 }
2056
2057 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002058 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002059 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2060 std::distance(RD->field_begin(), RD->field_end()));
2061
2062 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2063
Richard Smith745f5142012-01-27 01:14:48 +00002064 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002065 unsigned BasesSeen = 0;
2066#ifndef NDEBUG
2067 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2068#endif
2069 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2070 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002071 LValue Subobject = This;
2072 APValue *Value = &Result;
2073
2074 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002075 if ((*I)->isBaseInitializer()) {
2076 QualType BaseType((*I)->getBaseClass(), 0);
2077#ifndef NDEBUG
2078 // Non-virtual base classes are initialized in the order in the class
2079 // definition. We cannot have a virtual base class for a literal type.
2080 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2081 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2082 "base class initializers not in expected order");
2083 ++BaseIt;
2084#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002085 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002086 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002087 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002088 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002089 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002090 if (RD->isUnion()) {
2091 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002092 Value = &Result.getUnionValue();
2093 } else {
2094 Value = &Result.getStructField(FD->getFieldIndex());
2095 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002096 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002097 // Walk the indirect field decl's chain to find the object to initialize,
2098 // and make sure we've initialized every step along it.
2099 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2100 CE = IFD->chain_end();
2101 C != CE; ++C) {
2102 FieldDecl *FD = cast<FieldDecl>(*C);
2103 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2104 // Switch the union field if it differs. This happens if we had
2105 // preceding zero-initialization, and we're now initializing a union
2106 // subobject other than the first.
2107 // FIXME: In this case, the values of the other subobjects are
2108 // specified, since zero-initialization sets all padding bits to zero.
2109 if (Value->isUninit() ||
2110 (Value->isUnion() && Value->getUnionField() != FD)) {
2111 if (CD->isUnion())
2112 *Value = APValue(FD);
2113 else
2114 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2115 std::distance(CD->field_begin(), CD->field_end()));
2116 }
Richard Smith745f5142012-01-27 01:14:48 +00002117 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002118 if (CD->isUnion())
2119 Value = &Value->getUnionValue();
2120 else
2121 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002122 }
Richard Smith180f4792011-11-10 06:34:14 +00002123 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002124 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002125 }
Richard Smith745f5142012-01-27 01:14:48 +00002126
2127 if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
2128 (*I)->isBaseInitializer()
2129 ? CCEK_Constant : CCEK_MemberInit)) {
2130 // If we're checking for a potential constant expression, evaluate all
2131 // initializers even if some of them fail.
2132 if (!Info.keepEvaluatingAfterFailure())
2133 return false;
2134 Success = false;
2135 }
Richard Smith180f4792011-11-10 06:34:14 +00002136 }
2137
Richard Smith745f5142012-01-27 01:14:48 +00002138 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002139}
2140
Richard Smithd0dccea2011-10-28 22:34:42 +00002141namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002142class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002143 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002144 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002145public:
2146
Richard Smith1e12c592011-10-16 21:26:27 +00002147 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002148
2149 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002150 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002151 return true;
2152 }
2153
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002154 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2155 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002156 return Visit(E->getResultExpr());
2157 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002158 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002159 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002160 return true;
2161 return false;
2162 }
John McCallf85e1932011-06-15 23:02:42 +00002163 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002164 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002165 return true;
2166 return false;
2167 }
2168 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002169 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002170 return true;
2171 return false;
2172 }
2173
Mike Stumpc4c90452009-10-27 22:09:17 +00002174 // We don't want to evaluate BlockExprs multiple times, as they generate
2175 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002176 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2177 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2178 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002179 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002180 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2181 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2182 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2183 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2184 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2185 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002186 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002187 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002188 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002189 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002190 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002191 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2192 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2193 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2194 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002195 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002196 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2197 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2198 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2199 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2200 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002201 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002202 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002203 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002204 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002205 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002206
2207 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002208 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002209 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2210 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002211 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002212 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002213 return false;
2214 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002215
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002216 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002217};
2218
John McCall56ca35d2011-02-17 10:25:35 +00002219class OpaqueValueEvaluation {
2220 EvalInfo &info;
2221 OpaqueValueExpr *opaqueValue;
2222
2223public:
2224 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2225 Expr *value)
2226 : info(info), opaqueValue(opaqueValue) {
2227
2228 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002229 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002230 this->opaqueValue = 0;
2231 return;
2232 }
John McCall56ca35d2011-02-17 10:25:35 +00002233 }
2234
2235 bool hasError() const { return opaqueValue == 0; }
2236
2237 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002238 // FIXME: This will not work for recursive constexpr functions using opaque
2239 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002240 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2241 }
2242};
2243
Mike Stumpc4c90452009-10-27 22:09:17 +00002244} // end anonymous namespace
2245
Eli Friedman4efaa272008-11-12 09:44:48 +00002246//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002247// Generic Evaluation
2248//===----------------------------------------------------------------------===//
2249namespace {
2250
Richard Smithf48fdb02011-12-09 22:58:01 +00002251// FIXME: RetTy is always bool. Remove it.
2252template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002253class ExprEvaluatorBase
2254 : public ConstStmtVisitor<Derived, RetTy> {
2255private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002256 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002257 return static_cast<Derived*>(this)->Success(V, E);
2258 }
Richard Smith51201882011-12-30 21:15:51 +00002259 RetTy DerivedZeroInitialization(const Expr *E) {
2260 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002261 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002262
2263protected:
2264 EvalInfo &Info;
2265 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2266 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2267
Richard Smithdd1f29b2011-12-12 09:28:41 +00002268 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002269 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002270 }
2271
2272 /// Report an evaluation error. This should only be called when an error is
2273 /// first discovered. When propagating an error, just return false.
2274 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002275 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002276 return false;
2277 }
2278 bool Error(const Expr *E) {
2279 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2280 }
2281
Richard Smith51201882011-12-30 21:15:51 +00002282 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002283
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002284public:
2285 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2286
2287 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002288 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002289 }
2290 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002291 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002292 }
2293
2294 RetTy VisitParenExpr(const ParenExpr *E)
2295 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2296 RetTy VisitUnaryExtension(const UnaryOperator *E)
2297 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2298 RetTy VisitUnaryPlus(const UnaryOperator *E)
2299 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2300 RetTy VisitChooseExpr(const ChooseExpr *E)
2301 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2302 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2303 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002304 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2305 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002306 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2307 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002308 // We cannot create any objects for which cleanups are required, so there is
2309 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2310 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2311 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002312
Richard Smithc216a012011-12-12 12:46:16 +00002313 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2314 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2315 return static_cast<Derived*>(this)->VisitCastExpr(E);
2316 }
2317 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2318 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2319 return static_cast<Derived*>(this)->VisitCastExpr(E);
2320 }
2321
Richard Smithe24f5fc2011-11-17 22:56:20 +00002322 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2323 switch (E->getOpcode()) {
2324 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002325 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002326
2327 case BO_Comma:
2328 VisitIgnoredValue(E->getLHS());
2329 return StmtVisitorTy::Visit(E->getRHS());
2330
2331 case BO_PtrMemD:
2332 case BO_PtrMemI: {
2333 LValue Obj;
2334 if (!HandleMemberPointerAccess(Info, E, Obj))
2335 return false;
2336 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002337 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002338 return false;
2339 return DerivedSuccess(Result, E);
2340 }
2341 }
2342 }
2343
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002344 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2345 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2346 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002347 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002348
2349 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002350 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002351 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002352
2353 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2354 }
2355
2356 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002357 bool IsBcpCall = false;
2358 // If the condition (ignoring parens) is a __builtin_constant_p call,
2359 // the result is a constant expression if it can be folded without
2360 // side-effects. This is an important GNU extension. See GCC PR38377
2361 // for discussion.
2362 if (const CallExpr *CallCE =
2363 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2364 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2365 IsBcpCall = true;
2366
2367 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2368 // constant expression; we can't check whether it's potentially foldable.
2369 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2370 return false;
2371
2372 FoldConstant Fold(Info);
2373
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002374 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002375 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002376 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002377
Richard Smithc49bd112011-10-28 17:51:58 +00002378 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Richard Smithf15fda02012-02-02 01:16:57 +00002379 if (!StmtVisitorTy::Visit(EvalExpr))
2380 return false;
2381
2382 if (IsBcpCall)
2383 Fold.Fold(Info);
2384
2385 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002386 }
2387
2388 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002389 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002390 if (!Value) {
2391 const Expr *Source = E->getSourceExpr();
2392 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002393 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002394 if (Source == E) { // sanity checking.
2395 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002396 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002397 }
2398 return StmtVisitorTy::Visit(Source);
2399 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002400 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002401 }
Richard Smithf10d9172011-10-11 21:43:33 +00002402
Richard Smithd0dccea2011-10-28 22:34:42 +00002403 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002404 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002405 QualType CalleeType = Callee->getType();
2406
Richard Smithd0dccea2011-10-28 22:34:42 +00002407 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002408 LValue *This = 0, ThisVal;
2409 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002410
Richard Smith59efe262011-11-11 04:05:33 +00002411 // Extract function decl and 'this' pointer from the callee.
2412 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002413 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002414 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2415 // Explicit bound member calls, such as x.f() or p->g();
2416 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002417 return false;
2418 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002419 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002420 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2421 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002422 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2423 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002424 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002425 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002426 return Error(Callee);
2427
2428 FD = dyn_cast<FunctionDecl>(Member);
2429 if (!FD)
2430 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002431 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002432 LValue Call;
2433 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002434 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002435
Richard Smithb4e85ed2012-01-06 16:39:00 +00002436 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002437 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002438 FD = dyn_cast_or_null<FunctionDecl>(
2439 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002440 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002441 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002442
2443 // Overloaded operator calls to member functions are represented as normal
2444 // calls with '*this' as the first argument.
2445 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2446 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002447 // FIXME: When selecting an implicit conversion for an overloaded
2448 // operator delete, we sometimes try to evaluate calls to conversion
2449 // operators without a 'this' parameter!
2450 if (Args.empty())
2451 return Error(E);
2452
Richard Smith59efe262011-11-11 04:05:33 +00002453 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2454 return false;
2455 This = &ThisVal;
2456 Args = Args.slice(1);
2457 }
2458
2459 // Don't call function pointers which have been cast to some other type.
2460 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002461 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002462 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002463 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002464
Richard Smithb04035a2012-02-01 02:39:43 +00002465 if (This && !This->checkSubobject(Info, E, CSK_This))
2466 return false;
2467
Richard Smithc1c5f272011-12-13 06:39:58 +00002468 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002469 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002470 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002471
Richard Smithc1c5f272011-12-13 06:39:58 +00002472 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002473 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2474 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002475 return false;
2476
Richard Smithb4e85ed2012-01-06 16:39:00 +00002477 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002478 }
2479
Richard Smithc49bd112011-10-28 17:51:58 +00002480 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2481 return StmtVisitorTy::Visit(E->getInitializer());
2482 }
Richard Smithf10d9172011-10-11 21:43:33 +00002483 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002484 if (E->getNumInits() == 0)
2485 return DerivedZeroInitialization(E);
2486 if (E->getNumInits() == 1)
2487 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002488 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002489 }
2490 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002491 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002492 }
2493 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002494 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002495 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002496 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002497 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002498 }
Richard Smithf10d9172011-10-11 21:43:33 +00002499
Richard Smith180f4792011-11-10 06:34:14 +00002500 /// A member expression where the object is a prvalue is itself a prvalue.
2501 RetTy VisitMemberExpr(const MemberExpr *E) {
2502 assert(!E->isArrow() && "missing call to bound member function?");
2503
2504 CCValue Val;
2505 if (!Evaluate(Val, Info, E->getBase()))
2506 return false;
2507
2508 QualType BaseTy = E->getBase()->getType();
2509
2510 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002511 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002512 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2513 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2514 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2515
Richard Smithb4e85ed2012-01-06 16:39:00 +00002516 SubobjectDesignator Designator(BaseTy);
2517 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002518
Richard Smithf48fdb02011-12-09 22:58:01 +00002519 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002520 DerivedSuccess(Val, E);
2521 }
2522
Richard Smithc49bd112011-10-28 17:51:58 +00002523 RetTy VisitCastExpr(const CastExpr *E) {
2524 switch (E->getCastKind()) {
2525 default:
2526 break;
2527
David Chisnall7a7ee302012-01-16 17:27:18 +00002528 case CK_AtomicToNonAtomic:
2529 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002530 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002531 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002532 return StmtVisitorTy::Visit(E->getSubExpr());
2533
2534 case CK_LValueToRValue: {
2535 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002536 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2537 return false;
2538 CCValue RVal;
2539 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2540 return false;
2541 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002542 }
2543 }
2544
Richard Smithf48fdb02011-12-09 22:58:01 +00002545 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002546 }
2547
Richard Smith8327fad2011-10-24 18:44:57 +00002548 /// Visit a value which is evaluated, but whose value is ignored.
2549 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002550 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002551 if (!Evaluate(Scratch, Info, E))
2552 Info.EvalStatus.HasSideEffects = true;
2553 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002554};
2555
2556}
2557
2558//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002559// Common base class for lvalue and temporary evaluation.
2560//===----------------------------------------------------------------------===//
2561namespace {
2562template<class Derived>
2563class LValueExprEvaluatorBase
2564 : public ExprEvaluatorBase<Derived, bool> {
2565protected:
2566 LValue &Result;
2567 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2568 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2569
2570 bool Success(APValue::LValueBase B) {
2571 Result.set(B);
2572 return true;
2573 }
2574
2575public:
2576 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2577 ExprEvaluatorBaseTy(Info), Result(Result) {}
2578
2579 bool Success(const CCValue &V, const Expr *E) {
2580 Result.setFrom(V);
2581 return true;
2582 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002583
Richard Smithe24f5fc2011-11-17 22:56:20 +00002584 bool VisitMemberExpr(const MemberExpr *E) {
2585 // Handle non-static data members.
2586 QualType BaseTy;
2587 if (E->isArrow()) {
2588 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2589 return false;
2590 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002591 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002592 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002593 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2594 return false;
2595 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002596 } else {
2597 if (!this->Visit(E->getBase()))
2598 return false;
2599 BaseTy = E->getBase()->getType();
2600 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002601
Richard Smithd9b02e72012-01-25 22:15:11 +00002602 const ValueDecl *MD = E->getMemberDecl();
2603 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2604 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2605 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2606 (void)BaseTy;
2607 HandleLValueMember(this->Info, E, Result, FD);
2608 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2609 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2610 } else
2611 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002612
Richard Smithd9b02e72012-01-25 22:15:11 +00002613 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002614 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002615 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002616 RefValue))
2617 return false;
2618 return Success(RefValue, E);
2619 }
2620 return true;
2621 }
2622
2623 bool VisitBinaryOperator(const BinaryOperator *E) {
2624 switch (E->getOpcode()) {
2625 default:
2626 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2627
2628 case BO_PtrMemD:
2629 case BO_PtrMemI:
2630 return HandleMemberPointerAccess(this->Info, E, Result);
2631 }
2632 }
2633
2634 bool VisitCastExpr(const CastExpr *E) {
2635 switch (E->getCastKind()) {
2636 default:
2637 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2638
2639 case CK_DerivedToBase:
2640 case CK_UncheckedDerivedToBase: {
2641 if (!this->Visit(E->getSubExpr()))
2642 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002643
2644 // Now figure out the necessary offset to add to the base LV to get from
2645 // the derived class to the base class.
2646 QualType Type = E->getSubExpr()->getType();
2647
2648 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2649 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002650 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002651 *PathI))
2652 return false;
2653 Type = (*PathI)->getType();
2654 }
2655
2656 return true;
2657 }
2658 }
2659 }
2660};
2661}
2662
2663//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002664// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002665//
2666// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2667// function designators (in C), decl references to void objects (in C), and
2668// temporaries (if building with -Wno-address-of-temporary).
2669//
2670// LValue evaluation produces values comprising a base expression of one of the
2671// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002672// - Declarations
2673// * VarDecl
2674// * FunctionDecl
2675// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002676// * CompoundLiteralExpr in C
2677// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002678// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002679// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002680// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002681// * ObjCEncodeExpr
2682// * AddrLabelExpr
2683// * BlockExpr
2684// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002685// - Locals and temporaries
2686// * Any Expr, with a Frame indicating the function in which the temporary was
2687// evaluated.
2688// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002689//===----------------------------------------------------------------------===//
2690namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002691class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002692 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002693public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002694 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2695 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002696
Richard Smithc49bd112011-10-28 17:51:58 +00002697 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2698
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002699 bool VisitDeclRefExpr(const DeclRefExpr *E);
2700 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002701 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002702 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2703 bool VisitMemberExpr(const MemberExpr *E);
2704 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2705 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002706 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002707 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2708 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002709
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002710 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002711 switch (E->getCastKind()) {
2712 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002713 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002714
Eli Friedmandb924222011-10-11 00:13:24 +00002715 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002716 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002717 if (!Visit(E->getSubExpr()))
2718 return false;
2719 Result.Designator.setInvalid();
2720 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002721
Richard Smithe24f5fc2011-11-17 22:56:20 +00002722 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002723 if (!Visit(E->getSubExpr()))
2724 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002725 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002726 }
2727 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002728
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002729 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002730
Eli Friedman4efaa272008-11-12 09:44:48 +00002731};
2732} // end anonymous namespace
2733
Richard Smithc49bd112011-10-28 17:51:58 +00002734/// Evaluate an expression as an lvalue. This can be legitimately called on
2735/// expressions which are not glvalues, in a few cases:
2736/// * function designators in C,
2737/// * "extern void" objects,
2738/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002739static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002740 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2741 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2742 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002743 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002744}
2745
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002746bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002747 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2748 return Success(FD);
2749 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002750 return VisitVarDecl(E, VD);
2751 return Error(E);
2752}
Richard Smith436c8892011-10-24 23:14:33 +00002753
Richard Smithc49bd112011-10-28 17:51:58 +00002754bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002755 if (!VD->getType()->isReferenceType()) {
2756 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002757 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002758 return true;
2759 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002760 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002761 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002762
Richard Smith47a1eed2011-10-29 20:57:55 +00002763 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002764 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2765 return false;
2766 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002767}
2768
Richard Smithbd552ef2011-10-31 05:52:43 +00002769bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2770 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002771 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002772 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002773 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2774
2775 Result.set(E, Info.CurrentCall);
2776 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2777 Result, E->GetTemporaryExpr());
2778 }
2779
2780 // Materialization of an lvalue temporary occurs when we need to force a copy
2781 // (for instance, if it's a bitfield).
2782 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2783 if (!Visit(E->GetTemporaryExpr()))
2784 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002785 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002786 Info.CurrentCall->Temporaries[E]))
2787 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002788 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002789 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002790}
2791
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002792bool
2793LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002794 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2795 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2796 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002797 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002798}
2799
Richard Smith47d21452011-12-27 12:18:28 +00002800bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2801 if (E->isTypeOperand())
2802 return Success(E);
2803 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2804 if (RD && RD->isPolymorphic()) {
2805 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2806 << E->getExprOperand()->getType()
2807 << E->getExprOperand()->getSourceRange();
2808 return false;
2809 }
2810 return Success(E);
2811}
2812
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002813bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002814 // Handle static data members.
2815 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2816 VisitIgnoredValue(E->getBase());
2817 return VisitVarDecl(E, VD);
2818 }
2819
Richard Smithd0dccea2011-10-28 22:34:42 +00002820 // Handle static member functions.
2821 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2822 if (MD->isStatic()) {
2823 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002824 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002825 }
2826 }
2827
Richard Smith180f4792011-11-10 06:34:14 +00002828 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002829 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002830}
2831
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002832bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002833 // FIXME: Deal with vectors as array subscript bases.
2834 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002835 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002836
Anders Carlsson3068d112008-11-16 19:01:22 +00002837 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002838 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002839
Anders Carlsson3068d112008-11-16 19:01:22 +00002840 APSInt Index;
2841 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002842 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002843 int64_t IndexValue
2844 = Index.isSigned() ? Index.getSExtValue()
2845 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002846
Richard Smithb4e85ed2012-01-06 16:39:00 +00002847 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002848}
Eli Friedman4efaa272008-11-12 09:44:48 +00002849
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002850bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002851 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002852}
2853
Eli Friedman4efaa272008-11-12 09:44:48 +00002854//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002855// Pointer Evaluation
2856//===----------------------------------------------------------------------===//
2857
Anders Carlssonc754aa62008-07-08 05:13:58 +00002858namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002859class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002860 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002861 LValue &Result;
2862
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002863 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002864 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002865 return true;
2866 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002867public:
Mike Stump1eb44332009-09-09 15:08:12 +00002868
John McCallefdb83e2010-05-07 21:00:08 +00002869 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002870 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002871
Richard Smith47a1eed2011-10-29 20:57:55 +00002872 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002873 Result.setFrom(V);
2874 return true;
2875 }
Richard Smith51201882011-12-30 21:15:51 +00002876 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002877 return Success((Expr*)0);
2878 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002879
John McCallefdb83e2010-05-07 21:00:08 +00002880 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002881 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002882 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002883 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002884 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002885 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002886 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002887 bool VisitCallExpr(const CallExpr *E);
2888 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002889 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002890 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002891 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002892 }
Richard Smith180f4792011-11-10 06:34:14 +00002893 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2894 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002895 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002896 Result = *Info.CurrentCall->This;
2897 return true;
2898 }
John McCall56ca35d2011-02-17 10:25:35 +00002899
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002900 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002901};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002902} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002903
John McCallefdb83e2010-05-07 21:00:08 +00002904static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002905 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002906 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002907}
2908
John McCallefdb83e2010-05-07 21:00:08 +00002909bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002910 if (E->getOpcode() != BO_Add &&
2911 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002912 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002913
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002914 const Expr *PExp = E->getLHS();
2915 const Expr *IExp = E->getRHS();
2916 if (IExp->getType()->isPointerType())
2917 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002918
Richard Smith745f5142012-01-27 01:14:48 +00002919 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
2920 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00002921 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002922
John McCallefdb83e2010-05-07 21:00:08 +00002923 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00002924 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00002925 return false;
2926 int64_t AdditionalOffset
2927 = Offset.isSigned() ? Offset.getSExtValue()
2928 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002929 if (E->getOpcode() == BO_Sub)
2930 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002931
Richard Smith180f4792011-11-10 06:34:14 +00002932 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002933 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2934 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002935}
Eli Friedman4efaa272008-11-12 09:44:48 +00002936
John McCallefdb83e2010-05-07 21:00:08 +00002937bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2938 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002939}
Mike Stump1eb44332009-09-09 15:08:12 +00002940
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002941bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2942 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002943
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002944 switch (E->getCastKind()) {
2945 default:
2946 break;
2947
John McCall2de56d12010-08-25 11:45:40 +00002948 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002949 case CK_CPointerToObjCPointerCast:
2950 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002951 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002952 if (!Visit(SubExpr))
2953 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002954 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2955 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2956 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002957 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002958 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002959 if (SubExpr->getType()->isVoidPointerType())
2960 CCEDiag(E, diag::note_constexpr_invalid_cast)
2961 << 3 << SubExpr->getType();
2962 else
2963 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2964 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002965 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002966
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002967 case CK_DerivedToBase:
2968 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002969 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002970 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002971 if (!Result.Base && Result.Offset.isZero())
2972 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002973
Richard Smith180f4792011-11-10 06:34:14 +00002974 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002975 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002976 QualType Type =
2977 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002978
Richard Smith180f4792011-11-10 06:34:14 +00002979 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002980 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002981 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2982 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002983 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002984 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002985 }
2986
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002987 return true;
2988 }
2989
Richard Smithe24f5fc2011-11-17 22:56:20 +00002990 case CK_BaseToDerived:
2991 if (!Visit(E->getSubExpr()))
2992 return false;
2993 if (!Result.Base && Result.Offset.isZero())
2994 return true;
2995 return HandleBaseToDerivedCast(Info, E, Result);
2996
Richard Smith47a1eed2011-10-29 20:57:55 +00002997 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00002998 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002999
John McCall2de56d12010-08-25 11:45:40 +00003000 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003001 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3002
Richard Smith47a1eed2011-10-29 20:57:55 +00003003 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003004 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003005 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003006
John McCallefdb83e2010-05-07 21:00:08 +00003007 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003008 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3009 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003010 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003011 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00003012 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003013 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003014 return true;
3015 } else {
3016 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003017 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00003018 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003019 }
3020 }
John McCall2de56d12010-08-25 11:45:40 +00003021 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003022 if (SubExpr->isGLValue()) {
3023 if (!EvaluateLValue(SubExpr, Result, Info))
3024 return false;
3025 } else {
3026 Result.set(SubExpr, Info.CurrentCall);
3027 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
3028 Info, Result, SubExpr))
3029 return false;
3030 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003031 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003032 if (const ConstantArrayType *CAT
3033 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3034 Result.addArray(Info, E, CAT);
3035 else
3036 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003037 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003038
John McCall2de56d12010-08-25 11:45:40 +00003039 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003040 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003041 }
3042
Richard Smithc49bd112011-10-28 17:51:58 +00003043 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003044}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003045
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003046bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003047 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003048 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003049
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003050 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003051}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003052
3053//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003054// Member Pointer Evaluation
3055//===----------------------------------------------------------------------===//
3056
3057namespace {
3058class MemberPointerExprEvaluator
3059 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3060 MemberPtr &Result;
3061
3062 bool Success(const ValueDecl *D) {
3063 Result = MemberPtr(D);
3064 return true;
3065 }
3066public:
3067
3068 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3069 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3070
3071 bool Success(const CCValue &V, const Expr *E) {
3072 Result.setFrom(V);
3073 return true;
3074 }
Richard Smith51201882011-12-30 21:15:51 +00003075 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003076 return Success((const ValueDecl*)0);
3077 }
3078
3079 bool VisitCastExpr(const CastExpr *E);
3080 bool VisitUnaryAddrOf(const UnaryOperator *E);
3081};
3082} // end anonymous namespace
3083
3084static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3085 EvalInfo &Info) {
3086 assert(E->isRValue() && E->getType()->isMemberPointerType());
3087 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3088}
3089
3090bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3091 switch (E->getCastKind()) {
3092 default:
3093 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3094
3095 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003096 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003097
3098 case CK_BaseToDerivedMemberPointer: {
3099 if (!Visit(E->getSubExpr()))
3100 return false;
3101 if (E->path_empty())
3102 return true;
3103 // Base-to-derived member pointer casts store the path in derived-to-base
3104 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3105 // the wrong end of the derived->base arc, so stagger the path by one class.
3106 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3107 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3108 PathI != PathE; ++PathI) {
3109 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3110 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3111 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003112 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003113 }
3114 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3115 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003116 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003117 return true;
3118 }
3119
3120 case CK_DerivedToBaseMemberPointer:
3121 if (!Visit(E->getSubExpr()))
3122 return false;
3123 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3124 PathE = E->path_end(); PathI != PathE; ++PathI) {
3125 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3126 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3127 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003128 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003129 }
3130 return true;
3131 }
3132}
3133
3134bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3135 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3136 // member can be formed.
3137 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3138}
3139
3140//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003141// Record Evaluation
3142//===----------------------------------------------------------------------===//
3143
3144namespace {
3145 class RecordExprEvaluator
3146 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3147 const LValue &This;
3148 APValue &Result;
3149 public:
3150
3151 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3152 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3153
3154 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003155 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00003156 }
Richard Smith51201882011-12-30 21:15:51 +00003157 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003158
Richard Smith59efe262011-11-11 04:05:33 +00003159 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003160 bool VisitInitListExpr(const InitListExpr *E);
3161 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3162 };
3163}
3164
Richard Smith51201882011-12-30 21:15:51 +00003165/// Perform zero-initialization on an object of non-union class type.
3166/// C++11 [dcl.init]p5:
3167/// To zero-initialize an object or reference of type T means:
3168/// [...]
3169/// -- if T is a (possibly cv-qualified) non-union class type,
3170/// each non-static data member and each base-class subobject is
3171/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003172static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3173 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003174 const LValue &This, APValue &Result) {
3175 assert(!RD->isUnion() && "Expected non-union class type");
3176 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3177 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3178 std::distance(RD->field_begin(), RD->field_end()));
3179
3180 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3181
3182 if (CD) {
3183 unsigned Index = 0;
3184 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003185 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003186 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3187 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003188 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3189 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003190 Result.getStructBase(Index)))
3191 return false;
3192 }
3193 }
3194
Richard Smithb4e85ed2012-01-06 16:39:00 +00003195 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3196 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003197 // -- if T is a reference type, no initialization is performed.
3198 if ((*I)->getType()->isReferenceType())
3199 continue;
3200
3201 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003202 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003203
3204 ImplicitValueInitExpr VIE((*I)->getType());
3205 if (!EvaluateConstantExpression(
3206 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3207 return false;
3208 }
3209
3210 return true;
3211}
3212
3213bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3214 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3215 if (RD->isUnion()) {
3216 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3217 // object's first non-static named data member is zero-initialized
3218 RecordDecl::field_iterator I = RD->field_begin();
3219 if (I == RD->field_end()) {
3220 Result = APValue((const FieldDecl*)0);
3221 return true;
3222 }
3223
3224 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003225 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003226 Result = APValue(*I);
3227 ImplicitValueInitExpr VIE((*I)->getType());
3228 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3229 Subobject, &VIE);
3230 }
3231
Richard Smithb4e85ed2012-01-06 16:39:00 +00003232 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003233}
3234
Richard Smith59efe262011-11-11 04:05:33 +00003235bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3236 switch (E->getCastKind()) {
3237 default:
3238 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3239
3240 case CK_ConstructorConversion:
3241 return Visit(E->getSubExpr());
3242
3243 case CK_DerivedToBase:
3244 case CK_UncheckedDerivedToBase: {
3245 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003246 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003247 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003248 if (!DerivedObject.isStruct())
3249 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003250
3251 // Derived-to-base rvalue conversion: just slice off the derived part.
3252 APValue *Value = &DerivedObject;
3253 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3254 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3255 PathE = E->path_end(); PathI != PathE; ++PathI) {
3256 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3257 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3258 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3259 RD = Base;
3260 }
3261 Result = *Value;
3262 return true;
3263 }
3264 }
3265}
3266
Richard Smith180f4792011-11-10 06:34:14 +00003267bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3268 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3269 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3270
3271 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003272 const FieldDecl *Field = E->getInitializedFieldInUnion();
3273 Result = APValue(Field);
3274 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003275 return true;
Richard Smithec789162012-01-12 18:54:33 +00003276
3277 // If the initializer list for a union does not contain any elements, the
3278 // first element of the union is value-initialized.
3279 ImplicitValueInitExpr VIE(Field->getType());
3280 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3281
Richard Smith180f4792011-11-10 06:34:14 +00003282 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003283 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003284 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003285 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003286 }
3287
3288 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3289 "initializer list for class with base classes");
3290 Result = APValue(APValue::UninitStruct(), 0,
3291 std::distance(RD->field_begin(), RD->field_end()));
3292 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003293 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003294 for (RecordDecl::field_iterator Field = RD->field_begin(),
3295 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3296 // Anonymous bit-fields are not considered members of the class for
3297 // purposes of aggregate initialization.
3298 if (Field->isUnnamedBitfield())
3299 continue;
3300
3301 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003302
Richard Smith745f5142012-01-27 01:14:48 +00003303 bool HaveInit = ElementNo < E->getNumInits();
3304
3305 // FIXME: Diagnostics here should point to the end of the initializer
3306 // list, not the start.
3307 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3308 *Field, &Layout);
3309
3310 // Perform an implicit value-initialization for members beyond the end of
3311 // the initializer list.
3312 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3313
3314 if (!EvaluateConstantExpression(
3315 Result.getStructField((*Field)->getFieldIndex()),
3316 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3317 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003318 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003319 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003320 }
3321 }
3322
Richard Smith745f5142012-01-27 01:14:48 +00003323 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003324}
3325
3326bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3327 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003328 bool ZeroInit = E->requiresZeroInitialization();
3329 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003330 // If we've already performed zero-initialization, we're already done.
3331 if (!Result.isUninit())
3332 return true;
3333
Richard Smith51201882011-12-30 21:15:51 +00003334 if (ZeroInit)
3335 return ZeroInitialization(E);
3336
Richard Smith61802452011-12-22 02:22:31 +00003337 const CXXRecordDecl *RD = FD->getParent();
3338 if (RD->isUnion())
3339 Result = APValue((FieldDecl*)0);
3340 else
3341 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3342 std::distance(RD->field_begin(), RD->field_end()));
3343 return true;
3344 }
3345
Richard Smith180f4792011-11-10 06:34:14 +00003346 const FunctionDecl *Definition = 0;
3347 FD->getBody(Definition);
3348
Richard Smithc1c5f272011-12-13 06:39:58 +00003349 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3350 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003351
Richard Smith610a60c2012-01-10 04:32:03 +00003352 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003353 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003354 if (const MaterializeTemporaryExpr *ME
3355 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3356 return Visit(ME->GetTemporaryExpr());
3357
Richard Smith51201882011-12-30 21:15:51 +00003358 if (ZeroInit && !ZeroInitialization(E))
3359 return false;
3360
Richard Smith180f4792011-11-10 06:34:14 +00003361 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003362 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003363 cast<CXXConstructorDecl>(Definition), Info,
3364 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003365}
3366
3367static bool EvaluateRecord(const Expr *E, const LValue &This,
3368 APValue &Result, EvalInfo &Info) {
3369 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003370 "can't evaluate expression as a record rvalue");
3371 return RecordExprEvaluator(Info, This, Result).Visit(E);
3372}
3373
3374//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003375// Temporary Evaluation
3376//
3377// Temporaries are represented in the AST as rvalues, but generally behave like
3378// lvalues. The full-object of which the temporary is a subobject is implicitly
3379// materialized so that a reference can bind to it.
3380//===----------------------------------------------------------------------===//
3381namespace {
3382class TemporaryExprEvaluator
3383 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3384public:
3385 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3386 LValueExprEvaluatorBaseTy(Info, Result) {}
3387
3388 /// Visit an expression which constructs the value of this temporary.
3389 bool VisitConstructExpr(const Expr *E) {
3390 Result.set(E, Info.CurrentCall);
3391 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3392 Result, E);
3393 }
3394
3395 bool VisitCastExpr(const CastExpr *E) {
3396 switch (E->getCastKind()) {
3397 default:
3398 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3399
3400 case CK_ConstructorConversion:
3401 return VisitConstructExpr(E->getSubExpr());
3402 }
3403 }
3404 bool VisitInitListExpr(const InitListExpr *E) {
3405 return VisitConstructExpr(E);
3406 }
3407 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3408 return VisitConstructExpr(E);
3409 }
3410 bool VisitCallExpr(const CallExpr *E) {
3411 return VisitConstructExpr(E);
3412 }
3413};
3414} // end anonymous namespace
3415
3416/// Evaluate an expression of record type as a temporary.
3417static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003418 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003419 return TemporaryExprEvaluator(Info, Result).Visit(E);
3420}
3421
3422//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003423// Vector Evaluation
3424//===----------------------------------------------------------------------===//
3425
3426namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003427 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003428 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3429 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003430 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Richard Smith07fc6572011-10-22 21:10:00 +00003432 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3433 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003434
Richard Smith07fc6572011-10-22 21:10:00 +00003435 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3436 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3437 // FIXME: remove this APValue copy.
3438 Result = APValue(V.data(), V.size());
3439 return true;
3440 }
Richard Smith69c2c502011-11-04 05:33:44 +00003441 bool Success(const CCValue &V, const Expr *E) {
3442 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003443 Result = V;
3444 return true;
3445 }
Richard Smith51201882011-12-30 21:15:51 +00003446 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003447
Richard Smith07fc6572011-10-22 21:10:00 +00003448 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003449 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003450 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003451 bool VisitInitListExpr(const InitListExpr *E);
3452 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003453 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003454 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003455 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003456 };
3457} // end anonymous namespace
3458
3459static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003460 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003461 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003462}
3463
Richard Smith07fc6572011-10-22 21:10:00 +00003464bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3465 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003466 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Richard Smithd62ca372011-12-06 22:44:34 +00003468 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003469 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003470
Eli Friedman46a52322011-03-25 00:43:55 +00003471 switch (E->getCastKind()) {
3472 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003473 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003474 if (SETy->isIntegerType()) {
3475 APSInt IntResult;
3476 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003477 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003478 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003479 } else if (SETy->isRealFloatingType()) {
3480 APFloat F(0.0);
3481 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003482 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003483 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003484 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003485 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003486 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003487
3488 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003489 SmallVector<APValue, 4> Elts(NElts, Val);
3490 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003491 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003492 case CK_BitCast: {
3493 // Evaluate the operand into an APInt we can extract from.
3494 llvm::APInt SValInt;
3495 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3496 return false;
3497 // Extract the elements
3498 QualType EltTy = VTy->getElementType();
3499 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3500 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3501 SmallVector<APValue, 4> Elts;
3502 if (EltTy->isRealFloatingType()) {
3503 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3504 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3505 unsigned FloatEltSize = EltSize;
3506 if (&Sem == &APFloat::x87DoubleExtended)
3507 FloatEltSize = 80;
3508 for (unsigned i = 0; i < NElts; i++) {
3509 llvm::APInt Elt;
3510 if (BigEndian)
3511 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3512 else
3513 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3514 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3515 }
3516 } else if (EltTy->isIntegerType()) {
3517 for (unsigned i = 0; i < NElts; i++) {
3518 llvm::APInt Elt;
3519 if (BigEndian)
3520 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3521 else
3522 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3523 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3524 }
3525 } else {
3526 return Error(E);
3527 }
3528 return Success(Elts, E);
3529 }
Eli Friedman46a52322011-03-25 00:43:55 +00003530 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003531 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003532 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003533}
3534
Richard Smith07fc6572011-10-22 21:10:00 +00003535bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003536VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003537 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003538 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003539 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003540
Nate Begeman59b5da62009-01-18 03:20:47 +00003541 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003542 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003543
Eli Friedman3edd5a92012-01-03 23:24:20 +00003544 // The number of initializers can be less than the number of
3545 // vector elements. For OpenCL, this can be due to nested vector
3546 // initialization. For GCC compatibility, missing trailing elements
3547 // should be initialized with zeroes.
3548 unsigned CountInits = 0, CountElts = 0;
3549 while (CountElts < NumElements) {
3550 // Handle nested vector initialization.
3551 if (CountInits < NumInits
3552 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3553 APValue v;
3554 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3555 return Error(E);
3556 unsigned vlen = v.getVectorLength();
3557 for (unsigned j = 0; j < vlen; j++)
3558 Elements.push_back(v.getVectorElt(j));
3559 CountElts += vlen;
3560 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003561 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003562 if (CountInits < NumInits) {
3563 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3564 return Error(E);
3565 } else // trailing integer zero.
3566 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3567 Elements.push_back(APValue(sInt));
3568 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003569 } else {
3570 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003571 if (CountInits < NumInits) {
3572 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3573 return Error(E);
3574 } else // trailing float zero.
3575 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3576 Elements.push_back(APValue(f));
3577 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003578 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003579 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003580 }
Richard Smith07fc6572011-10-22 21:10:00 +00003581 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003582}
3583
Richard Smith07fc6572011-10-22 21:10:00 +00003584bool
Richard Smith51201882011-12-30 21:15:51 +00003585VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003586 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003587 QualType EltTy = VT->getElementType();
3588 APValue ZeroElement;
3589 if (EltTy->isIntegerType())
3590 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3591 else
3592 ZeroElement =
3593 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3594
Chris Lattner5f9e2722011-07-23 10:55:15 +00003595 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003596 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003597}
3598
Richard Smith07fc6572011-10-22 21:10:00 +00003599bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003600 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003601 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003602}
3603
Nate Begeman59b5da62009-01-18 03:20:47 +00003604//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003605// Array Evaluation
3606//===----------------------------------------------------------------------===//
3607
3608namespace {
3609 class ArrayExprEvaluator
3610 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003611 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003612 APValue &Result;
3613 public:
3614
Richard Smith180f4792011-11-10 06:34:14 +00003615 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3616 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003617
3618 bool Success(const APValue &V, const Expr *E) {
3619 assert(V.isArray() && "Expected array type");
3620 Result = V;
3621 return true;
3622 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003623
Richard Smith51201882011-12-30 21:15:51 +00003624 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003625 const ConstantArrayType *CAT =
3626 Info.Ctx.getAsConstantArrayType(E->getType());
3627 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003628 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003629
3630 Result = APValue(APValue::UninitArray(), 0,
3631 CAT->getSize().getZExtValue());
3632 if (!Result.hasArrayFiller()) return true;
3633
Richard Smith51201882011-12-30 21:15:51 +00003634 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003635 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003636 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003637 ImplicitValueInitExpr VIE(CAT->getElementType());
3638 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3639 Subobject, &VIE);
3640 }
3641
Richard Smithcc5d4f62011-11-07 09:22:26 +00003642 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003643 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003644 };
3645} // end anonymous namespace
3646
Richard Smith180f4792011-11-10 06:34:14 +00003647static bool EvaluateArray(const Expr *E, const LValue &This,
3648 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003649 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003650 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003651}
3652
3653bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3654 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3655 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003656 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003657
Richard Smith974c5f92011-12-22 01:07:19 +00003658 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3659 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003660 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003661 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3662 LValue LV;
3663 if (!EvaluateLValue(E->getInit(0), LV, Info))
3664 return false;
3665 uint64_t NumElements = CAT->getSize().getZExtValue();
3666 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3667
3668 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003669 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003670 for (uint64_t I = 0; I < NumElements; ++I) {
3671 CCValue Char;
3672 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
Richard Smith745f5142012-01-27 01:14:48 +00003673 CAT->getElementType(), LV, Char) ||
3674 !CheckConstantExpression(Info, E->getInit(0), Char,
3675 Result.getArrayInitializedElt(I)) ||
3676 !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
Richard Smithb4e85ed2012-01-06 16:39:00 +00003677 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003678 return false;
3679 }
3680 return true;
3681 }
3682
Richard Smith745f5142012-01-27 01:14:48 +00003683 bool Success = true;
3684
Richard Smithcc5d4f62011-11-07 09:22:26 +00003685 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3686 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003687 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003688 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003689 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003690 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003691 I != End; ++I, ++Index) {
3692 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
Richard Smith745f5142012-01-27 01:14:48 +00003693 Info, Subobject, cast<Expr>(*I)) ||
3694 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3695 CAT->getElementType(), 1)) {
3696 if (!Info.keepEvaluatingAfterFailure())
3697 return false;
3698 Success = false;
3699 }
Richard Smith180f4792011-11-10 06:34:14 +00003700 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003701
Richard Smith745f5142012-01-27 01:14:48 +00003702 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003703 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003704 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3705 // but sometimes does:
3706 // struct S { constexpr S() : p(&p) {} void *p; };
3707 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003708 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith745f5142012-01-27 01:14:48 +00003709 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003710}
3711
Richard Smithe24f5fc2011-11-17 22:56:20 +00003712bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3713 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3714 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003715 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003716
Richard Smithec789162012-01-12 18:54:33 +00003717 bool HadZeroInit = !Result.isUninit();
3718 if (!HadZeroInit)
3719 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003720 if (!Result.hasArrayFiller())
3721 return true;
3722
3723 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003724
Richard Smith51201882011-12-30 21:15:51 +00003725 bool ZeroInit = E->requiresZeroInitialization();
3726 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003727 if (HadZeroInit)
3728 return true;
3729
Richard Smith51201882011-12-30 21:15:51 +00003730 if (ZeroInit) {
3731 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003732 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003733 ImplicitValueInitExpr VIE(CAT->getElementType());
3734 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3735 Subobject, &VIE);
3736 }
3737
Richard Smith61802452011-12-22 02:22:31 +00003738 const CXXRecordDecl *RD = FD->getParent();
3739 if (RD->isUnion())
3740 Result.getArrayFiller() = APValue((FieldDecl*)0);
3741 else
3742 Result.getArrayFiller() =
3743 APValue(APValue::UninitStruct(), RD->getNumBases(),
3744 std::distance(RD->field_begin(), RD->field_end()));
3745 return true;
3746 }
3747
Richard Smithe24f5fc2011-11-17 22:56:20 +00003748 const FunctionDecl *Definition = 0;
3749 FD->getBody(Definition);
3750
Richard Smithc1c5f272011-12-13 06:39:58 +00003751 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3752 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003753
3754 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3755 // but sometimes does:
3756 // struct S { constexpr S() : p(&p) {} void *p; };
3757 // S s[10];
3758 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003759 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003760
Richard Smithec789162012-01-12 18:54:33 +00003761 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003762 ImplicitValueInitExpr VIE(CAT->getElementType());
3763 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3764 &VIE))
3765 return false;
3766 }
3767
Richard Smithe24f5fc2011-11-17 22:56:20 +00003768 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003769 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003770 cast<CXXConstructorDecl>(Definition),
3771 Info, Result.getArrayFiller());
3772}
3773
Richard Smithcc5d4f62011-11-07 09:22:26 +00003774//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003775// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003776//
3777// As a GNU extension, we support casting pointers to sufficiently-wide integer
3778// types and back in constant folding. Integer values are thus represented
3779// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003780//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003781
3782namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003783class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003784 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003785 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003786public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003787 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003788 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003789
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003790 bool Success(const llvm::APSInt &SI, const Expr *E) {
3791 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003792 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003793 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003794 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003795 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003796 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003797 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003798 return true;
3799 }
3800
Daniel Dunbar131eb432009-02-19 09:06:44 +00003801 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003802 assert(E->getType()->isIntegralOrEnumerationType() &&
3803 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003804 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003805 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003806 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003807 Result.getInt().setIsUnsigned(
3808 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003809 return true;
3810 }
3811
3812 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003813 assert(E->getType()->isIntegralOrEnumerationType() &&
3814 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003815 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003816 return true;
3817 }
3818
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003819 bool Success(CharUnits Size, const Expr *E) {
3820 return Success(Size.getQuantity(), E);
3821 }
3822
Richard Smith47a1eed2011-10-29 20:57:55 +00003823 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003824 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003825 Result = V;
3826 return true;
3827 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003828 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003829 }
Mike Stump1eb44332009-09-09 15:08:12 +00003830
Richard Smith51201882011-12-30 21:15:51 +00003831 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003832
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003833 //===--------------------------------------------------------------------===//
3834 // Visitor Methods
3835 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003836
Chris Lattner4c4867e2008-07-12 00:38:25 +00003837 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003838 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003839 }
3840 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003841 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003842 }
Eli Friedman04309752009-11-24 05:28:59 +00003843
3844 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3845 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003846 if (CheckReferencedDecl(E, E->getDecl()))
3847 return true;
3848
3849 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003850 }
3851 bool VisitMemberExpr(const MemberExpr *E) {
3852 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003853 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003854 return true;
3855 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003856
3857 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003858 }
3859
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003860 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003861 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003862 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003863 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003864
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003865 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003866 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003867
Anders Carlsson3068d112008-11-16 19:01:22 +00003868 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003869 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003870 }
Mike Stump1eb44332009-09-09 15:08:12 +00003871
Richard Smithf10d9172011-10-11 21:43:33 +00003872 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003873 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003874 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003875 }
3876
Sebastian Redl64b45f72009-01-05 20:52:13 +00003877 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003878 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003879 }
3880
Francois Pichet6ad6f282010-12-07 00:08:36 +00003881 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3882 return Success(E->getValue(), E);
3883 }
3884
John Wiegley21ff2e52011-04-28 00:16:57 +00003885 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3886 return Success(E->getValue(), E);
3887 }
3888
John Wiegley55262202011-04-25 06:54:41 +00003889 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3890 return Success(E->getValue(), E);
3891 }
3892
Eli Friedman722c7172009-02-28 03:59:05 +00003893 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003894 bool VisitUnaryImag(const UnaryOperator *E);
3895
Sebastian Redl295995c2010-09-10 20:55:47 +00003896 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003897 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003898
Chris Lattnerfcee0012008-07-11 21:24:13 +00003899private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003900 CharUnits GetAlignOfExpr(const Expr *E);
3901 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003902 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003903 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003904 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003905};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003906} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003907
Richard Smithc49bd112011-10-28 17:51:58 +00003908/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3909/// produce either the integer value or a pointer.
3910///
3911/// GCC has a heinous extension which folds casts between pointer types and
3912/// pointer-sized integral types. We support this by allowing the evaluation of
3913/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3914/// Some simple arithmetic on such values is supported (they are treated much
3915/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003916static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003917 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003918 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003919 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003920}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003921
Richard Smithf48fdb02011-12-09 22:58:01 +00003922static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003923 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003924 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003925 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003926 if (!Val.isInt()) {
3927 // FIXME: It would be better to produce the diagnostic for casting
3928 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003929 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003930 return false;
3931 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003932 Result = Val.getInt();
3933 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003934}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003935
Richard Smithf48fdb02011-12-09 22:58:01 +00003936/// Check whether the given declaration can be directly converted to an integral
3937/// rvalue. If not, no diagnostic is produced; there are other things we can
3938/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003939bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003940 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003941 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003942 // Check for signedness/width mismatches between E type and ECD value.
3943 bool SameSign = (ECD->getInitVal().isSigned()
3944 == E->getType()->isSignedIntegerOrEnumerationType());
3945 bool SameWidth = (ECD->getInitVal().getBitWidth()
3946 == Info.Ctx.getIntWidth(E->getType()));
3947 if (SameSign && SameWidth)
3948 return Success(ECD->getInitVal(), E);
3949 else {
3950 // Get rid of mismatch (otherwise Success assertions will fail)
3951 // by computing a new value matching the type of E.
3952 llvm::APSInt Val = ECD->getInitVal();
3953 if (!SameSign)
3954 Val.setIsSigned(!ECD->getInitVal().isSigned());
3955 if (!SameWidth)
3956 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3957 return Success(Val, E);
3958 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003959 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003960 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003961}
3962
Chris Lattnera4d55d82008-10-06 06:40:35 +00003963/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3964/// as GCC.
3965static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3966 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003967 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003968 enum gcc_type_class {
3969 no_type_class = -1,
3970 void_type_class, integer_type_class, char_type_class,
3971 enumeral_type_class, boolean_type_class,
3972 pointer_type_class, reference_type_class, offset_type_class,
3973 real_type_class, complex_type_class,
3974 function_type_class, method_type_class,
3975 record_type_class, union_type_class,
3976 array_type_class, string_type_class,
3977 lang_type_class
3978 };
Mike Stump1eb44332009-09-09 15:08:12 +00003979
3980 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003981 // ideal, however it is what gcc does.
3982 if (E->getNumArgs() == 0)
3983 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003984
Chris Lattnera4d55d82008-10-06 06:40:35 +00003985 QualType ArgTy = E->getArg(0)->getType();
3986 if (ArgTy->isVoidType())
3987 return void_type_class;
3988 else if (ArgTy->isEnumeralType())
3989 return enumeral_type_class;
3990 else if (ArgTy->isBooleanType())
3991 return boolean_type_class;
3992 else if (ArgTy->isCharType())
3993 return string_type_class; // gcc doesn't appear to use char_type_class
3994 else if (ArgTy->isIntegerType())
3995 return integer_type_class;
3996 else if (ArgTy->isPointerType())
3997 return pointer_type_class;
3998 else if (ArgTy->isReferenceType())
3999 return reference_type_class;
4000 else if (ArgTy->isRealType())
4001 return real_type_class;
4002 else if (ArgTy->isComplexType())
4003 return complex_type_class;
4004 else if (ArgTy->isFunctionType())
4005 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004006 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004007 return record_type_class;
4008 else if (ArgTy->isUnionType())
4009 return union_type_class;
4010 else if (ArgTy->isArrayType())
4011 return array_type_class;
4012 else if (ArgTy->isUnionType())
4013 return union_type_class;
4014 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004015 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004016}
4017
Richard Smith80d4b552011-12-28 19:48:30 +00004018/// EvaluateBuiltinConstantPForLValue - Determine the result of
4019/// __builtin_constant_p when applied to the given lvalue.
4020///
4021/// An lvalue is only "constant" if it is a pointer or reference to the first
4022/// character of a string literal.
4023template<typename LValue>
4024static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4025 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4026 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4027}
4028
4029/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4030/// GCC as we can manage.
4031static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4032 QualType ArgType = Arg->getType();
4033
4034 // __builtin_constant_p always has one operand. The rules which gcc follows
4035 // are not precisely documented, but are as follows:
4036 //
4037 // - If the operand is of integral, floating, complex or enumeration type,
4038 // and can be folded to a known value of that type, it returns 1.
4039 // - If the operand and can be folded to a pointer to the first character
4040 // of a string literal (or such a pointer cast to an integral type), it
4041 // returns 1.
4042 //
4043 // Otherwise, it returns 0.
4044 //
4045 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4046 // its support for this does not currently work.
4047 if (ArgType->isIntegralOrEnumerationType()) {
4048 Expr::EvalResult Result;
4049 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4050 return false;
4051
4052 APValue &V = Result.Val;
4053 if (V.getKind() == APValue::Int)
4054 return true;
4055
4056 return EvaluateBuiltinConstantPForLValue(V);
4057 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4058 return Arg->isEvaluatable(Ctx);
4059 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4060 LValue LV;
4061 Expr::EvalStatus Status;
4062 EvalInfo Info(Ctx, Status);
4063 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4064 : EvaluatePointer(Arg, LV, Info)) &&
4065 !Status.HasSideEffects)
4066 return EvaluateBuiltinConstantPForLValue(LV);
4067 }
4068
4069 // Anything else isn't considered to be sufficiently constant.
4070 return false;
4071}
4072
John McCall42c8f872010-05-10 23:27:23 +00004073/// Retrieves the "underlying object type" of the given expression,
4074/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004075QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4076 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4077 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004078 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004079 } else if (const Expr *E = B.get<const Expr*>()) {
4080 if (isa<CompoundLiteralExpr>(E))
4081 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004082 }
4083
4084 return QualType();
4085}
4086
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004087bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004088 // TODO: Perhaps we should let LLVM lower this?
4089 LValue Base;
4090 if (!EvaluatePointer(E->getArg(0), Base, Info))
4091 return false;
4092
4093 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004094 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004095
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004096 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004097 if (T.isNull() ||
4098 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004099 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004100 T->isVariablyModifiedType() ||
4101 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004102 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004103
4104 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4105 CharUnits Offset = Base.getLValueOffset();
4106
4107 if (!Offset.isNegative() && Offset <= Size)
4108 Size -= Offset;
4109 else
4110 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004111 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004112}
4113
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004114bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004115 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004116 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004117 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004118
4119 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004120 if (TryEvaluateBuiltinObjectSize(E))
4121 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004122
Eric Christopherb2aaf512010-01-19 22:58:35 +00004123 // If evaluating the argument has side-effects we can't determine
4124 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004125 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004126 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004127 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004128 return Success(0, E);
4129 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004130
Richard Smithf48fdb02011-12-09 22:58:01 +00004131 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004132 }
4133
Chris Lattner019f4e82008-10-06 05:28:25 +00004134 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004135 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004136
Richard Smith80d4b552011-12-28 19:48:30 +00004137 case Builtin::BI__builtin_constant_p:
4138 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004139
Chris Lattner21fb98e2009-09-23 06:06:36 +00004140 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004141 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004142 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004143 return Success(Operand, E);
4144 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004145
4146 case Builtin::BI__builtin_expect:
4147 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004148
Douglas Gregor5726d402010-09-10 06:27:15 +00004149 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004150 // A call to strlen is not a constant expression.
4151 if (Info.getLangOpts().CPlusPlus0x)
4152 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4153 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4154 else
4155 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4156 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004157 case Builtin::BI__builtin_strlen:
4158 // As an extension, we support strlen() and __builtin_strlen() as constant
4159 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004160 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004161 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4162 // The string literal may have embedded null characters. Find the first
4163 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004164 StringRef Str = S->getString();
4165 StringRef::size_type Pos = Str.find(0);
4166 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004167 Str = Str.substr(0, Pos);
4168
4169 return Success(Str.size(), E);
4170 }
4171
Richard Smithf48fdb02011-12-09 22:58:01 +00004172 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004173
4174 case Builtin::BI__atomic_is_lock_free: {
4175 APSInt SizeVal;
4176 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4177 return false;
4178
4179 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4180 // of two less than the maximum inline atomic width, we know it is
4181 // lock-free. If the size isn't a power of two, or greater than the
4182 // maximum alignment where we promote atomics, we know it is not lock-free
4183 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4184 // the answer can only be determined at runtime; for example, 16-byte
4185 // atomics have lock-free implementations on some, but not all,
4186 // x86-64 processors.
4187
4188 // Check power-of-two.
4189 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4190 if (!Size.isPowerOfTwo())
4191#if 0
4192 // FIXME: Suppress this folding until the ABI for the promotion width
4193 // settles.
4194 return Success(0, E);
4195#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004196 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004197#endif
4198
4199#if 0
4200 // Check against promotion width.
4201 // FIXME: Suppress this folding until the ABI for the promotion width
4202 // settles.
4203 unsigned PromoteWidthBits =
4204 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4205 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4206 return Success(0, E);
4207#endif
4208
4209 // Check against inlining width.
4210 unsigned InlineWidthBits =
4211 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4212 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4213 return Success(1, E);
4214
Richard Smithf48fdb02011-12-09 22:58:01 +00004215 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004216 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004217 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004218}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004219
Richard Smith625b8072011-10-31 01:37:14 +00004220static bool HasSameBase(const LValue &A, const LValue &B) {
4221 if (!A.getLValueBase())
4222 return !B.getLValueBase();
4223 if (!B.getLValueBase())
4224 return false;
4225
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004226 if (A.getLValueBase().getOpaqueValue() !=
4227 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004228 const Decl *ADecl = GetLValueBaseDecl(A);
4229 if (!ADecl)
4230 return false;
4231 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004232 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004233 return false;
4234 }
4235
4236 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00004237 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00004238}
4239
Richard Smith7b48a292012-02-01 05:53:12 +00004240/// Perform the given integer operation, which is known to need at most BitWidth
4241/// bits, and check for overflow in the original type (if that type was not an
4242/// unsigned type).
4243template<typename Operation>
4244static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4245 const APSInt &LHS, const APSInt &RHS,
4246 unsigned BitWidth, Operation Op) {
4247 if (LHS.isUnsigned())
4248 return Op(LHS, RHS);
4249
4250 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4251 APSInt Result = Value.trunc(LHS.getBitWidth());
4252 if (Result.extend(BitWidth) != Value)
4253 HandleOverflow(Info, E, Value, E->getType());
4254 return Result;
4255}
4256
Chris Lattnerb542afe2008-07-11 19:10:17 +00004257bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004258 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004259 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004260
John McCall2de56d12010-08-25 11:45:40 +00004261 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004262 VisitIgnoredValue(E->getLHS());
4263 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004264 }
4265
4266 if (E->isLogicalOp()) {
4267 // These need to be handled specially because the operands aren't
4268 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004269 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004270
Richard Smithc49bd112011-10-28 17:51:58 +00004271 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004272 // We were able to evaluate the LHS, see if we can get away with not
4273 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004274 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004275 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004276
Richard Smithc49bd112011-10-28 17:51:58 +00004277 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004278 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004279 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004280 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004281 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004282 }
4283 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004284 // FIXME: If both evaluations fail, we should produce the diagnostic from
4285 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4286 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004287 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004288 // We can't evaluate the LHS; however, sometimes the result
4289 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004290 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004291 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004292 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004293 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004294
4295 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004296 }
4297 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004298 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004299
Eli Friedmana6afa762008-11-13 06:09:17 +00004300 return false;
4301 }
4302
Anders Carlsson286f85e2008-11-16 07:17:21 +00004303 QualType LHSTy = E->getLHS()->getType();
4304 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004305
4306 if (LHSTy->isAnyComplexType()) {
4307 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004308 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004309
Richard Smith745f5142012-01-27 01:14:48 +00004310 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4311 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004312 return false;
4313
Richard Smith745f5142012-01-27 01:14:48 +00004314 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004315 return false;
4316
4317 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004318 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004319 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004320 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004321 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4322
John McCall2de56d12010-08-25 11:45:40 +00004323 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004324 return Success((CR_r == APFloat::cmpEqual &&
4325 CR_i == APFloat::cmpEqual), E);
4326 else {
John McCall2de56d12010-08-25 11:45:40 +00004327 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004328 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004329 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004330 CR_r == APFloat::cmpLessThan ||
4331 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004332 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004333 CR_i == APFloat::cmpLessThan ||
4334 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004335 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004336 } else {
John McCall2de56d12010-08-25 11:45:40 +00004337 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004338 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4339 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4340 else {
John McCall2de56d12010-08-25 11:45:40 +00004341 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004342 "Invalid compex comparison.");
4343 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4344 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4345 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004346 }
4347 }
Mike Stump1eb44332009-09-09 15:08:12 +00004348
Anders Carlsson286f85e2008-11-16 07:17:21 +00004349 if (LHSTy->isRealFloatingType() &&
4350 RHSTy->isRealFloatingType()) {
4351 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004352
Richard Smith745f5142012-01-27 01:14:48 +00004353 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4354 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004355 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004356
Richard Smith745f5142012-01-27 01:14:48 +00004357 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004358 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004359
Anders Carlsson286f85e2008-11-16 07:17:21 +00004360 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004361
Anders Carlsson286f85e2008-11-16 07:17:21 +00004362 switch (E->getOpcode()) {
4363 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004364 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004365 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004366 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004367 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004368 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004369 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004370 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004371 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004372 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004373 E);
John McCall2de56d12010-08-25 11:45:40 +00004374 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004375 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004376 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004377 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004378 || CR == APFloat::cmpLessThan
4379 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004380 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004381 }
Mike Stump1eb44332009-09-09 15:08:12 +00004382
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004383 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004384 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004385 LValue LHSValue, RHSValue;
4386
4387 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4388 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004389 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004390
Richard Smith745f5142012-01-27 01:14:48 +00004391 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004392 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004393
Richard Smith625b8072011-10-31 01:37:14 +00004394 // Reject differing bases from the normal codepath; we special-case
4395 // comparisons to null.
4396 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004397 if (E->getOpcode() == BO_Sub) {
4398 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004399 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4400 return false;
4401 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4402 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4403 if (!LHSExpr || !RHSExpr)
4404 return false;
4405 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4406 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4407 if (!LHSAddrExpr || !RHSAddrExpr)
4408 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004409 // Make sure both labels come from the same function.
4410 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4411 RHSAddrExpr->getLabel()->getDeclContext())
4412 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004413 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4414 return true;
4415 }
Richard Smith9e36b532011-10-31 05:11:32 +00004416 // Inequalities and subtractions between unrelated pointers have
4417 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004418 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004419 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004420 // A constant address may compare equal to the address of a symbol.
4421 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004422 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004423 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4424 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004425 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004426 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004427 // distinct addresses. In clang, the result of such a comparison is
4428 // unspecified, so it is not a constant expression. However, we do know
4429 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004430 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4431 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004432 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004433 // We can't tell whether weak symbols will end up pointing to the same
4434 // object.
4435 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004436 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004437 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004438 // (Note that clang defaults to -fmerge-all-constants, which can
4439 // lead to inconsistent results for comparisons involving the address
4440 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004441 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004442 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004443
Richard Smith15efc4d2012-02-01 08:10:20 +00004444 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4445 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4446
Richard Smithf15fda02012-02-02 01:16:57 +00004447 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4448 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4449
John McCall2de56d12010-08-25 11:45:40 +00004450 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004451 // C++11 [expr.add]p6:
4452 // Unless both pointers point to elements of the same array object, or
4453 // one past the last element of the array object, the behavior is
4454 // undefined.
4455 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4456 !AreElementsOfSameArray(getType(LHSValue.Base),
4457 LHSDesignator, RHSDesignator))
4458 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4459
Chris Lattner4992bdd2010-04-20 17:13:14 +00004460 QualType Type = E->getLHS()->getType();
4461 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004462
Richard Smith180f4792011-11-10 06:34:14 +00004463 CharUnits ElementSize;
4464 if (!HandleSizeof(Info, ElementType, ElementSize))
4465 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004466
Richard Smith15efc4d2012-02-01 08:10:20 +00004467 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4468 // and produce incorrect results when it overflows. Such behavior
4469 // appears to be non-conforming, but is common, so perhaps we should
4470 // assume the standard intended for such cases to be undefined behavior
4471 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004472
Richard Smith15efc4d2012-02-01 08:10:20 +00004473 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4474 // overflow in the final conversion to ptrdiff_t.
4475 APSInt LHS(
4476 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4477 APSInt RHS(
4478 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4479 APSInt ElemSize(
4480 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4481 APSInt TrueResult = (LHS - RHS) / ElemSize;
4482 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4483
4484 if (Result.extend(65) != TrueResult)
4485 HandleOverflow(Info, E, TrueResult, E->getType());
4486 return Success(Result, E);
4487 }
Richard Smith82f28582012-01-31 06:41:30 +00004488
4489 // C++11 [expr.rel]p3:
4490 // Pointers to void (after pointer conversions) can be compared, with a
4491 // result defined as follows: If both pointers represent the same
4492 // address or are both the null pointer value, the result is true if the
4493 // operator is <= or >= and false otherwise; otherwise the result is
4494 // unspecified.
4495 // We interpret this as applying to pointers to *cv* void.
4496 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004497 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004498 CCEDiag(E, diag::note_constexpr_void_comparison);
4499
Richard Smithf15fda02012-02-02 01:16:57 +00004500 // C++11 [expr.rel]p2:
4501 // - If two pointers point to non-static data members of the same object,
4502 // or to subobjects or array elements fo such members, recursively, the
4503 // pointer to the later declared member compares greater provided the
4504 // two members have the same access control and provided their class is
4505 // not a union.
4506 // [...]
4507 // - Otherwise pointer comparisons are unspecified.
4508 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4509 E->isRelationalOp()) {
4510 bool WasArrayIndex;
4511 unsigned Mismatch =
4512 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4513 RHSDesignator, WasArrayIndex);
4514 // At the point where the designators diverge, the comparison has a
4515 // specified value if:
4516 // - we are comparing array indices
4517 // - we are comparing fields of a union, or fields with the same access
4518 // Otherwise, the result is unspecified and thus the comparison is not a
4519 // constant expression.
4520 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4521 Mismatch < RHSDesignator.Entries.size()) {
4522 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4523 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4524 if (!LF && !RF)
4525 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4526 else if (!LF)
4527 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4528 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4529 << RF->getParent() << RF;
4530 else if (!RF)
4531 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4532 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4533 << LF->getParent() << LF;
4534 else if (!LF->getParent()->isUnion() &&
4535 LF->getAccess() != RF->getAccess())
4536 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4537 << LF << LF->getAccess() << RF << RF->getAccess()
4538 << LF->getParent();
4539 }
4540 }
4541
Richard Smith625b8072011-10-31 01:37:14 +00004542 switch (E->getOpcode()) {
4543 default: llvm_unreachable("missing comparison operator");
4544 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4545 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4546 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4547 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4548 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4549 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004550 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004551 }
4552 }
Richard Smithb02e4622012-02-01 01:42:44 +00004553
4554 if (LHSTy->isMemberPointerType()) {
4555 assert(E->isEqualityOp() && "unexpected member pointer operation");
4556 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4557
4558 MemberPtr LHSValue, RHSValue;
4559
4560 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4561 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4562 return false;
4563
4564 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4565 return false;
4566
4567 // C++11 [expr.eq]p2:
4568 // If both operands are null, they compare equal. Otherwise if only one is
4569 // null, they compare unequal.
4570 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4571 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4572 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4573 }
4574
4575 // Otherwise if either is a pointer to a virtual member function, the
4576 // result is unspecified.
4577 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4578 if (MD->isVirtual())
4579 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4580 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4581 if (MD->isVirtual())
4582 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4583
4584 // Otherwise they compare equal if and only if they would refer to the
4585 // same member of the same most derived object or the same subobject if
4586 // they were dereferenced with a hypothetical object of the associated
4587 // class type.
4588 bool Equal = LHSValue == RHSValue;
4589 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4590 }
4591
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004592 if (!LHSTy->isIntegralOrEnumerationType() ||
4593 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004594 // We can't continue from here for non-integral types.
4595 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004596 }
4597
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004598 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004599 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004600
4601 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4602 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004603 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004604
Richard Smith745f5142012-01-27 01:14:48 +00004605 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004606 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004607
Richard Smith47a1eed2011-10-29 20:57:55 +00004608 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004609
4610 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004611 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004612 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4613 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004614 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004615 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004616 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004617 LHSVal.getLValueOffset() -= AdditionalOffset;
4618 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004619 return true;
4620 }
4621
4622 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004623 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004624 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004625 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4626 LHSVal.getInt().getZExtValue());
4627 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004628 return true;
4629 }
4630
Eli Friedman65639282012-01-04 23:13:47 +00004631 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4632 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004633 if (!LHSVal.getLValueOffset().isZero() ||
4634 !RHSVal.getLValueOffset().isZero())
4635 return false;
4636 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4637 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4638 if (!LHSExpr || !RHSExpr)
4639 return false;
4640 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4641 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4642 if (!LHSAddrExpr || !RHSAddrExpr)
4643 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004644 // Make sure both labels come from the same function.
4645 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4646 RHSAddrExpr->getLabel()->getDeclContext())
4647 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004648 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4649 return true;
4650 }
4651
Eli Friedman42edd0d2009-03-24 01:14:50 +00004652 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004653 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004654 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004655
Richard Smithc49bd112011-10-28 17:51:58 +00004656 APSInt &LHS = LHSVal.getInt();
4657 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004658
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004659 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004660 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004661 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004662 case BO_Mul:
4663 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4664 LHS.getBitWidth() * 2,
4665 std::multiplies<APSInt>()), E);
4666 case BO_Add:
4667 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4668 LHS.getBitWidth() + 1,
4669 std::plus<APSInt>()), E);
4670 case BO_Sub:
4671 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4672 LHS.getBitWidth() + 1,
4673 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004674 case BO_And: return Success(LHS & RHS, E);
4675 case BO_Xor: return Success(LHS ^ RHS, E);
4676 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004677 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004678 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004679 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004680 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004681 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4682 // actually undefined behavior in C++11 due to a language defect.
4683 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4684 LHS.isSigned() && LHS.isMinSignedValue())
4685 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4686 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004687 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004688 // During constant-folding, a negative shift is an opposite shift. Such a
4689 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004690 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004691 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004692 RHS = -RHS;
4693 goto shift_right;
4694 }
4695
4696 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004697 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4698 // shifted type.
4699 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4700 if (SA != RHS) {
4701 CCEDiag(E, diag::note_constexpr_large_shift)
4702 << RHS << E->getType() << LHS.getBitWidth();
4703 } else if (LHS.isSigned()) {
4704 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4705 // operand, and must not overflow.
4706 if (LHS.isNegative())
4707 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4708 else if (LHS.countLeadingZeros() <= SA)
4709 HandleOverflow(Info, E, LHS.extend(LHS.getBitWidth() + SA) << SA,
4710 E->getType());
4711 }
4712
Richard Smithc49bd112011-10-28 17:51:58 +00004713 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004714 }
John McCall2de56d12010-08-25 11:45:40 +00004715 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004716 // During constant-folding, a negative shift is an opposite shift. Such a
4717 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004718 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004719 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004720 RHS = -RHS;
4721 goto shift_left;
4722 }
4723
4724 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004725 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4726 // shifted type.
4727 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4728 if (SA != RHS)
4729 CCEDiag(E, diag::note_constexpr_large_shift)
4730 << RHS << E->getType() << LHS.getBitWidth();
4731
Richard Smithc49bd112011-10-28 17:51:58 +00004732 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004733 }
Mike Stump1eb44332009-09-09 15:08:12 +00004734
Richard Smithc49bd112011-10-28 17:51:58 +00004735 case BO_LT: return Success(LHS < RHS, E);
4736 case BO_GT: return Success(LHS > RHS, E);
4737 case BO_LE: return Success(LHS <= RHS, E);
4738 case BO_GE: return Success(LHS >= RHS, E);
4739 case BO_EQ: return Success(LHS == RHS, E);
4740 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004741 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004742}
4743
Ken Dyck8b752f12010-01-27 17:10:57 +00004744CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004745 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4746 // the result is the size of the referenced type."
4747 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4748 // result shall be the alignment of the referenced type."
4749 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4750 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004751
4752 // __alignof is defined to return the preferred alignment.
4753 return Info.Ctx.toCharUnitsFromBits(
4754 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004755}
4756
Ken Dyck8b752f12010-01-27 17:10:57 +00004757CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004758 E = E->IgnoreParens();
4759
4760 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004761 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004762 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004763 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4764 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004765
Chris Lattneraf707ab2009-01-24 21:53:27 +00004766 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004767 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4768 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004769
Chris Lattnere9feb472009-01-24 21:09:06 +00004770 return GetAlignOfType(E->getType());
4771}
4772
4773
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004774/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4775/// a result as the expression's type.
4776bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4777 const UnaryExprOrTypeTraitExpr *E) {
4778 switch(E->getKind()) {
4779 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004780 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004781 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004782 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004783 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004784 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004785
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004786 case UETT_VecStep: {
4787 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004788
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004789 if (Ty->isVectorType()) {
4790 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004791
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004792 // The vec_step built-in functions that take a 3-component
4793 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4794 if (n == 3)
4795 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004796
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004797 return Success(n, E);
4798 } else
4799 return Success(1, E);
4800 }
4801
4802 case UETT_SizeOf: {
4803 QualType SrcTy = E->getTypeOfArgument();
4804 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4805 // the result is the size of the referenced type."
4806 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4807 // result shall be the alignment of the referenced type."
4808 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4809 SrcTy = Ref->getPointeeType();
4810
Richard Smith180f4792011-11-10 06:34:14 +00004811 CharUnits Sizeof;
4812 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004813 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004814 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004815 }
4816 }
4817
4818 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004819}
4820
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004821bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004822 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004823 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004824 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004825 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004826 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004827 for (unsigned i = 0; i != n; ++i) {
4828 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4829 switch (ON.getKind()) {
4830 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004831 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004832 APSInt IdxResult;
4833 if (!EvaluateInteger(Idx, IdxResult, Info))
4834 return false;
4835 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4836 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004837 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004838 CurrentType = AT->getElementType();
4839 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4840 Result += IdxResult.getSExtValue() * ElementSize;
4841 break;
4842 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004843
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004844 case OffsetOfExpr::OffsetOfNode::Field: {
4845 FieldDecl *MemberDecl = ON.getField();
4846 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004847 if (!RT)
4848 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004849 RecordDecl *RD = RT->getDecl();
4850 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004851 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004852 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004853 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004854 CurrentType = MemberDecl->getType().getNonReferenceType();
4855 break;
4856 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004857
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004858 case OffsetOfExpr::OffsetOfNode::Identifier:
4859 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004860
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004861 case OffsetOfExpr::OffsetOfNode::Base: {
4862 CXXBaseSpecifier *BaseSpec = ON.getBase();
4863 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004864 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004865
4866 // Find the layout of the class whose base we are looking into.
4867 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004868 if (!RT)
4869 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004870 RecordDecl *RD = RT->getDecl();
4871 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4872
4873 // Find the base class itself.
4874 CurrentType = BaseSpec->getType();
4875 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4876 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004877 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004878
4879 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004880 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004881 break;
4882 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004883 }
4884 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004885 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004886}
4887
Chris Lattnerb542afe2008-07-11 19:10:17 +00004888bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004889 switch (E->getOpcode()) {
4890 default:
4891 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4892 // See C99 6.6p3.
4893 return Error(E);
4894 case UO_Extension:
4895 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4896 // If so, we could clear the diagnostic ID.
4897 return Visit(E->getSubExpr());
4898 case UO_Plus:
4899 // The result is just the value.
4900 return Visit(E->getSubExpr());
4901 case UO_Minus: {
4902 if (!Visit(E->getSubExpr()))
4903 return false;
4904 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00004905 const APSInt &Value = Result.getInt();
4906 if (Value.isSigned() && Value.isMinSignedValue())
4907 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
4908 E->getType());
4909 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00004910 }
4911 case UO_Not: {
4912 if (!Visit(E->getSubExpr()))
4913 return false;
4914 if (!Result.isInt()) return Error(E);
4915 return Success(~Result.getInt(), E);
4916 }
4917 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004918 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004919 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004920 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004921 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004922 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004923 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004924}
Mike Stump1eb44332009-09-09 15:08:12 +00004925
Chris Lattner732b2232008-07-12 01:15:53 +00004926/// HandleCast - This is used to evaluate implicit or explicit casts where the
4927/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004928bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4929 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004930 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004931 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004932
Eli Friedman46a52322011-03-25 00:43:55 +00004933 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004934 case CK_BaseToDerived:
4935 case CK_DerivedToBase:
4936 case CK_UncheckedDerivedToBase:
4937 case CK_Dynamic:
4938 case CK_ToUnion:
4939 case CK_ArrayToPointerDecay:
4940 case CK_FunctionToPointerDecay:
4941 case CK_NullToPointer:
4942 case CK_NullToMemberPointer:
4943 case CK_BaseToDerivedMemberPointer:
4944 case CK_DerivedToBaseMemberPointer:
4945 case CK_ConstructorConversion:
4946 case CK_IntegralToPointer:
4947 case CK_ToVoid:
4948 case CK_VectorSplat:
4949 case CK_IntegralToFloating:
4950 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004951 case CK_CPointerToObjCPointerCast:
4952 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004953 case CK_AnyPointerToBlockPointerCast:
4954 case CK_ObjCObjectLValueCast:
4955 case CK_FloatingRealToComplex:
4956 case CK_FloatingComplexToReal:
4957 case CK_FloatingComplexCast:
4958 case CK_FloatingComplexToIntegralComplex:
4959 case CK_IntegralRealToComplex:
4960 case CK_IntegralComplexCast:
4961 case CK_IntegralComplexToFloatingComplex:
4962 llvm_unreachable("invalid cast kind for integral value");
4963
Eli Friedmane50c2972011-03-25 19:07:11 +00004964 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004965 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004966 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00004967 case CK_ARCProduceObject:
4968 case CK_ARCConsumeObject:
4969 case CK_ARCReclaimReturnedObject:
4970 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004971 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004972
Richard Smith7d580a42012-01-17 21:17:26 +00004973 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00004974 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00004975 case CK_AtomicToNonAtomic:
4976 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00004977 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004978 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004979
4980 case CK_MemberPointerToBoolean:
4981 case CK_PointerToBoolean:
4982 case CK_IntegralToBoolean:
4983 case CK_FloatingToBoolean:
4984 case CK_FloatingComplexToBoolean:
4985 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004986 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004987 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004988 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004989 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004990 }
4991
Eli Friedman46a52322011-03-25 00:43:55 +00004992 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004993 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004994 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004995
Eli Friedmanbe265702009-02-20 01:15:07 +00004996 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00004997 // Allow casts of address-of-label differences if they are no-ops
4998 // or narrowing. (The narrowing case isn't actually guaranteed to
4999 // be constant-evaluatable except in some narrow cases which are hard
5000 // to detect here. We let it through on the assumption the user knows
5001 // what they are doing.)
5002 if (Result.isAddrLabelDiff())
5003 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005004 // Only allow casts of lvalues if they are lossless.
5005 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5006 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005007
Richard Smithf72fccf2012-01-30 22:27:01 +00005008 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5009 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005010 }
Mike Stump1eb44332009-09-09 15:08:12 +00005011
Eli Friedman46a52322011-03-25 00:43:55 +00005012 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005013 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5014
John McCallefdb83e2010-05-07 21:00:08 +00005015 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005016 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005017 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005018
Daniel Dunbardd211642009-02-19 22:24:01 +00005019 if (LV.getLValueBase()) {
5020 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005021 // FIXME: Allow a larger integer size than the pointer size, and allow
5022 // narrowing back down to pointer width in subsequent integral casts.
5023 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005024 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005025 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005026
Richard Smithb755a9d2011-11-16 07:18:12 +00005027 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005028 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005029 return true;
5030 }
5031
Ken Dycka7305832010-01-15 12:37:54 +00005032 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5033 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005034 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005035 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005036
Eli Friedman46a52322011-03-25 00:43:55 +00005037 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005038 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005039 if (!EvaluateComplex(SubExpr, C, Info))
5040 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005041 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005042 }
Eli Friedman2217c872009-02-22 11:46:18 +00005043
Eli Friedman46a52322011-03-25 00:43:55 +00005044 case CK_FloatingToIntegral: {
5045 APFloat F(0.0);
5046 if (!EvaluateFloat(SubExpr, F, Info))
5047 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005048
Richard Smithc1c5f272011-12-13 06:39:58 +00005049 APSInt Value;
5050 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5051 return false;
5052 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005053 }
5054 }
Mike Stump1eb44332009-09-09 15:08:12 +00005055
Eli Friedman46a52322011-03-25 00:43:55 +00005056 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005057}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005058
Eli Friedman722c7172009-02-28 03:59:05 +00005059bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5060 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005061 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005062 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5063 return false;
5064 if (!LV.isComplexInt())
5065 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005066 return Success(LV.getComplexIntReal(), E);
5067 }
5068
5069 return Visit(E->getSubExpr());
5070}
5071
Eli Friedman664a1042009-02-27 04:45:43 +00005072bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005073 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005074 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005075 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5076 return false;
5077 if (!LV.isComplexInt())
5078 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005079 return Success(LV.getComplexIntImag(), E);
5080 }
5081
Richard Smith8327fad2011-10-24 18:44:57 +00005082 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005083 return Success(0, E);
5084}
5085
Douglas Gregoree8aff02011-01-04 17:33:58 +00005086bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5087 return Success(E->getPackLength(), E);
5088}
5089
Sebastian Redl295995c2010-09-10 20:55:47 +00005090bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5091 return Success(E->getValue(), E);
5092}
5093
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005094//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005095// Float Evaluation
5096//===----------------------------------------------------------------------===//
5097
5098namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005099class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005100 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005101 APFloat &Result;
5102public:
5103 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005104 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005105
Richard Smith47a1eed2011-10-29 20:57:55 +00005106 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005107 Result = V.getFloat();
5108 return true;
5109 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005110
Richard Smith51201882011-12-30 21:15:51 +00005111 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005112 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5113 return true;
5114 }
5115
Chris Lattner019f4e82008-10-06 05:28:25 +00005116 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005117
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005118 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005119 bool VisitBinaryOperator(const BinaryOperator *E);
5120 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005121 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005122
John McCallabd3a852010-05-07 22:08:54 +00005123 bool VisitUnaryReal(const UnaryOperator *E);
5124 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005125
Richard Smith51201882011-12-30 21:15:51 +00005126 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005127};
5128} // end anonymous namespace
5129
5130static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005131 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005132 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005133}
5134
Jay Foad4ba2a172011-01-12 09:06:06 +00005135static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005136 QualType ResultTy,
5137 const Expr *Arg,
5138 bool SNaN,
5139 llvm::APFloat &Result) {
5140 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5141 if (!S) return false;
5142
5143 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5144
5145 llvm::APInt fill;
5146
5147 // Treat empty strings as if they were zero.
5148 if (S->getString().empty())
5149 fill = llvm::APInt(32, 0);
5150 else if (S->getString().getAsInteger(0, fill))
5151 return false;
5152
5153 if (SNaN)
5154 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5155 else
5156 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5157 return true;
5158}
5159
Chris Lattner019f4e82008-10-06 05:28:25 +00005160bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005161 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005162 default:
5163 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5164
Chris Lattner019f4e82008-10-06 05:28:25 +00005165 case Builtin::BI__builtin_huge_val:
5166 case Builtin::BI__builtin_huge_valf:
5167 case Builtin::BI__builtin_huge_vall:
5168 case Builtin::BI__builtin_inf:
5169 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005170 case Builtin::BI__builtin_infl: {
5171 const llvm::fltSemantics &Sem =
5172 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005173 Result = llvm::APFloat::getInf(Sem);
5174 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005175 }
Mike Stump1eb44332009-09-09 15:08:12 +00005176
John McCalldb7b72a2010-02-28 13:00:19 +00005177 case Builtin::BI__builtin_nans:
5178 case Builtin::BI__builtin_nansf:
5179 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005180 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5181 true, Result))
5182 return Error(E);
5183 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005184
Chris Lattner9e621712008-10-06 06:31:58 +00005185 case Builtin::BI__builtin_nan:
5186 case Builtin::BI__builtin_nanf:
5187 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005188 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005189 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005190 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5191 false, Result))
5192 return Error(E);
5193 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005194
5195 case Builtin::BI__builtin_fabs:
5196 case Builtin::BI__builtin_fabsf:
5197 case Builtin::BI__builtin_fabsl:
5198 if (!EvaluateFloat(E->getArg(0), Result, Info))
5199 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005200
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005201 if (Result.isNegative())
5202 Result.changeSign();
5203 return true;
5204
Mike Stump1eb44332009-09-09 15:08:12 +00005205 case Builtin::BI__builtin_copysign:
5206 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005207 case Builtin::BI__builtin_copysignl: {
5208 APFloat RHS(0.);
5209 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5210 !EvaluateFloat(E->getArg(1), RHS, Info))
5211 return false;
5212 Result.copySign(RHS);
5213 return true;
5214 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005215 }
5216}
5217
John McCallabd3a852010-05-07 22:08:54 +00005218bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005219 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5220 ComplexValue CV;
5221 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5222 return false;
5223 Result = CV.FloatReal;
5224 return true;
5225 }
5226
5227 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005228}
5229
5230bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005231 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5232 ComplexValue CV;
5233 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5234 return false;
5235 Result = CV.FloatImag;
5236 return true;
5237 }
5238
Richard Smith8327fad2011-10-24 18:44:57 +00005239 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005240 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5241 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005242 return true;
5243}
5244
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005245bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005246 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005247 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005248 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005249 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005250 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005251 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5252 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005253 Result.changeSign();
5254 return true;
5255 }
5256}
Chris Lattner019f4e82008-10-06 05:28:25 +00005257
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005258bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005259 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5260 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005261
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005262 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005263 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5264 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005265 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005266 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005267 return false;
5268
5269 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005270 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005271 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005272 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005273 break;
John McCall2de56d12010-08-25 11:45:40 +00005274 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005275 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005276 break;
John McCall2de56d12010-08-25 11:45:40 +00005277 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005278 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005279 break;
John McCall2de56d12010-08-25 11:45:40 +00005280 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005281 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005282 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005283 }
Richard Smith7b48a292012-02-01 05:53:12 +00005284
5285 if (Result.isInfinity() || Result.isNaN())
5286 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5287 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005288}
5289
5290bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5291 Result = E->getValue();
5292 return true;
5293}
5294
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005295bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5296 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005297
Eli Friedman2a523ee2011-03-25 00:54:52 +00005298 switch (E->getCastKind()) {
5299 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005300 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005301
5302 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005303 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005304 return EvaluateInteger(SubExpr, IntResult, Info) &&
5305 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5306 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005307 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005308
5309 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005310 if (!Visit(SubExpr))
5311 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005312 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5313 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005314 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005315
Eli Friedman2a523ee2011-03-25 00:54:52 +00005316 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005317 ComplexValue V;
5318 if (!EvaluateComplex(SubExpr, V, Info))
5319 return false;
5320 Result = V.getComplexFloatReal();
5321 return true;
5322 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005323 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005324}
5325
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005326//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005327// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005328//===----------------------------------------------------------------------===//
5329
5330namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005331class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005332 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005333 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005334
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005335public:
John McCallf4cf1a12010-05-07 17:22:02 +00005336 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005337 : ExprEvaluatorBaseTy(info), Result(Result) {}
5338
Richard Smith47a1eed2011-10-29 20:57:55 +00005339 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005340 Result.setFrom(V);
5341 return true;
5342 }
Mike Stump1eb44332009-09-09 15:08:12 +00005343
Eli Friedman7ead5c72012-01-10 04:58:17 +00005344 bool ZeroInitialization(const Expr *E);
5345
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005346 //===--------------------------------------------------------------------===//
5347 // Visitor Methods
5348 //===--------------------------------------------------------------------===//
5349
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005350 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005351 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005352 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005353 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005354 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005355};
5356} // end anonymous namespace
5357
John McCallf4cf1a12010-05-07 17:22:02 +00005358static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5359 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005360 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005361 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005362}
5363
Eli Friedman7ead5c72012-01-10 04:58:17 +00005364bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005365 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005366 if (ElemTy->isRealFloatingType()) {
5367 Result.makeComplexFloat();
5368 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5369 Result.FloatReal = Zero;
5370 Result.FloatImag = Zero;
5371 } else {
5372 Result.makeComplexInt();
5373 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5374 Result.IntReal = Zero;
5375 Result.IntImag = Zero;
5376 }
5377 return true;
5378}
5379
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005380bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5381 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005382
5383 if (SubExpr->getType()->isRealFloatingType()) {
5384 Result.makeComplexFloat();
5385 APFloat &Imag = Result.FloatImag;
5386 if (!EvaluateFloat(SubExpr, Imag, Info))
5387 return false;
5388
5389 Result.FloatReal = APFloat(Imag.getSemantics());
5390 return true;
5391 } else {
5392 assert(SubExpr->getType()->isIntegerType() &&
5393 "Unexpected imaginary literal.");
5394
5395 Result.makeComplexInt();
5396 APSInt &Imag = Result.IntImag;
5397 if (!EvaluateInteger(SubExpr, Imag, Info))
5398 return false;
5399
5400 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5401 return true;
5402 }
5403}
5404
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005405bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005406
John McCall8786da72010-12-14 17:51:41 +00005407 switch (E->getCastKind()) {
5408 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005409 case CK_BaseToDerived:
5410 case CK_DerivedToBase:
5411 case CK_UncheckedDerivedToBase:
5412 case CK_Dynamic:
5413 case CK_ToUnion:
5414 case CK_ArrayToPointerDecay:
5415 case CK_FunctionToPointerDecay:
5416 case CK_NullToPointer:
5417 case CK_NullToMemberPointer:
5418 case CK_BaseToDerivedMemberPointer:
5419 case CK_DerivedToBaseMemberPointer:
5420 case CK_MemberPointerToBoolean:
5421 case CK_ConstructorConversion:
5422 case CK_IntegralToPointer:
5423 case CK_PointerToIntegral:
5424 case CK_PointerToBoolean:
5425 case CK_ToVoid:
5426 case CK_VectorSplat:
5427 case CK_IntegralCast:
5428 case CK_IntegralToBoolean:
5429 case CK_IntegralToFloating:
5430 case CK_FloatingToIntegral:
5431 case CK_FloatingToBoolean:
5432 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005433 case CK_CPointerToObjCPointerCast:
5434 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005435 case CK_AnyPointerToBlockPointerCast:
5436 case CK_ObjCObjectLValueCast:
5437 case CK_FloatingComplexToReal:
5438 case CK_FloatingComplexToBoolean:
5439 case CK_IntegralComplexToReal:
5440 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005441 case CK_ARCProduceObject:
5442 case CK_ARCConsumeObject:
5443 case CK_ARCReclaimReturnedObject:
5444 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005445 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005446
John McCall8786da72010-12-14 17:51:41 +00005447 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005448 case CK_AtomicToNonAtomic:
5449 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005450 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005451 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005452
5453 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005454 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005455 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005456 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005457
5458 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005459 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005460 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005461 return false;
5462
John McCall8786da72010-12-14 17:51:41 +00005463 Result.makeComplexFloat();
5464 Result.FloatImag = APFloat(Real.getSemantics());
5465 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005466 }
5467
John McCall8786da72010-12-14 17:51:41 +00005468 case CK_FloatingComplexCast: {
5469 if (!Visit(E->getSubExpr()))
5470 return false;
5471
5472 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5473 QualType From
5474 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5475
Richard Smithc1c5f272011-12-13 06:39:58 +00005476 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5477 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005478 }
5479
5480 case CK_FloatingComplexToIntegralComplex: {
5481 if (!Visit(E->getSubExpr()))
5482 return false;
5483
5484 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5485 QualType From
5486 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5487 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005488 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5489 To, Result.IntReal) &&
5490 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5491 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005492 }
5493
5494 case CK_IntegralRealToComplex: {
5495 APSInt &Real = Result.IntReal;
5496 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5497 return false;
5498
5499 Result.makeComplexInt();
5500 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5501 return true;
5502 }
5503
5504 case CK_IntegralComplexCast: {
5505 if (!Visit(E->getSubExpr()))
5506 return false;
5507
5508 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5509 QualType From
5510 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5511
Richard Smithf72fccf2012-01-30 22:27:01 +00005512 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5513 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005514 return true;
5515 }
5516
5517 case CK_IntegralComplexToFloatingComplex: {
5518 if (!Visit(E->getSubExpr()))
5519 return false;
5520
5521 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5522 QualType From
5523 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5524 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005525 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5526 To, Result.FloatReal) &&
5527 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5528 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005529 }
5530 }
5531
5532 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005533}
5534
John McCallf4cf1a12010-05-07 17:22:02 +00005535bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005536 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005537 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5538
Richard Smith745f5142012-01-27 01:14:48 +00005539 bool LHSOK = Visit(E->getLHS());
5540 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005541 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005542
John McCallf4cf1a12010-05-07 17:22:02 +00005543 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005544 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005545 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005546
Daniel Dunbar3f279872009-01-29 01:32:56 +00005547 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5548 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005549 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005550 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005551 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005552 if (Result.isComplexFloat()) {
5553 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5554 APFloat::rmNearestTiesToEven);
5555 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5556 APFloat::rmNearestTiesToEven);
5557 } else {
5558 Result.getComplexIntReal() += RHS.getComplexIntReal();
5559 Result.getComplexIntImag() += RHS.getComplexIntImag();
5560 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005561 break;
John McCall2de56d12010-08-25 11:45:40 +00005562 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005563 if (Result.isComplexFloat()) {
5564 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5565 APFloat::rmNearestTiesToEven);
5566 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5567 APFloat::rmNearestTiesToEven);
5568 } else {
5569 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5570 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5571 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005572 break;
John McCall2de56d12010-08-25 11:45:40 +00005573 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005574 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005575 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005576 APFloat &LHS_r = LHS.getComplexFloatReal();
5577 APFloat &LHS_i = LHS.getComplexFloatImag();
5578 APFloat &RHS_r = RHS.getComplexFloatReal();
5579 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005580
Daniel Dunbar3f279872009-01-29 01:32:56 +00005581 APFloat Tmp = LHS_r;
5582 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5583 Result.getComplexFloatReal() = Tmp;
5584 Tmp = LHS_i;
5585 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5586 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5587
5588 Tmp = LHS_r;
5589 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5590 Result.getComplexFloatImag() = Tmp;
5591 Tmp = LHS_i;
5592 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5593 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5594 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005595 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005596 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005597 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5598 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005599 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005600 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5601 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5602 }
5603 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005604 case BO_Div:
5605 if (Result.isComplexFloat()) {
5606 ComplexValue LHS = Result;
5607 APFloat &LHS_r = LHS.getComplexFloatReal();
5608 APFloat &LHS_i = LHS.getComplexFloatImag();
5609 APFloat &RHS_r = RHS.getComplexFloatReal();
5610 APFloat &RHS_i = RHS.getComplexFloatImag();
5611 APFloat &Res_r = Result.getComplexFloatReal();
5612 APFloat &Res_i = Result.getComplexFloatImag();
5613
5614 APFloat Den = RHS_r;
5615 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5616 APFloat Tmp = RHS_i;
5617 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5618 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5619
5620 Res_r = LHS_r;
5621 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5622 Tmp = LHS_i;
5623 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5624 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5625 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5626
5627 Res_i = LHS_i;
5628 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5629 Tmp = LHS_r;
5630 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5631 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5632 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5633 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005634 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5635 return Error(E, diag::note_expr_divide_by_zero);
5636
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005637 ComplexValue LHS = Result;
5638 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5639 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5640 Result.getComplexIntReal() =
5641 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5642 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5643 Result.getComplexIntImag() =
5644 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5645 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5646 }
5647 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005648 }
5649
John McCallf4cf1a12010-05-07 17:22:02 +00005650 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005651}
5652
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005653bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5654 // Get the operand value into 'Result'.
5655 if (!Visit(E->getSubExpr()))
5656 return false;
5657
5658 switch (E->getOpcode()) {
5659 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005660 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005661 case UO_Extension:
5662 return true;
5663 case UO_Plus:
5664 // The result is always just the subexpr.
5665 return true;
5666 case UO_Minus:
5667 if (Result.isComplexFloat()) {
5668 Result.getComplexFloatReal().changeSign();
5669 Result.getComplexFloatImag().changeSign();
5670 }
5671 else {
5672 Result.getComplexIntReal() = -Result.getComplexIntReal();
5673 Result.getComplexIntImag() = -Result.getComplexIntImag();
5674 }
5675 return true;
5676 case UO_Not:
5677 if (Result.isComplexFloat())
5678 Result.getComplexFloatImag().changeSign();
5679 else
5680 Result.getComplexIntImag() = -Result.getComplexIntImag();
5681 return true;
5682 }
5683}
5684
Eli Friedman7ead5c72012-01-10 04:58:17 +00005685bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5686 if (E->getNumInits() == 2) {
5687 if (E->getType()->isComplexType()) {
5688 Result.makeComplexFloat();
5689 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5690 return false;
5691 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5692 return false;
5693 } else {
5694 Result.makeComplexInt();
5695 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5696 return false;
5697 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5698 return false;
5699 }
5700 return true;
5701 }
5702 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5703}
5704
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005705//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005706// Void expression evaluation, primarily for a cast to void on the LHS of a
5707// comma operator
5708//===----------------------------------------------------------------------===//
5709
5710namespace {
5711class VoidExprEvaluator
5712 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5713public:
5714 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5715
5716 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005717
5718 bool VisitCastExpr(const CastExpr *E) {
5719 switch (E->getCastKind()) {
5720 default:
5721 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5722 case CK_ToVoid:
5723 VisitIgnoredValue(E->getSubExpr());
5724 return true;
5725 }
5726 }
5727};
5728} // end anonymous namespace
5729
5730static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5731 assert(E->isRValue() && E->getType()->isVoidType());
5732 return VoidExprEvaluator(Info).Visit(E);
5733}
5734
5735//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005736// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005737//===----------------------------------------------------------------------===//
5738
Richard Smith47a1eed2011-10-29 20:57:55 +00005739static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005740 // In C, function designators are not lvalues, but we evaluate them as if they
5741 // are.
5742 if (E->isGLValue() || E->getType()->isFunctionType()) {
5743 LValue LV;
5744 if (!EvaluateLValue(E, LV, Info))
5745 return false;
5746 LV.moveInto(Result);
5747 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005748 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005749 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005750 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005751 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005752 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005753 } else if (E->getType()->hasPointerRepresentation()) {
5754 LValue LV;
5755 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005756 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005757 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005758 } else if (E->getType()->isRealFloatingType()) {
5759 llvm::APFloat F(0.0);
5760 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005761 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005762 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005763 } else if (E->getType()->isAnyComplexType()) {
5764 ComplexValue C;
5765 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005766 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005767 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005768 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005769 MemberPtr P;
5770 if (!EvaluateMemberPointer(E, P, Info))
5771 return false;
5772 P.moveInto(Result);
5773 return true;
Richard Smith51201882011-12-30 21:15:51 +00005774 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005775 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005776 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005777 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005778 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005779 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005780 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005781 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005782 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005783 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5784 return false;
5785 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005786 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005787 if (Info.getLangOpts().CPlusPlus0x)
5788 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5789 << E->getType();
5790 else
5791 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005792 if (!EvaluateVoid(E, Info))
5793 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005794 } else if (Info.getLangOpts().CPlusPlus0x) {
5795 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5796 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005797 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005798 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005799 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005800 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005801
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005802 return true;
5803}
5804
Richard Smith69c2c502011-11-04 05:33:44 +00005805/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5806/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5807/// since later initializers for an object can indirectly refer to subobjects
5808/// which were initialized earlier.
5809static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005810 const LValue &This, const Expr *E,
5811 CheckConstantExpressionKind CCEK) {
Richard Smith51201882011-12-30 21:15:51 +00005812 if (!CheckLiteralType(Info, E))
5813 return false;
5814
5815 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005816 // Evaluate arrays and record types in-place, so that later initializers can
5817 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005818 if (E->getType()->isArrayType())
5819 return EvaluateArray(E, This, Result, Info);
5820 else if (E->getType()->isRecordType())
5821 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005822 }
5823
5824 // For any other type, in-place evaluation is unimportant.
5825 CCValue CoreConstResult;
5826 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005827 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005828}
5829
Richard Smithf48fdb02011-12-09 22:58:01 +00005830/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5831/// lvalue-to-rvalue cast if it is an lvalue.
5832static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005833 if (!CheckLiteralType(Info, E))
5834 return false;
5835
Richard Smithf48fdb02011-12-09 22:58:01 +00005836 CCValue Value;
5837 if (!::Evaluate(Value, Info, E))
5838 return false;
5839
5840 if (E->isGLValue()) {
5841 LValue LV;
5842 LV.setFrom(Value);
5843 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5844 return false;
5845 }
5846
5847 // Check this core constant expression is a constant expression, and if so,
5848 // convert it to one.
5849 return CheckConstantExpression(Info, E, Value, Result);
5850}
Richard Smithc49bd112011-10-28 17:51:58 +00005851
Richard Smith51f47082011-10-29 00:50:52 +00005852/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005853/// any crazy technique (that has nothing to do with language standards) that
5854/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005855/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5856/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005857bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005858 // Fast-path evaluations of integer literals, since we sometimes see files
5859 // containing vast quantities of these.
5860 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5861 Result.Val = APValue(APSInt(L->getValue(),
5862 L->getType()->isUnsignedIntegerType()));
5863 return true;
5864 }
5865
Richard Smith2d6a5672012-01-14 04:30:29 +00005866 // FIXME: Evaluating values of large array and record types can cause
5867 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005868 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5869 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005870 return false;
5871
Richard Smithf48fdb02011-12-09 22:58:01 +00005872 EvalInfo Info(Ctx, Result);
5873 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005874}
5875
Jay Foad4ba2a172011-01-12 09:06:06 +00005876bool Expr::EvaluateAsBooleanCondition(bool &Result,
5877 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005878 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005879 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005880 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5881 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005882 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005883}
5884
Richard Smith80d4b552011-12-28 19:48:30 +00005885bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5886 SideEffectsKind AllowSideEffects) const {
5887 if (!getType()->isIntegralOrEnumerationType())
5888 return false;
5889
Richard Smithc49bd112011-10-28 17:51:58 +00005890 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005891 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5892 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005893 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005894
Richard Smithc49bd112011-10-28 17:51:58 +00005895 Result = ExprResult.Val.getInt();
5896 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005897}
5898
Jay Foad4ba2a172011-01-12 09:06:06 +00005899bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005900 EvalInfo Info(Ctx, Result);
5901
John McCallefdb83e2010-05-07 21:00:08 +00005902 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005903 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005904 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5905 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005906}
5907
Richard Smith099e7f62011-12-19 06:19:21 +00005908bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5909 const VarDecl *VD,
5910 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005911 // FIXME: Evaluating initializers for large array and record types can cause
5912 // performance problems. Only do so in C++11 for now.
5913 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5914 !Ctx.getLangOptions().CPlusPlus0x)
5915 return false;
5916
Richard Smith099e7f62011-12-19 06:19:21 +00005917 Expr::EvalStatus EStatus;
5918 EStatus.Diag = &Notes;
5919
5920 EvalInfo InitInfo(Ctx, EStatus);
5921 InitInfo.setEvaluatingDecl(VD, Value);
5922
Richard Smith51201882011-12-30 21:15:51 +00005923 if (!CheckLiteralType(InitInfo, this))
5924 return false;
5925
Richard Smith099e7f62011-12-19 06:19:21 +00005926 LValue LVal;
5927 LVal.set(VD);
5928
Richard Smith51201882011-12-30 21:15:51 +00005929 // C++11 [basic.start.init]p2:
5930 // Variables with static storage duration or thread storage duration shall be
5931 // zero-initialized before any other initialization takes place.
5932 // This behavior is not present in C.
5933 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5934 !VD->getType()->isReferenceType()) {
5935 ImplicitValueInitExpr VIE(VD->getType());
5936 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5937 return false;
5938 }
5939
Richard Smith099e7f62011-12-19 06:19:21 +00005940 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5941 !EStatus.HasSideEffects;
5942}
5943
Richard Smith51f47082011-10-29 00:50:52 +00005944/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5945/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005946bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005947 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005948 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005949}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005950
Jay Foad4ba2a172011-01-12 09:06:06 +00005951bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005952 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005953}
5954
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005955APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005956 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005957 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005958 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005959 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005960 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005961
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005962 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005963}
John McCalld905f5a2010-05-07 05:32:02 +00005964
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005965 bool Expr::EvalResult::isGlobalLValue() const {
5966 assert(Val.isLValue());
5967 return IsGlobalLValue(Val.getLValueBase());
5968 }
5969
5970
John McCalld905f5a2010-05-07 05:32:02 +00005971/// isIntegerConstantExpr - this recursive routine will test if an expression is
5972/// an integer constant expression.
5973
5974/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5975/// comma, etc
5976///
5977/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5978/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5979/// cast+dereference.
5980
5981// CheckICE - This function does the fundamental ICE checking: the returned
5982// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5983// Note that to reduce code duplication, this helper does no evaluation
5984// itself; the caller checks whether the expression is evaluatable, and
5985// in the rare cases where CheckICE actually cares about the evaluated
5986// value, it calls into Evalute.
5987//
5988// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005989// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005990// 1: This expression is not an ICE, but if it isn't evaluated, it's
5991// a legal subexpression for an ICE. This return value is used to handle
5992// the comma operator in C99 mode.
5993// 2: This expression is not an ICE, and is not a legal subexpression for one.
5994
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005995namespace {
5996
John McCalld905f5a2010-05-07 05:32:02 +00005997struct ICEDiag {
5998 unsigned Val;
5999 SourceLocation Loc;
6000
6001 public:
6002 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6003 ICEDiag() : Val(0) {}
6004};
6005
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006006}
6007
6008static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006009
6010static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6011 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006012 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006013 !EVResult.Val.isInt()) {
6014 return ICEDiag(2, E->getLocStart());
6015 }
6016 return NoDiag();
6017}
6018
6019static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6020 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006021 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006022 return ICEDiag(2, E->getLocStart());
6023 }
6024
6025 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006026#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006027#define STMT(Node, Base) case Expr::Node##Class:
6028#define EXPR(Node, Base)
6029#include "clang/AST/StmtNodes.inc"
6030 case Expr::PredefinedExprClass:
6031 case Expr::FloatingLiteralClass:
6032 case Expr::ImaginaryLiteralClass:
6033 case Expr::StringLiteralClass:
6034 case Expr::ArraySubscriptExprClass:
6035 case Expr::MemberExprClass:
6036 case Expr::CompoundAssignOperatorClass:
6037 case Expr::CompoundLiteralExprClass:
6038 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006039 case Expr::DesignatedInitExprClass:
6040 case Expr::ImplicitValueInitExprClass:
6041 case Expr::ParenListExprClass:
6042 case Expr::VAArgExprClass:
6043 case Expr::AddrLabelExprClass:
6044 case Expr::StmtExprClass:
6045 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006046 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006047 case Expr::CXXDynamicCastExprClass:
6048 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006049 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006050 case Expr::CXXNullPtrLiteralExprClass:
6051 case Expr::CXXThisExprClass:
6052 case Expr::CXXThrowExprClass:
6053 case Expr::CXXNewExprClass:
6054 case Expr::CXXDeleteExprClass:
6055 case Expr::CXXPseudoDestructorExprClass:
6056 case Expr::UnresolvedLookupExprClass:
6057 case Expr::DependentScopeDeclRefExprClass:
6058 case Expr::CXXConstructExprClass:
6059 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006060 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006061 case Expr::CXXTemporaryObjectExprClass:
6062 case Expr::CXXUnresolvedConstructExprClass:
6063 case Expr::CXXDependentScopeMemberExprClass:
6064 case Expr::UnresolvedMemberExprClass:
6065 case Expr::ObjCStringLiteralClass:
6066 case Expr::ObjCEncodeExprClass:
6067 case Expr::ObjCMessageExprClass:
6068 case Expr::ObjCSelectorExprClass:
6069 case Expr::ObjCProtocolExprClass:
6070 case Expr::ObjCIvarRefExprClass:
6071 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006072 case Expr::ObjCIsaExprClass:
6073 case Expr::ShuffleVectorExprClass:
6074 case Expr::BlockExprClass:
6075 case Expr::BlockDeclRefExprClass:
6076 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006077 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006078 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006079 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006080 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006081 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006082 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006083 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006084 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006085 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006086 return ICEDiag(2, E->getLocStart());
6087
Douglas Gregoree8aff02011-01-04 17:33:58 +00006088 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006089 case Expr::GNUNullExprClass:
6090 // GCC considers the GNU __null value to be an integral constant expression.
6091 return NoDiag();
6092
John McCall91a57552011-07-15 05:09:51 +00006093 case Expr::SubstNonTypeTemplateParmExprClass:
6094 return
6095 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6096
John McCalld905f5a2010-05-07 05:32:02 +00006097 case Expr::ParenExprClass:
6098 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006099 case Expr::GenericSelectionExprClass:
6100 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006101 case Expr::IntegerLiteralClass:
6102 case Expr::CharacterLiteralClass:
6103 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006104 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006105 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006106 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006107 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006108 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006109 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006110 return NoDiag();
6111 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006112 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006113 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6114 // constant expressions, but they can never be ICEs because an ICE cannot
6115 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006116 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006117 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006118 return CheckEvalInICE(E, Ctx);
6119 return ICEDiag(2, E->getLocStart());
6120 }
6121 case Expr::DeclRefExprClass:
6122 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6123 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00006124 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006125 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
6126
6127 // Parameter variables are never constants. Without this check,
6128 // getAnyInitializer() can find a default argument, which leads
6129 // to chaos.
6130 if (isa<ParmVarDecl>(D))
6131 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6132
6133 // C++ 7.1.5.1p2
6134 // A variable of non-volatile const-qualified integral or enumeration
6135 // type initialized by an ICE can be used in ICEs.
6136 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006137 if (!Dcl->getType()->isIntegralOrEnumerationType())
6138 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6139
Richard Smith099e7f62011-12-19 06:19:21 +00006140 const VarDecl *VD;
6141 // Look for a declaration of this variable that has an initializer, and
6142 // check whether it is an ICE.
6143 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6144 return NoDiag();
6145 else
6146 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006147 }
6148 }
6149 return ICEDiag(2, E->getLocStart());
6150 case Expr::UnaryOperatorClass: {
6151 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6152 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006153 case UO_PostInc:
6154 case UO_PostDec:
6155 case UO_PreInc:
6156 case UO_PreDec:
6157 case UO_AddrOf:
6158 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006159 // C99 6.6/3 allows increment and decrement within unevaluated
6160 // subexpressions of constant expressions, but they can never be ICEs
6161 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006162 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006163 case UO_Extension:
6164 case UO_LNot:
6165 case UO_Plus:
6166 case UO_Minus:
6167 case UO_Not:
6168 case UO_Real:
6169 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006170 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006171 }
6172
6173 // OffsetOf falls through here.
6174 }
6175 case Expr::OffsetOfExprClass: {
6176 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006177 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006178 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006179 // compliance: we should warn earlier for offsetof expressions with
6180 // array subscripts that aren't ICEs, and if the array subscripts
6181 // are ICEs, the value of the offsetof must be an integer constant.
6182 return CheckEvalInICE(E, Ctx);
6183 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006184 case Expr::UnaryExprOrTypeTraitExprClass: {
6185 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6186 if ((Exp->getKind() == UETT_SizeOf) &&
6187 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006188 return ICEDiag(2, E->getLocStart());
6189 return NoDiag();
6190 }
6191 case Expr::BinaryOperatorClass: {
6192 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6193 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006194 case BO_PtrMemD:
6195 case BO_PtrMemI:
6196 case BO_Assign:
6197 case BO_MulAssign:
6198 case BO_DivAssign:
6199 case BO_RemAssign:
6200 case BO_AddAssign:
6201 case BO_SubAssign:
6202 case BO_ShlAssign:
6203 case BO_ShrAssign:
6204 case BO_AndAssign:
6205 case BO_XorAssign:
6206 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006207 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6208 // constant expressions, but they can never be ICEs because an ICE cannot
6209 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006210 return ICEDiag(2, E->getLocStart());
6211
John McCall2de56d12010-08-25 11:45:40 +00006212 case BO_Mul:
6213 case BO_Div:
6214 case BO_Rem:
6215 case BO_Add:
6216 case BO_Sub:
6217 case BO_Shl:
6218 case BO_Shr:
6219 case BO_LT:
6220 case BO_GT:
6221 case BO_LE:
6222 case BO_GE:
6223 case BO_EQ:
6224 case BO_NE:
6225 case BO_And:
6226 case BO_Xor:
6227 case BO_Or:
6228 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006229 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6230 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006231 if (Exp->getOpcode() == BO_Div ||
6232 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006233 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006234 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006235 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006236 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006237 if (REval == 0)
6238 return ICEDiag(1, E->getLocStart());
6239 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006240 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006241 if (LEval.isMinSignedValue())
6242 return ICEDiag(1, E->getLocStart());
6243 }
6244 }
6245 }
John McCall2de56d12010-08-25 11:45:40 +00006246 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006247 if (Ctx.getLangOptions().C99) {
6248 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6249 // if it isn't evaluated.
6250 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6251 return ICEDiag(1, E->getLocStart());
6252 } else {
6253 // In both C89 and C++, commas in ICEs are illegal.
6254 return ICEDiag(2, E->getLocStart());
6255 }
6256 }
6257 if (LHSResult.Val >= RHSResult.Val)
6258 return LHSResult;
6259 return RHSResult;
6260 }
John McCall2de56d12010-08-25 11:45:40 +00006261 case BO_LAnd:
6262 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006263 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6264 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6265 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6266 // Rare case where the RHS has a comma "side-effect"; we need
6267 // to actually check the condition to see whether the side
6268 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006269 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006270 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006271 return RHSResult;
6272 return NoDiag();
6273 }
6274
6275 if (LHSResult.Val >= RHSResult.Val)
6276 return LHSResult;
6277 return RHSResult;
6278 }
6279 }
6280 }
6281 case Expr::ImplicitCastExprClass:
6282 case Expr::CStyleCastExprClass:
6283 case Expr::CXXFunctionalCastExprClass:
6284 case Expr::CXXStaticCastExprClass:
6285 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006286 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006287 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006288 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006289 if (isa<ExplicitCastExpr>(E)) {
6290 if (const FloatingLiteral *FL
6291 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6292 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6293 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6294 APSInt IgnoredVal(DestWidth, !DestSigned);
6295 bool Ignored;
6296 // If the value does not fit in the destination type, the behavior is
6297 // undefined, so we are not required to treat it as a constant
6298 // expression.
6299 if (FL->getValue().convertToInteger(IgnoredVal,
6300 llvm::APFloat::rmTowardZero,
6301 &Ignored) & APFloat::opInvalidOp)
6302 return ICEDiag(2, E->getLocStart());
6303 return NoDiag();
6304 }
6305 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006306 switch (cast<CastExpr>(E)->getCastKind()) {
6307 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006308 case CK_AtomicToNonAtomic:
6309 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006310 case CK_NoOp:
6311 case CK_IntegralToBoolean:
6312 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006313 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006314 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006315 return ICEDiag(2, E->getLocStart());
6316 }
John McCalld905f5a2010-05-07 05:32:02 +00006317 }
John McCall56ca35d2011-02-17 10:25:35 +00006318 case Expr::BinaryConditionalOperatorClass: {
6319 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6320 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6321 if (CommonResult.Val == 2) return CommonResult;
6322 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6323 if (FalseResult.Val == 2) return FalseResult;
6324 if (CommonResult.Val == 1) return CommonResult;
6325 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006326 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006327 return FalseResult;
6328 }
John McCalld905f5a2010-05-07 05:32:02 +00006329 case Expr::ConditionalOperatorClass: {
6330 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6331 // If the condition (ignoring parens) is a __builtin_constant_p call,
6332 // then only the true side is actually considered in an integer constant
6333 // expression, and it is fully evaluated. This is an important GNU
6334 // extension. See GCC PR38377 for discussion.
6335 if (const CallExpr *CallCE
6336 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006337 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6338 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006339 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006340 if (CondResult.Val == 2)
6341 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006342
Richard Smithf48fdb02011-12-09 22:58:01 +00006343 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6344 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006345
John McCalld905f5a2010-05-07 05:32:02 +00006346 if (TrueResult.Val == 2)
6347 return TrueResult;
6348 if (FalseResult.Val == 2)
6349 return FalseResult;
6350 if (CondResult.Val == 1)
6351 return CondResult;
6352 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6353 return NoDiag();
6354 // Rare case where the diagnostics depend on which side is evaluated
6355 // Note that if we get here, CondResult is 0, and at least one of
6356 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006357 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006358 return FalseResult;
6359 }
6360 return TrueResult;
6361 }
6362 case Expr::CXXDefaultArgExprClass:
6363 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6364 case Expr::ChooseExprClass: {
6365 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6366 }
6367 }
6368
David Blaikie30263482012-01-20 21:50:17 +00006369 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006370}
6371
Richard Smithf48fdb02011-12-09 22:58:01 +00006372/// Evaluate an expression as a C++11 integral constant expression.
6373static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6374 const Expr *E,
6375 llvm::APSInt *Value,
6376 SourceLocation *Loc) {
6377 if (!E->getType()->isIntegralOrEnumerationType()) {
6378 if (Loc) *Loc = E->getExprLoc();
6379 return false;
6380 }
6381
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006382 APValue Result;
6383 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006384 return false;
6385
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006386 assert(Result.isInt() && "pointer cast to int is not an ICE");
6387 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006388 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006389}
6390
Richard Smithdd1f29b2011-12-12 09:28:41 +00006391bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006392 if (Ctx.getLangOptions().CPlusPlus0x)
6393 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6394
John McCalld905f5a2010-05-07 05:32:02 +00006395 ICEDiag d = CheckICE(this, Ctx);
6396 if (d.Val != 0) {
6397 if (Loc) *Loc = d.Loc;
6398 return false;
6399 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006400 return true;
6401}
6402
6403bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6404 SourceLocation *Loc, bool isEvaluated) const {
6405 if (Ctx.getLangOptions().CPlusPlus0x)
6406 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6407
6408 if (!isIntegerConstantExpr(Ctx, Loc))
6409 return false;
6410 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006411 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006412 return true;
6413}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006414
6415bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6416 SourceLocation *Loc) const {
6417 // We support this checking in C++98 mode in order to diagnose compatibility
6418 // issues.
6419 assert(Ctx.getLangOptions().CPlusPlus);
6420
6421 Expr::EvalStatus Status;
6422 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6423 Status.Diag = &Diags;
6424 EvalInfo Info(Ctx, Status);
6425
6426 APValue Scratch;
6427 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6428
6429 if (!Diags.empty()) {
6430 IsConstExpr = false;
6431 if (Loc) *Loc = Diags[0].first;
6432 } else if (!IsConstExpr) {
6433 // FIXME: This shouldn't happen.
6434 if (Loc) *Loc = getExprLoc();
6435 }
6436
6437 return IsConstExpr;
6438}
Richard Smith745f5142012-01-27 01:14:48 +00006439
6440bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6441 llvm::SmallVectorImpl<
6442 PartialDiagnosticAt> &Diags) {
6443 // FIXME: It would be useful to check constexpr function templates, but at the
6444 // moment the constant expression evaluator cannot cope with the non-rigorous
6445 // ASTs which we build for dependent expressions.
6446 if (FD->isDependentContext())
6447 return true;
6448
6449 Expr::EvalStatus Status;
6450 Status.Diag = &Diags;
6451
6452 EvalInfo Info(FD->getASTContext(), Status);
6453 Info.CheckingPotentialConstantExpression = true;
6454
6455 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6456 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6457
6458 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6459 // is a temporary being used as the 'this' pointer.
6460 LValue This;
6461 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6462 This.set(&VIE, Info.CurrentCall);
6463
6464 APValue Scratch;
6465 ArrayRef<const Expr*> Args;
6466
6467 SourceLocation Loc = FD->getLocation();
6468
6469 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
6470 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6471 } else
6472 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6473 Args, FD->getBody(), Info, Scratch);
6474
6475 return Diags.empty();
6476}